diff --git a/.gitmodules b/.gitmodules index 73baf268fde7..7b2e9ccc4868 100644 --- a/.gitmodules +++ b/.gitmodules @@ -202,7 +202,7 @@ url = https://github.com/ClickHouse/azure-sdk-for-cpp [submodule "contrib/minizip-ng"] path = contrib/minizip-ng - url = https://github.com/zlib-ng/minizip-ng + url = https://github.com/ClickHouse/minizip-ng [submodule "contrib/wyhash"] path = contrib/wyhash url = https://github.com/wangyi-fudan/wyhash diff --git a/base/glibc-compatibility/glibc-compatibility.c b/base/glibc-compatibility/glibc-compatibility.c index 738cda47877a..b2e741ddac89 100644 --- a/base/glibc-compatibility/glibc-compatibility.c +++ b/base/glibc-compatibility/glibc-compatibility.c @@ -427,6 +427,14 @@ int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *fa) { return 0; } +/// gettid was added in glibc 2.30. Use the raw syscall for compatibility with older systems. +/// Rust's standard library (since ~nightly-2026) references gettid as a weak symbol; +/// providing it here prevents pulling in GLIBC_2.30. +pid_t gettid(void) +{ + return syscall(__NR_gettid); +} + #if defined (__cplusplus) } #endif diff --git a/ci/docker/binary-builder/Dockerfile b/ci/docker/binary-builder/Dockerfile index 115a4bd58475..402674446465 100644 --- a/ci/docker/binary-builder/Dockerfile +++ b/ci/docker/binary-builder/Dockerfile @@ -19,10 +19,6 @@ COPY --from=altinityinfra/cctools:c0aae9395f33405b6e2b \ /etc/ssl/ RUN apt-get update \ - && apt-get install software-properties-common --yes --no-install-recommends --verbose-versions - -RUN add-apt-repository ppa:ubuntu-toolchain-r/test --yes \ - && apt-get update \ && apt-get remove --yes clang-tools-${LLVM_VERSION} || true \ && apt-get install --yes \ clang-tools-${LLVM_VERSION} \ diff --git a/ci/docker/fasttest/Dockerfile b/ci/docker/fasttest/Dockerfile index 48412b092395..01f555340ccc 100644 --- a/ci/docker/fasttest/Dockerfile +++ b/ci/docker/fasttest/Dockerfile @@ -95,8 +95,8 @@ RUN ARCH=$(uname -m) && \ ./rustup-init -y && \ rm rustup-init && \ chmod 777 -R /rust && \ - rustup toolchain install nightly-2025-07-07 --no-self-update && \ - rustup default nightly-2025-07-07 && \ + rustup toolchain install nightly-2026-11-02 --no-self-update && \ + rustup default nightly-2026-11-02 && \ rustup toolchain remove stable && \ rustup component add rust-src && \ rustup target add x86_64-unknown-linux-gnu && \ diff --git a/ci/jobs/build_clickhouse.py b/ci/jobs/build_clickhouse.py index 0fee05526581..4a08b132858f 100644 --- a/ci/jobs/build_clickhouse.py +++ b/ci/jobs/build_clickhouse.py @@ -89,14 +89,17 @@ def run_shell(name, command, **kwargs): def check_ppc64le_patches(build_root): - asm_path = os.path.join(build_root, "contrib/libunwind-cmake/UnwindRegistersSave.S") + # The ppc64le VSX register save fix is part of contrib/llvm-project itself now, + # so the unpatched libunwind source must contain it and must be the build input. + libunwind_asm = "contrib/llvm-project/libunwind/src/UnwindRegistersSave.S" + asm_path = os.path.join(current_directory, libunwind_asm) ninja_path = os.path.join(build_root, "build.ninja") try: with open(asm_path, encoding="utf-8") as asm_file: asm = asm_file.read() except OSError as error: - print(f"Could not read patched libunwind source {asm_path}: {error}") + print(f"Could not read libunwind source {asm_path}: {error}") return False restored = ( @@ -105,12 +108,11 @@ def check_ppc64le_patches(build_root): " xxswapd n, n ;\\" ) if restored not in asm: - print(f"ppc64le libunwind patch was not applied to {asm_path}") + print(f"ppc64le libunwind VSX register save fix is missing in {asm_path}") return False # CMAKE_CXX_FLAGS in CMakeCache.txt stays empty. The real flags are on the ninja FLAGS lines. frame_flag = "-Wframe-larger-than=131072" - patched_asm = "contrib/libunwind-cmake/UnwindRegistersSave.S" found_frame = False found_asm = False found_altivec = False @@ -118,11 +120,11 @@ def check_ppc64le_patches(build_root): try: with open(ninja_path, encoding="utf-8", errors="replace") as ninja: for line in ninja: - if "FLAGS" not in line and patched_asm not in line: + if "FLAGS" not in line and libunwind_asm not in line: continue if not found_frame and frame_flag in line: found_frame = True - if not found_asm and patched_asm in line: + if not found_asm and libunwind_asm in line: found_asm = True if "FLAGS" in line: if "-maltivec" in line and ( @@ -144,7 +146,7 @@ def check_ppc64le_patches(build_root): print(f"{frame_flag} is not in {ninja_path}") return False if not found_asm: - print(f"{patched_asm} is not a build input in {ninja_path}") + print(f"{libunwind_asm} is not a build input in {ninja_path}") return False print("ppc64le patches are present") return True diff --git a/ci/tests/data/integration_test_durations_sample.tsv b/ci/tests/data/integration_test_durations_sample.tsv index 55fbf44d0ff0..6d85307a7032 100644 --- a/ci/tests/data/integration_test_durations_sample.tsv +++ b/ci/tests/data/integration_test_durations_sample.tsv @@ -317,7 +317,6 @@ test_keeper_opentelemetry_tracing/test.py 82072 test_refreshable_mv_watch_fault/test.py 81637 test_always_fetch_merged/test.py 80848 test_system_flush_logs/test.py 80564 -test_store_cleanup/test.py 80458 test_rmv_access_denied_on_rename_race/test.py 80328 test_replicated_merge_tree_compatibility/test.py 79758 test_clickhouse_server_wait_server_pool/test.py 79623 diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index 476aba3f5265..bd9470b11cb1 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,13 +2,13 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54571) +SET(VERSION_REVISION 54584) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 64) -SET(VERSION_GITHASH f4eb235f16580439cd374038ecd8c013a0011cd9) -SET(VERSION_DESCRIBE v26.3.64.10001.altinitytest) -SET(VERSION_STRING 26.3.64.10001.altinitytest) +SET(VERSION_PATCH 77) +SET(VERSION_GITHASH 510026b533dac3dda78e8c67076b01ff496b0c72) +SET(VERSION_DESCRIBE v26.3.77.10001.altinitytest) +SET(VERSION_STRING 26.3.77.10001.altinitytest) # end of autochange SET(VERSION_TWEAK 10001) diff --git a/cmake/cpu_features.cmake b/cmake/cpu_features.cmake index 3d298def547d..68d2115d83a9 100644 --- a/cmake/cpu_features.cmake +++ b/cmake/cpu_features.cmake @@ -18,7 +18,7 @@ if (ARCH_AARCH64) # crc32 is optional in v8.0 and mandatory in v8.1. Enable it as __crc32()* is used in lot's of places and even very old ARM CPUs # support it. set (COMPILER_FLAGS "${COMPILER_FLAGS} -march=armv8+crc") - list(APPEND RUSTFLAGS_CPU "-C" "target_feature=+crc,-neon") + list(APPEND RUSTFLAGS_CPU "-C" "target_feature=+crc") else () # ARMv8.2 is quite ancient but the lowest common denominator supported by both Graviton 2 and 3 processors [1, 10]. In particular, it # includes LSE (made mandatory with ARMv8.1) which provides nice speedups without having to fall back to compat flag diff --git a/contrib/chdig b/contrib/chdig index cbe8b89dacab..af4005a0dba2 160000 --- a/contrib/chdig +++ b/contrib/chdig @@ -1 +1 @@ -Subproject commit cbe8b89dacab6760732db09fadb8940f1faf1c3c +Subproject commit af4005a0dba22924bb295c0986d481f037e0d802 diff --git a/contrib/chdig-cmake/CMakeLists.txt b/contrib/chdig-cmake/CMakeLists.txt index 45272022cfe8..d5d45c612ab2 100644 --- a/contrib/chdig-cmake/CMakeLists.txt +++ b/contrib/chdig-cmake/CMakeLists.txt @@ -17,10 +17,10 @@ if (NOT ENABLE_CHDIG OR NOT ENABLE_RUST) return() endif() -clickhouse_import_crate(MANIFEST_PATH ../chdig/Cargo.toml) -clickhouse_config_crate_flags(chdig) -add_library(ch_rust::chdig ALIAS chdig) +clickhouse_import_crate(MANIFEST_PATH Cargo.toml) +clickhouse_config_crate_flags(_ch_rust_chdig) +add_library(ch_rust::chdig ALIAS _ch_rust_chdig) if (OS_DARWIN) - target_link_libraries(chdig INTERFACE "-framework AppKit") + target_link_libraries(_ch_rust_chdig INTERFACE "-framework AppKit") endif() diff --git a/contrib/chdig-cmake/Cargo.lock b/contrib/chdig-cmake/Cargo.lock new file mode 100644 index 000000000000..26ec2ffdc050 --- /dev/null +++ b/contrib/chdig-cmake/Cargo.lock @@ -0,0 +1,2658 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "_ch_rust_chdig" +version = "0.1.0" +dependencies = [ + "chdig", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chdig" +version = "26.11.1" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "chrono-tz", + "clap", + "clap_complete", + "clickhouse-rs", + "crossbeam-channel", + "crossterm", + "flamelens", + "flate2", + "flexi_logger", + "futures", + "futures-util", + "fuzzy-matcher", + "getrandom 0.2.17", + "humantime", + "libc", + "log", + "percent-encoding", + "perfetto_protos", + "protobuf", + "quick-xml", + "ratatui", + "regex", + "semver", + "serde", + "serde_json", + "serde_norway", + "signal-hook", + "size", + "strfmt", + "tempfile", + "tiny_http", + "tokio", + "unicode-width", + "url", + "uuid", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "chrono-tz" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59ae0466b83e838b81a54256c39d5d7c20b9d7daa10510a242d9b75abd5936e" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433e39f13c9a060046954e0592a8d0a4bcb1040125cbf91cb8ee58964cfb350f" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", +] + +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clickhouse-rs" +version = "1.1.0-alpha.1" +source = "git+https://github.com/azat-rust/clickhouse-rs?branch=next#50f683f0ae358d784c34eb0545c056fa3939c502" +dependencies = [ + "byteorder", + "cfg-if", + "chrono", + "chrono-tz", + "clickhouse-rs-cityhash-sys", + "combine", + "crossbeam-queue", + "either", + "futures-core", + "futures-sink", + "futures-util", + "hostname", + "lazy_static", + "log", + "lz4", + "percent-encoding", + "pin-project", + "rustls", + "thiserror 2.0.21", + "tokio", + "tokio-rustls", + "url", + "uuid", + "webpki-roots", +] + +[[package]] +name = "clickhouse-rs-cityhash-sys" +version = "0.1.2" +source = "git+https://github.com/azat-rust/clickhouse-rs?branch=next#50f683f0ae358d784c34eb0545c056fa3939c502" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags", + "crossterm_winapi", + "derive_more", + "document-features", + "filedescriptor", + "mio", + "parking_lot", + "rustix 1.1.6", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flamelens" +version = "0.4.0" +source = "git+https://github.com/azat-rust/flamelens?branch=chdig#40706414c879da3359acd432547c05938c47bad0" +dependencies = [ + "anyhow", + "cfg-if", + "clap", + "crossterm", + "ratatui", + "regex", + "serde", + "serde_json", + "tui-input", +] + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "flexi_logger" +version = "0.27.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469e584c031833564840fb0cdbce99bdfe946fd45480a188545e73a76f45461c" +dependencies = [ + "chrono", + "glob", + "lazy_static", + "log", + "thiserror 1.0.69", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fuzzy-matcher" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94" +dependencies = [ + "thread_local", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c731c3e10504cc8ed35cfe2f1db4c9274c3d35fa486e3b31df46f068ef3e867" +dependencies = [ + "libc", + "match_cfg", + "winapi", +] + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "lz4" +version = "1.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" +dependencies = [ + "lz4-sys", +] + +[[package]] +name = "lz4-sys" +version = "1.11.1+lz4-1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "match_cfg" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "perfetto_protos" +version = "0.51.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634f88ebef917643d9e470dbf99637fbfa8295f54525954d156641f06823f9ac" +dependencies = [ + "protobuf", + "protobuf-codegen", + "protoc-bin-vendored", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "protobuf" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d65a1d4ddae7d8b5de68153b48f6aa3bba8cb002b243dbdbc55a5afbc98f99f4" +dependencies = [ + "once_cell", + "protobuf-support", + "thiserror 1.0.69", +] + +[[package]] +name = "protobuf-codegen" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d3976825c0014bbd2f3b34f0001876604fe87e0c86cd8fa54251530f1544ace" +dependencies = [ + "anyhow", + "once_cell", + "protobuf", + "protobuf-parse", + "regex", + "tempfile", + "thiserror 1.0.69", +] + +[[package]] +name = "protobuf-parse" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4aeaa1f2460f1d348eeaeed86aea999ce98c1bded6f089ff8514c9d9dbdc973" +dependencies = [ + "anyhow", + "indexmap", + "log", + "protobuf", + "protobuf-support", + "tempfile", + "thiserror 1.0.69", + "which", +] + +[[package]] +name = "protobuf-support" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e36c2f31e0a47f9280fb347ef5e461ffcd2c52dd520d8e216b52f93b0b0d7d6" +dependencies = [ + "thiserror 1.0.69", +] + +[[package]] +name = "protoc-bin-vendored" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8760a25b6ff9c620324822737e468478fa092234190d2e449760344354896ed9" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fa2624782ca04cd44f51554566717377acd240e4c0016d757dd74fccc9324f" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2417e9817fa237dab803ad4dda7357a111656e242959cc6b8f9a1a583367d42" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d189c34636356a46a7ed3188233dc8a88c431278cc54d4a19b096a2d270e985" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171e39f1e846e5f322ced1ac3b8d4cd3a3833ca24b6e5d58b3632574fe6204fa" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "873cdcc097593432086661aa432b8078f1cd87bfb02847c332e98ae2c119e966" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb72df001783b8297847fe8f5f874ee400fd742c843d60583e8c23d96977c7f" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04652167eca899dda05f32f5481adeaf25c623a98ce2fc146a001cc59a2add7" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263a3f48f01e7309e857138bd47f785585b4a005e8e56c6d2824ce91195999c3" + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags", + "compact_str", + "critical-section", + "hashbrown", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags", + "hashbrown", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_norway" +version = "0.9.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml-norway", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c48f464f8e2766494cb2223d1683ff6801dd56f0d07298500f9c970de2571cf0" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strfmt" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046d549b88a663d317cd04d39696fca5f77db4db44e1db65bfb9dee7f9e680bd" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tui-input" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4fa0cb7933d19f91eb3109781bf7297d5e4cba57e857d97a29b9465d3383f56" +dependencies = [ + "crossterm", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "unsafe-libyaml-norway" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/contrib/chdig-cmake/Cargo.toml b/contrib/chdig-cmake/Cargo.toml new file mode 100644 index 000000000000..d36786053af7 --- /dev/null +++ b/contrib/chdig-cmake/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "_ch_rust_chdig" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["staticlib"] + +[dependencies] +chdig = { path = "../chdig", default-features = false, features = ["tls"] } + +# Standalone, so that the lock in this directory is used instead of the one in `chdig` +[workspace] diff --git a/contrib/chdig-cmake/src/lib.rs b/contrib/chdig-cmake/src/lib.rs new file mode 100644 index 000000000000..4a18a6b2ef29 --- /dev/null +++ b/contrib/chdig-cmake/src/lib.rs @@ -0,0 +1 @@ +pub use chdig; diff --git a/contrib/corrosion-cmake/CMakeLists.txt b/contrib/corrosion-cmake/CMakeLists.txt index b32168d64b6b..1f2101f536a9 100644 --- a/contrib/corrosion-cmake/CMakeLists.txt +++ b/contrib/corrosion-cmake/CMakeLists.txt @@ -35,7 +35,7 @@ endmacro() # Keep in sync with toolchain in docker images # (must be called before find_package(Rust) and inclusion of Corrosion.cmake) -set(Rust_TOOLCHAIN "nightly-2025-07-07") +set(Rust_TOOLCHAIN "nightly-2026-11-02") macro(find_rust) set_rust_target() diff --git a/contrib/corrosion-cmake/config.toml.in b/contrib/corrosion-cmake/config.toml.in index da1f465a6d10..c2a1513744c3 100644 --- a/contrib/corrosion-cmake/config.toml.in +++ b/contrib/corrosion-cmake/config.toml.in @@ -19,19 +19,7 @@ replace-with = 'vendored-sources' git = "https://github.com/azat-rust/clickhouse-rs" branch = "next" replace-with = "vendored-sources" -[source."git+https://github.com/azat-rust/cursive-flexi-logger-view?branch=next"] -git = "https://github.com/azat-rust/cursive-flexi-logger-view" -branch = "next" -replace-with = "vendored-sources" -[source."git+https://github.com/azat-rust/cursive?branch=chdig-next"] -git = "https://github.com/azat-rust/cursive" -branch = "chdig-next" -replace-with = "vendored-sources" -[source."git+https://github.com/azat-rust/cursive_table_view?branch=next"] -git = "https://github.com/azat-rust/cursive_table_view" -branch = "next" -replace-with = "vendored-sources" -[source."git+https://github.com/ys-l/flamelens?branch=main"] -git = "https://github.com/ys-l/flamelens" -branch = "main" +[source."git+https://github.com/azat-rust/flamelens?branch=chdig"] +git = "https://github.com/azat-rust/flamelens" +branch = "chdig" replace-with = "vendored-sources" diff --git a/contrib/delta-kernel-rs b/contrib/delta-kernel-rs index 609a93b33560..32287c524706 160000 --- a/contrib/delta-kernel-rs +++ b/contrib/delta-kernel-rs @@ -1 +1 @@ -Subproject commit 609a93b33560cd64d2d062e000ecd609fe5d0edd +Subproject commit 32287c524706da4114a624f652d70749efd8615c diff --git a/contrib/delta-kernel-rs-cmake/CMakeLists.txt b/contrib/delta-kernel-rs-cmake/CMakeLists.txt index 7fc6082ee436..3141a4141330 100644 --- a/contrib/delta-kernel-rs-cmake/CMakeLists.txt +++ b/contrib/delta-kernel-rs-cmake/CMakeLists.txt @@ -6,7 +6,14 @@ include(ExternalProject) set(USE_DELTA_KERNEL_RS ${ENABLE_LIBRARIES}) -# MSAN: Disabled because ring does not generate the appropriate symbols +# MSAN: Disabled because `ring` is still compiled in, and its hand-written assembly does +# not generate the symbols required by MSan. Switching to `default-engine-native-tls` +# only makes `delta-kernel-rs`'s own HTTP client (`reqwest`) able to use ClickHouse's +# OpenSSL; it does not remove `ring`. `object_store` pulls in `ring` two ways: directly +# (for AWS request HMAC signing) and transitively through `rustls`, which it forces onto +# `reqwest` via `rustls-tls-native-roots`. Because Cargo unifies features, `reqwest` ends +# up built with both the `native-tls` and `rustls` backends, so this is only a partial +# `native-tls` enablement. Tracking upstream: https://github.com/apache/arrow-rs-object-store/pull/585 # NO_ARMV81_OR_HIGHER: Disabled because ring assumes that Neon is available with ARM if (NOT ENABLE_LIBRARIES OR (NOT OS_LINUX AND NOT OS_DARWIN) OR (NOT ARCH_AMD64 AND NOT ARCH_AARCH64) OR (SANITIZE STREQUAL "memory") OR NO_ARMV81_OR_HIGHER) message(STATUS "Disabling delta kernel because of incompatible platform or Rust is disabled") @@ -23,7 +30,7 @@ endif() # * default-engine: Needed for its s3 client (we can't pass our own s3 client via ffi) clickhouse_import_crate( MANIFEST_PATH "${DELTA_KERNEL_RS_SOURCE_DIR}/ffi/Cargo.toml" - FEATURES "default-engine-rustls, test-ffi, tracing" + FEATURES "default-engine-native-tls, test-ffi, tracing, arrow" ) clickhouse_config_crate_flags(delta_kernel_ffi) @@ -36,7 +43,17 @@ corrosion_set_env_vars(delta_kernel_ffi "OPENSSL_LIBS=ssl:crypto" "OPENSSL_STATIC=1" "OPENSSL_LIB_DIR=${CMAKE_BINARY_DIR}/contrib/openssl-cmake/" - "OPENSSL_INCLUDE_DIR=${CMAKE_BINARY_DIR}/contrib/openssl-cmake/common/") + "OPENSSL_INCLUDE_DIR=${ClickHouse_SOURCE_DIR}/contrib/openssl-cmake/common/include/" + # The build-script for `openssl-sys` expects all includes to be in one path + # but the CMake build for OpenSSL results in headers in two different places + "CFLAGS=${RUST_CFLAGS} -I ${ClickHouse_SOURCE_DIR}/contrib/openssl/include/") + +# aws-lc-sys's memcmp_check links a small test binary via cc; clang adds +# -lgcc_s / -lgcc_eh by default but the bundled Linux sysroot ships only +# libgcc.a. +if (OS_LINUX) + corrosion_set_env_vars(delta_kernel_ffi "LDFLAGS=-nodefaultlibs -lc -lgcc") +endif() target_include_directories(delta_kernel_ffi INTERFACE "${DELTA_KERNEL_TARGET_PATH}/") target_link_libraries(delta_kernel_ffi INTERFACE OpenSSL::Crypto OpenSSL::SSL) diff --git a/contrib/krb5 b/contrib/krb5 index 857c2d1edd7a..17f660ca561d 160000 --- a/contrib/krb5 +++ b/contrib/krb5 @@ -1 +1 @@ -Subproject commit 857c2d1edd7a4218b84594768587aa53fd63da9e +Subproject commit 17f660ca561db6716125041396ce2cdd8ebd594a diff --git a/contrib/krb5-cmake/autoconf_darwin.h b/contrib/krb5-cmake/autoconf_darwin.h index 64c28f90b41b..7c7ee22fa1ff 100644 --- a/contrib/krb5-cmake/autoconf_darwin.h +++ b/contrib/krb5-cmake/autoconf_darwin.h @@ -635,7 +635,7 @@ #define PACKAGE_NAME "Kerberos 5" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Kerberos 5 1.22.1" +#define PACKAGE_STRING "Kerberos 5 1.22.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "krb5" @@ -644,7 +644,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.22.1" +#define PACKAGE_VERSION "1.22.3" /* Define if setjmp indicates POSIX interface */ #define POSIX_SETJMP 1 diff --git a/contrib/krb5-cmake/autoconf_linux.h b/contrib/krb5-cmake/autoconf_linux.h index ec8e867eec38..efa76cd145fc 100644 --- a/contrib/krb5-cmake/autoconf_linux.h +++ b/contrib/krb5-cmake/autoconf_linux.h @@ -637,7 +637,7 @@ #define PACKAGE_NAME "Kerberos 5" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Kerberos 5 1.22.1" +#define PACKAGE_STRING "Kerberos 5 1.22.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "krb5" @@ -646,7 +646,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.22.1" +#define PACKAGE_VERSION "1.22.3" /* Define if setjmp indicates POSIX interface */ /* #undef POSIX_SETJMP */ diff --git a/contrib/libunwind-cmake/CMakeLists.txt b/contrib/libunwind-cmake/CMakeLists.txt index 1f10c2881ab0..c37c485f0f0b 100644 --- a/contrib/libunwind-cmake/CMakeLists.txt +++ b/contrib/libunwind-cmake/CMakeLists.txt @@ -17,32 +17,6 @@ set(LIBUNWIND_ASM_SOURCES "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersRestore.S" "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S") -# stxvd2x stores VSX doublewords swapped on ppc64le. The first xxswapd fixes the -# saved image and leaves the live register swapped; the patch swaps it back. -if(ARCH_PPC64LE) - find_program(LIBUNWIND_PATCH_EXECUTABLE patch REQUIRED) - set(LIBUNWIND_REGISTERS_SAVE_ASM "${CMAKE_CURRENT_BINARY_DIR}/UnwindRegistersSave.S") - set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS - "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S" - "${CMAKE_CURRENT_SOURCE_DIR}/ppc64le-vsx-register-save.patch") - execute_process( - COMMAND "${LIBUNWIND_PATCH_EXECUTABLE}" -o "${LIBUNWIND_REGISTERS_SAVE_ASM}" - "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S" - "${CMAKE_CURRENT_SOURCE_DIR}/ppc64le-vsx-register-save.patch" - RESULT_VARIABLE LIBUNWIND_PATCH_RESULT - OUTPUT_VARIABLE LIBUNWIND_PATCH_OUTPUT - ERROR_VARIABLE LIBUNWIND_PATCH_ERROR - ) - if(NOT LIBUNWIND_PATCH_RESULT EQUAL 0) - message(FATAL_ERROR "Failed to apply ppc64le-vsx-register-save.patch\n${LIBUNWIND_PATCH_OUTPUT}\n${LIBUNWIND_PATCH_ERROR}") - endif() - list(REMOVE_ITEM LIBUNWIND_ASM_SOURCES "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S") - list(APPEND LIBUNWIND_ASM_SOURCES "${LIBUNWIND_REGISTERS_SAVE_ASM}") - # "assembly.h" is included from the directory of the .S file. - set_source_files_properties("${LIBUNWIND_REGISTERS_SAVE_ASM}" PROPERTIES - COMPILE_FLAGS "-I${LIBUNWIND_SOURCE_DIR}/src") -endif() - enable_language(ASM) set(LIBUNWIND_SOURCES diff --git a/contrib/libunwind-cmake/ppc64le-vsx-register-save.patch b/contrib/libunwind-cmake/ppc64le-vsx-register-save.patch deleted file mode 100644 index 79eed78d63ab..000000000000 --- a/contrib/libunwind-cmake/ppc64le-vsx-register-save.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/UnwindRegistersSave.S -+++ b/UnwindRegistersSave.S -@@ -427,6 +427,7 @@ - #define PPC64_STVS(n) \ - xxswapd n, n ;\ - stxvd2x n, 0, 4 ;\ -+ xxswapd n, n ;\ - addi 4, 4, 16 - #else - #define PPC64_STVS(n) \ diff --git a/contrib/llvm-project b/contrib/llvm-project index 1e8c7547d529..85d6c707358a 160000 --- a/contrib/llvm-project +++ b/contrib/llvm-project @@ -1 +1 @@ -Subproject commit 1e8c7547d529e162040b73827333f4ce501f4d36 +Subproject commit 85d6c707358aea53a686d32dea6b994dc729891d diff --git a/contrib/minizip-ng b/contrib/minizip-ng index 95ba7abdd24a..fd8abd88f4d8 160000 --- a/contrib/minizip-ng +++ b/contrib/minizip-ng @@ -1 +1 @@ -Subproject commit 95ba7abdd24a956bde584db54d1d55e37d511e2f +Subproject commit fd8abd88f4d8215f2becdefe3ef2bfbc06edc3d1 diff --git a/contrib/mongo-c-driver b/contrib/mongo-c-driver index 58b4e1f39c6f..69c77fcb894e 160000 --- a/contrib/mongo-c-driver +++ b/contrib/mongo-c-driver @@ -1 +1 @@ -Subproject commit 58b4e1f39c6f8bcf4da4204deb84f9b3527388d4 +Subproject commit 69c77fcb894eeadd4cc2059d4c65e8968db1462c diff --git a/contrib/postgres b/contrib/postgres index ab6952af3ac8..c7649becd213 160000 --- a/contrib/postgres +++ b/contrib/postgres @@ -1 +1 @@ -Subproject commit ab6952af3ac8cdede654be4dc68f990b0352c213 +Subproject commit c7649becd213231466df7e679154e8ac0f744788 diff --git a/contrib/postgres-cmake/pg_config.h b/contrib/postgres-cmake/pg_config.h index 84e435838d41..9df1b95a3b33 100644 --- a/contrib/postgres-cmake/pg_config.h +++ b/contrib/postgres-cmake/pg_config.h @@ -593,7 +593,7 @@ #define PACKAGE_NAME "PostgreSQL" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "PostgreSQL 18.3" +#define PACKAGE_STRING "PostgreSQL 18.6" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "postgresql" @@ -602,7 +602,7 @@ #define PACKAGE_URL "https://www.postgresql.org/" /* Define to the version of this package. */ -#define PACKAGE_VERSION "18.3" +#define PACKAGE_VERSION "18.6" /* Define to the name of a signed 128-bit integer type. */ #define PG_INT128_TYPE __int128 @@ -618,7 +618,7 @@ #define PG_MAJORVERSION_NUM 18 /* PostgreSQL minor version number */ -#define PG_MINORVERSION_NUM 4 +#define PG_MINORVERSION_NUM 6 /* Define to best C++ printf format archetype, usually gnu_printf if available. */ @@ -629,13 +629,13 @@ #define PG_C_PRINTF_ATTRIBUTE gnu_printf /* PostgreSQL version as a string */ -#define PG_VERSION "18.4" +#define PG_VERSION "18.6" /* PostgreSQL version as a number */ -#define PG_VERSION_NUM 180004 +#define PG_VERSION_NUM 180006 /* A string containing the version number, platform, and C compiler */ -#define PG_VERSION_STR "PostgreSQL 18.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 15.2.1 20250813, 64-bit" +#define PG_VERSION_STR "PostgreSQL 18.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 15.2.1 20250813, 64-bit" /* Define to 1 to allow profiling output to be saved separately for each process. */ diff --git a/contrib/rust_vendor b/contrib/rust_vendor index 3332fd445e9c..11cea4f35a9a 160000 --- a/contrib/rust_vendor +++ b/contrib/rust_vendor @@ -1 +1 @@ -Subproject commit 3332fd445e9cc0c21ff82b81dccc250eb4560821 +Subproject commit 11cea4f35a9a6184e391d76333aea8662c6e3c1d diff --git a/contrib/wasmtime b/contrib/wasmtime index c411eb43e6c4..1c05b58b727c 160000 --- a/contrib/wasmtime +++ b/contrib/wasmtime @@ -1 +1 @@ -Subproject commit c411eb43e6c43e9d476ed831098abab256467f58 +Subproject commit 1c05b58b727cdb87dfdc8f076feef2b1666e6a53 diff --git a/contrib/zstd b/contrib/zstd index 437081852c39..1663170820f4 160000 --- a/contrib/zstd +++ b/contrib/zstd @@ -1 +1 @@ -Subproject commit 437081852c396eeb61edb7d47044d8cad911885e +Subproject commit 1663170820f4825123ddfc4976223ad2c78b21cc diff --git a/docker/keeper/Dockerfile b/docker/keeper/Dockerfile index e877588b61fe..925af74d8ec3 100644 --- a/docker/keeper/Dockerfile +++ b/docker/keeper/Dockerfile @@ -51,6 +51,9 @@ RUN addgroup -S -g "${DEFAULT_GID}" clickhouse && \ adduser -S -h "/var/lib/clickhouse" -s /bin/bash -G clickhouse -g "ClickHouse keeper" -u "${DEFAULT_UID}" clickhouse ARG TARGETARCH +# `apk upgrade` runs before `apk add` because `apk add` never bumps packages already in +# the base image, so without it the image keeps whatever (possibly vulnerable) packages +# the `alpine` snapshot had at build time. RUN arch=${TARGETARCH:-amd64} \ && cd /tmp && rm -f /tmp/*tgz && rm -f /tmp/*tgz.sha512 |: \ && if [ -n "${DIRECT_DOWNLOAD_URLS}" ]; then \ @@ -71,6 +74,7 @@ RUN arch=${TARGETARCH:-amd64} \ ; done \ && rm /tmp/*.tgz /install -r \ && chmod +x /entrypoint.sh \ + && apk upgrade --no-cache \ && apk add --no-cache su-exec bash tzdata \ && cp /usr/share/zoneinfo/UTC /etc/localtime \ && echo "UTC" > /etc/timezone diff --git a/docker/server/Dockerfile.alpine b/docker/server/Dockerfile.alpine index c35cbc4e0db1..e20d86476437 100644 --- a/docker/server/Dockerfile.alpine +++ b/docker/server/Dockerfile.alpine @@ -47,6 +47,9 @@ ARG DEFAULT_GID="101" RUN addgroup -S -g "${DEFAULT_GID}" clickhouse && \ adduser -S -h "/var/lib/clickhouse" -s /bin/bash -G clickhouse -g "ClickHouse server" -u "${DEFAULT_UID}" clickhouse +# `apk upgrade` runs before `apk add` because `apk add` never bumps packages already in +# the base image, so without it the image keeps whatever (possibly vulnerable) packages +# the `alpine` snapshot had at build time. RUN arch=${TARGETARCH:-amd64} \ && cd /tmp \ && if [ -n "${DIRECT_DOWNLOAD_URLS}" ]; then \ @@ -67,6 +70,7 @@ RUN arch=${TARGETARCH:-amd64} \ ; done \ && rm /tmp/*.tgz /install -r \ && chmod +x /entrypoint.sh \ + && apk upgrade --no-cache \ && apk add --no-cache bash tzdata \ && cp /usr/share/zoneinfo/UTC /etc/localtime \ && echo "UTC" > /etc/timezone diff --git a/docs/en/development/build.md b/docs/en/development/build.md index 50b3354719ec..311dc4090127 100644 --- a/docs/en/development/build.md +++ b/docs/en/development/build.md @@ -70,8 +70,8 @@ As with C++ dependencies, ClickHouse uses vendoring to control exactly what's in Although in release mode any rust modern rustup toolchain version should work with these dependencies, if you plan to enable sanitizers you must use a version that matches the exact same `std` as the one used in CI (for which we vendor the crates): ```bash -rustup toolchain install nightly-2025-07-07 -rustup default nightly-2025-07-07 +rustup toolchain install nightly-2026-11-02 +rustup default nightly-2026-11-02 rustup component add rust-src ``` ## Build ClickHouse {#build-clickhouse} diff --git a/docs/en/engines/table-engines/integrations/kafka.md b/docs/en/engines/table-engines/integrations/kafka.md index e06880eccfed..32b8a446a040 100644 --- a/docs/en/engines/table-engines/integrations/kafka.md +++ b/docs/en/engines/table-engines/integrations/kafka.md @@ -233,6 +233,8 @@ Similar to GraphiteMergeTree, the Kafka engine supports extended configuration u For a list of possible configuration options, see the [librdkafka configuration reference](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md). Use the underscore (`_`) instead of a dot in the ClickHouse configuration. For example, `check.crcs=true` will be `true`. +A named collection created with `CREATE NAMED COLLECTION` accepts only the `librdkafka` properties on the [allowlist](https://github.com/ClickHouse/ClickHouse/blob/26.3/src/Storages/Kafka/KafkaConfigLoader.cpp), such as `security.protocol`, `sasl.username`, and `fetch.min.bytes`. If a table uses a collection with an unlisted property, such as `ssl.ca.location` or `sasl.kerberos.keytab`, ClickHouse returns `BAD_ARGUMENTS`. To use these properties, define the collection in the server configuration file. This restriction also applies to properties added with `ALTER NAMED COLLECTION` after the table was created. Instead of the path of a TLS file, a named collection created with SQL can contain the contents of the file: `ssl.key.pem`, `ssl.certificate.pem`, and `ssl.ca.pem`. + ### Kerberos support {#kafka-kerberos-support} To deal with Kerberos-aware Kafka, add `security_protocol` child element with `sasl_plaintext` value. It is enough if Kerberos ticket-granting ticket is obtained and cached by OS facilities. diff --git a/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md b/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md index ad6c5526870e..dbfde47274d6 100644 --- a/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md +++ b/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md @@ -1837,7 +1837,7 @@ Settings for optional improvements in the access control system. | Setting | Description | Default | |-------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| | `on_cluster_queries_require_cluster_grant` | Sets whether `ON CLUSTER` queries require the `CLUSTER` grant. | `true` | -| `readonly_restricts_set_role` | Sets whether the `SET ROLE` statement is refused when the session or the query is readonly. When `false`, `readonly` does not restrict `SET ROLE`. The `role` HTTP query parameter is not affected. | `false` | +| `readonly_restricts_set_role` | Sets whether the `SET ROLE` and `SET DEFAULT ROLE` statements are refused when the session or the query is readonly. When `false`, `readonly` does not restrict `SET ROLE`, nor `SET DEFAULT ROLE ... TO CURRENT_USER`. The `role` HTTP query parameter is not affected. | `false` | | `role_cache_expiration_time_seconds` | Sets the number of seconds since last access, that a role is stored in the Role Cache. | `600` | | `select_from_information_schema_requires_grant` | Sets whether `SELECT * FROM information_schema.` requires any grants and can be executed by any user. If set to true, then this query requires `GRANT SELECT ON information_schema.
`, just as for ordinary tables. | `true` | | `select_from_system_db_requires_grant` | Sets whether `SELECT * FROM system.
` requires any grants and can be executed by any user. If set to true then this query requires `GRANT SELECT ON system.
` just as for non-system tables. Exceptions: a few system tables (`tables`, `columns`, `databases`, and some constant tables like `one`, `contributors`) are still accessible for everyone; and if there is a `SHOW` privilege (e.g. `SHOW USERS`) granted then the corresponding system table (i.e. `system.users`) will be accessible. | `true` | diff --git a/programs/client/FuzzLoop.cpp b/programs/client/FuzzLoop.cpp index d56b75acb33e..a5f83e5ef94d 100644 --- a/programs/client/FuzzLoop.cpp +++ b/programs/client/FuzzLoop.cpp @@ -435,7 +435,7 @@ bool Client::processWithASTFuzzer(std::string_view full_query) { String bytes; { - auto read_buf = getReadBufferFromASTInsertQuery(query); + auto read_buf = getReadBufferFromASTInsertQuery(query, client_context); WriteBufferFromString write_buf(bytes); copyData(*read_buf, write_buf); } diff --git a/programs/format/Format.cpp b/programs/format/Format.cpp index 6d64f7057d54..8d677663dc9c 100644 --- a/programs/format/Format.cpp +++ b/programs/format/Format.cpp @@ -285,7 +285,7 @@ int mainEntryClickHouseFormat(int argc, char ** argv) const char * this_query_end = find_first_symbols<'\n'>(insert_query->data, end); insert_query->end = this_query_end; pos = this_query_end; - insert_query_payload = getReadBufferFromASTInsertQuery(res); + insert_query_payload = getReadBufferFromASTInsertQuery(res, context); } if (!quiet) diff --git a/programs/server/binary.html b/programs/server/binary.html index 896a88ec3640..8117738b8890 100644 --- a/programs/server/binary.html +++ b/programs/server/binary.html @@ -267,15 +267,22 @@ `${url}&default_format=JSON`, { method: 'POST', - body: `SELECT encodeXMLComponent(demangle(addressToSymbol(${addr_int}::UInt64))) AS name, - encodeXMLComponent(addressToLine(${addr_int}::UInt64)) AS line` + body: `SELECT demangle(addressToSymbol(${addr_int}::UInt64)) AS name, + addressToLine(${addr_int}::UInt64) AS line` }).then(response => response.json().then(o => { let name = o.rows ? o.data[0].name : 'nothing'; let line = o.rows ? o.data[0].line : ''; if (addr_int == current_requested_addr) { - popup.setContent(`

${addr_hex}

${name}

${line}

`); + /// The response is untrusted (the server can be specified by the `host` parameter), + /// so it is inserted as text, never as HTML. + const content = document.createElement('div'); + const addr_elem = content.appendChild(document.createElement('p')).appendChild(document.createElement('b')); + addr_elem.textContent = addr_hex; + content.appendChild(document.createElement('p')).textContent = name; + content.appendChild(document.createElement('p')).textContent = line; + popup.setContent(content); } })); diff --git a/programs/server/config.xml b/programs/server/config.xml index 9f546c756069..e75eb60beac0 100644 --- a/programs/server/config.xml +++ b/programs/server/config.xml @@ -870,7 +870,7 @@ however you can change this behaviour by setting this to true --> false - false diff --git a/rust/vendor.sh b/rust/vendor.sh index 08610c6f0c79..e31032eb560a 100755 --- a/rust/vendor.sh +++ b/rust/vendor.sh @@ -4,7 +4,7 @@ set -e # std is required for sanitizers builds # and we need to match toolchain version for std (to vendor proper dependencies) -TOOLCHAIN=nightly-2025-07-07 +TOOLCHAIN=nightly-2026-11-02 function cargo() { rustup run "$TOOLCHAIN" cargo "$@"; } function rustc() { rustup run "$TOOLCHAIN" rustc "$@"; } rustup component add --toolchain "$TOOLCHAIN" rust-src @@ -37,7 +37,7 @@ cd "$CH_TOP_DIR"/contrib/delta-kernel-rs || exit 1 cargo vendor --no-delete --locked --versioned-dirs --manifest-path Cargo.toml "$CH_TOP_DIR"/contrib/rust_vendor # chdig -cd "$CH_TOP_DIR"/contrib/chdig || exit 1 +cd "$CH_TOP_DIR"/contrib/chdig-cmake || exit 1 cargo vendor --no-delete --locked --versioned-dirs --manifest-path Cargo.toml "$CH_TOP_DIR"/contrib/rust_vendor # wasmtime diff --git a/rust/workspace/Cargo.lock b/rust/workspace/Cargo.lock index d181ad2d4d15..2c297f7e81dd 100644 --- a/rust/workspace/Cargo.lock +++ b/rust/workspace/Cargo.lock @@ -38,18 +38,18 @@ dependencies = [ [[package]] name = "addr2line" -version = "0.25.1" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a" dependencies = [ "gimli", ] [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -62,9 +62,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "android_system_properties" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" dependencies = [ "libc", ] @@ -129,7 +129,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -140,29 +140,20 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] name = "anyhow" -version = "1.0.102" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" - -[[package]] -name = "ar_archive_writer" -version = "0.5.1" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb93bbb63b9c227414f6eb3a0adfddca591a8ce1e9b60661bb08969b87e340b" -dependencies = [ - "object", -] +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "arbitrary" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" [[package]] name = "ariadne" @@ -176,26 +167,26 @@ dependencies = [ [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "async-trait" -version = "0.1.89" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "beef" @@ -211,57 +202,66 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.11.0" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] [[package]] name = "bstr" -version = "1.12.1" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ "memchr", - "regex-automata 0.4.14", - "serde", + "regex-automata", + "serde_core", ] [[package]] name = "bumpalo" -version = "3.20.2" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" dependencies = [ "allocator-api2", ] [[package]] name = "cc" -version = "1.2.57" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", - "shlex", + "shlex 2.0.1", ] [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chrono" -version = "0.4.44" +version = "0.4.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", "js-sys", @@ -272,23 +272,22 @@ dependencies = [ [[package]] name = "chumsky" -version = "0.11.2" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acc17a6284abccac6e50db35c1cee87f605474a72939b959a3a67d9371800efd" +checksum = "e0d2bfadce76f963d776feff99db6dc33783829539258314776383b33e2a00f8" dependencies = [ "hashbrown 0.15.5", - "regex-automata 0.3.9", + "regex-automata", "serde", - "stacker", "unicode-ident", "unicode-segmentation", ] [[package]] name = "clap" -version = "4.6.0" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", "clap_derive", @@ -296,9 +295,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.0" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ "anstream 1.0.0", "anstyle", @@ -308,32 +307,32 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.6.0" +version = "4.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19c9f1dde76b736e3681f28cec9d5a61299cbaae0fce80a68e43724ad56031eb" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" dependencies = [ "clap", ] [[package]] name = "clap_derive" -version = "4.6.0" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ "anstyle", "heck", "proc-macro2", "pulldown-cmark", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "cobs" @@ -341,7 +340,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" dependencies = [ - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -352,7 +351,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" dependencies = [ "serde", "termcolor", - "unicode-width 0.2.2", + "unicode-width 0.2.3", ] [[package]] @@ -369,45 +368,56 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpp_demangle" -version = "0.4.5" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" +checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" dependencies = [ "cfg-if", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cranelift-assembler-x64" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-assembler-x64-meta", ] [[package]] name = "cranelift-assembler-x64-meta" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-srcgen", ] [[package]] name = "cranelift-bforest" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-entity", + "wasmtime-internal-core", ] [[package]] name = "cranelift-bitset" -version = "0.128.1" +version = "0.137.1" dependencies = [ "serde", "serde_derive", + "wasmtime-internal-core", ] [[package]] name = "cranelift-codegen" -version = "0.128.1" +version = "0.137.1" dependencies = [ "bumpalo", "cranelift-assembler-x64", @@ -419,20 +429,24 @@ dependencies = [ "cranelift-entity", "cranelift-isle", "gimli", - "hashbrown 0.15.5", + "hashbrown 0.17.1", + "libm", "log", + "postcard", "pulley-interpreter", "regalloc2", "rustc-hash", "serde", + "serde_derive", + "sha2", "smallvec", "target-lexicon", - "wasmtime-internal-math", + "wasmtime-internal-core", ] [[package]] name = "cranelift-codegen-meta" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-assembler-x64-meta", "cranelift-codegen-shared", @@ -443,29 +457,31 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" -version = "0.128.1" +version = "0.137.1" [[package]] name = "cranelift-control" -version = "0.128.1" +version = "0.137.1" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-bitset", "serde", "serde_derive", + "wasmtime-internal-core", ] [[package]] name = "cranelift-frontend" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-codegen", + "hashbrown 0.17.1", "log", "smallvec", "target-lexicon", @@ -473,35 +489,36 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.128.1" +version = "0.137.1" [[package]] name = "cranelift-native" -version = "0.128.1" +version = "0.137.1" dependencies = [ "cranelift-codegen", "libc", + "mach2", "target-lexicon", ] [[package]] name = "cranelift-srcgen" -version = "0.128.1" +version = "0.137.1" [[package]] name = "crc32fast" -version = "1.5.0" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] [[package]] name = "crossbeam" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8" +checksum = "e71406cd8807725f7ac2f999a4cdd32e98f829fdf65f528343cebf945e41df1e" dependencies = [ "crossbeam-channel", "crossbeam-deque", @@ -512,18 +529,18 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.15" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -531,27 +548,37 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-queue" -version = "0.3.12" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] [[package]] name = "csv" @@ -576,9 +603,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.194" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "747d8437319e3a2f43d93b341c137927ca70c0f5dabeea7a005a73665e247c7e" +checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40" dependencies = [ "cc", "cxx-build", @@ -591,9 +618,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.194" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0f4697d190a142477b16aef7da8a99bfdc41e7e8b1687583c0d23a79c7afc1e" +checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f" dependencies = [ "cc", "codespan-reporting", @@ -601,39 +628,39 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn", + "syn 3.0.10", ] [[package]] name = "cxxbridge-cmd" -version = "1.0.194" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0956799fa8678d4c50eed028f2de1c0552ae183c76e976cf7ca8c4e36a7c328" +checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2" dependencies = [ "clap", "codespan-reporting", "indexmap", "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "cxxbridge-flags" -version = "1.0.194" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23384a836ab4f0ad98ace7e3955ad2de39de42378ab487dc28d3990392cb283a" +checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a" [[package]] name = "cxxbridge-macro" -version = "1.0.194" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6acc6b5822b9526adfb4fc377b67128fdd60aac757cc4a741a6278603f763cf" +checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575" dependencies = [ "indexmap", "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -657,7 +684,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn", + "syn 2.0.119", ] [[package]] @@ -668,7 +695,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -683,12 +710,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "powerfmt", -] +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] name = "derive_builder" @@ -708,7 +732,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -718,7 +742,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", - "syn", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", ] [[package]] @@ -750,9 +784,9 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "either" -version = "1.15.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "embedded-io" @@ -768,21 +802,21 @@ checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" [[package]] name = "enum-as-inner" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" +checksum = "0359ee92f81184d7985519e474bda2a5738476334edd3746c9b1265c067afe70" dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "env_filter" -version = "1.0.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" dependencies = [ "log", "regex", @@ -796,11 +830,11 @@ checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" [[package]] name = "env_logger" -version = "0.11.9" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" dependencies = [ - "anstream 0.6.21", + "anstream 1.0.0", "anstyle", "env_filter", "jiff", @@ -809,31 +843,25 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] -[[package]] -name = "fallible-iterator" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" - [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "fnv" @@ -853,6 +881,70 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + [[package]] name = "fuzzy-matcher" version = "0.3.7" @@ -862,6 +954,16 @@ dependencies = [ "thread_local", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -887,11 +989,12 @@ dependencies = [ [[package]] name = "gimli" -version = "0.32.3" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" dependencies = [ - "fallible-iterator", + "fnv", + "hashbrown 0.16.1", "indexmap", "stable_deref_trait", ] @@ -905,7 +1008,6 @@ dependencies = [ "allocator-api2", "equivalent", "foldhash 0.1.5", - "serde", ] [[package]] @@ -914,6 +1016,17 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", + "serde", + "serde_core", +] + [[package]] name = "heck" version = "0.5.0" @@ -952,12 +1065,12 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "indexmap" -version = "2.13.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.16.1", + "hashbrown 0.17.1", "serde", "serde_core", ] @@ -977,18 +1090,28 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" -version = "1.0.17" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.23" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ + "jiff-core", "jiff-static", "log", "portable-atomic", @@ -996,32 +1119,43 @@ dependencies = [ "serde_core", ] +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" -version = "0.2.23" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ + "jiff-core", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "js-sys" -version = "0.3.91" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "leb128fmt" @@ -1031,9 +1165,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.183" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libm" @@ -1043,9 +1177,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.14" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1744e39d1d6a9948f4f388969627434e31128196de472883b39f148769bfe30a" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] @@ -1067,30 +1201,27 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" -version = "0.4.29" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "mach2" -version = "0.4.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" -dependencies = [ - "libc", -] +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memfd" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad38eb12aea514a0466ea40a80fd8cc83637065948eb4a426e4aa46261175227" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" dependencies = [ "rustix", ] @@ -1101,7 +1232,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "cfg-if", "cfg_aliases", "libc", @@ -1109,9 +1240,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "num-traits" @@ -1124,21 +1255,21 @@ dependencies = [ [[package]] name = "num_threads" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" dependencies = [ "libc", ] [[package]] name = "object" -version = "0.37.3" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "crc32fast", - "hashbrown 0.15.5", + "hashbrown 0.17.1", "indexmap", "memchr", ] @@ -1163,9 +1294,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "polyglot-sql" -version = "0.1.13" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7d17752e25da3d490c7a5d8b1f7f1c7f1583be33c8463c59f389f4160394a6e" +checksum = "e2182e70eca8ef9207889597fec219bfa64efa2ec6ae8ead9a02bf95899fc6a4" dependencies = [ "serde", "serde_json", @@ -1175,15 +1306,15 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.13.1" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" -version = "0.2.5" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ "portable-atomic", ] @@ -1202,9 +1333,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "ppv-lite86" @@ -1217,25 +1348,25 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "prqlc" -version = "0.13.10" +version = "0.13.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8abe1a5ce31be22b91ff324a0a0bdbbba0b70474167d4fd3281c2fcc43273687" +checksum = "43a839cca77a001d05147bc1d39e60f33df9c2b50716d54b194dcdd8ad508f5a" dependencies = [ - "anstream 0.6.21", + "anstream 1.0.0", "ariadne", "chrono", "csv", "enum-as-inner", - "itertools", + "itertools 0.15.0", "log", "prqlc-parser", "regex", @@ -1252,66 +1383,55 @@ dependencies = [ [[package]] name = "prqlc-parser" -version = "0.13.10" +version = "0.13.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e23243464e0cf6ba4f129c4fa3062ef4bc9388922a59c1abffd6557001bb9c" +checksum = "464024b555e5c1dc48eca2d600e583dbeb5ff7a960b22f4346997a1b5aca3165" dependencies = [ "chumsky", "enum-as-inner", - "itertools", + "itertools 0.15.0", "log", "schemars", "semver", "serde", - "stacker", "strum", ] -[[package]] -name = "psm" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3852766467df634d74f0b2d7819bf8dc483a0eb2e3b0f50f756f9cfe8b0d18d8" -dependencies = [ - "ar_archive_writer", - "cc", -] - [[package]] name = "pulldown-cmark" -version = "0.13.1" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83c41efbf8f90ac44de7f3a868f0867851d261b56291732d0cbf7cceaaeb55a6" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "memchr", "unicase", ] [[package]] name = "pulley-interpreter" -version = "41.0.1" +version = "50.0.1" dependencies = [ "cranelift-bitset", "log", "pulley-macros", - "wasmtime-internal-math", + "wasmtime-internal-core", ] [[package]] name = "pulley-macros" -version = "41.0.1" +version = "50.0.1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "quote" -version = "1.0.45" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -1324,9 +1444,9 @@ checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rand" -version = "0.9.2" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha", "rand_core", @@ -1353,9 +1473,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" dependencies = [ "either", "rayon-core", @@ -1384,114 +1504,98 @@ dependencies = [ [[package]] name = "ref-cast" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "regalloc2" -version = "0.13.5" +version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08effbc1fa53aaebff69521a5c05640523fab037b34a4a2c109506bc938246fa" +checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85" dependencies = [ "allocator-api2", "bumpalo", - "hashbrown 0.15.5", + "hashbrown 0.17.1", "log", "rustc-hash", + "serde", "smallvec", ] [[package]] name = "regex" -version = "1.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata 0.4.14", - "regex-syntax 0.8.10", -] - -[[package]] -name = "regex-automata" -version = "0.3.9" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.7.5", + "regex-automata", + "regex-syntax", ] [[package]] name = "regex-automata" -version = "0.4.14" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.10", + "regex-syntax", ] [[package]] name = "regex-syntax" -version = "0.7.5" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" - -[[package]] -name = "regex-syntax" -version = "0.8.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "rustc-demangle" -version = "0.1.27" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" [[package]] name = "rustc-hash" -version = "2.1.1" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "ryu" @@ -1501,9 +1605,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "schemars" -version = "1.2.1" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", @@ -1514,14 +1618,14 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "1.2.1" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn", + "syn 3.0.10", ] [[package]] @@ -1532,9 +1636,9 @@ checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" [[package]] name = "semver" -version = "1.0.27" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" dependencies = [ "serde", "serde_core", @@ -1542,9 +1646,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -1552,40 +1656,40 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "serde_derive_internals" -version = "0.29.1" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "serde_json" -version = "1.0.149" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -1594,6 +1698,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shell-quote" version = "0.7.2" @@ -1609,6 +1724,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "skim" version = "0.20.5" @@ -1632,12 +1753,12 @@ dependencies = [ "rayon", "regex", "shell-quote", - "shlex", + "shlex 1.3.0", "skim-common", "skim-tuikit", "time", "timer", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "vte", "which", ] @@ -1660,14 +1781,20 @@ dependencies = [ "nix", "skim-common", "term 0.7.0", - "unicode-width 0.2.2", + "unicode-width 0.2.3", ] +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -1684,9 +1811,9 @@ dependencies = [ [[package]] name = "sqlparser" -version = "0.60.0" +version = "0.62.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "505aa16b045c4c1375bf5f125cce3813d0176325bfe9ffc4a903f423de7774ff" +checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec" dependencies = [ "log", "serde", @@ -1698,19 +1825,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" -[[package]] -name = "stacker" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d74a23609d509411d10e2176dc2a4346e3b4aea2e7b1869f19fdedbc71c013" -dependencies = [ - "cc", - "cfg-if", - "libc", - "psm", - "windows-sys 0.59.0", -] - [[package]] name = "strsim" version = "0.11.1" @@ -1719,30 +1833,41 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "strum" -version = "0.27.2" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" dependencies = [ "strum_macros", ] [[package]] name = "strum_macros" -version = "0.27.2" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", ] [[package]] name = "syn" -version = "2.0.117" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1751,9 +1876,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.13.5" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" [[package]] name = "term" @@ -1772,7 +1897,7 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8c27177b12a6399ffc08b98f76f7c9a1f4fe9fc967c784c5a071fa8d93cf7e1" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1795,11 +1920,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -1810,37 +1935,36 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] [[package]] name = "time" -version = "0.3.47" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa", "libc", "num-conv", "num_threads", @@ -1852,15 +1976,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "time-macros" -version = "0.2.27" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ "num-conv", "time-core", @@ -1882,47 +2006,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", - "tracing-attributes", "tracing-core", ] -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "tracing-core" version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicase" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" -version = "1.12.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" @@ -1932,9 +2047,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "unicode_categories" @@ -1997,6 +2112,12 @@ dependencies = [ "rustversion", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "vte" version = "0.15.0" @@ -2015,21 +2136,20 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.2+wasi-0.2.9" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -2037,9 +2157,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2047,54 +2167,54 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.114" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] [[package]] name = "wasm-encoder" -version = "0.243.0" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c55db9c896d70bd9fa535ce83cd4e1f2ec3726b0edd2142079f594fc3be1cb35" +checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" dependencies = [ "leb128fmt", - "wasmparser 0.243.0", + "wasmparser 0.261.0", ] [[package]] name = "wasm-encoder" -version = "0.245.1" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c" +checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" dependencies = [ "leb128fmt", - "wasmparser 0.245.1", + "wasmparser 0.263.0", ] [[package]] name = "wasmparser" -version = "0.243.0" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d8db401b0528ec316dfbe579e6ab4152d61739cfe076706d2009127970159d" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" dependencies = [ - "bitflags 2.11.0", - "hashbrown 0.15.5", + "bitflags 2.13.2", + "hashbrown 0.17.1", "indexmap", "semver", "serde", @@ -2102,40 +2222,37 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.245.1" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e" +checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "indexmap", "semver", ] [[package]] name = "wasmprinter" -version = "0.243.0" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2b6035559e146114c29a909a3232928ee488d6507a1504d8934e8607b36d7b" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" dependencies = [ "anyhow", "termcolor", - "wasmparser 0.243.0", + "wasmparser 0.261.0", ] [[package]] name = "wasmtime" -version = "41.0.1" +version = "50.0.1" dependencies = [ "addr2line", - "anyhow", "async-trait", - "bitflags 2.11.0", + "bitflags 2.13.2", "bumpalo", "cc", - "cfg-if", + "futures", "gimli", - "hashbrown 0.15.5", - "indexmap", "libc", "log", "mach2", @@ -2149,27 +2266,24 @@ dependencies = [ "serde_derive", "smallvec", "target-lexicon", - "wasm-encoder 0.243.0", - "wasmparser 0.243.0", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmtime-environ", + "wasmtime-internal-core", "wasmtime-internal-cranelift", "wasmtime-internal-fiber", "wasmtime-internal-jit-debug", "wasmtime-internal-jit-icache-coherence", - "wasmtime-internal-math", - "wasmtime-internal-slab", "wasmtime-internal-unwinder", "wasmtime-internal-versioned-export-macros", - "wasmtime-internal-winch", "wat", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] name = "wasmtime-c-api-impl" -version = "41.0.1" +version = "50.0.1" dependencies = [ - "anyhow", "log", "tracing", "wasmtime", @@ -2179,76 +2293,92 @@ dependencies = [ [[package]] name = "wasmtime-environ" -version = "41.0.1" +version = "50.0.1" dependencies = [ "anyhow", "cpp_demangle", + "cranelift-bforest", "cranelift-bitset", "cranelift-entity", "gimli", + "hashbrown 0.17.1", "indexmap", "log", "object", "postcard", "rustc-demangle", + "semver", "serde", "serde_derive", "smallvec", "target-lexicon", - "wasm-encoder 0.243.0", - "wasmparser 0.243.0", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmprinter", + "wasmtime-internal-component-util", + "wasmtime-internal-core", ] [[package]] name = "wasmtime-internal-c-api-macros" -version = "41.0.1" +version = "50.0.1" dependencies = [ "proc-macro2", "quote", ] +[[package]] +name = "wasmtime-internal-component-util" +version = "50.0.1" + +[[package]] +name = "wasmtime-internal-core" +version = "50.0.1" +dependencies = [ + "hashbrown 0.17.1", + "libm", + "serde", +] + [[package]] name = "wasmtime-internal-cranelift" -version = "41.0.1" +version = "50.0.1" dependencies = [ - "cfg-if", "cranelift-codegen", "cranelift-control", "cranelift-entity", "cranelift-frontend", "cranelift-native", "gimli", - "itertools", + "itertools 0.14.0", "log", "object", "pulley-interpreter", "smallvec", "target-lexicon", - "thiserror 2.0.18", - "wasmparser 0.243.0", + "thiserror 2.0.21", + "wasmparser 0.261.0", "wasmtime-environ", - "wasmtime-internal-math", + "wasmtime-internal-core", "wasmtime-internal-unwinder", "wasmtime-internal-versioned-export-macros", ] [[package]] name = "wasmtime-internal-fiber" -version = "41.0.1" +version = "50.0.1" dependencies = [ "cc", - "cfg-if", "libc", "rustix", "wasmtime-environ", "wasmtime-internal-versioned-export-macros", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] name = "wasmtime-internal-jit-debug" -version = "41.0.1" +version = "50.0.1" dependencies = [ "cc", "wasmtime-internal-versioned-export-macros", @@ -2256,30 +2386,17 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-icache-coherence" -version = "41.0.1" +version = "50.0.1" dependencies = [ - "cfg-if", "libc", - "wasmtime-environ", - "windows-sys 0.61.2", -] - -[[package]] -name = "wasmtime-internal-math" -version = "41.0.1" -dependencies = [ - "libm", + "wasmtime-internal-core", + "windows-sys", ] -[[package]] -name = "wasmtime-internal-slab" -version = "41.0.1" - [[package]] name = "wasmtime-internal-unwinder" -version = "41.0.1" +version = "50.0.1" dependencies = [ - "cfg-if", "cranelift-codegen", "log", "object", @@ -2288,46 +2405,31 @@ dependencies = [ [[package]] name = "wasmtime-internal-versioned-export-macros" -version = "41.0.1" +version = "50.0.1" dependencies = [ "proc-macro2", "quote", - "syn", -] - -[[package]] -name = "wasmtime-internal-winch" -version = "41.0.1" -dependencies = [ - "cranelift-codegen", - "gimli", - "log", - "object", - "target-lexicon", - "wasmparser 0.243.0", - "wasmtime-environ", - "wasmtime-internal-cranelift", - "winch-codegen", + "syn 3.0.10", ] [[package]] name = "wast" -version = "245.0.1" +version = "263.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cf1149285569120b8ce39db8b465e8a2b55c34cbb586bd977e43e2bc7300bf" +checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" dependencies = [ "bumpalo", "leb128fmt", "memchr", - "unicode-width 0.2.2", - "wasm-encoder 0.245.1", + "unicode-width 0.2.3", + "wasm-encoder 0.263.0", ] [[package]] name = "wat" -version = "1.245.1" +version = "1.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd48d1679b6858988cb96b154dda0ec5bbb09275b71db46057be37332d5477be" +checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" dependencies = [ "wast", ] @@ -2366,7 +2468,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -2375,24 +2477,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "winch-codegen" -version = "41.0.1" -dependencies = [ - "anyhow", - "cranelift-assembler-x64", - "cranelift-codegen", - "gimli", - "regalloc2", - "smallvec", - "target-lexicon", - "thiserror 2.0.18", - "wasmparser 0.243.0", - "wasmtime-environ", - "wasmtime-internal-cranelift", - "wasmtime-internal-math", -] - [[package]] name = "windows-core" version = "0.62.2" @@ -2414,7 +2498,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2425,7 +2509,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2452,15 +2536,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -2470,70 +2545,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "winnow" version = "0.6.26" @@ -2551,9 +2562,9 @@ checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" [[package]] name = "wit-bindgen" -version = "0.51.0" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "yansi" @@ -2563,26 +2574,26 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "zerocopy" -version = "0.8.42" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2578b716f8a7a858b7f02d5bd870c14bf4ddbbcf3a4c05414ba6503640505e3" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.42" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e6cc098ea4d3bd6246687de65af3f920c430e236bee1e3bf2e441463f08a02f" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/src/Access/AccessRights.cpp b/src/Access/AccessRights.cpp index 16e8518686e0..2cb66e10b800 100644 --- a/src/Access/AccessRights.cpp +++ b/src/Access/AccessRights.cpp @@ -38,6 +38,10 @@ namespace if (left.full_name.size() != right.full_name.size()) return left.full_name.size() < right.full_name.size(); + /// Wildcards before exact names: `db*` covers `db`, so its element must be applied first. + if (left.wildcard != right.wildcard) + return left.wildcard; + /// Grants before partial revokes. if (left.is_partial_revoke != right.is_partial_revoke) return right.is_partial_revoke; /// if left is grant, right is partial revoke, we assume left < right @@ -974,7 +978,9 @@ struct AccessRights::Node auto grants = flags - parent_fl - grants_go; /// Inserts into result only meaningful nodes (e.g. wildcards or leafs). - if (target_node && (target_node->isLeaf() || target_node->wildcard_grant)) + const bool node_meaningful = node && (node->isLeaf() || node->wildcard_grant); + const bool node_go_meaningful = node_go && (node_go->isLeaf() || node_go->wildcard_grant); + if (node_meaningful || node_go_meaningful) { boost::container::small_vector new_full_name = full_name; @@ -990,19 +996,27 @@ struct AccessRights::Node } } - if (node && revokes) + if (node_meaningful && revokes) res.push_back(ProtoElement{revokes, new_full_name, false, true, node->wildcard_grant}); - if (node_go && revokes_go) + if (node_go_meaningful && revokes_go) res.push_back(ProtoElement{revokes_go, new_full_name, true, true, node_go->wildcard_grant}); - if (node && grants) + if (node_meaningful && grants) res.push_back(ProtoElement{grants, new_full_name, false, false, node->wildcard_grant}); - if (node_go && grants_go) + if (node_go_meaningful && grants_go) res.push_back(ProtoElement{grants_go, new_full_name, true, false, node_go->wildcard_grant}); } + /// The two tries compress child names independently: a child of one can be a strict name + /// prefix of a child of the other, and only exactly-named pairs can be walked together. + if (node && node_go && node_go->children) + { + for (auto & child_go : *node_go->children) + node->getLeaf(child_go.node_name, child_go.level, !child_go.isLeaf()); + } + if (node && node->children) { for (auto & child : *node->children) @@ -1022,19 +1036,8 @@ struct AccessRights::Node { for (auto & child : *node_go->children) { - if (node && node->children) - { - auto starts_with = [&child](const Node & n) - { - if (child.isLeaf()) - return n.isLeaf(); - - return !n.isLeaf() && child.node_name[0] == n.node_name[0]; - }; - - if (auto it = std::find_if(node->children->begin(), node->children->end(), starts_with); it != node->children->end()) - continue; /// already processed - } + if (node && node->tryGetChildNode(child.node_name)) + continue; /// already processed String new_path = path; new_path.append(child.node_name); diff --git a/src/Access/ContextAccess.cpp b/src/Access/ContextAccess.cpp index aedfc9fa08a5..080eab0c7fa1 100644 --- a/src/Access/ContextAccess.cpp +++ b/src/Access/ContextAccess.cpp @@ -783,15 +783,16 @@ bool ContextAccess::checkAccessImplHelper(const ContextPtr & context, AccessFlag const AccessFlags function_ddl = AccessType::CREATE_FUNCTION | AccessType::DROP_FUNCTION; const AccessFlags workload_ddl = AccessType::CREATE_WORKLOAD | AccessType::DROP_WORKLOAD; const AccessFlags resource_ddl = AccessType::CREATE_RESOURCE | AccessType::DROP_RESOURCE; + const AccessFlags named_collection_ddl = AccessType::CREATE_NAMED_COLLECTION | AccessType::DROP_NAMED_COLLECTION | AccessType::ALTER_NAMED_COLLECTION; const AccessFlags table_and_dictionary_ddl = table_ddl | dictionary_ddl; const AccessFlags table_and_dictionary_and_function_ddl = table_ddl | dictionary_ddl | function_ddl; const AccessFlags write_table_access = AccessType::INSERT | AccessType::OPTIMIZE; const AccessFlags write_dcl_access = AccessType::ACCESS_MANAGEMENT - AccessType::SHOW_ACCESS; - const AccessFlags not_readonly_flags = write_table_access | table_and_dictionary_and_function_ddl | workload_ddl | resource_ddl | write_dcl_access | AccessType::SYSTEM | AccessType::KILL_QUERY; + const AccessFlags not_readonly_flags = write_table_access | table_and_dictionary_and_function_ddl | workload_ddl | resource_ddl | named_collection_ddl | write_dcl_access | AccessType::SYSTEM | AccessType::KILL_QUERY; const AccessFlags not_readonly_1_flags = AccessType::CREATE_TEMPORARY_TABLE; - const AccessFlags ddl_flags = table_ddl | dictionary_ddl | function_ddl | workload_ddl | resource_ddl; + const AccessFlags ddl_flags = table_ddl | dictionary_ddl | function_ddl | workload_ddl | resource_ddl | named_collection_ddl; const AccessFlags introspection_flags = AccessType::INTROSPECTION; }; static const PrecalculatedFlags precalc; diff --git a/src/Access/LDAPAccessStorage.cpp b/src/Access/LDAPAccessStorage.cpp index 939b99396c30..e0f18010b2e4 100644 --- a/src/Access/LDAPAccessStorage.cpp +++ b/src/Access/LDAPAccessStorage.cpp @@ -400,37 +400,36 @@ String LDAPAccessStorage::getStorageParamsJSON() const } +/// The read-only methods below don't lock `mutex`: `memory_storage` is synchronized by itself, +/// and `mutex` is held by `authenticateImpl` during the network communication with the LDAP server. +/// Waiting for it here would make lookups (e.g. the check for a name collision in `MultipleAccessStorage`) +/// wait for unrelated LDAP authentications. std::optional LDAPAccessStorage::findImpl(AccessEntityType type, const String & name) const { - std::lock_guard lock(mutex); return memory_storage.find(type, name); } std::vector LDAPAccessStorage::findAllImpl(AccessEntityType type) const { - std::lock_guard lock(mutex); return memory_storage.findAll(type); } bool LDAPAccessStorage::exists(const UUID & id) const { - std::lock_guard lock(mutex); return memory_storage.exists(id); } AccessEntityPtr LDAPAccessStorage::readImpl(const UUID & id, bool throw_if_not_exists) const { - std::lock_guard lock(mutex); return memory_storage.read(id, throw_if_not_exists); } std::optional> LDAPAccessStorage::readNameWithTypeImpl(const UUID & id, bool throw_if_not_exists) const { - std::lock_guard lock(mutex); return memory_storage.readNameWithType(id, throw_if_not_exists); } diff --git a/src/Access/MultipleAccessStorage.cpp b/src/Access/MultipleAccessStorage.cpp index c7247900b1c2..40158681c287 100644 --- a/src/Access/MultipleAccessStorage.cpp +++ b/src/Access/MultipleAccessStorage.cpp @@ -17,6 +17,7 @@ namespace ErrorCodes extern const int ACCESS_ENTITY_ALREADY_EXISTS; extern const int ACCESS_STORAGE_FOR_INSERTION_NOT_FOUND; extern const int ACCESS_ENTITY_NOT_FOUND; + extern const int AUTHENTICATION_FAILED; } using Storage = IAccessStorage; @@ -256,6 +257,24 @@ void MultipleAccessStorage::moveAccessEntities(const std::vector & ids, co auto destination_storage = getStorageByName(destination_storage_name); auto to_move = source_storage->read(ids); + + /// The same name must not refer to entities in different storages, so a move is refused if any storage + /// other than the source one already holds the name (e.g. a user of the config with the same name). + /// This is checked before anything is removed from the source storage. + auto storages = getStoragesInternal(); + for (const auto & entity : to_move) + { + for (const auto & other_storage : *storages) + { + if (other_storage == source_storage) + continue; + if (other_storage->find(entity->getType(), entity->getName())) + throw Exception(ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS, "{}: cannot move to {} because {} already exists in {}", + entity->formatTypeWithName(), backQuote(destination_storage_name), entity->formatTypeWithName(), + backQuote(other_storage->getStorageName())); + } + } + bool need_rollback = false; try @@ -397,6 +416,22 @@ bool MultipleAccessStorage::insertImpl(const UUID & id, const AccessEntityPtr & getStorageName()); } + /// The same name must not refer to entities in different storages. + /// A replacement replaces only an entity of the destination storage, so it is refused too if another storage holds the name. + for (const auto & other_storage : *storages) + { + if (other_storage == storage_for_insertion) + continue; + if (auto existing_id = other_storage->find(entity->getType(), entity->getName())) + { + if (conflicting_id) + *conflicting_id = *existing_id; + if (throw_if_exists || replace_if_exists) + throwNameCollisionCannotInsert(entity->getType(), entity->getName(), other_storage->getStorageName()); + return false; + } + } + if (storage_for_insertion->insert(id, entity, replace_if_exists, throw_if_exists, conflicting_id)) { std::lock_guard lock{mutex}; @@ -431,9 +466,10 @@ bool MultipleAccessStorage::updateImpl(const UUID & id, const UpdateFunc & updat return false; } - /// If the updating involves renaming check that the renamed entity will be accessible by name. + /// If the updating involves renaming check that the new name is not used in another storage: + /// the same name must not refer to entities in different storages. auto storages = getStoragesInternal(); - if ((storages->size() > 1) && (storages->front() != storage_for_updating)) + if (storages->size() > 1) { if (auto old_entity = storage_for_updating->tryRead(id)) { @@ -443,7 +479,7 @@ bool MultipleAccessStorage::updateImpl(const UUID & id, const UpdateFunc & updat for (const auto & storage : *storages) { if (storage == storage_for_updating) - break; + continue; if (storage->find(new_entity->getType(), new_entity->getName())) { throw Exception(ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS, "{}: cannot rename to {} because {} already exists in {}", @@ -466,15 +502,62 @@ MultipleAccessStorage::authenticateImpl(const Credentials & credentials, const P bool allow_no_password, bool allow_plaintext_password) const { auto storages = getStoragesInternal(); - for (size_t i = 0; i != storages->size(); ++i) + + /// Users from different user directories are distinct entities, but some code identifies users by name, + /// so the same name must not refer to more than one user. + auto throw_name_collision = [&](const String & user_name, const StoragePtr & storage, const StoragePtr & other_storage) -> void + { + throw Exception(ErrorCodes::AUTHENTICATION_FAILED, + "User {} exists in {}, but a user with the same name also exists in {}", + backQuote(user_name), storage->getStorageName(), other_storage->getStorageName()); + }; + + /// If a user with this name already exists, only its storage may authenticate it. Otherwise an external directory + /// (e.g. LDAP) could introduce a second user with the same name on login, in particular with `AlwaysAllowCredentials`, + /// which LDAP accepts without contacting the LDAP server. + /// + /// The same name with the same ID in several storages is one identity, not a collision: external directories + /// which derive both the name and the ID of a user from the verified identity (e.g. several token-based directories, + /// one per signing key or identity provider) each keep their own copy of the same user, and any of them may authenticate it. + std::vector existing_user_storages; + if (storages->size() > 1 && credentials.isReady()) + { + std::optional existing_user_id; + for (const auto & storage : *storages) + { + auto user_id = storage->find(AccessEntityType::USER, credentials.getUserName()); + if (!user_id) + continue; + if (existing_user_id && *existing_user_id != *user_id) + throw_name_collision(credentials.getUserName(), existing_user_storages.front(), storage); + existing_user_id = user_id; + existing_user_storages.push_back(storage); + } + } + + /// The storages which may authenticate these credentials. + std::vector candidate_storages = existing_user_storages.empty() ? *storages : existing_user_storages; + + for (size_t i = 0; i != candidate_storages.size(); ++i) { - const auto & storage = (*storages)[i]; - bool is_last_storage = (i == storages->size() - 1); + const auto & storage = candidate_storages[i]; + bool is_last_storage = (i == candidate_storages.size() - 1); auto auth_result = storage->authenticate(credentials, address, external_authenticators, client_info, (throw_if_user_not_exists && is_last_storage), allow_no_password, allow_plaintext_password); if (auth_result) { + /// Check again: a user with the same name could have appeared in another storage concurrently, + /// or the storage could have just introduced the user. + for (const auto & other_storage : *storages) + { + if (other_storage == storage) + continue; + auto other_user_id = other_storage->find(AccessEntityType::USER, auth_result->user_name); + if (other_user_id && *other_user_id != auth_result->user_id) + throw_name_collision(auth_result->user_name, storage, other_storage); + } + std::lock_guard lock{mutex}; ids_cache.set(auth_result->user_id, storage); return auth_result; diff --git a/src/Access/tests/gtest_access_rights_ops.cpp b/src/Access/tests/gtest_access_rights_ops.cpp index 7e6f3362a902..25a0b13b2108 100644 --- a/src/Access/tests/gtest_access_rights_ops.cpp +++ b/src/Access/tests/gtest_access_rights_ops.cpp @@ -96,13 +96,13 @@ TEST(AccessRights, GrantWildcard) root.grantWildcard(AccessType::INSERT, "default", "t"); ASSERT_EQ(root.isGranted(AccessType::SELECT, "default", "t"), true); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "t"), true); - ASSERT_EQ(root.toString(), "GRANT SELECT ON default.t, GRANT INSERT ON default.t*"); + ASSERT_EQ(root.toString(), "GRANT INSERT ON default.t*, GRANT SELECT ON default.t"); root.revoke(AccessType::INSERT, "default", "t"); ASSERT_EQ(root.isGranted(AccessType::SELECT, "default", "t"), true); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "t"), false); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "test"), true); - ASSERT_EQ(root.toString(), "GRANT SELECT ON default.t, GRANT INSERT ON default.t*, REVOKE INSERT ON default.t"); + ASSERT_EQ(root.toString(), "GRANT INSERT ON default.t*, GRANT SELECT ON default.t, REVOKE INSERT ON default.t"); root = {}; root.grant(AccessType::SELECT, "default", "t"); @@ -235,6 +235,51 @@ TEST(AccessRights, GrantWildcard) ASSERT_EQ(root.toString(), "GRANT SELECT ON db*.* WITH GRANT OPTION, GRANT INSERT ON db.`table`"); } +TEST(AccessRights, WildcardBeforeExactNameInElements) +{ + /// The elements are applied in the order of `getElements`, so `REVOKE ... ON dbx*.*` must precede `GRANT ... ON dbx.*`. + AccessRights root; + root.grantWildcard(AccessType::SELECT, "db"); + root.revokeWildcard(AccessType::SELECT, "dbx"); + root.grant(AccessType::SELECT, "dbx"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON db*.*, REVOKE SELECT ON dbx*.*, GRANT SELECT ON dbx.*"); + AccessRights restored{root.getElements()}; + ASSERT_TRUE(restored.isGranted(AccessType::SELECT, "dbx")); + ASSERT_FALSE(restored.isGranted(AccessType::SELECT, "dbx1")); + ASSERT_EQ(restored, root); + + root = {}; + root.grant(AccessType::SELECT, "db"); + root.revokeWildcard(AccessType::SELECT, "db", "t"); + root.grant(AccessType::SELECT, "db", "t"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON db.*, REVOKE SELECT ON db.t*, GRANT SELECT ON db.t"); + restored = AccessRights{root.getElements()}; + ASSERT_TRUE(restored.isGranted(AccessType::SELECT, "db", "t")); + ASSERT_FALSE(restored.isGranted(AccessType::SELECT, "db", "t1")); + ASSERT_EQ(restored, root); + + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revokeWildcardGrantOption(AccessType::SELECT, "db"); + root.grantWithGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), + "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db*.*, GRANT SELECT ON db.* WITH GRANT OPTION"); + restored = AccessRights{root.getElements()}; + ASSERT_TRUE(restored.hasGrantOption(AccessType::SELECT, "db")); + ASSERT_FALSE(restored.hasGrantOption(AccessType::SELECT, "db1")); + ASSERT_EQ(restored, root); + + /// The same after a union, like the rights of two roles. + AccessRights lhs; + AccessRights rhs; + lhs.grant(AccessType::SELECT); + lhs.revokeWildcard(AccessType::SELECT, "db"); + rhs.grant(AccessType::SELECT, "db"); + lhs.makeUnion(rhs); + ASSERT_EQ(lhs.toString(), "GRANT SELECT ON *.*, REVOKE SELECT ON db*.*, GRANT SELECT ON db.*"); + ASSERT_TRUE(AccessRights{lhs.getElements()}.isGranted(AccessType::SELECT, "db")); +} + TEST(AccessRights, Union) { AccessRights lhs; @@ -598,6 +643,55 @@ TEST(AccessRights, ParialRevokeWithGrantOption) ASSERT_TRUE(root.isGranted(AccessType::SELECT, "default", "zoo")); } +TEST(AccessRights, PartialRevokeGrantOptionWithSharedPrefix) +{ + /// Each arm pairs a grant-option-only revoke whose name shares a prefix with a plain revoke + /// (the shape that used to be dropped) with a control name that shares nothing. + + /// Database level. + AccessRights root; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "db1"); + root.revokeGrantOption(AccessType::SELECT, "db2"); + root.revokeGrantOption(AccessType::SELECT, "zdb2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON db1.*, " + "REVOKE GRANT OPTION SELECT ON db2.*, REVOKE GRANT OPTION SELECT ON zdb2.*"); + + /// Database level, grant-option name is a strict prefix of the plain one. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "dbx"); + root.revokeGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db.*, " + "REVOKE SELECT ON dbx.*"); + + /// Table level. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "d", "t1"); + root.revokeGrantOption(AccessType::SELECT, "d", "t2"); + root.revokeGrantOption(AccessType::SELECT, "d", "zt2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON d.t1, " + "REVOKE GRANT OPTION SELECT ON d.t2, REVOKE GRANT OPTION SELECT ON d.zt2"); + + /// Column level. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "d", "t", "c1"); + root.revokeGrantOption(AccessType::SELECT, "d", "t", "c2"); + root.revokeGrantOption(AccessType::SELECT, "d", "t", "zc2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT(c1) ON d.t, " + "REVOKE GRANT OPTION SELECT(c2, zc2) ON d.t"); + + /// Wildcard grant-option revoke whose name is a strict prefix of the plain one. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "dbx1"); + root.revokeWildcardGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db*.*, " + "REVOKE SELECT ON dbx1.*"); +} + TEST(AccessRights, WildcardGrantEdgeCases) { AccessRights root; diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp index eea1590813d0..8d6467666f88 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp @@ -25,6 +25,10 @@ struct AggregateFunctionCombinatorArgMinArgMaxData SingleValueDataBase & data() { return v_data.get(); } const SingleValueDataBase & data() const { return v_data.get(); } + + /// False after the nested state is destroyed until it is created again, so a throwing nested `create` does not lead + /// to a second nested `destroy`. + bool nested_created = true; }; template @@ -49,6 +53,19 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH return *reinterpret_cast(place + key_offset); } + /// Replaces the nested state with an empty one. + void resetNested(AggregateDataPtr __restrict place) const + { + auto & key = data(place); + if (key.nested_created) + { + nested_function->destroy(place); + key.nested_created = false; + } + nested_function->create(place); + key.nested_created = true; + } + public: AggregateFunctionCombinatorArgMinArgMax(AggregateFunctionPtr nested_function_, const DataTypes & arguments, const Array & params) : IAggregateFunctionHelper>{arguments, params, nested_function_->getResultType()} @@ -108,19 +125,31 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH void create(AggregateDataPtr __restrict place) const override { nested_function->create(place); - new (place + key_offset) Key(key_type); + try + { + new (place + key_offset) Key(key_type); + } + catch (...) + { + nested_function->destroy(place); + throw; + } } void destroy(AggregateDataPtr __restrict place) const noexcept override { + const bool nested_created = data(place).nested_created; data(place).~Key(); - nested_function->destroy(place); + if (nested_created) + nested_function->destroy(place); } void destroyUpToState(AggregateDataPtr __restrict place) const noexcept override { + const bool nested_created = data(place).nested_created; data(place).~Key(); - nested_function->destroyUpToState(place); + if (nested_created) + nested_function->destroyUpToState(place); } void add(AggregateDataPtr __restrict place, const IColumn ** columns, size_t row_num, Arena * arena) const override @@ -128,8 +157,7 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH if ((isMin && data(place).data().setIfSmaller(*columns[key_col], row_num, arena)) || (!isMin && data(place).data().setIfGreater(*columns[key_col], row_num, arena))) { - nested_function->destroy(place); - nested_function->create(place); + resetNested(place); nested_function->add(place, columns, row_num, arena); } else if (data(place).data().isEqualTo(*columns[key_col], row_num)) @@ -143,8 +171,7 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH if ((isMin && data(place).data().setIfSmaller(data(rhs).data(), arena)) || (!isMin && data(place).data().setIfGreater(data(rhs).data(), arena))) { - nested_function->destroy(place); - nested_function->create(place); + resetNested(place); nested_function->merge(place, rhs, arena); } else if (data(place).data().isEqualTo(data(rhs).data())) diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h b/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h index 8eb7300a9e30..5a8c1da8ac5c 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h +++ b/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h @@ -257,7 +257,15 @@ class AggregateFunctionDistinct final : public IAggregateFunctionDataHelpercreate(getNestedPlace(place)); + try + { + nested_func->create(getNestedPlace(place)); + } + catch (...) + { + this->data(place).~Data(); + throw; + } } void destroy(AggregateDataPtr __restrict place) const noexcept override diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp index 19d26afcdad2..4c2dd3634462 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -306,7 +307,19 @@ class AggregateFunctionMap final KeyType key{}; this->data(place).readKey(key, buf); - + if constexpr (std::is_same_v) + { + /// `keyAt` reads exactly N bytes of a `FixedString(N)` key, so a key of another length + /// could never be found again (e.g. by `rollbackInsertResult`). + if (key_type->getTypeId() == TypeIndex::FixedString) + { + const size_t n = assert_cast(*key_type).getN(); + if (key.size() != n) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key of size {} in the serialized state of aggregate function {} does not match its type {}", + key.size(), getName(), key_type->getName()); + } + } /// Take the slot before creating the state. `emplace` on a key that is already present /// does not insert, so creating first would abandon the fresh state: nothing would /// reference it and `destroyImpl` walks only `merged_maps`. `serialize` writes each key diff --git a/src/AggregateFunctions/SingleValueData.cpp b/src/AggregateFunctions/SingleValueData.cpp index d5767ab9d07d..fbead839a698 100644 --- a/src/AggregateFunctions/SingleValueData.cpp +++ b/src/AggregateFunctions/SingleValueData.cpp @@ -1224,6 +1224,14 @@ void SingleValueDataString::read(ReadBuffer & buf, const ISerialization & /*seri } else { + /// The buffer was allocated for `size - 1` bytes above, so it may have no room for the appended byte. + if (capacity < size) + { + /// Arena allocations remain valid until the Arena is destroyed. + const char * old_data = large_data; + allocateLargeDataIfNeeded(size, arena); + memcpy(large_data, old_data, size - 1); + } large_data[size - 1] = last_char; } ++size; diff --git a/src/AggregateFunctions/WindowFunction.h b/src/AggregateFunctions/WindowFunction.h index 27a25ebe6384..1128a4ae484b 100644 --- a/src/AggregateFunctions/WindowFunction.h +++ b/src/AggregateFunctions/WindowFunction.h @@ -53,6 +53,10 @@ struct WindowFunctionWorkspace // Will not be initialized for a pure window function. mutable AlignedBuffer aggregate_function_state; + /// False after the state is destroyed until it is created again, so a throwing `create` does not lead to a second + /// `destroy`. + bool aggregate_function_state_created = false; + // Argument columns. Be careful, this is a per-block cache. VectorWithMemoryTracking argument_columns; UInt64 cached_block_number = std::numeric_limits::max(); diff --git a/src/Analyzer/FunctionNode.h b/src/Analyzer/FunctionNode.h index c0005016def6..c449dc331005 100644 --- a/src/Analyzer/FunctionNode.h +++ b/src/Analyzer/FunctionNode.h @@ -204,6 +204,9 @@ class FunctionNode final : public IQueryTreeNode wrap_with_nullable = true; } + /// Whether `convertToNullable` was called, also when the result type cannot be `Nullable` and did not change. + bool isConvertedToNullable() const { return wrap_with_nullable; } + void dumpTreeImpl(WriteBuffer & buffer, FormatState & format_state, size_t indent) const override; protected: diff --git a/src/Analyzer/Passes/IfChainToMultiIfPass.cpp b/src/Analyzer/Passes/IfChainToMultiIfPass.cpp index 067e9caa6f59..4f7c5de8c202 100644 --- a/src/Analyzer/Passes/IfChainToMultiIfPass.cpp +++ b/src/Analyzer/Passes/IfChainToMultiIfPass.cpp @@ -3,9 +3,13 @@ #include #include +#include +#include #include #include +#include + namespace DB { namespace Setting @@ -18,6 +22,39 @@ namespace Setting namespace { +/// The `if` nodes of the query, outside of its subqueries, that are `GROUP BY` keys, collected before any of them is rewritten. +std::unordered_set collectGroupByKeyIfNodes(const QueryNode & query_node) +{ + auto is_if = [](const QueryTreeNodePtr & node) + { + const auto * function_node = node->as(); + return function_node && function_node->getFunctionName() == "if" && function_node->getArguments().getNodes().size() == 3; + }; + + auto if_keys = getGroupByKeys(query_node); + std::erase_if(if_keys, [&](const auto & key) { return !is_if(key); }); + + std::unordered_set result; + if (if_keys.empty()) + return result; + + std::vector nodes{&query_node}; + while (!nodes.empty()) + { + const auto * node = nodes.back(); + nodes.pop_back(); + for (const auto & child : node->getChildren()) + { + if (!child || child->getNodeType() == QueryTreeNodeType::QUERY || child->getNodeType() == QueryTreeNodeType::UNION) + continue; + if (is_if(child) && isGroupByKeyAfterAggregation(child, if_keys)) + result.insert(child); + nodes.push_back(child.get()); + } + } + return result; +} + class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContext { public: @@ -27,10 +64,19 @@ class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContextas()) + { + group_by_key_if_nodes_stack.push_back( + getSettings()[Setting::optimize_if_chain_to_multiif] ? collectGroupByKeyIfNodes(*query_node) : std::unordered_set{}); + return; + } + if (!getSettings()[Setting::optimize_if_chain_to_multiif]) return; @@ -52,6 +98,10 @@ class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContextgetFunctionName() != "if" || if_chain_function_node->getArguments().getNodes().size() != 3) break; + /// A `GROUP BY` key is read from the aggregation result, so it is not spliced into the chain. + if (if_chain_function_node->isConvertedToNullable() || group_by_key_if_nodes_stack.back().contains(if_chain_node)) + break; + /// Replace last `multiIf` argument with `if` function arguments multi_if_arguments.pop_back(); @@ -79,8 +129,17 @@ class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContextgetNodeType() == QueryTreeNodeType::QUERY) + group_by_key_if_nodes_stack.pop_back(); + } + private: FunctionOverloadResolverPtr multi_if_function_ptr; + + /// For each enclosing query, its `if` nodes that are `GROUP BY` keys; the first set is for an expression outside of any query. + std::vector> group_by_key_if_nodes_stack; }; } diff --git a/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp new file mode 100644 index 000000000000..39ea2a9457b7 --- /dev/null +++ b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp @@ -0,0 +1,41 @@ +#include + +#include + +#include +#include +#include +#include + +namespace DB +{ + +QueryTreeNodes getGroupByKeys(const QueryNode & query_node) +{ + QueryTreeNodes keys; + if (!query_node.hasGroupBy()) + return keys; + + for (const auto & node : query_node.getGroupBy().getNodes()) + { + if (query_node.isGroupByWithGroupingSets()) + { + const auto & grouping_set_keys = node->as().getNodes(); + keys.insert(keys.end(), grouping_set_keys.begin(), grouping_set_keys.end()); + } + else + { + keys.push_back(node); + } + } + return keys; +} + +bool isGroupByKeyAfterAggregation(const QueryTreeNodePtr & node, const QueryTreeNodes & group_by_keys) +{ + if (const auto * function_node = node->as(); function_node && function_node->isConvertedToNullable()) + return true; + return std::ranges::any_of(group_by_keys, [&](const auto & key) { return compareGroupByKeys(node, key); }); +} + +} diff --git a/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h new file mode 100644 index 000000000000..352cfb757081 --- /dev/null +++ b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace DB +{ + +class QueryNode; + +/// The `GROUP BY` keys of `query_node`, of all grouping sets. +QueryTreeNodes getGroupByKeys(const QueryNode & query_node); + +/// Returns true if `node`, in an expression computed after `GROUP BY`, is a key, read from the aggregation result. +/// Under `group_by_use_nulls` the analyzer replaces a key there with a copy converted to `Nullable`, not equal to the key. +bool isGroupByKeyAfterAggregation(const QueryTreeNodePtr & node, const QueryTreeNodes & group_by_keys); + +} diff --git a/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp b/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp index 7c1060821240..e346bbea180d 100644 --- a/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp +++ b/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -21,13 +22,17 @@ class OrderByTupleEliminationVisitor : public InDepthQueryTreeVisitorhasOrderBy()) return; + const auto group_by_keys = getGroupByKeys(*query_node); + QueryTreeNodes result_nodes; for (auto & sort_node : query_node->getOrderBy().getNodes()) { auto & sort_node_typed = sort_node->as(); auto * function_expression = sort_node_typed.getExpression()->as(); - if (sort_node_typed.withFill() || !function_expression || function_expression->getFunctionName() != "tuple") + /// Splitting a key would read its arguments, which do not exist after aggregation. + if (sort_node_typed.withFill() || !function_expression || function_expression->getFunctionName() != "tuple" + || isGroupByKeyAfterAggregation(sort_node_typed.getExpression(), group_by_keys)) { result_nodes.push_back(sort_node); continue; diff --git a/src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp b/src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp index 4e1dec0a9b27..009499e1bcfc 100644 --- a/src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp +++ b/src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp @@ -20,11 +20,70 @@ namespace DB namespace Setting { extern const SettingsBool optimize_rewrite_aggregate_function_with_if; + extern const SettingsShortCircuitFunctionEvaluation short_circuit_function_evaluation; } namespace { +/// A branch of `if` runs only on the rows its condition selects when lazy execution picks it up. +/// A nested short-circuit mask is not assumed to protect the rows the outer condition excluded, so +/// the walk continues through it. +bool branchCanBeSkippedByShortCircuit(const QueryTreeNodePtr & branch, bool every_function_is_lazy) +{ + std::vector nodes_to_process; + nodes_to_process.push_back(branch.get()); + + while (!nodes_to_process.empty()) + { + const auto * node = nodes_to_process.back(); + nodes_to_process.pop_back(); + + /// A constant is already evaluated when the query tree is built, so it cannot throw per row. + if (node->as()) + continue; + + /// A table expression or a subquery in an argument slot is evaluated in its own scope, as a + /// set or a scalar, so lazy execution of this expression never reaches inside it. + switch (node->getNodeType()) + { + case QueryTreeNodeType::TABLE: + case QueryTreeNodeType::TABLE_FUNCTION: + case QueryTreeNodeType::QUERY: + case QueryTreeNodeType::UNION: + continue; + default: + break; + } + + if (const auto * function_node = node->as()) + { + if (auto function_base = function_node->getFunction()) + { + if (every_function_is_lazy) + return true; + + /// getArgumentColumns describes each slot the way the resolver did, so the `in` + /// right-hand side is reported as a set instead of being asked for a result type. + const auto argument_columns = function_node->getArgumentColumns(); + DataTypesWithConstInfo argument_types; + argument_types.reserve(argument_columns.size()); + for (const auto & argument_column : argument_columns) + argument_types.push_back({argument_column.type, argument_column.column != nullptr}); + + if (function_base->isSuitableForShortCircuitArgumentsExecution(argument_types)) + return true; + } + } + + for (const auto & child : node->getChildren()) + if (child) + nodes_to_process.push_back(child.get()); + } + + return false; +} + class RewriteAggregateFunctionWithIfVisitor : public InDepthQueryTreeVisitorWithContext { public: @@ -57,6 +116,18 @@ class RewriteAggregateFunctionWithIfVisitor : public InDepthQueryTreeVisitorWith auto if_arguments_nodes = if_node->getArguments().getNodes(); auto * first_const_node = if_arguments_nodes[1]->as(); auto * second_const_node = if_arguments_nodes[2]->as(); + + const auto short_circuit = getSettings()[Setting::short_circuit_function_evaluation]; + if (short_circuit != ShortCircuitFunctionEvaluation::DISABLE && (second_const_node || first_const_node)) + { + /// The -If combinator evaluates its argument for every row, so lifting a branch that lazy + /// execution would have skipped makes a throwing expression run on the rows the condition + /// excluded. + const auto & lifted_branch = second_const_node ? if_arguments_nodes[1] : if_arguments_nodes[2]; + if (branchCanBeSkippedByShortCircuit(lifted_branch, short_circuit == ShortCircuitFunctionEvaluation::FORCE_ENABLE)) + return; + } + if (second_const_node) { const auto & second_const_value = second_const_node->getValue(); diff --git a/src/Analyzer/Resolve/IdentifierLookup.h b/src/Analyzer/Resolve/IdentifierLookup.h index 9c6176cb4a95..25e20f6214fc 100644 --- a/src/Analyzer/Resolve/IdentifierLookup.h +++ b/src/Analyzer/Resolve/IdentifierLookup.h @@ -46,6 +46,13 @@ struct IdentifierLookup IdentifierLookupContext lookup_context; ASTPtr original_ast_node = nullptr; + /// Join tree resolution of an expression identifier that binds to columns of several joined tables + /// returns a result with `ambiguous_in_join_tree` set instead of throwing `AMBIGUOUS_IDENTIFIER`. + /// The caller decides whether another resolution path (aliases) can take over. + /// Participates in comparison and hashing, so such a lookup does not share an identifier resolve + /// cache entry with an ordinary expression lookup. + bool allow_ambiguous_join_tree_identifier = false; + bool isExpressionLookup() const { return lookup_context == IdentifierLookupContext::EXPRESSION; @@ -69,7 +76,9 @@ struct IdentifierLookup inline bool operator==(const IdentifierLookup & lhs, const IdentifierLookup & rhs) { - return lhs.identifier.getFullName() == rhs.identifier.getFullName() && lhs.lookup_context == rhs.lookup_context; + return lhs.identifier.getFullName() == rhs.identifier.getFullName() + && lhs.lookup_context == rhs.lookup_context + && lhs.allow_ambiguous_join_tree_identifier == rhs.allow_ambiguous_join_tree_identifier; } [[maybe_unused]] inline bool operator!=(const IdentifierLookup & lhs, const IdentifierLookup & rhs) @@ -81,7 +90,9 @@ struct IdentifierLookupHash { size_t operator()(const IdentifierLookup & identifier_lookup) const { - return std::hash()(identifier_lookup.identifier.getFullName()) ^ static_cast(identifier_lookup.lookup_context); + return std::hash()(identifier_lookup.identifier.getFullName()) + ^ static_cast(identifier_lookup.lookup_context) + ^ (static_cast(identifier_lookup.allow_ambiguous_join_tree_identifier) << 9); } }; @@ -120,6 +131,15 @@ struct IdentifierResolveResult QueryTreeNodePtr resolved_identifier; IdentifierResolvePlace resolve_place = IdentifierResolvePlace::NONE; + /// Only for lookups with `allow_ambiguous_join_tree_identifier`: the identifier binds to columns + /// of several joined tables, so `resolved_identifier` is empty and no join tree column may win. + bool ambiguous_in_join_tree = false; + + static IdentifierResolveResult ambiguousInJoinTree() + { + return { .resolved_identifier = nullptr, .resolve_place = IdentifierResolvePlace::NONE, .ambiguous_in_join_tree = true }; + } + explicit operator bool() const { chassert(check_invariant()); @@ -160,7 +180,7 @@ struct IdentifierResolveResult { if (!resolved_identifier) { - buffer << "unresolved"; + buffer << (ambiguous_in_join_tree ? "ambiguous" : "unresolved"); return; } diff --git a/src/Analyzer/Resolve/IdentifierResolver.cpp b/src/Analyzer/Resolve/IdentifierResolver.cpp index 62655bb77430..b3fa657aefb6 100644 --- a/src/Analyzer/Resolve/IdentifierResolver.cpp +++ b/src/Analyzer/Resolve/IdentifierResolver.cpp @@ -927,6 +927,8 @@ IdentifierResolveResult IdentifierResolver::tryResolveIdentifierFromCrossJoin(co for (const auto & expr : from_cross_join_node.getTableExpressions()) { auto identifier = tryResolveIdentifierFromJoinTreeNode(identifier_lookup, expr, scope); + if (identifier.ambiguous_in_join_tree) + return identifier; if (!identifier) continue; @@ -963,6 +965,9 @@ IdentifierResolveResult IdentifierResolver::tryResolveIdentifierFromCrossJoin(co } else if (!prefer_left_table) { + if (identifier_lookup.allow_ambiguous_join_tree_identifier) + return IdentifierResolveResult::ambiguousInJoinTree(); + throw Exception(ErrorCodes::AMBIGUOUS_IDENTIFIER, "JOIN {} ambiguous identifier '{}'. In scope {}", table_expression_node->formatASTForErrorMessage(), @@ -1065,12 +1070,14 @@ IdentifierResolveResult IdentifierResolver::tryResolveIdentifierFromJoin(const I } } + bool ambiguous_in_join_tree = false; auto try_resolve_identifier_from_join_tree_node = [&](const QueryTreeNodePtr & join_tree_node, bool may_be_override_by_using_column) { if (may_be_override_by_using_column && !join_using_column_name_to_column_node.empty()) scope.join_using_columns.push_back(&join_using_column_name_to_column_node); auto res = tryResolveIdentifierFromJoinTreeNode(identifier_lookup, join_tree_node, scope); + ambiguous_in_join_tree |= res.ambiguous_in_join_tree; if (may_be_override_by_using_column && !join_using_column_name_to_column_node.empty()) scope.join_using_columns.pop_back(); @@ -1081,6 +1088,9 @@ IdentifierResolveResult IdentifierResolver::tryResolveIdentifierFromJoin(const I auto left_resolved_identifier = try_resolve_identifier_from_join_tree_node(from_join_node.getLeftTableExpression(), join_kind == JoinKind::Right); auto right_resolved_identifier = try_resolve_identifier_from_join_tree_node(from_join_node.getRightTableExpression(), join_kind != JoinKind::Right); + if (ambiguous_in_join_tree) + return IdentifierResolveResult::ambiguousInJoinTree(); + if (!identifier_lookup.isExpressionLookup()) { if (left_resolved_identifier && right_resolved_identifier) @@ -1267,6 +1277,10 @@ IdentifierResolveResult IdentifierResolver::tryResolveIdentifierFromJoin(const I resolved_side = JoinTableSide::Left; resolved_identifier = left_resolved_identifier; } + else if (identifier_lookup.allow_ambiguous_join_tree_identifier) + { + return IdentifierResolveResult::ambiguousInJoinTree(); + } else { throw Exception(ErrorCodes::AMBIGUOUS_IDENTIFIER, @@ -1495,6 +1509,8 @@ IdentifierResolveResult IdentifierResolver::tryResolveIdentifierFromArrayJoin(co { const auto & from_array_join_node = table_expression_node->as(); auto resolve_result = tryResolveIdentifierFromJoinTreeNode(identifier_lookup, from_array_join_node.getTableExpression(), scope); + if (resolve_result.ambiguous_in_join_tree) + return resolve_result; if (scope.table_expressions_in_resolve_process.contains(table_expression_node.get()) || !identifier_lookup.isExpressionLookup()) return resolve_result; diff --git a/src/Analyzer/Resolve/QueryAnalyzer.cpp b/src/Analyzer/Resolve/QueryAnalyzer.cpp index a5eefcfbda44..51065c6d99d5 100644 --- a/src/Analyzer/Resolve/QueryAnalyzer.cpp +++ b/src/Analyzer/Resolve/QueryAnalyzer.cpp @@ -1397,15 +1397,40 @@ IdentifierResolveResult QueryAnalyzer::tryResolveIdentifier(const IdentifierLook if (unlikely(prefer_column_name_to_alias)) { + bool can_check_aliases = identifier_resolve_settings.allow_to_check_aliases && !already_in_resolve_process; + bool ambiguous_in_join_tree = false; + if (identifier_resolve_settings.allow_to_check_join_tree) { - resolve_result = identifier_resolver.tryResolveIdentifierFromJoinTree(identifier_lookup, scope); + /** A column name that is ambiguous between joined tables but also names an alias resolves to the alias, + * as the old analyzer did (`JoinToSubqueryTransformVisitor`, `allow_ambiguous = got_alias`). + * Example: SELECT t1.x AS x FROM t1, t2, t3 WHERE ... ORDER BY x + */ + bool alias_can_take_over = can_check_aliases + && identifier_lookup.isExpressionLookup() + && scope.aliases.find(identifier_lookup, ScopeAliases::FindOption::FIRST_NAME) != nullptr; + + if (alias_can_take_over) + { + auto tolerant_lookup = identifier_lookup; + tolerant_lookup.allow_ambiguous_join_tree_identifier = true; + resolve_result = identifier_resolver.tryResolveIdentifierFromJoinTree(tolerant_lookup, scope); + ambiguous_in_join_tree = resolve_result.ambiguous_in_join_tree; + } + else + { + resolve_result = identifier_resolver.tryResolveIdentifierFromJoinTree(identifier_lookup, scope); + } } - if (identifier_resolve_settings.allow_to_check_aliases && !resolve_result.resolved_identifier && !already_in_resolve_process) + if (can_check_aliases && !resolve_result.resolved_identifier) { resolve_result = tryResolveIdentifierFromAliases(identifier_lookup, scope, identifier_resolve_settings); } + + /// No alias took over: resolve from the join tree again to throw the original `AMBIGUOUS_IDENTIFIER`. + if (ambiguous_in_join_tree && !resolve_result.resolved_identifier) + resolve_result = identifier_resolver.tryResolveIdentifierFromJoinTree(identifier_lookup, scope); } else { @@ -4574,6 +4599,20 @@ void QueryAnalyzer::resolveJoin(QueryTreeNodePtr & join_node, IdentifierResolveS auto & join_using_list = join_node_typed.getJoinExpression()->as(); std::unordered_set join_using_identifiers; + /// The old analyzer rewrote a query with several JOINs into nested subqueries, so an inner JOIN never saw an alias + /// of the query and resolved its key from the left table. Only the outermost JOIN keeps the alias lookup. + auto is_outermost_join = [&join_node, &scope]() -> bool + { + const auto * scope_query_node = scope.scope_node ? scope.scope_node->as() : nullptr; + if (!scope_query_node) + return false; + + IQueryTreeNode * join_tree_root = scope_query_node->getJoinTree().get(); + while (join_tree_root->getNodeType() == QueryTreeNodeType::ARRAY_JOIN) + join_tree_root = join_tree_root->as().getTableExpression().get(); + return join_tree_root == join_node.get(); + }; + for (auto & join_using_node : join_using_list.getNodes()) { auto * identifier_node = join_using_node->as(); @@ -4612,30 +4651,71 @@ void QueryAnalyzer::resolveJoin(QueryTreeNodePtr & join_node, IdentifierResolveS { if (projection_node->hasAlias() && identifier_full_name_ == projection_node->getAlias()) { + /// The query node only scopes the resolution: identifier lookups and matchers inside the expression reach the left + /// side through its join tree, and it names the scope in error messages. auto left_subquery = std::make_shared(query_node->getMutableContext()); left_subquery->getProjection().getNodes().push_back(projection_node->clone()); left_subquery->getJoinTree() = left_table_expression; IdentifierResolveScope & left_subquery_scope = createIdentifierResolveScope(left_subquery, nullptr /*parent_scope*/); /// We are using alias column mechanism for USING column from projection. - /// It will be calculated right after reading, so column will be not nullable there. + /// It will be calculated right after reading, so column will be not nullable there, and a column of a USING key + /// inside the left side keeps the type it is read with rather than the key's supertype, the same way as in PREWHERE. left_subquery_scope.join_use_nulls = false; + left_subquery_scope.allow_resolve_from_using = false; + + /// The left side is already resolved (a USING list inside it holds columns, not identifiers), so it must not be + /// resolved again; the scope takes over what resolveQuery builds for a join tree: the table expression data of + /// the leaves, their aliases (a qualified matcher such as `t1.*` finds its table only through them) and the + /// join counter. + for (const auto & table_expression : extractTableExpressions(left_table_expression, true /*add_array_join*/)) + { + left_subquery_scope.registered_table_expression_nodes.insert(table_expression); + if (table_expression->hasAlias()) + left_subquery_scope.aliases.alias_name_to_table_expression_node.emplace(table_expression->getAlias(), table_expression); + if (table_expression->getNodeType() != QueryTreeNodeType::ARRAY_JOIN) + left_subquery_scope.table_expression_node_to_data.emplace(table_expression, scope_.getTableExpressionDataOrThrow(table_expression)); + } + + for (std::vector join_tree_nodes{left_table_expression.get()}; !join_tree_nodes.empty();) + { + const auto * join_tree_node = join_tree_nodes.back(); + join_tree_nodes.pop_back(); + + if (const auto * join = join_tree_node->as()) + { + ++left_subquery_scope.joins_count; + join_tree_nodes.push_back(join->getLeftTableExpression().get()); + join_tree_nodes.push_back(join->getRightTableExpression().get()); + } + else if (const auto * cross_join = join_tree_node->as()) + { + left_subquery_scope.joins_count += cross_join->getTableExpressions().size() - 1; + for (const auto & cross_join_table_expression : cross_join->getTableExpressions()) + join_tree_nodes.push_back(cross_join_table_expression.get()); + } + else if (const auto * array_join = join_tree_node->as()) + join_tree_nodes.push_back(array_join->getTableExpression().get()); + } - resolveQuery(left_subquery, left_subquery_scope); + auto & resolved_node = left_subquery->getProjection().getNodes().front(); + QueryExpressionsAliasVisitor alias_visitor(left_subquery_scope.aliases); + alias_visitor.visit(resolved_node); + resolveExpressionNode(resolved_node, left_subquery_scope, false /*allow_lambda_expression*/, false /*allow_table_expression*/); - const auto & resolved_nodes = left_subquery->getProjection().getNodes(); - if (resolved_nodes.size() == 1) + /// A matcher resolves into a list of columns. + if (resolved_node->getNodeType() != QueryTreeNodeType::LIST) { /// Added column should not conflict with existing column names NameSet existing_columns; if (!getColumnsFromTableExpression(left_table_expression, existing_columns)) return nullptr; - NameAndTypePair column_name_type(identifier_full_name_, resolved_nodes.front()->getResultType()); + NameAndTypePair column_name_type(identifier_full_name_, resolved_node->getResultType()); while (existing_columns.contains(column_name_type.name)) column_name_type.name = "_" + column_name_type.name; - auto [expression_source, is_single_source] = getExpressionSource(resolved_nodes.front()); + auto [expression_source, is_single_source] = getExpressionSource(resolved_node); /// Do not support `SELECT t1.a + t2.a AS id ... USING id` if (!is_single_source) return nullptr; @@ -4650,7 +4730,7 @@ void QueryAnalyzer::resolveJoin(QueryTreeNodePtr & join_node, IdentifierResolveS return nullptr; /// Create ColumnNode with expression from parent projection - return std::make_shared(std::move(column_name_type), resolved_nodes.front(), + return std::make_shared(std::move(column_name_type), resolved_node, expression_source ? expression_source : left_table_expression); } } @@ -4664,9 +4744,9 @@ void QueryAnalyzer::resolveJoin(QueryTreeNodePtr & join_node, IdentifierResolveS /** With `analyzer_compatibility_join_using_top_level_identifier` alias in projection has higher priority than column from left table. * But if aliased expression cannot be resolved from left table, we get UNKNOW_IDENTIFIER error, * despite the fact that column from USING could be resolved from left table. - * It's compatible with a default behavior for old analyzer. + * It's compatible with a default behavior for old analyzer, which also never used an alias for an inner JOIN. */ - if (settings[Setting::analyzer_compatibility_join_using_top_level_identifier]) + if (settings[Setting::analyzer_compatibility_join_using_top_level_identifier] && is_outermost_join()) result_left_table_expression = try_resolve_identifier_from_query_projection(identifier_full_name, join_node_typed.getLeftTableExpression(), scope); if (!result_left_table_expression) @@ -4679,7 +4759,7 @@ void QueryAnalyzer::resolveJoin(QueryTreeNodePtr & join_node, IdentifierResolveS { String extra_message; const QueryNode * query_node = scope.scope_node ? scope.scope_node->as() : nullptr; - if (!settings[Setting::analyzer_compatibility_join_using_top_level_identifier] && query_node) + if (!settings[Setting::analyzer_compatibility_join_using_top_level_identifier] && query_node && is_outermost_join()) { for (const auto & projection_node : query_node->getProjection().getNodes()) { diff --git a/src/Analyzer/Resolve/resolveFunction.cpp b/src/Analyzer/Resolve/resolveFunction.cpp index 47e5d7d3f538..907064725386 100644 --- a/src/Analyzer/Resolve/resolveFunction.cpp +++ b/src/Analyzer/Resolve/resolveFunction.cpp @@ -434,7 +434,10 @@ ProjectionNames QueryAnalyzer::resolveFunction(QueryTreeNodePtr & node, Identifi if (is_special_function_dict_get) { - scope.context->getExternalDictionariesLoader().assertDictionaryStructureExists(identifier.getFullName(), scope.context); + /// Check access before reading the dictionary definition, so that a user without access learns nothing + /// about the dictionary. + const auto & external_loader = scope.context->getExternalDictionariesLoader(); + (void)external_loader.getDictionaryStructure(external_loader.resolveDictionaryCheckingAccess(identifier.getFullName(), scope.context)); } else { diff --git a/src/Client/Connection.cpp b/src/Client/Connection.cpp index 4e386216d0a9..9edb613ee927 100644 --- a/src/Client/Connection.cpp +++ b/src/Client/Connection.cpp @@ -79,6 +79,7 @@ namespace FailPoints namespace ErrorCodes { + extern const int AUTHENTICATION_FAILED; extern const int NETWORK_ERROR; extern const int SOCKET_TIMEOUT; extern const int UNEXPECTED_PACKET_FROM_SERVER; @@ -624,7 +625,8 @@ void Connection::receiveHello() if (server_revision >= DBMS_MIN_REVISION_WITH_SERVER_SETTINGS) { Settings settings; - settings.read(*in, SettingsWriteFormat::STRINGS_WITH_FLAGS); + /// A server of another version may send values that this version rejects. + settings.read(*in, SettingsWriteFormat::STRINGS_WITH_FLAGS, /* skip_invalid_values= */ true); settings_from_server = settings.changes(); } @@ -913,6 +915,20 @@ void Connection::sendQuery( disconnect(); }); + /// Over the cluster secret a shard authenticates as `initial_user` without a password, so forward + /// only an `initial_user` equal to the authenticated `current_user`. Skip the check when + /// `current_user` is empty -- server-internal paths (async `Distributed` insert, buffer flush) have none. + if (!cluster_secret.empty() && client_info && !client_info->current_user.empty() + && client_info->initial_user != client_info->current_user) + { + /// A mismatch means a forged SECONDARY_QUERY impersonating another user -- including an empty + /// initial_user, which the shard would otherwise run with full access -- so refuse it. + throw Exception(ErrorCodes::AUTHENTICATION_FAILED, + "Refusing to forward a query over the cluster secret: its initial_user '{}' differs " + "from the authenticated user '{}'.", + client_info->initial_user, client_info->current_user); + } + writeVarUInt(Protocol::Client::Query, *out); writeStringBinary(query_id, *out); diff --git a/src/Columns/ColumnAggregateFunction.cpp b/src/Columns/ColumnAggregateFunction.cpp index a88103df3b89..91fb6b37671b 100644 --- a/src/Columns/ColumnAggregateFunction.cpp +++ b/src/Columns/ColumnAggregateFunction.cpp @@ -39,6 +39,7 @@ namespace ErrorCodes namespace FailPoints { extern const char column_aggregate_function_ensureOwnership_exception[]; + extern const char column_aggregate_function_expand_exception[]; } @@ -392,32 +393,61 @@ void ColumnAggregateFunction::expand(const Filter & mask, bool inverted) if (mask.size() < data.size()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Mask size should be no less than data size."); - ssize_t from = data.size() - 1; - ssize_t index = mask.size() - 1; - data.resize(mask.size()); - while (index >= 0) + const size_t set_bytes = countBytesInFilter(mask); + const size_t selected = inverted ? mask.size() - set_bytes : set_bytes; + if (selected > data.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Too many bytes in mask"); + if (selected < data.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Not enough bytes in mask"); + + bool inject_memory_limit_exceeded = false; + /// Avoid checking failpoint in a loop, since it uses atomic's + fiu_do_on(FailPoints::column_aggregate_function_expand_exception, { - if (!!mask[index] ^ inverted) - { - if (from < 0) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Too many bytes in mask"); + inject_memory_limit_exceeded = true; + }); - /// Copy only if it makes sense. - if (index != from) - data[index] = data[from]; - --from; - } - else + /// The destructor destroys every state in `data`, so `data` must never hold a pointer to a state + /// that is not created. Build the expanded array aside and publish it only when it is complete. + Container new_data; + new_data.resize_exact(mask.size()); + + size_t from = 0; + size_t index = 0; + try + { + for (; index < mask.size(); ++index) { - data[index] = arena.alignedAlloc(func->sizeOfData(), func->alignOfData()); - func->create(data[index]); - } + if (!!mask[index] ^ inverted) + { + new_data[index] = data[from]; + ++from; + } + else + { + new_data[index] = arena.alignedAlloc(func->sizeOfData(), func->alignOfData()); + func->create(new_data[index]); - --index; + /// Throw after a state is created, so that the cleanup has something to destroy. + if (unlikely(inject_memory_limit_exceeded)) + { + ++index; + throw Exception(ErrorCodes::MEMORY_LIMIT_EXCEEDED, "Failpoint triggered"); + } + } + } + } + catch (...) + { + /// Destroy the states created so far; the ones taken from `data` stay owned by `data`. + if (!func->hasTrivialDestructor()) + for (size_t i = 0; i < index; ++i) + if (!(!!mask[i] ^ inverted)) + func->destroy(new_data[i]); + throw; } - if (from != -1) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Not enough bytes in mask"); + data.swap(new_data); } ColumnPtr ColumnAggregateFunction::permute(const Permutation & perm, size_t limit) const diff --git a/src/Columns/ColumnObject.cpp b/src/Columns/ColumnObject.cpp index de82de324970..51a79919b02d 100644 --- a/src/Columns/ColumnObject.cpp +++ b/src/Columns/ColumnObject.cpp @@ -15,6 +15,7 @@ namespace DB namespace ErrorCodes { extern const int ATTEMPT_TO_READ_AFTER_EOF; + extern const int INCORRECT_DATA; extern const int NOT_IMPLEMENTED; extern const int LOGICAL_ERROR; extern const int PARAMETER_OUT_OF_BOUND; @@ -1112,6 +1113,7 @@ void ColumnObject::deserializeDynamicPathsAndSharedDataFromArena(ReadBuffer & in readBinaryLittleEndian(num_paths, in); const auto [shared_data_paths, shared_data_values] = getSharedDataPathsAndValues(); + const size_t shared_data_row_start = shared_data_paths->size(); for (size_t i = 0; i != num_paths; ++i) { size_t path_size; @@ -1130,9 +1132,17 @@ void ColumnObject::deserializeDynamicPathsAndSharedDataFromArena(ReadBuffer & in size_t value_size; readBinaryLittleEndian(value_size, in); + /// `serializeDynamicPathsAndSharedDataIntoArena` writes every path of a row once. A path repeated + /// in the row would get several values in a column of a dynamic path, or break the order of shared data. + /// Typed paths are deserialized before, so a typed path here would be a second value of it. + if (typed_paths.contains(path)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Typed path '{}' in dynamic paths of a serialized value of JSON column", path); + /// Check if we have this path in dynamic paths. if (auto dynamic_it = dynamic_paths.find(path); dynamic_it != dynamic_paths.end()) { + if (dynamic_it->second->size() != current_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Duplicate path '{}' in a serialized value of JSON column", path); getDynamicSerialization()->deserializeBinary(*dynamic_it->second, in, getFormatSettings()); } /// Try to add a new dynamic path. @@ -1150,6 +1160,9 @@ void ColumnObject::deserializeDynamicPathsAndSharedDataFromArena(ReadBuffer & in "Attempt to read {} bytes for the value size, but only {} bytes are available", value_size, in.available()); + if (shared_data_paths->size() > shared_data_row_start && shared_data_paths->getDataAt(shared_data_paths->size() - 1) >= path) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Paths of a serialized value of JSON column are not sorted or have duplicates (at path '{}')", path); std::string_view value(in.position(), value_size); in.ignore(value_size); shared_data_paths->insertData(path.data(), path.size()); diff --git a/src/Columns/ColumnUnique.h b/src/Columns/ColumnUnique.h index f83dc7613196..59a1ac0efce6 100644 --- a/src/Columns/ColumnUnique.h +++ b/src/Columns/ColumnUnique.h @@ -29,6 +29,7 @@ namespace DB namespace ErrorCodes { extern const int ATTEMPT_TO_READ_AFTER_EOF; + extern const int INCORRECT_DATA; extern const int LOGICAL_ERROR; extern const int ILLEGAL_COLUMN; extern const int NOT_IMPLEMENTED; @@ -559,6 +560,9 @@ size_t ColumnUnique::uniqueDeserializeAndInsertFromArena(ReadBuffer if (in.available() < string_size) throw Exception(ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF, "Not enough data to deserialize string value in ColumnUnique."); + if (unlikely(string_size < serialize_string_with_zero_byte)) + throw Exception(ErrorCodes::INCORRECT_DATA, "String size is smaller than its zero-byte terminator"); + size_t ret = uniqueInsertData(in.position(), string_size - serialize_string_with_zero_byte); in.ignore(string_size); return ret; @@ -567,39 +571,8 @@ size_t ColumnUnique::uniqueDeserializeAndInsertFromArena(ReadBuffer template size_t ColumnUnique::uniqueDeserializeAndInsertAggregationStateValueFromArena(ReadBuffer & in) { - if (is_nullable) - { - UInt8 val; - readBinaryLittleEndian(val, in); - - if (val) - return getNullValueIndex(); - - } - - /// Numbers, FixedString - if (size_of_value_if_fixed) - { - if (in.available() < size_of_value_if_fixed) - throw Exception(ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF, "Not enough data to deserialize fixed size value in ColumnUnique."); - - size_t ret = uniqueInsertData(in.position(), size_of_value_if_fixed); - in.ignore(size_of_value_if_fixed); - return ret; - - } - - /// String - /// For compatibility, serialized string value contains zero byte at the end, we just ignore this byte. - size_t string_size_with_zero_byte; - readBinaryLittleEndian(string_size_with_zero_byte, in); - if (in.available() < string_size_with_zero_byte) - throw Exception(ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF, "Not enough data to deserialize string value in ColumnUnique."); - - size_t ret = uniqueInsertData(in.position(), string_size_with_zero_byte - 1); - in.ignore(string_size_with_zero_byte); - - return ret; + const auto settings = IColumn::SerializationSettings::createForAggregationState(); + return uniqueDeserializeAndInsertFromArena(in, &settings); } template diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 7dfb2f297886..bdaf883c95fd 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -109,6 +109,7 @@ static struct InitFiu ONCE(delta_kernel_force_stale_token_error) \ REGULAR(object_storage_force_refresh_callback_success) \ ONCE(column_aggregate_function_ensureOwnership_exception) \ + ONCE(column_aggregate_function_expand_exception) \ REGULAR(keepermap_fail_drop_data) \ REGULAR(keeper_fault_on_watch_request) \ REGULAR(lazy_pipe_fds_fail_close) \ diff --git a/src/Common/HTTPHeaderFilter.cpp b/src/Common/HTTPHeaderFilter.cpp index 2285f8f6ab02..59e0e5948e0d 100644 --- a/src/Common/HTTPHeaderFilter.cpp +++ b/src/Common/HTTPHeaderFilter.cpp @@ -3,7 +3,9 @@ #include #include #include +#include #include +#include #include #include @@ -53,6 +55,37 @@ void HTTPHeaderFilter::checkAndNormalizeHeaders(HTTPHeaderEntries & entries) con } } +void HTTPHeaderFilter::checkBasicCredentials(const Poco::Net::HTTPBasicCredentials & credentials) const +{ + if (credentials.getUsername().empty()) + return; + + checkAuthorizationHeader("Basic authentication credentials, for example the userinfo of a URL, are sent in this header"); +} + +void HTTPHeaderFilter::checkURIUserInfo(const Poco::URI & uri) const +{ + if (uri.getUserInfo().empty()) + return; + + checkAuthorizationHeader("The userinfo of the URL is sent in this header as Basic authentication credentials"); +} + +void HTTPHeaderFilter::checkAuthorizationHeader(const std::string & reason) const +{ + /// A forbidden header is matched by name, and a Base64 value has no CR or LF, so a placeholder value suffices. + HTTPHeaderEntries entries{{"Authorization", "Basic"}}; + try + { + checkAndNormalizeHeaders(entries); + } + catch (Exception & e) + { + e.addMessage(reason); + throw; + } +} + void HTTPHeaderFilter::setValuesFromConfig(const Poco::Util::AbstractConfiguration & config) { std::lock_guard guard(mutex); diff --git a/src/Common/HTTPHeaderFilter.h b/src/Common/HTTPHeaderFilter.h index b6232b40b932..4d3a034320fc 100644 --- a/src/Common/HTTPHeaderFilter.h +++ b/src/Common/HTTPHeaderFilter.h @@ -8,6 +8,8 @@ #include namespace re2 { class RE2; } +namespace Poco { class URI; } +namespace Poco::Net { class HTTPBasicCredentials; } namespace DB { @@ -19,7 +21,14 @@ class HTTPHeaderFilter void setValuesFromConfig(const Poco::Util::AbstractConfiguration & config); void checkAndNormalizeHeaders(HTTPHeaderEntries & entries) const; + /// Throws if the `Authorization` header that sends these credentials is forbidden. An empty username sends no header. + void checkBasicCredentials(const Poco::Net::HTTPBasicCredentials & credentials) const; + /// The same for a sender that sends any non-empty userinfo of `uri` as Basic credentials, even without a username. + void checkURIUserInfo(const Poco::URI & uri) const; + private: + void checkAuthorizationHeader(const std::string & reason) const; + /// Header names are case-insensitive (RFC 7230 3.2): entries are stored /// lower-cased and the incoming name is lower-cased before lookup. std::unordered_set forbidden_headers; diff --git a/src/Common/NamedCollections/NamedCollections.cpp b/src/Common/NamedCollections/NamedCollections.cpp index 90e4b5aaa141..6b524d379a71 100644 --- a/src/Common/NamedCollections/NamedCollections.cpp +++ b/src/Common/NamedCollections/NamedCollections.cpp @@ -178,10 +178,12 @@ class NamedCollection::Impl NamedCollection::NamedCollection( ImplPtr pimpl_, const std::string & collection_name_, - const bool is_mutable_) + const bool is_mutable_, + const SourceId source_id_) : pimpl(std::move(pimpl_)) , collection_name(collection_name_) , is_mutable(is_mutable_) + , source_id(source_id_) { } @@ -286,7 +288,7 @@ MutableNamedCollectionPtr NamedCollection::duplicate() const std::lock_guard lock(mutex); auto impl = pimpl->createCopy(collection_name); return std::unique_ptr( - new NamedCollection(std::move(impl), collection_name, true)); + new NamedCollection(std::move(impl), collection_name, true, source_id)); } NamedCollection::Keys NamedCollection::getKeys(ssize_t depth, const std::string & prefix) const @@ -335,7 +337,8 @@ NamedCollectionFromConfig::NamedCollectionFromConfig( const std::string & collection_name_, const std::string & collection_path_, const Keys & keys_) - : NamedCollection(Impl::create(config_, collection_name_, collection_path_, keys_), collection_name_, /* is_mutable */ false) + : NamedCollection( + Impl::create(config_, collection_name_, collection_path_, keys_), collection_name_, /* is_mutable */ false, SourceId::CONFIG) { } @@ -356,7 +359,7 @@ MutableNamedCollectionPtr NamedCollectionFromSQL::create(const ASTCreateNamedCol } NamedCollectionFromSQL::NamedCollectionFromSQL(const ASTCreateNamedCollectionQuery & query_) - : NamedCollection(nullptr, query_.collection_name, true) + : NamedCollection(nullptr, query_.collection_name, true, SourceId::SQL) , create_query_ptr(query_.clone()->as()) { const auto config = NamedCollectionConfiguration::createConfiguration(collection_name, create_query_ptr.changes, create_query_ptr.overridability); diff --git a/src/Common/NamedCollections/NamedCollections.h b/src/Common/NamedCollections/NamedCollections.h index 673476271387..bc0693724b8c 100644 --- a/src/Common/NamedCollections/NamedCollections.h +++ b/src/Common/NamedCollections/NamedCollections.h @@ -29,8 +29,6 @@ class NamedCollection using Keys = std::set>; enum class SourceId : uint8_t { - /// None source_id is possible only if the object is a - /// duplicate of some named collection. See `duplicate` method. NONE = 0, CONFIG = 1, SQL = 2, @@ -65,7 +63,7 @@ class NamedCollection template void remove(const Key & key); - /// Creates mutable, with NONE source id full copy. + /// Creates a mutable full copy, keeping the source of the original. MutableNamedCollectionPtr duplicate() const; Keys getKeys(ssize_t depth = -1, const std::string & prefix = "") const; @@ -81,7 +79,7 @@ class NamedCollection bool isMutable() const { return is_mutable; } - virtual SourceId getSourceId() const { return SourceId::NONE; } + SourceId getSourceId() const { return source_id; } virtual String getCreateStatement(bool /*show_secrects*/) { return {}; } @@ -95,7 +93,8 @@ class NamedCollection NamedCollection( ImplPtr pimpl_, const std::string & collection_name, - bool is_mutable_ + bool is_mutable_, + SourceId source_id_ ); void assertMutable() const; @@ -104,6 +103,7 @@ class NamedCollection ImplPtr pimpl; const std::string collection_name; const bool is_mutable; + const SourceId source_id; mutable std::mutex mutex; }; @@ -116,8 +116,6 @@ class NamedCollectionFromSQL final : public NamedCollection void update(const ASTAlterNamedCollectionQuery & query) override; - NamedCollection::SourceId getSourceId() const override { return SourceId::SQL; } - private: explicit NamedCollectionFromSQL(const ASTCreateNamedCollectionQuery & query_); @@ -138,8 +136,6 @@ class NamedCollectionFromConfig final : public NamedCollection void update(const ASTAlterNamedCollectionQuery & /*query*/) override { NamedCollection::assertMutable(); } - NamedCollection::SourceId getSourceId() const override { return SourceId::CONFIG; } - private: NamedCollectionFromConfig( diff --git a/src/Common/RemoteHostFilter.cpp b/src/Common/RemoteHostFilter.cpp index 5b5da5ec7c6b..a5f8b81e1220 100644 --- a/src/Common/RemoteHostFilter.cpp +++ b/src/Common/RemoteHostFilter.cpp @@ -17,13 +17,15 @@ namespace ErrorCodes bool RemoteHostFilter::checkURL(const Poco::URI & uri, bool throw_on_error) const { - if (checkForDirectEntry(uri.getHost()) || checkForDirectEntry(uri.getHost() + ":" + toString(uri.getPort()))) + const std::string host_and_port = uri.getHost() + ":" + toString(uri.getPort()); + if (checkForDirectEntry(uri.getHost()) || checkForDirectEntry(host_and_port)) return true; if (!throw_on_error) return false; + /// Only the host and port are checked. The rest of the URL can carry secrets and is not printed. throw Exception(ErrorCodes::UNACCEPTABLE_URL, "URL \"{}\" is not allowed in configuration file, " - "see ", uri.toString()); + "see ", host_and_port); } void RemoteHostFilter::checkHostAndPort(const std::string & host, const std::string & port) const diff --git a/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp b/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp index a06fed9710e4..ed55f0e0c8a6 100644 --- a/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp +++ b/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp @@ -178,8 +178,12 @@ WorkloadEntityStorageBase::OperationResult WorkloadEntityKeeperStorage::storeEnt auto component_guard = Coordination::setCurrentComponent("WorkloadEntityKeeperStorage::storeEntityImpl"); LOG_DEBUG(log, "Storing workload entity {}", backQuote(entity_name)); - String new_data = serializeLocalEntities(Event{entity_type, entity_name, create_entity_query}); + Int32 validated_version = current_version; auto zookeeper = getZooKeeper(); + if (current_version != validated_version) + return OperationResult::Retry; /// A new session has refreshed the entities, so the caller's validation is stale + + String new_data = serializeLocalEntities(Event{entity_type, entity_name, create_entity_query}); Coordination::Stat stat; auto code = zookeeper->trySet(zookeeper_path, new_data, current_version, &stat); @@ -206,8 +210,12 @@ WorkloadEntityStorageBase::OperationResult WorkloadEntityKeeperStorage::removeEn auto component_guard = Coordination::setCurrentComponent("WorkloadEntityKeeperStorage::removeEntityImpl"); LOG_DEBUG(log, "Removing workload entity {}", backQuote(entity_name)); - String new_data = serializeLocalEntities(Event{entity_type, entity_name, {}}); + Int32 validated_version = current_version; auto zookeeper = getZooKeeper(); + if (current_version != validated_version) + return OperationResult::Retry; /// A new session has refreshed the entities, so the caller's validation is stale + + String new_data = serializeLocalEntities(Event{entity_type, entity_name, {}}); Coordination::Stat stat; auto code = zookeeper->trySet(zookeeper_path, new_data, current_version, &stat); diff --git a/src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp b/src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp index 27947b32e243..cb722a4c7650 100644 --- a/src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp +++ b/src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp @@ -535,7 +535,7 @@ bool WorkloadEntityStorageBase::removeEntity( { std::unique_lock lock(mutex); auto it = entities.find(entity_name); - if (it == entities.end()) + if (it == entities.end() || getEntityType(it->second) != entity_type) { if (throw_if_not_exists) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Workload entity '{}' doesn't exist", entity_name); diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index a4f762ec2d57..a16f7263c508 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -71,10 +71,11 @@ inline bool maskURIPassword(std::string * uri) } /** Mask the values of the query parameters that carry credentials in a presigned URL, so that - * `...?X-Amz-Signature=abc&foo=1` becomes `...?X-Amz-Signature=[HIDDEN]&foo=1`. Every occurrence - * is masked. Returns whether anything was masked. + * `...?X-Amz-Signature=abc&foo=1` becomes `...?X-Amz-Signature=[HIDDEN]&foo=1`, and of the + * `connection_string` parameter of an ODBC/JDBC bridge request. Every occurrence is masked. + * Returns whether anything was masked. * - * Mirrors the regular expression + * Apart from `connection_string`, mirrors the regular expression * `([?&](?:AWSAccessKeyId|Signature|Expires|GoogleAccessId|X-Amz-[A-Za-z0-9\-]*|X-Goog-[A-Za-z0-9\-]*)=)[^&#]*` * that `FunctionSecretArgumentsFinder` applies to a presigned URL, and the parameter set mirrors * `BackupInfo::removeCredentialsFromS3URL`. Matching is case-sensitive, as in the expression. @@ -86,6 +87,9 @@ inline bool maskPresignedURLParameters(std::string & url) auto is_secret_parameter = [](std::string_view name) { + if (name == "connection_string") + return true; + for (auto exact : exact_names) if (name == exact) return true; diff --git a/src/Coordination/KeeperStorage.cpp b/src/Coordination/KeeperStorage.cpp index 3319668b9508..dcb92d03788b 100644 --- a/src/Coordination/KeeperStorage.cpp +++ b/src/Coordination/KeeperStorage.cpp @@ -2573,7 +2573,9 @@ processImpl(const Coordination::ZooKeeperCheckWatchRequest & zk_request, Storage } } - if (!storage.containsWatch(zk_request.getPath(), zk_request.type)) + if (!magic_enum::enum_contains(zk_request.type)) + response->error = Coordination::Error::ZBADARGUMENTS; + else if (!storage.containsWatch(zk_request.getPath(), zk_request.type)) response->error = Coordination::Error::ZNOWATCHER; return response; } @@ -2610,7 +2612,9 @@ processImpl(const Coordination::ZooKeeperRemoveWatchRequest & zk_request, Storag } } - if (!storage.removePersistentWatch(zk_request.path, zk_request.type, session_id)) + if (!magic_enum::enum_contains(zk_request.type)) + response->error = Coordination::Error::ZBADARGUMENTS; + else if (!storage.removePersistentWatch(zk_request.path, zk_request.type, session_id)) response->error = Coordination::Error::ZNOWATCHER; return response; @@ -2648,7 +2652,10 @@ processImpl(const Coordination::ZooKeeperAddWatchRequest & zk_request, Storage & } } - storage.addPersistentWatch(zk_request.path, zk_request.mode, session_id); + if (!magic_enum::enum_contains(zk_request.mode)) + response->error = Coordination::Error::ZBADARGUMENTS; + else + storage.addPersistentWatch(zk_request.path, zk_request.mode, session_id); return response; } diff --git a/src/Core/BackgroundSchedulePool.cpp b/src/Core/BackgroundSchedulePool.cpp index e0511c7643fe..227db0b72fb5 100644 --- a/src/Core/BackgroundSchedulePool.cpp +++ b/src/Core/BackgroundSchedulePool.cpp @@ -414,10 +414,12 @@ void BackgroundSchedulePool::scheduleDelayedTask(TaskInfo & task, size_t ms, std { std::lock_guard lock(delayed_tasks_mutex); + /// Insert before erasing the old entry: if the insertion throws, the task keeps its old entry and `task.iterator` stays valid. + auto it = delayed_tasks.emplace(current_time + (ms * 1000), task.shared_from_this()); if (task.delayed) delayed_tasks.erase(task.iterator); - task.iterator = delayed_tasks.emplace(current_time + (ms * 1000), task.shared_from_this()); + task.iterator = it; task.delayed = true; } diff --git a/src/Core/BaseSettings.cpp b/src/Core/BaseSettings.cpp index df8aae280239..f39686140dfe 100644 --- a/src/Core/BaseSettings.cpp +++ b/src/Core/BaseSettings.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -9,6 +10,7 @@ namespace DB { namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int INCORRECT_DATA; extern const int TOO_LARGE_ARRAY_SIZE; extern const int UNKNOWN_SETTING; @@ -95,6 +97,15 @@ void BaseSettingsHelpers::warningSettingNotFound(std::string_view name) } } +bool BaseSettingsHelpers::skipInvalidSettingValue(std::string_view name, const Exception & e) +{ + if (e.code() != ErrorCodes::BAD_ARGUMENTS && !isParseError(e.code())) + return false; + + LOG_WARNING(getLogger("Settings"), "Cannot parse the value of setting `{}`, skipping it: {}", name, e.message()); + return true; +} + void BaseSettingsHelpers::flushWarnings() { unknown_settings.clear(); diff --git a/src/Core/BaseSettings.h b/src/Core/BaseSettings.h index 2952f9c3f287..49d3411d5a1c 100644 --- a/src/Core/BaseSettings.h +++ b/src/Core/BaseSettings.h @@ -53,6 +53,8 @@ struct BaseSettingsHelpers [[noreturn]] static void throwSettingNotFound(std::string_view name); [[noreturn]] static void throwTooManySettings(std::string_view what); static void warningSettingNotFound(std::string_view name); + /// Returns true (and logs a warning) if `e` is `BAD_ARGUMENTS` or a parse error (`isParseError`); other errors are not skipped. + static bool skipInvalidSettingValue(std::string_view name, const Exception & e); static void flushWarnings(); /// Serialization helpers @@ -253,8 +255,9 @@ class BaseSettings : public TTraits::Data /// Write all settings (or only changed ones depending on format) void write(WriteBuffer & out, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT) const; - /// Read settings from a buffer - void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT); + /// Read settings from a buffer. + /// With `skip_invalid_values`, a non-important setting whose value is rejected keeps its default instead of failing the read. + void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT, bool skip_invalid_values = false); /// Write only changed settings in binary format void writeChangedBinary(WriteBuffer & out) const; @@ -662,7 +665,7 @@ void BaseSettings::readBinary(ReadBuffer & in) } template -void BaseSettings::read(ReadBuffer & in, SettingsWriteFormat format) +void BaseSettings::read(ReadBuffer & in, SettingsWriteFormat format, bool skip_invalid_values) { resetToDefault(); const auto & accessor = Traits::Accessor::instance(); @@ -695,7 +698,26 @@ void BaseSettings::read(ReadBuffer & in, SettingsWriteFormat format) accessor.setValue(*this, index, static_cast(temp)); } else if (format >= SettingsWriteFormat::STRINGS_WITH_FLAGS) - accessor.setValueString(*this, index, BaseSettingsHelpers::readString(in)); + { + String value = BaseSettingsHelpers::readString(in); + try + { + accessor.setValueString(*this, index, value); + /// In this version some values are rejected only when a setting is assigned from a `Field`, + /// not when it is parsed from a string (e.g. a negative value of a `Seconds` setting). + /// The caller applies the settings it has read as `SettingsChanges`, that is, as `Field`s, + /// so a value that cannot be assigned this way is rejected here as well. + if (skip_invalid_values) + accessor.setValue(*this, index, accessor.getValue(*this, index)); + } + catch (const Exception & e) + { + if (!skip_invalid_values || is_important || !BaseSettingsHelpers::skipInvalidSettingValue(name, e)) + throw; + /// A failed parse may have assigned the field already. + accessor.resetValueToDefault(*this, index); + } + } else accessor.readBinary(*this, index, in); } diff --git a/src/Core/Field.cpp b/src/Core/Field.cpp index ceb68fc42be2..eec1a4aab8bc 100644 --- a/src/Core/Field.cpp +++ b/src/Core/Field.cpp @@ -631,29 +631,40 @@ void writeText(const CustomType & x, WriteBuffer & buf) template void readQuoted(DecimalField & x, ReadBuffer & buf) { - assertChar('\'', buf); - T value; - UInt32 scale; - int32_t exponent; + String text; + readQuotedString(text, buf); + ReadBufferFromString in(text); + T value{}; + int32_t exponent = 0; uint32_t max_digits = static_cast(-1); - readDigits(buf, value, max_digits, exponent, true); - if (exponent > 0) + bool has_digits = false; + if (!text.empty()) + readDigits(in, value, max_digits, exponent, true, &has_digits); + if (!has_digits || !in.eof()) + throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot parse decimal dump '{}'", text); + + /// `readDigits` drops trailing fractional zeroes, but the dump writes them to keep the scale. + size_t mantissa_end = std::min(text.find_first_of("eE"), text.size()); + uint32_t trailing_zeroes = 0; + if (text.find('.') < mantissa_end) + while (text[mantissa_end - 1 - trailing_zeroes] == '0') + ++trailing_zeroes; + if (!mulPow10AddChecked(value.value, trailing_zeroes, typename T::NativeType(0))) + throw Exception(ErrorCodes::DECIMAL_OVERFLOW, "Decimal math overflow"); + + /// An out-of-range scale overruns the decimal text writer. + Int64 total_exponent = static_cast(exponent) - trailing_zeroes; + UInt32 scale = 0; + if (total_exponent > 0) { - scale = 0; - if (common::mulOverflow(value.value, DecimalUtils::scaleMultiplier(exponent), value.value)) + if (!mulPow10AddChecked(value.value, static_cast(std::min(total_exponent, UINT32_MAX)), typename T::NativeType(0))) throw Exception(ErrorCodes::DECIMAL_OVERFLOW, "Decimal math overflow"); } - else - scale = -exponent; - /// The scale comes from untrusted text: `restoreFromDump` is reached from the pre-auth native - /// settings reader for a `CUSTOM`-flagged setting (`SettingFieldCustom::parseFromString`), and an - /// exponent-form value such as `Decimal64_'1e-1000'` builds a scale that bypasses the binary - /// reader's check. An out-of-range scale later overruns a fixed-size buffer in the decimal text - /// writer, so reject it here, matching `readDecimalFieldBinary` and `DataTypeDecimalBase`. - if (scale > DecimalUtils::max_precision) + else if (-total_exponent > static_cast(DecimalUtils::max_precision)) throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Scale {} is out of bounds (max scale: {})", - scale, DecimalUtils::max_precision); - assertChar('\'', buf); + -total_exponent, DecimalUtils::max_precision); + else + scale = static_cast(-total_exponent); x = DecimalField{value, scale}; } diff --git a/src/Core/ServerSettings.cpp b/src/Core/ServerSettings.cpp index 70f5fc447fdc..fa8a2398d2d3 100644 --- a/src/Core/ServerSettings.cpp +++ b/src/Core/ServerSettings.cpp @@ -382,38 +382,9 @@ namespace The delay during which a dropped table can be restored using the [`UNDROP`](/sql-reference/statements/undrop.md) statement. If `DROP TABLE` ran with a `SYNC` modifier, the setting is ignored. The default for this setting is `480` (8 minutes). )", 0) \ - DECLARE(UInt64, database_catalog_unused_dir_hide_timeout_sec, 60 * 60, R"( - Parameter of a task that cleans up garbage from `store/` directory. - If some subdirectory is not used by clickhouse-server and this directory was not modified for last - [`database_catalog_unused_dir_hide_timeout_sec`](/operations/server-configuration-parameters/settings#database_catalog_unused_dir_hide_timeout_sec) seconds, the task will "hide" this directory by - removing all access rights. It also works for directories that clickhouse-server does not - expect to see inside `store/`. - - :::note - A value of `0` means "immediately". - ::: - )", 0) \ - DECLARE(UInt64, database_catalog_unused_dir_rm_timeout_sec, 30 * 24 * 60 * 60, R"( - Parameter of a task that cleans up garbage from `store/` directory. - If some subdirectory is not used by clickhouse-server and it was previously "hidden" - (see [database_catalog_unused_dir_hide_timeout_sec](/operations/server-configuration-parameters/settings#database_catalog_unused_dir_hide_timeout_sec)) - and this directory was not modified for last - [`database_catalog_unused_dir_rm_timeout_sec`]/operations/server-configuration-parameters/settings#database_catalog_unused_dir_rm_timeout_sec) seconds, the task will remove this directory. - It also works for directories that clickhouse-server does not - expect to see inside `store/`. - - :::note - A value of `0` means "never". The default value corresponds to 30 days. - ::: - )", 0) \ - DECLARE(UInt64, database_catalog_unused_dir_cleanup_period_sec, 24 * 60 * 60, R"( - Parameter of a task that cleans up garbage from `store/` directory. - Sets scheduling period of the task. - - :::note - A value of `0` means "never". The default value corresponds to 1 day. - ::: - )", 0) \ + DECLARE(UInt64, database_catalog_unused_dir_hide_timeout_sec, 60 * 60, R"(Parameter of the background task that cleaned up garbage from the `store/` directory: the time after which the task revoked all access rights from an unused directory. The setting is deprecated and has no effect: the task was removed, and ClickHouse never hides or removes unused directories in `store/` automatically.)", SettingsTierType::OBSOLETE) \ + DECLARE(UInt64, database_catalog_unused_dir_rm_timeout_sec, 30 * 24 * 60 * 60, R"(Parameter of the background task that cleaned up garbage from the `store/` directory: the time after which the task removed an unused directory. The setting is deprecated and has no effect: the task was removed, and ClickHouse never hides or removes unused directories in `store/` automatically.)", SettingsTierType::OBSOLETE) \ + DECLARE(UInt64, database_catalog_unused_dir_cleanup_period_sec, 24 * 60 * 60, R"(Parameter of the background task that cleaned up garbage from the `store/` directory: the scheduling period of the task. The setting is deprecated and has no effect: the task was removed, and ClickHouse never hides or removes unused directories in `store/` automatically.)", SettingsTierType::OBSOLETE) \ DECLARE(UInt64, database_catalog_drop_error_cooldown_sec, 5, R"(In case of a failed table drop, ClickHouse will wait for this time-out before retrying the operation.)", 0) \ DECLARE(UInt64, database_catalog_drop_table_concurrency, 16, R"(The size of the threadpool used for dropping tables.)", 0) \ \ diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index 560027c5a800..aa1a7986e593 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -2693,6 +2693,22 @@ Possible values: - 0 — The column name is substituted with the alias. - 1 — The column name is not substituted with the alias. +If the column name is ambiguous between joined tables and an alias with the same name exists, the alias is used: + +```sql +SET prefer_column_name_to_alias = 1; +SELECT t1.id + 10 AS id, id AS x +FROM (SELECT 1 AS id) AS t1, (SELECT 1 AS k) AS t2, (SELECT 2 AS id) AS t3; +``` + +```text +┌─id─┬──x─┐ +│ 11 │ 11 │ +└────┴────┘ +``` + +Here `id` in `id AS x` is a column of both `t1` and `t3`, so it resolves to the alias `t1.id + 10`. + **Example** The difference between enabled and disabled: @@ -7232,7 +7248,7 @@ Cloud default value: `1`. Allow new query analyzer. )", IMPORTANT, enable_analyzer) \ DECLARE(Bool, analyzer_compatibility_join_using_top_level_identifier, false, R"( -Force to resolve identifier in JOIN USING from projection (for example, in `SELECT a + 1 AS b FROM t1 JOIN t2 USING (b)` join will be performed by `t1.a + 1 = t2.b`, rather then `t1.b = t2.b`). +Force to resolve identifier in JOIN USING from projection (for example, in `SELECT a + 1 AS b FROM t1 JOIN t2 USING (b)` join will be performed by `t1.a + 1 = t2.b`, rather then `t1.b = t2.b`). In a query with several `JOIN`s only the outermost `JOIN` resolves its `USING` identifier from an alias; an inner `JOIN` resolves it from its left table, as the old analyzer did. )", 0) \ DECLARE(Bool, analyzer_compatibility_allow_compound_identifiers_in_unflatten_nested, true, R"( Allow to add compound identifiers to nested. This is a compatibility setting because it changes the query result. When disabled, `SELECT a.b.c FROM table ARRAY JOIN a` does not work, and `SELECT a FROM table` does not include `a.b.c` column into `Nested a` result. @@ -8462,9 +8478,9 @@ void Settings::write(WriteBuffer & out, SettingsWriteFormat format) const impl->write(out, format); } -void Settings::read(ReadBuffer & in, SettingsWriteFormat format) +void Settings::read(ReadBuffer & in, SettingsWriteFormat format, bool skip_invalid_values) { - impl->read(in, format); + impl->read(in, format, skip_invalid_values); } void Settings::writeEmpty(WriteBuffer & out) diff --git a/src/Core/Settings.h b/src/Core/Settings.h index d0487e7de990..f32c14f55cd7 100644 --- a/src/Core/Settings.h +++ b/src/Core/Settings.h @@ -158,7 +158,7 @@ struct Settings NameToNameMap toNameToNameMap() const; void write(WriteBuffer & out, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT) const; - void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT); + void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT, bool skip_invalid_values = false); /// Equivalent to Settings().write(out, ) but faster. static void writeEmpty(WriteBuffer & out); diff --git a/src/Core/SettingsFields.cpp b/src/Core/SettingsFields.cpp index 14ac68e209ab..ac533bcf9a84 100644 --- a/src/Core/SettingsFields.cpp +++ b/src/Core/SettingsFields.cpp @@ -315,14 +315,14 @@ namespace if (d != 0.0 && !std::isnormal(d)) throw Exception( ErrorCodes::CANNOT_PARSE_NUMBER, "A setting's value in seconds must be a normal floating point number or zero. Got {}", d); -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wimplicit-const-int-float-conversion" - if (d * 1000000 > std::numeric_limits::max() || d * 1000000 < std::numeric_limits::min()) + if (d < 0) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "A setting's value in seconds cannot be negative. Got {}", d); + const Float64 microseconds = d * 1000000; + if (accurate::greaterOp(microseconds, std::numeric_limits::max())) throw Exception( ErrorCodes::BAD_ARGUMENTS, "Cannot convert seconds to microseconds: the setting's value in seconds is too big: {}", d); -#pragma clang diagnostic pop - return static_cast(d * 1000000); + return static_cast(microseconds); } } diff --git a/src/Core/tests/gtest_field.cpp b/src/Core/tests/gtest_field.cpp index 560370bbd0c9..aa495ea93652 100644 --- a/src/Core/tests/gtest_field.cpp +++ b/src/Core/tests/gtest_field.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -9,6 +10,8 @@ namespace DB::ErrorCodes { extern const int TOO_DEEP_RECURSION; extern const int ARGUMENT_OUT_OF_BOUND; + extern const int CANNOT_PARSE_NUMBER; + extern const int DECIMAL_OVERFLOW; } using namespace DB; @@ -210,3 +213,76 @@ GTEST_TEST(Field, RestoreFromDumpDecimalOutOfRangeScaleThrows) Field restored = Field::restoreFromDump("Decimal64_'1e-5'"); ASSERT_EQ(restored.safeGet>().getScale(), 5u); } + +static void expectRestoreFromDumpError(const std::string & dump, int code) +{ + try + { + Field::restoreFromDump(dump); + FAIL() << "expected error " << code << " for " << dump; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), code) << dump; + } +} + +GTEST_TEST(Field, RestoreFromDumpDecimalExtremeExponent) +{ + /// Negating `INT32_MIN` must not be reached. + expectRestoreFromDumpError("Decimal64_'1e-2147483648'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + /// The exponent sum overflows `int32_t` (only digits after the point decrease it). + expectRestoreFromDumpError("Decimal64_'0.1e-2147483648'", ErrorCodes::CANNOT_PARSE_NUMBER); + /// `scaleMultiplier` saturates beyond the precision, so `1 * max` must not be accepted as the value. + expectRestoreFromDumpError("Decimal64_'1e100'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal32_'1e2147483647'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal256_'1e100'", ErrorCodes::DECIMAL_OVERFLOW); + /// No digits at all. + expectRestoreFromDumpError("Decimal64_'.'", ErrorCodes::CANNOT_PARSE_NUMBER); + expectRestoreFromDumpError("Decimal64_'-'", ErrorCodes::CANNOT_PARSE_NUMBER); + expectRestoreFromDumpError("Decimal64_''", ErrorCodes::CANNOT_PARSE_NUMBER); + + /// The largest exponents that fit still work, and zero takes any positive exponent. + ASSERT_EQ(Field::restoreFromDump("Decimal64_'1e18'").safeGet>().getValue(), Decimal64(1000000000000000000LL)); + ASSERT_EQ(Field::restoreFromDump("Decimal64_'1e-18'").safeGet>().getScale(), 18u); + ASSERT_EQ(Field::restoreFromDump("Decimal64_'0e2147483647'").safeGet>().getValue(), Decimal64(0)); +} + +GTEST_TEST(Field, RestoreFromDumpDecimalMantissaOverflow) +{ + /// A mantissa that does not fit the native integer must not wrap (here to zero, skipping the exponent check). + expectRestoreFromDumpError("Decimal32_'4294967296e2147483647'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal64_'18446744073709551616e2147483647'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal32_'2147483648'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal128_'170141183460469231731687303715884105728'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal256_'-57896044618658097711785492504343953926634992332820282019728792003956564819969'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + + /// The exponent must not wrap the wide types either. + expectRestoreFromDumpError("Decimal128_'2e38'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal128_'-18e37'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal256_'6e76'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal256_'-58e75'", ErrorCodes::DECIMAL_OVERFLOW); + ASSERT_EQ(Field::restoreFromDump("Decimal128_'17e37'").safeGet>().getValue(), Decimal128(Int128(17) * DecimalUtils::scaleMultiplier(37))); + ASSERT_EQ(Field::restoreFromDump("Decimal256_'-57e75'").safeGet>().getValue().value, Int256(-57) * DecimalUtils::scaleMultiplier(75)); + + /// The full native range and the scale (trailing zeroes) round-trip through a dump. + auto round_trip = [](const DecimalField & decimal) + { + const String dump = Field(decimal).dump(); + const auto restored = Field::restoreFromDump(dump).safeGet>(); + EXPECT_EQ(restored.getValue(), decimal.getValue()) << dump; + EXPECT_EQ(restored.getScale(), decimal.getScale()) << dump; + }; + round_trip(DecimalField(std::numeric_limits::max(), 0)); + round_trip(DecimalField(std::numeric_limits::min(), 3)); + round_trip(DecimalField(std::numeric_limits::max(), 18)); + round_trip(DecimalField(std::numeric_limits::min(), 0)); + round_trip(DecimalField(std::numeric_limits::max(), 38)); + round_trip(DecimalField(std::numeric_limits::min(), 1)); + round_trip(DecimalField(std::numeric_limits::max(), 0)); + round_trip(DecimalField(std::numeric_limits::min(), 76)); + round_trip(DecimalField(100, 2)); + round_trip(DecimalField(100, 1)); + round_trip(DecimalField(0, 3)); + round_trip(DecimalField(-1000, 18)); +} diff --git a/src/Core/tests/gtest_settings.cpp b/src/Core/tests/gtest_settings.cpp index 21fff5dc25b5..de4508ad0f4f 100644 --- a/src/Core/tests/gtest_settings.cpp +++ b/src/Core/tests/gtest_settings.cpp @@ -15,6 +15,7 @@ #include #include +#include #include namespace DB::ErrorCodes @@ -22,6 +23,9 @@ namespace DB::ErrorCodes extern const int ATTEMPT_TO_READ_AFTER_EOF; extern const int TOO_LARGE_STRING_SIZE; extern const int ARGUMENT_OUT_OF_BOUND; + extern const int BAD_ARGUMENTS; + extern const int CANNOT_PARSE_BOOL; + extern const int UNKNOWN_LOAD_BALANCING; } namespace @@ -337,3 +341,66 @@ GTEST_TEST(Settings, CustomFlaggedDecimalWithOutOfRangeScaleRejected) ASSERT_EQ(e.code(), ErrorCodes::ARGUMENT_OUT_OF_BOUND); } } + +GTEST_TEST(Settings, SkipInvalidValuesKeepsTheDefaultsAndReadsTheRest) +{ + /// The settings a server of an older version sends in `Hello` may hold values this version rejects. + using Entry = std::tuple; + auto wire = [](std::initializer_list entries) + { + WriteBufferFromOwnString out; + for (const auto & [name, flags, value] : entries) + { + BaseSettingsHelpers::writeString(name, out); + BaseSettingsHelpers::writeFlags(flags, out); + BaseSettingsHelpers::writeString(value, out); + } + BaseSettingsHelpers::writeString("", out); /// end of settings + return out.str(); + }; + + auto read_error_code = [](const String & bytes, bool skip_invalid_values) + { + ReadBufferFromString in(bytes); + Settings settings; + try + { + settings.read(in, SettingsWriteFormat::STRINGS_WITH_FLAGS, skip_invalid_values); + } + catch (const Exception & e) + { + return e.code(); + } + return 0; + }; + + const String bytes = wire({ + /// In this version a negative value of a `Seconds` setting is rejected when it is assigned from a `Field`, + /// but not when it is parsed from a string. + {"max_execution_time", {}, "-1"}, + {"max_block_size", {}, "0"}, /// `NonZeroUInt64` assigns the value before it rejects it. + {"log_queries", {}, "maybe"}, + {"max_threads", {}, "4"}, + }); + ReadBufferFromString in(bytes); + Settings settings; + settings.read(in, SettingsWriteFormat::STRINGS_WITH_FLAGS, /* skip_invalid_values= */ true); + const SettingsChanges changes = settings.changes(); + ASSERT_EQ(changes.size(), 1u); + ASSERT_EQ(changes[0].name, "max_threads"); + ASSERT_EQ(changes[0].value, Field(UInt64(4))); + ASSERT_FALSE(settings.isChanged("max_execution_time")); + ASSERT_FALSE(settings.isChanged("max_block_size")); + ASSERT_EQ(settings.get("max_block_size"), Settings().get("max_block_size")); + ASSERT_FALSE(settings.isChanged("log_queries")); + + /// Every change that was read can be applied as a `Field`, which is what the client does with them. + Settings applied; + applied.applyChanges(changes); + + /// The default read stays strict; an important setting and other error codes are not skipped. + ASSERT_EQ(read_error_code(bytes, false), ErrorCodes::BAD_ARGUMENTS); + ASSERT_EQ(read_error_code(wire({{"log_queries", {}, "maybe"}}), false), ErrorCodes::CANNOT_PARSE_BOOL); + ASSERT_EQ(read_error_code(wire({{"max_execution_time", BaseSettingsHelpers::Flags::IMPORTANT, "-1"}}), true), ErrorCodes::BAD_ARGUMENTS); + ASSERT_EQ(read_error_code(wire({{"load_balancing", {}, "nonsense"}}), true), ErrorCodes::UNKNOWN_LOAD_BALANCING); +} diff --git a/src/DataTypes/Serializations/SerializationInfo.cpp b/src/DataTypes/Serializations/SerializationInfo.cpp index cbae0c80aae7..e7f79bfdd14b 100644 --- a/src/DataTypes/Serializations/SerializationInfo.cpp +++ b/src/DataTypes/Serializations/SerializationInfo.cpp @@ -231,12 +231,6 @@ void SerializationInfo::checkKindStack(ISerialization::KindSet allowed_kinds) co for (auto kind : kind_stack) { - if (!allowed_kinds.contains(kind)) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "Unexpected serialization kind {} in the received data", - ISerialization::kindToString(kind)); - expected = std::find(expected, canonical_kind_order.end(), kind); if (expected == canonical_kind_order.end()) throw Exception( @@ -246,6 +240,14 @@ void SerializationInfo::checkKindStack(ISerialization::KindSet allowed_kinds) co ++expected; } + + /// A well-formed stack is checked from the outermost kind, the first one a consumer would have to unwrap. + for (auto it = kind_stack.rbegin(); it != kind_stack.rend(); ++it) + if (!allowed_kinds.contains(*it)) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Unexpected serialization kind {} in the received data", + ISerialization::kindToString(*it)); } void SerializationInfo::deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds) diff --git a/src/DataTypes/Serializations/SerializationInfoTuple.cpp b/src/DataTypes/Serializations/SerializationInfoTuple.cpp index 7807d2d5e846..bc806b1ac9dd 100644 --- a/src/DataTypes/Serializations/SerializationInfoTuple.cpp +++ b/src/DataTypes/Serializations/SerializationInfoTuple.cpp @@ -161,8 +161,9 @@ void SerializationInfoTuple::deserializeFromKindsBinary(ReadBuffer & in, ISerial { SerializationInfo::deserializeFromKindsBinary(in, allowed_kinds); - /// A detached blob always covers a whole column, never a single tuple element. - auto elements_allowed_kinds = allowed_kinds.without(ISerialization::Kind::DETACHED); + /// `Detached` and `Replicated` always wrap a whole column, never a single tuple element: + /// no writer builds such an element, and both are unwrapped only at the top level of a column. + auto elements_allowed_kinds = allowed_kinds.without(ISerialization::Kind::DETACHED).without(ISerialization::Kind::REPLICATED); for (const auto & elem : elems) elem->deserializeFromKindsBinary(in, elements_allowed_kinds); } diff --git a/src/Databases/DatabaseFactory.cpp b/src/Databases/DatabaseFactory.cpp index 4b518dd89080..fa2185afed5e 100644 --- a/src/Databases/DatabaseFactory.cpp +++ b/src/Databases/DatabaseFactory.cpp @@ -59,8 +59,8 @@ void cckMetadataPathForOrdinary(const ASTCreateQuery & create, const String & me /// Between 20.7 and 22.7 metadata/db_name.sql was created in this case as well. /// Since 20.7 `default` database is created with Atomic engine on the very first server run. /// The problem is that if server crashed during the very first run and metadata/db_name/ -> store/whatever symlink was created - /// then it's considered as Ordinary database. And it even works somehow - /// until background task tries to remove unused dir from store/... + /// then it's considered as Ordinary database. And it even worked somehow + /// until the background task (which no longer exists) tried to remove the unused dir from store/... throw Exception(ErrorCodes::CANNOT_CREATE_DATABASE, "Metadata directory {} for Ordinary database {} is a symbolic link to {}. " "It may be a result of manual intervention, crash on very first server start or a bug. " diff --git a/src/Databases/DatabaseFilesystem.cpp b/src/Databases/DatabaseFilesystem.cpp index 6e5e3010d685..34826778564b 100644 --- a/src/Databases/DatabaseFilesystem.cpp +++ b/src/Databases/DatabaseFilesystem.cpp @@ -18,6 +18,8 @@ #include #include #include +#include +#include #include #include @@ -43,6 +45,31 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + +/// Whether `table_path`, already normalized, stays inside `directory`. The `file` table function +/// expands `{a,b}` groups before it walks the filesystem and does not normalize the result, so an +/// alternative carrying a `..` is refused instead of being resolved against a possible symlink. +bool isInsideDirectory(const String & table_path, const String & directory) +{ + if (!containsGlobs(table_path)) + return fileOrSymlinkPathStartsWith(table_path, directory); + + for (const auto & expanded_path : expandSelectionGlob(table_path)) + { + for (const auto & component : fs::path(expanded_path)) + if (component == "..") + return false; + + if (!fileOrSymlinkPathStartsWith(expanded_path, directory)) + return false; + } + return true; +} + +} + DatabaseFilesystem::DatabaseFilesystem( const String & name_, const String & path_, ContextPtr context_, bool is_internal_metadata_replay) : IDatabase(name_), WithContext(context_->getGlobalContext()), path(path_), log(getLogger("DatabaseFileSystem(" + name_ + ")")) @@ -105,6 +132,10 @@ bool DatabaseFilesystem::checkTableFilePath(const std::string & table_path, Cont throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File is not inside {}", user_files_path); } + /// A table of this database is a file under its own directory, not anywhere in `user_files`. + if (check_path && !isInsideDirectory(table_path, path)) + throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File is not inside the database directory {}", path); + if (!containsGlobs(table_path)) { /// Check if the corresponding file exists. diff --git a/src/Databases/DatabaseOnDisk.cpp b/src/Databases/DatabaseOnDisk.cpp index c3e3756181d8..7d2a82ea83e7 100644 --- a/src/Databases/DatabaseOnDisk.cpp +++ b/src/Databases/DatabaseOnDisk.cpp @@ -484,11 +484,9 @@ void DatabaseOnDisk::renameTable( if (auto * target_db = dynamic_cast(&to_database)) target_db->checkMetadataFilenameAvailability(to_table_name); - /// This place is actually quite dangerous. Since data directory is moved to store/ - /// DatabaseCatalog may try to clean it up as unused. We add UUID mapping to avoid this. - /// However, we may fail after data directory move, but before metadata file creation in the destination db. - /// In this case nothing will protect data directory (except 30-days timeout). - /// But this situation (when table in Ordinary database is partially renamed) require manual intervention anyway. + /// The data directory is moved to store/, so the UUID must be marked as used first (see `DatabaseCatalog::addUUIDMapping`). + /// We may fail after data directory move, but before metadata file creation in the destination db. + /// This situation (when table in Ordinary database is partially renamed) requires manual intervention. if (from_ordinary_to_atomic) { DatabaseCatalog::instance().addUUIDMapping(create.uuid); diff --git a/src/Databases/DatabaseOrdinary.cpp b/src/Databases/DatabaseOrdinary.cpp index d7ef12962b2f..27ef012a5fba 100644 --- a/src/Databases/DatabaseOrdinary.cpp +++ b/src/Databases/DatabaseOrdinary.cpp @@ -160,12 +160,20 @@ void DatabaseOrdinary::checkReplicaPathIsSafe(const ASTCreateQuery & create_quer /*validate_substitutions=*/true); } +String DatabaseOrdinary::getConvertedMergeTreeEngineName(const String & engine_name, bool replicated) +{ + if (replicated) + return "Replicated" + engine_name; + chassert(engine_name.starts_with("Replicated")); + return engine_name.substr(strlen("Replicated")); +} + void DatabaseOrdinary::setMergeTreeEngine(ASTCreateQuery & create_query, ContextPtr local_context, bool replicated) { auto * storage = create_query.storage; auto args = make_intrusive(); auto engine = make_intrusive(); - String engine_name; + const String engine_name = getConvertedMergeTreeEngineName(storage->engine->name, replicated); if (replicated) { @@ -182,8 +190,6 @@ void DatabaseOrdinary::setMergeTreeEngine(ASTCreateQuery & create_query, Context for (size_t i = 0; i < storage->engine->arguments->children.size(); ++i) args->children.push_back(storage->engine->arguments->children[i]->clone()); } - - engine_name = "Replicated" + storage->engine->name; } else { @@ -193,8 +199,6 @@ void DatabaseOrdinary::setMergeTreeEngine(ASTCreateQuery & create_query, Context for (size_t i = 2; i < storage->engine->arguments->children.size(); ++i) args->children.push_back(storage->engine->arguments->children[i]->clone()); } - - engine_name = storage->engine->name.substr(strlen("Replicated")); } /// Set new engine for the old query diff --git a/src/Databases/DatabaseOrdinary.h b/src/Databases/DatabaseOrdinary.h index 4360b695a2aa..628d5c13279c 100644 --- a/src/Databases/DatabaseOrdinary.h +++ b/src/Databases/DatabaseOrdinary.h @@ -87,6 +87,10 @@ class DatabaseOrdinary : public DatabaseOnDisk static void setMergeTreeEngine(ASTCreateQuery & create_query, ContextPtr context, bool replicated); + /// The name of the engine that `setMergeTreeEngine` sets for a table of the engine `engine_name`. + /// For `replicated = false`, `engine_name` must start with `Replicated`. + static String getConvertedMergeTreeEngineName(const String & engine_name, bool replicated); + /// Rejects a conversion to a replicated engine whose Keeper path would not be a safe one. /// Contacts nothing and mutates nothing, so a caller can run it before its own side effects. static void checkReplicaPathIsSafe(const ASTCreateQuery & create_query, ContextPtr context); diff --git a/src/Databases/PostgreSQL/fetchPostgreSQLTableStructure.cpp b/src/Databases/PostgreSQL/fetchPostgreSQLTableStructure.cpp index 50dbf8ed4cd8..29a4aac9e4ba 100644 --- a/src/Databases/PostgreSQL/fetchPostgreSQLTableStructure.cpp +++ b/src/Databases/PostgreSQL/fetchPostgreSQLTableStructure.cpp @@ -30,6 +30,29 @@ namespace ErrorCodes extern const int UNKNOWN_TABLE; extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; +} + +namespace +{ + +/// PostgreSQL itself does not allow more than 6 dimensions (MAXDIM). The number comes from the remote server, +/// and each dimension is one more level of `Array`, so refuse absurd values instead of building a type +/// so deep that working with it exhausts the stack. +constexpr Int64 MAX_POSTGRESQL_ARRAY_DIMENSIONS = 100; + +DataTypePtr wrapInArrays(DataTypePtr type, Int64 dimensions) +{ + if (dimensions < 1 || dimensions > MAX_POSTGRESQL_ARRAY_DIMENSIONS) + throw Exception(ErrorCodes::INCORRECT_DATA, + "PostgreSQL array has unsupported number of dimensions: {} (must be from 1 to {})", + dimensions, MAX_POSTGRESQL_ARRAY_DIMENSIONS); + + for (Int64 i = 0; i < dimensions; ++i) + type = std::make_shared(type); + return type; +} + } @@ -156,8 +179,7 @@ static DataTypePtr convertPostgreSQLDataType(String & type, Fn auto && r } else { - while (dimensions--) - res = std::make_shared(res); + res = wrapInArrays(res, dimensions); } } @@ -276,9 +298,7 @@ PostgreSQLTableStructure::ColumnsInfoPtr readNamesAndTypesList( int dimensions = result[0][1].as(); /// It is always 1d array if it is in recheck. - DataTypePtr type = assert_cast(name_and_type.type.get())->getNestedType(); - while (dimensions--) - type = std::make_shared(type); + DataTypePtr type = wrapInArrays(assert_cast(name_and_type.type.get())->getNestedType(), dimensions); columns[i] = NameAndTypePair(name_and_type.name, type); } diff --git a/src/Dictionaries/HTTPDictionarySource.cpp b/src/Dictionaries/HTTPDictionarySource.cpp index acad7babb588..051b21de8bd3 100644 --- a/src/Dictionaries/HTTPDictionarySource.cpp +++ b/src/Dictionaries/HTTPDictionarySource.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -86,9 +87,17 @@ void HTTPDictionarySource::getUpdateFieldAndDate(Poco::URI & uri) } } +void HTTPDictionarySource::checkCredentials() const +{ + /// Per request: a loaded source is kept and cloned across updates, and can change meanwhile. + if (configuration.created_from_ddl) + context->getHTTPHeaderFilter().checkBasicCredentials(credentials); +} + BlockIO HTTPDictionarySource::loadAll() { LOG_TRACE(log, "loadAll {}", toString()); + checkCredentials(); Poco::URI uri(configuration.url); @@ -106,9 +115,12 @@ BlockIO HTTPDictionarySource::loadAll() BlockIO HTTPDictionarySource::loadUpdatedAll() { + checkCredentials(); Poco::URI uri(configuration.url); getUpdateFieldAndDate(uri); - LOG_TRACE(log, "loadUpdatedAll {}", uri.toString()); + String masked_uri = uri.toString(); + maskURICredentials(masked_uri); + LOG_TRACE(log, "loadUpdatedAll {}", masked_uri); auto buf = BuilderRWBufferFromHTTP(uri) .withConnectionGroup(HTTPConnectionGroupType::STORAGE) @@ -126,6 +138,7 @@ BlockIO HTTPDictionarySource::loadUpdatedAll() BlockIO HTTPDictionarySource::loadIds(const VectorWithMemoryTracking & ids) { LOG_TRACE(log, "loadIds {} size = {}", toString(), ids.size()); + checkCredentials(); auto block = blockForIds(dict_struct, ids); @@ -157,6 +170,7 @@ BlockIO HTTPDictionarySource::loadIds(const VectorWithMemoryTracking & i BlockIO HTTPDictionarySource::loadKeys(const Columns & key_columns, const VectorWithMemoryTracking & requested_rows) { LOG_TRACE(log, "loadKeys {} size = {}", toString(), requested_rows.size()); + checkCredentials(); auto block = blockForKeys(dict_struct, key_columns, requested_rows); @@ -207,8 +221,10 @@ DictionarySourcePtr HTTPDictionarySource::clone() const std::string HTTPDictionarySource::toString() const { - Poco::URI uri(configuration.url); - return uri.toString(); + /// Shown in `system.dictionaries` and in the logs. + String uri = Poco::URI(configuration.url).toString(); + maskURICredentials(uri); + return uri; } void registerDictionarySourceHTTP(DictionarySourceFactory & factory) @@ -304,7 +320,8 @@ void registerDictionarySourceHTTP(DictionarySourceFactory & factory) .format = format, .update_field = config.getString(settings_config_prefix + ".update_field", ""), .update_lag = config.getUInt64(settings_config_prefix + ".update_lag", 1), - .header_entries = std::move(header_entries) + .header_entries = std::move(header_entries), + .created_from_ddl = created_from_ddl }; return std::make_unique(dict_struct, configuration, credentials, sample_block, context); diff --git a/src/Dictionaries/HTTPDictionarySource.h b/src/Dictionaries/HTTPDictionarySource.h index b3638051ec24..2a9b845846f6 100644 --- a/src/Dictionaries/HTTPDictionarySource.h +++ b/src/Dictionaries/HTTPDictionarySource.h @@ -31,6 +31,8 @@ class HTTPDictionarySource final : public IDictionarySource const std::string update_field; const UInt64 update_lag; const HTTPHeaderEntries header_entries; + /// Whether the dictionary was created via DDL (`CREATE DICTIONARY`). + const bool created_from_ddl = false; }; HTTPDictionarySource( @@ -64,6 +66,8 @@ class HTTPDictionarySource final : public IDictionarySource private: void getUpdateFieldAndDate(Poco::URI & uri); + void checkCredentials() const; + // wrap buffer using encoding from made request QueryPipeline createWrappedBuffer(std::unique_ptr http_buffer); diff --git a/src/Dictionaries/IDictionary.h b/src/Dictionaries/IDictionary.h index 754037e9d386..dfb2688fe330 100644 --- a/src/Dictionaries/IDictionary.h +++ b/src/Dictionaries/IDictionary.h @@ -97,7 +97,12 @@ class IDictionary : public IExternalLoadable, public IKeyValueEntity std::string getDatabaseOrNoDatabaseTag() const { std::lock_guard lock{mutex}; + return getDatabaseOrNoDatabaseTag(dictionary_id); + } + /// The database name used for access checks of the dictionary with the given ID. + static std::string getDatabaseOrNoDatabaseTag(const StorageID & dictionary_id) + { if (!dictionary_id.database_name.empty()) return dictionary_id.database_name; diff --git a/src/Dictionaries/MongoDBDictionarySource.cpp b/src/Dictionaries/MongoDBDictionarySource.cpp index 21fc0088c6ba..3b9f964193e2 100644 --- a/src/Dictionaries/MongoDBDictionarySource.cpp +++ b/src/Dictionaries/MongoDBDictionarySource.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -210,7 +211,10 @@ BlockIO MongoDBDictionarySource::loadKeys(const Columns & key_columns, const Vec std::string MongoDBDictionarySource::toString() const { - return fmt::format("MongoDB: {}", configuration->uri->to_string()); + /// Shown in `system.dictionaries` and in the logs. + String uri = configuration->uri->to_string(); + maskURIPassword(&uri); + return fmt::format("MongoDB: {}", uri); } #endif diff --git a/src/Disks/DiskEncrypted.cpp b/src/Disks/DiskEncrypted.cpp index 3433b7e9cf8c..f208abeff6ea 100644 --- a/src/Disks/DiskEncrypted.cpp +++ b/src/Disks/DiskEncrypted.cpp @@ -2,6 +2,7 @@ #if USE_SSL #include +#include #include #include #include @@ -13,10 +14,14 @@ #include #include #include + #if CLICKHOUSE_CLOUD #include #endif +#include +#include + namespace DB { @@ -185,6 +190,16 @@ namespace return parseAlgorithmFromString(config.getString(path)); } + void checkCustomDiskPathIsInsideWrappedDisk(const String & path) + { + std::filesystem::path fs_path(path); + if (fs_path.is_absolute() || std::ranges::any_of(fs_path, [](const auto & component) { return component == ".."; })) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Path of the encrypted custom disk must be relative to the wrapped disk and must not contain `..`, but got {}", + quoteString(path)); + } + /// Reads the name of a wrapped disk & the path on the wrapped disk and then finds that disk in a disk map. void getDiskAndPathFromConfig(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, const DisksMap & map, DiskPtr & out_disk, String & out_path) @@ -519,11 +534,24 @@ void registerDiskEncrypted(DiskFactory & factory, bool global_skip_access_check) const String & name, const Poco::Util::AbstractConfiguration & config, const String & config_prefix, - ContextPtr, + ContextPtr context, const DisksMap & map, - bool, bool) -> DiskPtr + bool attach, + bool custom_disk) -> DiskPtr { bool skip_access_check = global_skip_access_check || config.getBool(config_prefix + ".skip_access_check", false); + + if (custom_disk && !attach) + { + DiskPtr wrapped_disk; + String path; + getDiskAndPathFromConfig(config, config_prefix, map, wrapped_disk, path); + + checkCustomDiskPathIsInsideWrappedDisk(path); + if (!wrapped_disk->isRemote()) + checkCustomLocalDiskPath(wrapped_disk->getPath() + path, context); + } + DiskPtr disk = std::make_shared(name, config, config_prefix, map); disk->startup(skip_access_check); return disk; diff --git a/src/Disks/DiskFromAST.cpp b/src/Disks/DiskFromAST.cpp index 44765fb4726d..6c4cb60aa3d4 100644 --- a/src/Disks/DiskFromAST.cpp +++ b/src/Disks/DiskFromAST.cpp @@ -1,11 +1,10 @@ #include +#include +#include #include #include -#include #include #include -#include -#include #include #include #include @@ -17,6 +16,8 @@ #include #include +#include + namespace DB { @@ -93,6 +94,9 @@ std::string getOrCreateCustomDisk( disk_name = DiskSelector::TMP_INTERNAL_DISK_PREFIX + toString(disk_settings_hash); } + if (!attach && (disk_name.empty() || disk_name == "." || disk_name == ".." || disk_name.contains('/'))) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Disk name cannot be empty, `.`, `..` or contain `/` ({})", disk_name); + auto disk = context->getOrCreateDisk(disk_name, [&](const DisksMap & disks_map) -> DiskPtr { auto result = DiskFactory::instance().create( disk_name, *config, /* config_path */"", context, disks_map, /* attach */attach, /* custom_disk */true); @@ -113,24 +117,6 @@ std::string getOrCreateCustomDisk( "The disk `{}` is already configured as a custom disk in another table. It can't be redefined with different settings.", disk_name); - if (!attach && !disk->isRemote() && disk->getName() != "backup") - { - static constexpr auto custom_local_disks_base_dir_in_config = "custom_local_disks_base_directory"; - auto disk_path_expected_prefix = context->getConfigRef().getString(custom_local_disks_base_dir_in_config, ""); - - if (disk_path_expected_prefix.empty()) - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Base path for custom local disks must be defined in config file by `{}`", - custom_local_disks_base_dir_in_config); - - if (!pathStartsWith(disk->getPath(), disk_path_expected_prefix)) - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Path of the custom local disk must be inside `{}` directory", - disk_path_expected_prefix); - } - return disk_name; } diff --git a/src/Disks/DiskLocal.cpp b/src/Disks/DiskLocal.cpp index 878fe1cec4d4..ee716254669a 100644 --- a/src/Disks/DiskLocal.cpp +++ b/src/Disks/DiskLocal.cpp @@ -827,12 +827,16 @@ void registerDiskLocal(DiskFactory & factory, bool global_skip_access_check) const String & config_prefix, ContextPtr context, const DisksMap & map, - bool, bool) -> DiskPtr + bool attach, + bool custom_disk) -> DiskPtr { String path; UInt64 keep_free_space_bytes; loadDiskLocalConfig(name, config, config_prefix, context, path, keep_free_space_bytes); + if (custom_disk && !attach) + checkCustomLocalDiskPath(path, context); + for (const auto & [disk_name, disk_ptr] : map) if (path == disk_ptr->getPath()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Disk {} and disk {} cannot have the same path ({})", name, disk_name, path); diff --git a/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp b/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp index 4afdc245699f..7edc914a97bd 100644 --- a/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp @@ -31,6 +31,7 @@ #include #include #include +#include namespace DB { @@ -451,6 +452,15 @@ time_t DiskObjectStorage::getLastChanged(const String & path) const return metadata_storage->getLastChanged(path); } +bool DiskObjectStorage::isRemote() const +{ + for (const auto & location : cluster->getEnabledLocations()) + if (object_storages->takePointingTo(location)->isRemote()) + return true; + + return metadata_storage->isRemote(); +} + struct stat DiskObjectStorage::stat(const String & path) const { return metadata_storage->stat(path); diff --git a/src/Disks/DiskObjectStorage/DiskObjectStorage.h b/src/Disks/DiskObjectStorage/DiskObjectStorage.h index 747c8cfb794b..f368801ca3ff 100644 --- a/src/Disks/DiskObjectStorage/DiskObjectStorage.h +++ b/src/Disks/DiskObjectStorage/DiskObjectStorage.h @@ -139,7 +139,7 @@ friend class DiskObjectStorageReservation; time_t getLastChanged(const String & path) const override; - bool isRemote() const override { return true; } + bool isRemote() const override; void shutdown() override; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp index f1d1af2ae2c2..45e24f40c8b2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp @@ -169,6 +169,11 @@ bool MetadataStorageFromCacheObjectStorage::isReadOnly() const return underlying->isReadOnly(); } +bool MetadataStorageFromCacheObjectStorage::isRemote() const +{ + return underlying->isRemote(); +} + bool MetadataStorageFromCacheObjectStorage::isTransactional() const { return underlying->isTransactional(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h index 5cc03281bcba..f10cd5378a48 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h @@ -63,6 +63,7 @@ class MetadataStorageFromCacheObjectStorage : public IMetadataStorage std::optional getStorageObjectsIfExist(const std::string & path) const override; bool isReadOnly() const override; + bool isRemote() const override; bool isTransactional() const override; bool isPlain() const override; bool isWriteOnce() const override; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h index e82735548a4b..87ffeca4bde3 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h @@ -273,6 +273,7 @@ class IMetadataStorage : private boost::noncopyable } virtual bool isReadOnly() const = 0; + virtual bool isRemote() const = 0; virtual bool isTransactional() const { diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h b/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h index af562ac5e672..567d78ebf65a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h @@ -86,6 +86,7 @@ class MetadataStorageFromDisk final : public IMetadataStorage DiskObjectStorageMetadataPtr readMetadataUnlocked(const std::string & path, std::shared_lock & lock) const; bool isReadOnly() const override { return disk->isReadOnly(); } + bool isRemote() const override { return disk->isRemote(); } BlobsToRemove getBlobsToRemove(const ClusterConfigurationPtr & cluster, int64_t max_count) override; int64_t recordAsRemoved(const StoredObjects & blobs) override; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp index ce61194091ed..3d224205f95b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include @@ -100,7 +101,8 @@ MetadataStoragePtr MetadataStorageFactory::create( const std::string & config_prefix, const ClusterConfigurationPtr & cluster, const ObjectStorageRouterPtr & object_storages, - const std::string & compatibility_type_hint) const + const std::string & compatibility_type_hint, + bool run_local_paths_check) const { const auto type = getMetadataType(config, config_prefix, compatibility_type_hint); const auto it = registry.find(type); @@ -111,7 +113,7 @@ MetadataStoragePtr MetadataStorageFactory::create( "MetadataStorageFactory: unknown metadata storage type: {}", type); } - return it->second(name, config, config_prefix, cluster, object_storages); + return it->second(name, config, config_prefix, cluster, object_storages, run_local_paths_check); } void registerMetadataStorageFromDisk(MetadataStorageFactory & factory) @@ -121,7 +123,8 @@ void registerMetadataStorageFromDisk(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool run_local_paths_check) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -129,6 +132,9 @@ void registerMetadataStorageFromDisk(MetadataStorageFactory & factory) fs::path(Context::getGlobalContextInstance()->getPath()) / "disks" / name / ""); auto metadata_keep_free_space_bytes = config.getUInt64(config_prefix + ".metadata_keep_free_space_bytes", 0); + if (run_local_paths_check && config.has(config_prefix + ".metadata_path")) + checkCustomLocalDiskPath(metadata_path, Context::getGlobalContextInstance()); + fs::create_directories(metadata_path); const auto db_disk = std::make_shared(name + "-metadata", metadata_path, metadata_keep_free_space_bytes, config, config_prefix); const auto local_object_storage = object_storages->takePointingTo(cluster->getLocalLocation()); @@ -147,7 +153,8 @@ void registerMetadataStorageFromKeeper(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { auto component_guard = Coordination::setCurrentComponent("registerMetadataStorageFromKeeper"); LOG_INFO(getLogger("registerDiskS3"), "Using DiskS3 with metadata keeper"); @@ -173,7 +180,8 @@ void registerPlainMetadataStorage(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -192,7 +200,8 @@ void registerPlainRewritableMetadataStorage(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -210,7 +219,8 @@ void registerMetadataStorageFromStaticFilesWebServer(MetadataStorageFactory & fa const Poco::Util::AbstractConfiguration & /* config */, const std::string & /* config_prefix */, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h index 687394a4357d..9aa72aa4eb74 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h @@ -17,7 +17,8 @@ class MetadataStorageFactory final : private boost::noncopyable const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages)>; + const ObjectStorageRouterPtr & object_storages, + bool run_local_paths_check)>; static MetadataStorageFactory & instance(); @@ -29,7 +30,8 @@ class MetadataStorageFactory final : private boost::noncopyable const std::string & config_prefix, const ClusterConfigurationPtr & cluster, const ObjectStorageRouterPtr & object_storages, - const std::string & compatibility_type_hint) const; + const std::string & compatibility_type_hint, + bool run_local_paths_check) const; static std::string getMetadataType( const Poco::Util::AbstractConfiguration & config, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h index 527cd9e6d8e8..f2c33330abad 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h @@ -48,6 +48,7 @@ class MetadataStorageFromPlainObjectStorage : public IMetadataStorage bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return false; } + bool isRemote() const override { return object_storage->isRemote(); } bool areBlobPathsRandom() const override { return false; } bool isPlain() const override { return true; } bool isWriteOnce() const override { return true; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h index faec0d0fdc93..b4f479f6c745 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h @@ -49,6 +49,7 @@ class MetadataStorageFromPlainRewritableObjectStorage final : public IMetadataSt bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return false; } + bool isRemote() const override { return object_storage->isRemote(); } bool areBlobPathsRandom() const override { return false; } bool isPlain() const override { return true; } bool isWriteOnce() const override { return false; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp index 7bc2a3e32b66..b67c2af415a9 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp @@ -677,11 +677,8 @@ MetadataStorageFromPlainObjectStorageRemoveRecursiveOperation::MetadataStorageFr void MetadataStorageFromPlainObjectStorageRemoveRecursiveOperation::execute() { - /// Unfortunately we are able to create merge tree unlinked from database directory. - /// In this case during the dropAllData method removeRecursive can be called pointing to the root folder. - /// I don't know what to do in this case, so right now it is a no-op. if (normalizePath(path).empty()) - return; + throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't remove root folder"); if (fs_tree->existsDirectory(path).first) { diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h index 5b0cee709647..e02d2651445f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h @@ -56,6 +56,7 @@ class MetadataStorageFromStaticFilesWebServer final : public IMetadataStorage bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return true; } + bool isRemote() const override { return true; } bool areBlobPathsRandom() const override { return false; } }; diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp index 2514e0562e21..8e193288c84f 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp @@ -69,7 +69,8 @@ ObjectStoragePtr ObjectStorageFactory::create( const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool skip_access_check, + bool run_access_check, + bool run_local_paths_check, RemoteHostFilterCheck remote_host_filter_check) const { std::string type; @@ -90,7 +91,7 @@ ObjectStoragePtr ObjectStorageFactory::create( "ObjectStorageFactory: unknown object storage type: {}", type); } - return it->second(name, config, config_prefix, context, skip_access_check, remote_host_filter_check); + return it->second(name, config, config_prefix, context, run_access_check, run_local_paths_check, remote_host_filter_check); } #if USE_AWS_S3 @@ -161,7 +162,8 @@ void registerS3ObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck remote_host_filter_check) -> ObjectStoragePtr { auto uri = getS3URI(config, config_prefix, context); @@ -201,7 +203,8 @@ void registerHDFSObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { auto uri = context->getMacros()->expand(config.getString(config_prefix + ".endpoint")); @@ -225,7 +228,8 @@ void registerAzureObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { auto azure_settings = AzureBlobStorage::getRequestSettings(config, config_prefix, context->getSettingsRef()); @@ -264,7 +268,8 @@ void registerWebObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { auto uri = context->getMacros()->expand(config.getString(config_prefix + ".endpoint")); @@ -292,13 +297,17 @@ void registerLocalObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool run_local_paths_check, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { String object_key_prefix; UInt64 keep_free_space_bytes; loadDiskLocalConfig(name, config, config_prefix, context, object_key_prefix, keep_free_space_bytes); + if (run_local_paths_check) + checkCustomLocalDiskPath(object_key_prefix, context); + /// keys are mapped to the fs, object_key_prefix is a directory also fs::create_directories(object_key_prefix); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h index ace512c91f4c..c4dc7e1dc949 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h +++ b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h @@ -24,7 +24,8 @@ class ObjectStorageFactory final : private boost::noncopyable const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool skip_access_check, + bool run_access_check, + bool run_local_paths_check, RemoteHostFilterCheck remote_host_filter_check)>; static ObjectStorageFactory & instance(); @@ -36,7 +37,8 @@ class ObjectStorageFactory final : private boost::noncopyable const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool skip_access_check, + bool run_access_check, + bool run_local_paths_check, RemoteHostFilterCheck remote_host_filter_check) const; void clearRegistry(); diff --git a/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp b/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp index 6771807555a9..801e58f19e2f 100644 --- a/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp @@ -29,7 +29,8 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch bool attach, bool custom_disk) -> DiskPtr { - const bool skip_access_check = global_skip_access_check || config.getBool(config_prefix + ".skip_access_check", false); + const bool run_access_check = !global_skip_access_check && !config.getBool(config_prefix + ".skip_access_check", false); + const bool run_local_paths_check = custom_disk && !attach; /// Custom disk from a query: a rejection throws. Custom disk loaded from existing metadata (attach: /// server start, UNDROP): a rejection is reported. A user ATTACH, short or with a definition, is not attach here. const auto remote_host_filter_check = !custom_disk ? RemoteHostFilterCheck::None @@ -48,14 +49,14 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch const std::string object_storage_config_prefix = config_prefix + ".locations." + location; const bool local = config.getBool(object_storage_config_prefix + ".local"); const bool enabled = config.getBool(object_storage_config_prefix + ".enabled"); - const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(fmt::format("{}.{}", name, location), config, object_storage_config_prefix, context, /*skip_access_check=*/skip_access_check || !enabled, remote_host_filter_check); + const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(fmt::format("{}.{}", name, location), config, object_storage_config_prefix, context, run_access_check && enabled, run_local_paths_check, remote_host_filter_check); object_storage_registry[location] = object_storage; cluster_registry[location] = {enabled, local, object_storage_config_prefix}; } } else { - const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(name, config, config_prefix, context, skip_access_check, remote_host_filter_check); + const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(name, config, config_prefix, context, run_access_check, run_local_paths_check, remote_host_filter_check); object_storage_registry["main"] = object_storage; cluster_registry["main"] = { .enabled = true, .local = true, .config_prefix = config_prefix }; } @@ -79,7 +80,7 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch } LOG_DEBUG(getLogger("registerDiskObjectStorage"), "Metadata type hint: {}", compatibility_metadata_type_hint); - auto metadata_storage = MetadataStorageFactory::instance().create(name, config, config_prefix, cluster, object_storages, compatibility_metadata_type_hint); + auto metadata_storage = MetadataStorageFactory::instance().create(name, config, config_prefix, cluster, object_storages, compatibility_metadata_type_hint, run_local_paths_check); bool use_fake_transaction = config.getBool(config_prefix + ".use_fake_transaction", metadata_storage->getType() != MetadataStorageType::Keeper); DiskPtr disk = std::make_shared( @@ -100,7 +101,7 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch disk = std::make_shared(disk); } - disk->startup(skip_access_check); + disk->startup(/*skip_access_check=*/!run_access_check); return disk; }; diff --git a/src/Disks/DiskType.cpp b/src/Disks/DiskType.cpp index bf4506b4cbf6..fab5b4b88812 100644 --- a/src/Disks/DiskType.cpp +++ b/src/Disks/DiskType.cpp @@ -1,7 +1,10 @@ #include -#include +#include + #include +#include + namespace DB { namespace ErrorCodes @@ -86,4 +89,13 @@ String DataSourceDescription::toString() const name(), description, is_encrypted, is_cached, zookeeper_name); } +bool isDiskObjectStorage(std::shared_ptr disk) +{ + while (auto delegate_disk = disk->getDelegateDiskIfExists()) + disk = delegate_disk; + + return std::dynamic_pointer_cast(disk) != nullptr; + +} + } diff --git a/src/Disks/DiskType.h b/src/Disks/DiskType.h index 9018cd605481..9c2835fbdd97 100644 --- a/src/Disks/DiskType.h +++ b/src/Disks/DiskType.h @@ -60,4 +60,7 @@ struct DataSourceDescription String toString() const; }; +class IDisk; +bool isDiskObjectStorage(std::shared_ptr disk); + } diff --git a/src/Disks/MetadataStorageWithPathWrapper.h b/src/Disks/MetadataStorageWithPathWrapper.h index 7e9f2876fee6..1352a663e97a 100644 --- a/src/Disks/MetadataStorageWithPathWrapper.h +++ b/src/Disks/MetadataStorageWithPathWrapper.h @@ -275,6 +275,11 @@ class MetadataStorageWithPathWrapper final : public IMetadataStorage return delegate->isReadOnly(); } + bool isRemote() const override + { + return delegate->isRemote(); + } + void updateCache(const std::vector & paths, bool recursive, bool enforce_fresh, std::string * serialized_cache_update_description) override { delegate->updateCache(wrappedPaths(paths), recursive, enforce_fresh, serialized_cache_update_description); diff --git a/src/Disks/ReadOnlyDiskWrapper.h b/src/Disks/ReadOnlyDiskWrapper.h index 2a52dfb21699..3a13e15f0b70 100644 --- a/src/Disks/ReadOnlyDiskWrapper.h +++ b/src/Disks/ReadOnlyDiskWrapper.h @@ -103,6 +103,8 @@ class ReadOnlyDiskWrapper : public IDisk bool supportsChmod() const override { return delegate->supportsChmod(); } void chmod(const String & path, mode_t mode) override { delegate->chmod(path, mode); } + DiskPtr getDelegateDiskIfExists() const override { return delegate; } + bool isReadOnly() const override { return true; } std::unique_ptr writeFile(const String &, size_t, WriteMode, const WriteSettings &) override { throwNotAllowed(); } void moveFile(const String &, const String &) override { throwNotAllowed(); } diff --git a/src/Disks/loadLocalDiskConfig.cpp b/src/Disks/loadLocalDiskConfig.cpp index d3e0bbdf888b..8afdefbb0c7e 100644 --- a/src/Disks/loadLocalDiskConfig.cpp +++ b/src/Disks/loadLocalDiskConfig.cpp @@ -3,6 +3,7 @@ #include #include #include +#include namespace DB { @@ -11,6 +12,7 @@ namespace ErrorCodes { extern const int UNKNOWN_ELEMENT_IN_CONFIG; extern const int EXCESSIVE_ELEMENT_IN_CONFIG; + extern const int BAD_ARGUMENTS; } void loadDiskLocalConfig(const String & name, @@ -61,4 +63,22 @@ void loadDiskLocalConfig(const String & name, } } +void checkCustomLocalDiskPath(const String & path, ContextPtr context) +{ + static constexpr auto custom_local_disks_base_dir_in_config = "custom_local_disks_base_directory"; + auto disk_path_expected_prefix = context->getConfigRef().getString(custom_local_disks_base_dir_in_config, ""); + + if (disk_path_expected_prefix.empty()) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Base path for custom local disks must be defined in config file by `{}`", + custom_local_disks_base_dir_in_config); + + if (!pathStartsWith(path, disk_path_expected_prefix)) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Path of the custom local disk must be inside `{}` directory", + disk_path_expected_prefix); +} + } diff --git a/src/Disks/loadLocalDiskConfig.h b/src/Disks/loadLocalDiskConfig.h index ba1ac5378a4c..7a5ae1a6f83e 100644 --- a/src/Disks/loadLocalDiskConfig.h +++ b/src/Disks/loadLocalDiskConfig.h @@ -6,6 +6,7 @@ namespace Poco::Util { class AbstractConfiguration; } namespace DB { + void loadDiskLocalConfig( const String & name, const Poco::Util::AbstractConfiguration & config, @@ -13,4 +14,7 @@ void loadDiskLocalConfig( ContextPtr context, String & path, UInt64 & keep_free_space_bytes); + +void checkCustomLocalDiskPath(const String & path, ContextPtr context); + } diff --git a/src/Disks/tests/gtest_disk_object_storage.cpp b/src/Disks/tests/gtest_disk_object_storage.cpp index da89958266ef..12971567301c 100644 --- a/src/Disks/tests/gtest_disk_object_storage.cpp +++ b/src/Disks/tests/gtest_disk_object_storage.cpp @@ -220,7 +220,7 @@ class DiskObjectStorageTest : public testing::Test getContext().context, initialized_disks, /*attach*/ false, - /*custom_disk*/ true, + /*custom_disk*/ false, /*skip_types*/ {}); initialized_disks.emplace(name, disk); diff --git a/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp b/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp index b83b39f722a1..3289064e8871 100644 --- a/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp +++ b/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp @@ -837,12 +837,6 @@ TEST_F(MetadataPlainRewritableDiskTest, RemoveRoot) EXPECT_ANY_THROW(tx->commit(DB::NoCommitOptions{})); } - { - auto tx = metadata->createTransaction(); - tx->removeRecursive("/", /*should_remove_blob=*/nullptr); - tx->commit(DB::NoCommitOptions{}); - } - EXPECT_EQ(listAllBlobs("RemoveRecursiveRoot"), std::vector({ "./RemoveRecursiveRoot/__root/A", "./RemoveRecursiveRoot/__root/B" diff --git a/src/Formats/CapnProtoSerializer.cpp b/src/Formats/CapnProtoSerializer.cpp index 0daca1c6e51d..77e635b289ab 100644 --- a/src/Formats/CapnProtoSerializer.cpp +++ b/src/Formats/CapnProtoSerializer.cpp @@ -35,6 +35,7 @@ namespace ErrorCodes extern const int CAPN_PROTO_BAD_CAST; extern const int INCORRECT_DATA; extern const int ILLEGAL_COLUMN; + extern const int SIZES_OF_ARRAYS_DONT_MATCH; } namespace @@ -96,17 +97,38 @@ namespace std::vector> field_builders; }; + /// A group (or a named union) is stored inline in its parent struct: it has no slot and shares the parent's storage. + bool isGroup(const capnp::StructSchema & schema) + { + return schema.getProto().getStruct().getIsGroup(); + } + + UInt32 getFieldSlotOffset(const capnp::StructSchema::Field & field) + { + auto proto = field.getProto(); + return proto.isSlot() ? proto.getSlot().getOffset() : 0; + } + template std::unique_ptr initStructBuilder(ParentBuilder & parent_builder, UInt32 offset_or_index, const capnp::_::StructSize & struct_size, size_t elements, const capnp::StructSchema & schema) { capnp::DynamicStruct::Builder builder_impl; if constexpr (std::is_same_v) - builder_impl = capnp::DynamicStruct::Builder(schema, parent_builder.getBuilderImpl().getPointerField(offset_or_index).initStruct(struct_size)); + { + auto parent_impl = parent_builder.getBuilderImpl(); + builder_impl = capnp::DynamicStruct::Builder(schema, isGroup(schema) ? parent_impl : parent_impl.getPointerField(offset_or_index).initStruct(struct_size)); + } else builder_impl = capnp::DynamicStruct::Builder(schema, parent_builder.getBuilderImpl().getStructElement(offset_or_index)); return std::make_unique(std::move(builder_impl), elements); } + capnp::DynamicStruct::Reader getStructReader(const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset, const capnp::StructSchema & schema) + { + auto parent_impl = parent_struct_reader.getReaderImpl(); + return capnp::DynamicStruct::Reader(schema, isGroup(schema) ? parent_impl : parent_impl.getPointerField(slot_offset).getStruct(nullptr)); + } + class ICapnProtoSerializer { public: @@ -927,15 +949,18 @@ namespace auto first = union_fields[0]; auto second = union_fields[1]; auto nested_type = assert_cast(data_type.get())->getNestedType(); - nested_slot_offset = first.getProto().getSlot().getOffset(); /// Both fields have the same offset. + /// The offset of the value is taken from the non-`Void` member: `Void` always has offset 0, + /// while the value of a union declared inline in a struct can be in any slot of that struct. if (first.getType().isVoid()) { + nested_slot_offset = getFieldSlotOffset(second); nested_serializer = createSerializer(nested_type, column_name, second.getType(), settings); null_discriminant = 0; nested_discriminant = 1; } else if (second.getType().isVoid()) { + nested_slot_offset = getFieldSlotOffset(first); nested_serializer = createSerializer(nested_type, column_name, first.getType(), settings); null_discriminant = 1; nested_discriminant = 0; @@ -961,7 +986,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -983,9 +1008,8 @@ namespace const auto & nullable_column = assert_cast(*column); if (nullable_column.isNullAt(row_num)) { - auto struct_builder_impl = struct_builder.impl.getBuilderImpl(); - struct_builder_impl.setDataField(discriminant_offset, null_discriminant); - struct_builder_impl.setDataField(nested_slot_offset, capnp::Void()); + /// `Void` occupies no space, so only the discriminant is written. + struct_builder.impl.getBuilderImpl().setDataField(discriminant_offset, null_discriminant); } else { @@ -1078,6 +1102,14 @@ namespace field_builder = std::make_unique(capnp::DynamicList::Builder(list_schema, initListBuilder(parent_builder, offset_or_index, size)), size); auto & list_builder = assert_cast(*field_builder); + /// Several columns with flattened names (like `l.x` and `l.y`) write to the same list. + if (list_builder.nested_builders.size() != size) + throw Exception( + ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH, + "Arrays that are written to the same CapnProto list have different sizes: {} and {}", + list_builder.nested_builders.size(), + size); + for (UInt32 i = 0; i != size; ++i) nested_serializer->writeRow(nested_column, list_builder.nested_builders[i], list_builder.impl, i, offset + i); } @@ -1198,7 +1230,7 @@ namespace Names names = {"key", "value"}; auto entries_type = std::make_shared(std::make_shared(types, names)); nested_serializer = createSerializer(entries_type, column_name, field_type, settings); - entries_slot_offset = struct_schema.getFields()[0].getProto().getSlot().getOffset(); + entries_slot_offset = getFieldSlotOffset(struct_schema.getFields()[0]); } void writeRow(const ColumnPtr & column, std::unique_ptr & field_builder, capnp::DynamicStruct::Builder & parent_struct_builder, UInt32 slot_offset, size_t row_num) override @@ -1213,7 +1245,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -1273,6 +1305,7 @@ namespace data_type->getName(), getCapnProtoFullTypeName(capnp_type)); + is_tuple = true; const auto * tuple_data_type = assert_cast(data_type.get()); auto nested_types = tuple_data_type->getElements(); Names nested_names; @@ -1328,7 +1361,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -1363,7 +1396,7 @@ namespace auto capnp_type = field->getType(); fields_serializers.push_back(createSerializer(data_types[i], names[i], capnp_type, settings)); - fields_offsets.push_back(field->getProto().getSlot().getOffset()); + fields_offsets.push_back(getFieldSlotOffset(*field)); fields_indexes.push_back(field->getIndex()); } } @@ -1375,9 +1408,9 @@ namespace field_builder = initStructBuilder(parent_builder, offset_or_index, struct_size, fields_count, struct_schema); auto & struct_builder = assert_cast(*field_builder); - if (const auto * tuple_column = typeid_cast(column.get())) + if (is_tuple) { - const auto & columns = tuple_column->getColumns(); + const auto & columns = assert_cast(*column).getColumns(); for (size_t i = 0; i != columns.size(); ++i) fields_serializers[i]->writeRow(columns[i], struct_builder.field_builders[fields_indexes[i]], struct_builder.impl, fields_offsets[i], row_num); } @@ -1389,8 +1422,9 @@ namespace void readRowImpl(IColumn & column, const capnp::DynamicStruct::Reader & struct_reader) { - if (auto * tuple_column = typeid_cast(&column)) + if (is_tuple) { + auto * tuple_column = assert_cast(&column); auto read_tuple = [&]() { for (size_t i = 0; i != tuple_column->tupleSize(); ++i) @@ -1406,6 +1440,10 @@ namespace capnp::StructSchema struct_schema; capnp::_::StructSize struct_size; size_t fields_count; + /// True if the struct is mapped to a `Tuple` column, one field per tuple element. + /// Otherwise the serializer is the root one or an adapter for a flattened column name (`a.b`) + /// with a single field, which gets the whole column, even if the column itself is a `Tuple`. + bool is_tuple = false; std::vector> fields_serializers; std::vector fields_offsets; std::vector fields_indexes; diff --git a/src/Formats/FormatSchemaInfo.cpp b/src/Formats/FormatSchemaInfo.cpp index aa76491a33d7..d3e4fdc044f5 100644 --- a/src/Formats/FormatSchemaInfo.cpp +++ b/src/Formats/FormatSchemaInfo.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include namespace DB @@ -291,12 +290,8 @@ void FormatSchemaInfo::storeSchemaOnDisk(const fs::path & file_path, const Strin out.sync(); out.close(); - if (fs::exists(file_path)) - DB::renameExchange(temp_path, file_path); - else - DB::renameNoReplace(temp_path, file_path); - - fs::remove(temp_path); + /// `rename` replaces the target atomically, so a concurrent writer of the same schema cannot make it fail. + fs::rename(temp_path, file_path); } catch (...) { diff --git a/src/Formats/JSONExtractTree.cpp b/src/Formats/JSONExtractTree.cpp index 4dc4a33a4ce1..8bac3f5adf32 100644 --- a/src/Formats/JSONExtractTree.cpp +++ b/src/Formats/JSONExtractTree.cpp @@ -1748,10 +1748,9 @@ class DynamicNode : public JSONExtractTreeNode return DataTypeFactory::instance().get("Bool"); case ElementType::INT64: { - auto type = std::make_shared(); if (element.getInt64() < 0) - json_inference_info.negative_integers.insert(type.get()); - return type; + return json_inference_info.getNegativeInt64(); + return std::make_shared(); } case ElementType::UINT64: return std::make_shared(); @@ -1767,10 +1766,7 @@ class DynamicNode : public JSONExtractTreeNode if (format_settings.json.try_infer_numbers_from_strings) { if (auto type = tryInferJSONNumberFromString(data, format_settings, &json_inference_info)) - { - json_inference_info.numbers_parsed_from_json_strings.insert(type.get()); - return type; - } + return json_inference_info.getNumberParsedFromString(type); } return std::make_shared(); diff --git a/src/Formats/NativeReader.cpp b/src/Formats/NativeReader.cpp index 4d632c9da7b3..be3bb22d92d5 100644 --- a/src/Formats/NativeReader.cpp +++ b/src/Formats/NativeReader.cpp @@ -50,12 +50,14 @@ NativeReader::NativeReader( const Block & header_, UInt64 server_revision_, std::optional format_settings_, - BlockMissingValues * block_missing_values_) + BlockMissingValues * block_missing_values_, + ISerialization::KindSet allowed_kinds_) : istr(istr_) , header(header_) , server_revision(server_revision_) , format_settings(std::move(format_settings_)) , block_missing_values(block_missing_values_) + , allowed_kinds(allowed_kinds_) { } diff --git a/src/Formats/NativeReader.h b/src/Formats/NativeReader.h index ab82d68ee5b0..546da2c94cf5 100644 --- a/src/Formats/NativeReader.h +++ b/src/Formats/NativeReader.h @@ -45,7 +45,8 @@ class NativeReader const Block & header_, UInt64 server_revision_, std::optional format_settings_ = std::nullopt, - BlockMissingValues * block_missing_values_ = nullptr); + BlockMissingValues * block_missing_values_ = nullptr, + ISerialization::KindSet allowed_kinds_ = default_allowed_kinds); /// For cases when we have an index. It allows to skip columns. Only columns specified in the index will be read. NativeReader(ReadBuffer & istr_, UInt64 server_revision_, diff --git a/src/Formats/SchemaInferenceUtils.cpp b/src/Formats/SchemaInferenceUtils.cpp index 276af29a8e8e..4e12886389ed 100644 --- a/src/Formats/SchemaInferenceUtils.cpp +++ b/src/Formats/SchemaInferenceUtils.cpp @@ -35,6 +35,7 @@ namespace ErrorCodes extern const int NOT_IMPLEMENTED; extern const int INCORRECT_DATA; extern const int ONLY_NULLS_WHILE_READING_SCHEMA; + extern const int LOGICAL_ERROR; } namespace @@ -274,10 +275,16 @@ namespace { if (WhichDataType(type).isInt64()) { - bool is_negative = json_info && json_info->negative_integers.contains(type.get()); + bool is_negative = json_info && json_info->isNegativeInteger(*type); have_negative_integers |= is_negative; if (!is_negative) - type = std::make_shared(); + { + auto new_type = std::make_shared(); + if (json_info && json_info->isNumberParsedFromString(*type)) + type = json_info->getNumberParsedFromString(new_type); + else + type = new_type; + } } } @@ -299,9 +306,10 @@ namespace if (which.isInt64() || which.isUInt64()) { auto new_type = std::make_shared(); - if (json_info && json_info->numbers_parsed_from_json_strings.erase(type.get())) - json_info->numbers_parsed_from_json_strings.insert(new_type.get()); - type = new_type; + if (json_info && json_info->isNumberParsedFromString(*type)) + type = json_info->getNumberParsedFromString(new_type); + else + type = new_type; } } @@ -392,7 +400,7 @@ namespace { if (isNumber(type) && (settings.json.read_numbers_as_strings || !json_info - || json_info->numbers_parsed_from_json_strings.contains(type.get()))) + || json_info->isNumberParsedFromString(*type))) type = std::make_shared(); } @@ -1043,10 +1051,9 @@ namespace buf.position() = number_start; if (tryReadIntText(tmp_int, buf)) { - auto type = std::make_shared(); if (json_info && tmp_int < 0) - json_info->negative_integers.insert(type.get()); - return type; + return json_info->getNegativeInt64(); + return std::make_shared(); } /// In case of Int64 overflow we can try to infer UInt64. @@ -1071,10 +1078,9 @@ namespace Int64 tmp_int; if (tryReadIntText(tmp_int, peekable_buf)) { - auto type = std::make_shared(); if (json_info && tmp_int < 0) - json_info->negative_integers.insert(type.get()); - return type; + return json_info->getNegativeInt64(); + return std::make_shared(); } peekable_buf.rollbackToCheckpoint(/* drop= */ true); @@ -1102,10 +1108,9 @@ namespace Int64 tmp_int; if (tryReadIntText(tmp_int, buf) && buf.eof()) { - auto type = std::make_shared(); if (json_inference_info && tmp_int < 0) - json_inference_info->negative_integers.insert(type.get()); - return type; + return json_inference_info->getNegativeInt64(); + return std::make_shared(); } /// We can safely get back to the start of buffer, because we read from a string and we didn't reach eof. @@ -1158,10 +1163,7 @@ namespace if (settings.json.try_infer_numbers_from_strings) { if (auto number_type = tryInferNumberFromStringImpl(field, settings, json_info)) - { - json_info->numbers_parsed_from_json_strings.insert(number_type.get()); - return number_type; - } + return json_info->getNumberParsedFromString(number_type); } } @@ -1404,6 +1406,42 @@ namespace /// Number return tryInferNumber(buf, settings, json_info); } + + template + DataTypePtr getOrCreate(DataTypePtr & instance) + { + if (!instance) + instance = std::make_shared(); + return instance; + } +} + +DataTypePtr JSONInferenceInfo::getNegativeInt64() +{ + return getOrCreate(negative_int64); +} + +DataTypePtr JSONInferenceInfo::getNumberParsedFromString(const DataTypePtr & number_type) +{ + WhichDataType which(number_type); + if (which.isInt64()) + return getOrCreate(isNegativeInteger(*number_type) ? negative_int64_from_string : int64_from_string); + if (which.isUInt64()) + return getOrCreate(uint64_from_string); + if (which.isFloat64()) + return getOrCreate(float64_from_string); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected type {} of a number parsed from a string", number_type->getName()); +} + +bool JSONInferenceInfo::isNegativeInteger(const IDataType & type) const +{ + return &type == negative_int64.get() || &type == negative_int64_from_string.get(); +} + +bool JSONInferenceInfo::isNumberParsedFromString(const IDataType & type) const +{ + return &type == int64_from_string.get() || &type == negative_int64_from_string.get() || &type == uint64_from_string.get() + || &type == float64_from_string.get(); } bool canBeInsideNullableBySchemaSettings(const DataTypePtr & type, const FormatSettings & settings) diff --git a/src/Formats/SchemaInferenceUtils.h b/src/Formats/SchemaInferenceUtils.h index 83151305f104..2700297e5ba9 100644 --- a/src/Formats/SchemaInferenceUtils.h +++ b/src/Formats/SchemaInferenceUtils.h @@ -17,13 +17,13 @@ using NamesAndTypesLists = std::vector; /// Struct with some additional information about inferred types for JSON formats. struct JSONInferenceInfo { - /// We store numbers that were parsed from strings. - /// It's used in types transformation to change such numbers back to string if needed. - std::unordered_set numbers_parsed_from_json_strings; - /// Store integer types that were inferred from negative numbers. - /// It's used to determine common type for Int64 and UInt64 - /// TODO: check it not only in JSON formats. - std::unordered_set negative_integers; + /// Int64 inferred from a negative number and numbers parsed from JSON strings are marked by being one of + /// the instances owned below. + DataTypePtr getNegativeInt64(); + /// number_type is Int64, UInt64 or Float64. + DataTypePtr getNumberParsedFromString(const DataTypePtr & number_type); + [[nodiscard]] bool isNegativeInteger(const IDataType & type) const; + [[nodiscard]] bool isNumberParsedFromString(const IDataType & type) const; /// Indicates if currently we are inferring type for Map/Object key. bool is_object_key = false; @@ -32,6 +32,13 @@ struct JSONInferenceInfo /// because DataTypeJSONPaths was already finalized to named tuple. IN this case /// we can only merge named tuples from different files together. bool allow_merging_named_tuples = false; + +private: + DataTypePtr negative_int64; + DataTypePtr int64_from_string; + DataTypePtr negative_int64_from_string; + DataTypePtr uint64_from_string; + DataTypePtr float64_from_string; }; /// Check whether a type can be wrapped into Nullable according to schema inference settings. diff --git a/src/Functions/FunctionsExternalDictionaries.h b/src/Functions/FunctionsExternalDictionaries.h index 540987259a61..cac2cac0dcea 100644 --- a/src/Functions/FunctionsExternalDictionaries.h +++ b/src/Functions/FunctionsExternalDictionaries.h @@ -72,15 +72,10 @@ class FunctionDictHelper std::shared_ptr getDictionary(const String & dictionary_name) { - auto dict = context->getExternalDictionariesLoader().getDictionary(dictionary_name, context); - - if (!access_checked) - { - context->checkAccess(AccessType::dictGet, dict->getDatabaseOrNoDatabaseTag(), dict->getDictionaryID().getTableName()); - access_checked = true; - } - - return dict; + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and load the dictionary that passed the check. + const auto & external_loader = context->getExternalDictionariesLoader(); + return external_loader.getDictionary(external_loader.resolveDictionaryCheckingAccess(dictionary_name, context), context); } std::shared_ptr getDictionary(const ColumnPtr & column) @@ -140,17 +135,16 @@ class FunctionDictHelper return getDictionary(dictionary_name)->isInjective(attribute_name); } - DictionaryStructure getDictionaryStructure(const String & dictionary_name) const + DictionaryStructure getDictionaryStructure(const String & dictionary_name) { - return context->getExternalDictionariesLoader().getDictionaryStructure(dictionary_name, context); + /// Check access before reading the definition, so that a user without access learns nothing about the dictionary. + const auto & external_loader = context->getExternalDictionariesLoader(); + return external_loader.getDictionaryStructure(external_loader.resolveDictionaryCheckingAccess(dictionary_name, context)); } const ContextPtr context; private: - /// Access cannot be not granted, since in this case checkAccess() will throw and access_checked will not be updated. - std::atomic access_checked = false; - /// We must not cache dictionary or dictionary's structure here, because there are places /// where ExpressionActionsPtr is cached (StorageDistributed caching it for sharding_key_expr and /// optimize_skip_unused_shards), and if the dictionary will be cached within "query" then diff --git a/src/IO/Archives/ZipArchiveReader.cpp b/src/IO/Archives/ZipArchiveReader.cpp index e9fa97cc2099..9ce05eb6fbf3 100644 --- a/src/IO/Archives/ZipArchiveReader.cpp +++ b/src/IO/Archives/ZipArchiveReader.cpp @@ -134,6 +134,10 @@ namespace { if (strm.at_end) return 0; + /// minizip computes the size as `int32_t` from sizes stored in the archive, and a negative one + /// arrives here converted to a huge number. + if (size > static_cast(std::numeric_limits::max())) // NOLINT(google-runtime-int) + throw Exception(ErrorCodes::CANNOT_UNPACK_ARCHIVE, "Invalid size of a read from a zip archive: {}", size); return strm.read_buffer->read(reinterpret_cast(buf), size); } catch (...) diff --git a/src/IO/WriteHelpers.h b/src/IO/WriteHelpers.h index fcb3b0d01f1c..e49df563dcdc 100644 --- a/src/IO/WriteHelpers.h +++ b/src/IO/WriteHelpers.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +32,11 @@ namespace DB { +namespace ErrorCodes +{ + extern const int ARGUMENT_OUT_OF_BOUND; +} + class Exception; /// Helper functions for formatted and binary output. @@ -1294,6 +1300,17 @@ template void writeText(Decimal x, UInt32 scale, WriteBuffer & ostr, bool trailing_zeros = false, bool fixed_fractional_length = false, UInt32 fractional_length = 0) { + /// The scale of a `DecimalField` is not tied to a data type, so check it in the release build before any + /// arithmetic that depends on it: a scale wider than the type overflows `scaleMultiplier` and the rounding + /// in `writeDecimalFractional`, and a scale of 2^31 or more becomes a negative exponent, which gives a + /// division by zero. + constexpr size_t max_scale = DecimalUtils::max_precision>; + constexpr size_t max_fractional_length = std::numeric_limits::digits10; + if (scale > max_scale || fractional_length > max_fractional_length) [[unlikely]] + throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, + "Cannot write a decimal with scale {} and {} fractional digits: the maximum scale is {} and at most {} fractional digits are supported", + scale, fractional_length, max_scale, max_fractional_length); + T part = DecimalUtils::getWholePart(x, scale); if (x.value < 0 && part == 0) diff --git a/src/IO/readDecimalText.h b/src/IO/readDecimalText.h index 5cda5ea5a7cb..6a399e072bca 100644 --- a/src/IO/readDecimalText.h +++ b/src/IO/readDecimalText.h @@ -1,8 +1,9 @@ #pragma once #include -#include #include +#include +#include #include @@ -15,12 +16,37 @@ namespace ErrorCodes extern const int ARGUMENT_OUT_OF_BOUND; } +/// Sets `x = x * 10^power + addend` and returns false if the result does not fit `N`. `addend` must be zero or +/// have the sign of `x`, or `x` must be zero. Exact for the wide integer types too, unlike `common::mulOverflow`, +/// which never reports overflow for them. +template +inline bool mulPow10AddChecked(N & x, uint32_t power, N addend) +{ + if (x == 0) + { + x = addend; + return true; + } + /// A nonzero `x` times `10^(digits10 + 1)` does not fit. + if (power > static_cast(std::numeric_limits::digits10)) + return false; + const N multiplier = intExp10OfSize(static_cast(power)); + if (x > 0 ? x > (std::numeric_limits::max() - addend) / multiplier + : x < (std::numeric_limits::min() - addend) / multiplier) + return false; + x = x * multiplier + addend; + return true; +} + /// Try to read Decimal into underlying type T from ReadBuffer. Throws if 'digits_only' is set and there's unexpected symbol in input. /// Returns integer 'exponent' factor that x should be multiplied by to get correct Decimal value: result = x * 10^exponent. /// Use 'digits' input as max allowed meaning decimal digits in result. Place actual number of meaning digits in 'digits' output. /// Does not care about decimal scale, only about meaningful digits in decimal text representation. +/// When 'has_digits' is provided, it is set to whether at least one digit character was read. This lets a +/// caller with 'digits_only = false' tell a real number (including a bare zero) apart from a token with no +/// digits at all, such as ".", "-" or "e9", which is otherwise consumed as zero. template -inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exponent, bool digits_only = false) +inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exponent, bool digits_only = false, bool * has_digits = nullptr) { x = T(0); exponent = 0; @@ -28,9 +54,15 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp digits = 0; uint32_t places = 0; typename T::NativeType sign = 1; + /// When more digits are allowed than the native integer always holds (`Field` dumps allow any number), the + /// mantissa is accumulated with its sign and checked, so it does not wrap and keeps the full native range. + const bool check_overflow = max_digits > static_cast(std::numeric_limits::digits10); bool leading_zeroes = true; bool after_point = false; + if (has_digits) + *has_digits = false; + if (buf.eof()) { if constexpr (_throw_on_error) @@ -52,6 +84,8 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp while (!buf.eof() && !stop) { const char & byte = *buf.position(); + if (has_digits && byte >= '0' && byte <= '9') + *has_digits = true; switch (byte) { case '.': @@ -105,11 +139,21 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp if (after_point) exponent -= places; - // TODO: accurate shift10 for big integers - x *= intExp10OfSize(places); + if (check_overflow) + { + if (!mulPow10AddChecked(x.value, places, sign * static_cast(byte - '0'))) + { + if constexpr (_throw_on_error) + throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal value does not fit its native integer type"); + return false; + } + } + else + { + x *= intExp10OfSize(places); + x += (byte - '0'); + } places = 0; - - x += (byte - '0'); break; } case 'e': [[fallthrough]]; @@ -124,7 +168,14 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp else return false; } - exponent += addition_exp; + /// The exponent comes from the text, so the sum can be anything, e.g. `0.1e-2147483648`. + if (common::addOverflow(exponent, addition_exp, exponent)) + { + if constexpr (_throw_on_error) + throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Exponent is out of range while reading decimal"); + else + return false; + } stop = true; continue; } @@ -142,23 +193,25 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp ++buf.position(); } - x *= sign; + if (!check_overflow) + x *= sign; return true; } template -inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, uint32_t & scale, bool digits_only = false) +inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, uint32_t & scale, bool digits_only = false, bool * has_digits = nullptr) { static constexpr bool throw_exception = std::is_same_v; uint32_t digits = precision; - int32_t exponent; - auto ok = readDigits(buf, x, digits, exponent, digits_only); + int32_t exponent = 0; + auto ok = readDigits(buf, x, digits, exponent, digits_only, has_digits); if (!throw_exception && !ok) return ReturnType(false); - if (static_cast(digits) + exponent > static_cast(precision - scale)) + /// Compute in 64 bits: the exponent can be close to the `int32_t` limits. + if (static_cast(digits) + exponent > static_cast(precision) - static_cast(scale)) { if constexpr (throw_exception) { @@ -170,9 +223,9 @@ inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, u return ReturnType(false); } - if (static_cast(scale) + exponent < 0) + if (static_cast(scale) + exponent < 0) { - auto divisor_exp = -exponent - static_cast(scale); + int64_t divisor_exp = -static_cast(exponent) - static_cast(scale); if (divisor_exp >= std::numeric_limits::digits10) { @@ -183,8 +236,8 @@ inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, u } /// Too many digits after point. Just cut off excessive digits. - auto divisor = intExp10OfSize(divisor_exp); - assert(divisor > 0); /// This is for Clang Static Analyzer. It is not smart enough to infer it automatically. + auto divisor = intExp10OfSize(static_cast(divisor_exp)); + chassert(divisor > 0); /// This is for Clang Static Analyzer. It is not smart enough to infer it automatically. x.value /= divisor; /// NOLINT(clang-analyzer-core.DivideZero) scale = 0; return ReturnType(true); diff --git a/src/IO/tests/gtest_WriteHelpers.cpp b/src/IO/tests/gtest_WriteHelpers.cpp index b3c7062be580..7319180f78cd 100644 --- a/src/IO/tests/gtest_WriteHelpers.cpp +++ b/src/IO/tests/gtest_WriteHelpers.cpp @@ -3,6 +3,9 @@ #include #include #include +#include +#include +#include using namespace DB; @@ -30,3 +33,64 @@ TEST(WriteHelpersTest, ToStringWithFinalSeparatorTest) EXPECT_EQ(toStringWithFinalSeparator(v, " or "), "'AAA', 'BBB', 'CCC' or 'DDD'"); } } + + +template +static void expectDecimalTextThrows(UInt32 scale, bool fixed_fractional_length = false, UInt32 fractional_length = 0) +{ + WriteBufferFromOwnString buf; + try + { + writeText(Decimal(1), scale, buf, false, fixed_fractional_length, fractional_length); + FAIL() << "expected ARGUMENT_OUT_OF_BOUND for scale " << scale << ", fractional length " << fractional_length; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::ARGUMENT_OUT_OF_BOUND); + } +} + +template +static std::string decimalText(T value, UInt32 scale, bool fixed_fractional_length = false, UInt32 fractional_length = 0) +{ + WriteBufferFromOwnString buf; + writeText(Decimal(value), scale, buf, false, fixed_fractional_length, fractional_length); + return buf.str(); +} + +template +static void checkDecimalScaleBoundary() +{ + constexpr UInt32 max_scale = DecimalUtils::max_precision>; + expectDecimalTextThrows(max_scale + 1); + /// Rounding to fewer fractional digits multiplies by a power of ten that depends on the scale. + expectDecimalTextThrows(max_scale + 1, true, 0); + EXPECT_NO_THROW(decimalText(1, max_scale)); + EXPECT_NO_THROW(decimalText(1, max_scale, true, 0)); +} + +/// A `DecimalField` does not validate its scale, and `FieldVisitorToString` formats it with `writeText`. +/// A scale of 2^31 or more used to reach a division by zero in `DecimalUtils::getWholePart`, +/// and a scale wider than the type overflowed the rounding arithmetic. +TEST(WriteHelpersTest, DecimalTextOutOfRangeScaleThrows) +{ + for (UInt32 scale : {77u, 0x80000000u, 0xffffffffu}) + { + expectDecimalTextThrows(scale); + expectDecimalTextThrows(scale); + expectDecimalTextThrows(scale); + expectDecimalTextThrows(scale); + } + expectDecimalTextThrows(0x80000000u, true, 2); + + checkDecimalScaleBoundary(); + checkDecimalScaleBoundary(); + checkDecimalScaleBoundary(); + checkDecimalScaleBoundary(); + + /// 77 fractional digits are supported (`toDecimalString` accepts them), 78 are not. + expectDecimalTextThrows(2, true, 78); + EXPECT_EQ(decimalText(12345, 2, true, 77), "123.45" + std::string(75, '0')); + + EXPECT_EQ(decimalText(12345, 2), "123.45"); +} diff --git a/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp b/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp index cec66bc8ce5d..4df18ccb520c 100644 --- a/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp @@ -129,10 +129,12 @@ BlockIO InterpreterCreateQuotaQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp b/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp index 7c0262df363f..ea1d81e02154 100644 --- a/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp @@ -96,10 +96,12 @@ BlockIO InterpreterCreateRoleQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp index 51442059b01f..633d3eb0d38a 100644 --- a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp @@ -57,9 +57,13 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() auto & query = updated_query_ptr->as(); auto required_access = getRequiredAccess(); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) { query.replaceCurrentUserTag(getContext()->getUserName()); + required_access.replaceEmptyDatabase(getContext()->getCurrentDatabase()); DDLQueryOnClusterParams params; params.access_to_check = std::move(required_access); return executeDDLQueryOnCluster(updated_query_ptr, getContext(), params); @@ -69,8 +73,6 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(required_access); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - std::optional roles_from_query; if (query.roles) roles_from_query = RolesOrUsersSet{*query.roles, access_control, getContext()->getUserID()}; @@ -96,10 +98,12 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() if (query.if_exists) { auto ids = storage->find(names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(names), update_func); + access_control.update(storage->getIDs(names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp b/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp index 61a6f66a3113..73f9b173a426 100644 --- a/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp @@ -107,10 +107,12 @@ BlockIO InterpreterCreateSettingsProfileQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateUserQuery.cpp b/src/Interpreters/Access/InterpreterCreateUserQuery.cpp index 82184d0cf54c..043d488f5a8e 100644 --- a/src/Interpreters/Access/InterpreterCreateUserQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateUserQuery.cpp @@ -303,10 +303,12 @@ BlockIO InterpreterCreateUserQuery::execute() if (query.if_exists) { auto ids = storage->find(names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(names), update_func); + access_control.update(storage->getIDs(names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp b/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp index 9763dedcef49..27d2746c9c67 100644 --- a/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp +++ b/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp @@ -28,11 +28,12 @@ BlockIO InterpreterDropAccessEntityQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(getRequiredAccess()); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) return executeDDLQueryOnCluster(updated_query_ptr, getContext()); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - auto do_drop = [&](const Strings & names, const String & storage_name) { IAccessStorage * storage = &access_control; diff --git a/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp b/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp index dffa03b2eee8..951a4efe6b3e 100644 --- a/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp +++ b/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp @@ -23,11 +23,12 @@ BlockIO InterpreterMoveAccessEntityQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(getRequiredAccess()); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) return executeDDLQueryOnCluster(query_ptr, getContext()); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - std::vector ids; if (query.type == AccessEntityType::ROW_POLICY) ids = access_control.getIDs(query.type, query.row_policy_names->toStrings()); diff --git a/src/Interpreters/Access/InterpreterSetRoleQuery.cpp b/src/Interpreters/Access/InterpreterSetRoleQuery.cpp index e175282ff202..252ca3e991e9 100644 --- a/src/Interpreters/Access/InterpreterSetRoleQuery.cpp +++ b/src/Interpreters/Access/InterpreterSetRoleQuery.cpp @@ -23,6 +23,26 @@ namespace ErrorCodes } +namespace +{ + +/// `readonly` is read from the query context: a client `--readonly 1` raises it there only, while a +/// mid-session `SET readonly = 1` also reaches it because a query context inherits session settings. +void throwIfReadonlyRestrictsSetRole(const ContextPtr & context, std::string_view statement) +{ + if (context->getAccessControl().doesReadonlyRestrictSetRole() && context->getSettingsRef()[Setting::readonly]) + { + throw Exception( + ErrorCodes::READONLY, + "Cannot execute {} in readonly mode. " + "This restriction is enabled by access_control_improvements.readonly_restricts_set_role", + statement); + } +} + +} + + BlockIO InterpreterSetRoleQuery::execute() { const auto & query = query_ptr->as(); @@ -38,14 +58,7 @@ void InterpreterSetRoleQuery::setRole(const ASTSetRoleQuery & query) { auto session_context = getContext()->getSessionContext(); - /// `readonly` is read from the query context: a client `--readonly 1` raises it there only, while a - /// mid-session `SET readonly = 1` also reaches it because a query context inherits session settings. - if (getContext()->getAccessControl().doesReadonlyRestrictSetRole() - && getContext()->getSettingsRef()[Setting::readonly]) - throw Exception( - ErrorCodes::READONLY, - "Cannot execute SET ROLE in readonly mode. " - "This restriction is enabled by access_control_improvements.readonly_restricts_set_role"); + throwIfReadonlyRestrictsSetRole(getContext(), "SET ROLE"); if (query.kind == ASTSetRoleQuery::Kind::SET_ROLE_DEFAULT) session_context->setCurrentRolesDefault(); @@ -56,6 +69,11 @@ void InterpreterSetRoleQuery::setRole(const ASTSetRoleQuery & query) void InterpreterSetRoleQuery::setDefaultRole(const ASTSetRoleQuery & query) { + /// The default roles are what the next session of the user starts with, so changing them is a way around the + /// restriction of `SET ROLE` if it is not restricted as well. The access check below does not catch it for the + /// user's own default roles: `TO CURRENT_USER` requires no grant, so `readonly` has nothing to deny there. + throwIfReadonlyRestrictsSetRole(getContext(), "SET DEFAULT ROLE"); + getContext()->checkAccess(query.to_users->collectRequiredGrants(AccessType::ALTER_USER)); auto & access_control = getContext()->getAccessControl(); diff --git a/src/Interpreters/AggregateDescription.cpp b/src/Interpreters/AggregateDescription.cpp index 91b0f5c33ab6..5371e806240b 100644 --- a/src/Interpreters/AggregateDescription.cpp +++ b/src/Interpreters/AggregateDescription.cpp @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include #include #include @@ -14,6 +17,7 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; } void AggregateDescription::explain(WriteBuffer & out, const std::string & prefix, size_t additonal_indent) const @@ -203,4 +207,130 @@ void deserializeAggregateDescriptions(AggregateDescriptions & aggregates, ReadBu } +void checkDeserializedAggregateArguments(const AggregateDescriptions & aggregates, const Block & header) +{ + for (const auto & aggregate : aggregates) + { + /// `AggregateFunctionFactory` resolves functions for the types without `LowCardinality`, + /// and the `Aggregator` removes it from the argument columns accordingly. + const auto & argument_types = aggregate.function->getArgumentTypes(); + if (argument_types.size() != aggregate.argument_names.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Aggregate function {} of a deserialized query plan step has {} argument types for {} arguments", + aggregate.column_name, argument_types.size(), aggregate.argument_names.size()); + + for (size_t i = 0; i < argument_types.size(); ++i) + { + const auto & name = aggregate.argument_names[i]; + const auto * column = header.findByName(name); + if (!column) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Argument {} of aggregate function {} is not in the input of a deserialized query plan step", + name, aggregate.column_name); + + if (!recursiveRemoveLowCardinality(column->type)->equals(*recursiveRemoveLowCardinality(argument_types[i]))) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Argument {} of aggregate function {} has type {} in the input of a deserialized query plan step, " + "but the function is resolved for {}", + name, aggregate.column_name, column->type->getName(), argument_types[i]->getName()); + } + } +} + +void checkDeserializedFinalizedAggregates(const AggregateDescriptions & aggregates, const Block & header) +{ + for (const auto & aggregate : aggregates) + { + const auto * column = header.findByName(aggregate.column_name); + if (!column) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} is not in the input of a deserialized query plan step", + aggregate.column_name); + + const auto * state_type = typeid_cast(column->type.get()); + if (!state_type || !state_type->getFunction()->haveSameStateRepresentation(*aggregate.function)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} has type {} in the input of a deserialized query plan step, " + "which is not a state of {}", + aggregate.column_name, column->type->getName(), aggregate.function->getName()); + } +} + +void checkDeserializedAggregateOutputNames(const Names & keys, const AggregateDescriptions & aggregates) +{ + /// The output header has a column for every key and aggregate, and the finalization finds the states by name, + /// so a repeated name would leave a state of the second occurrence unfinalized under a finalized type. + NameSet names; + for (const auto & key : keys) + if (!names.insert(key).second) + throw Exception(ErrorCodes::INCORRECT_DATA, "Duplicate key or aggregate function {} in a deserialized query plan step", key); + for (const auto & aggregate : aggregates) + if (!names.insert(aggregate.column_name).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step", aggregate.column_name); +} + +void checkDeserializedMergedAggregatesLayout( + const Names & keys, const AggregateDescriptions & aggregates, const ColumnsWithTypeAndName & layout, bool exact) +{ + const size_t keys_size = keys.size(); + if (exact && layout.size() != keys_size + aggregates.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized query plan step merging aggregate states has {} columns " + "instead of {} keys and {} aggregate functions", + layout.size(), keys_size, aggregates.size()); + if (layout.size() < keys_size + aggregates.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized query plan step merging aggregate states has {} columns " + "for {} keys and {} aggregate functions", + layout.size(), keys_size, aggregates.size()); + + /// The `Aggregator` looks up the types of the keys and the states by name, but merges the columns + /// by position. With distinct names at the expected positions, both refer to the same columns. + NameSet names; + for (size_t i = 0; i < keys_size; ++i) + { + if (!names.insert(keys[i]).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step merging aggregate states", keys[i]); + if (layout[i].name != keys[i]) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key {} is expected at position {} of the input of a deserialized query plan step merging aggregate states, " + "but there is {}", + keys[i], i, layout[i].name); + } + + for (size_t i = 0; i < aggregates.size(); ++i) + { + const auto & aggregate = aggregates[i]; + const auto & column = layout[keys_size + i]; + if (!names.insert(aggregate.column_name).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step merging aggregate states", + aggregate.column_name); + if (column.name != aggregate.column_name) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} is expected at position {} of the input of a deserialized query plan step, " + "but there is {}", + aggregate.column_name, keys_size + i, column.name); + + const auto * state_type = typeid_cast(column.type.get()); + if (!state_type || !state_type->getFunction()->haveSameStateRepresentation(*aggregate.function)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} has type {} in the input of a deserialized query plan step, " + "which is not a state of {}", + aggregate.column_name, column.type->getName(), aggregate.function->getName()); + } + + /// The headers of the merge-only steps are built from the whole input, so a later column with the name + /// of a key or a state would also be there, but not in the merged chunks. + for (size_t i = keys_size + aggregates.size(); i < layout.size(); ++i) + { + if (names.contains(layout[i].name)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step merging aggregate states", + layout[i].name); + } +} + } diff --git a/src/Interpreters/AggregateDescription.h b/src/Interpreters/AggregateDescription.h index 11e18d241a95..908d38818f4a 100644 --- a/src/Interpreters/AggregateDescription.h +++ b/src/Interpreters/AggregateDescription.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -10,6 +11,7 @@ namespace DB { class WriteBuffer; +class Block; namespace JSONBuilder { class JSONMap; } @@ -29,4 +31,24 @@ using AggregateDescriptions = std::vector; void serializeAggregateDescriptions(const AggregateDescriptions & aggregates, WriteBuffer & out); void deserializeAggregateDescriptions(AggregateDescriptions & aggregates, ReadBuffer & in); +/// The aggregate functions of a deserialized query plan are resolved from the types written in the plan, +/// but they are executed on the columns of the step's input. The plan may come from an untrusted client, +/// so check that they agree, or a function would interpret a column of another type. Both throw `INCORRECT_DATA`. + +/// The arguments of the aggregates are found in the input by name and must have the types the functions are resolved for. +void checkDeserializedAggregateArguments(const AggregateDescriptions & aggregates, const Block & header); + +/// The steps finalizing the states (`TotalsHaving`) find them in the input by name: every aggregate must name +/// a column of the input holding a state of the same representation as its function. +void checkDeserializedFinalizedAggregates(const AggregateDescriptions & aggregates, const Block & header); + +/// The steps merging the states read the keys and then the states by position: `layout` (the input as it reaches +/// the `Aggregator`) must start with `keys` and then the states of `aggregates` (named by `column_name`), in order. +/// With `exact`, there must be no other columns. +void checkDeserializedMergedAggregatesLayout( + const Names & keys, const AggregateDescriptions & aggregates, const ColumnsWithTypeAndName & layout, bool exact = false); + +/// The names of the keys and the aggregates (the columns of the output) must be distinct. +void checkDeserializedAggregateOutputNames(const Names & keys, const AggregateDescriptions & aggregates); + } diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index b5599a2b6ee6..3b1e8590f14c 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -5,11 +5,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -471,7 +473,7 @@ AsynchronousInsertQueue::pushQueryWithInlinedData(ASTPtr query, ContextPtr query /// If limit is exceeded we will fallback to synchronous insert /// to avoid buffering of huge amount of data in memory. - auto read_buf = getReadBufferFromASTInsertQuery(query); + auto read_buf = getReadBufferFromASTInsertQuery(query, query_context); LimitReadBuffer limit_buf( *read_buf, @@ -514,8 +516,31 @@ AsynchronousInsertQueue::pushQueryWithInlinedData(ASTPtr query, ContextPtr query return pushDataChunk(std::move(query), std::move(bytes), std::move(query_context)); } +/// Whether the column, or a subcolumn at any nesting depth, is a `ColumnBLOB`, `ColumnConst`, `ColumnReplicated` +/// or `ColumnSparse`. `LowCardinality` does not count: it is a part of the type, not a representation. +static bool hasWrappedColumn(const IColumn & column) +{ + if (typeid_cast(&column) || column.isConst() || column.isReplicated() || column.isSparse()) + return true; + + bool res = false; + column.forEachSubcolumn([&](const IColumn::WrappedPtr & subcolumn) { res = res || hasWrappedColumn(*subcolumn); }); + return res; +} + AsynchronousInsertQueue::PushResult AsynchronousInsertQueue::pushQueryWithBlock(ASTPtr query, Block && block, ContextPtr query_context) { + /// The flush copies queued blocks into full columns with `insertRangeFrom`, whose `assert_cast` would misread a + /// wrapped column (`Sparse`, `Replicated`, ...) at any nesting depth. Every producer materializes before queuing. + /// An insert without data queues a block without columns. + for (const auto & elem : block) + if (elem.column && hasWrappedColumn(*elem.column)) + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Async insert block column '{}' must be materialized before queuing, but has a " + "non-default serialization representation: {}", + elem.name, elem.column->dumpStructure()); + query = query->clone(); preprocessInsertQuery(query, query_context); return pushDataChunk(std::move(query), std::move(block), std::move(query_context)); diff --git a/src/Interpreters/DatabaseCatalog.cpp b/src/Interpreters/DatabaseCatalog.cpp index cf578636d761..ecc4af9e179b 100644 --- a/src/Interpreters/DatabaseCatalog.cpp +++ b/src/Interpreters/DatabaseCatalog.cpp @@ -62,9 +62,6 @@ namespace ServerSetting { extern const ServerSettingsUInt64 database_atomic_delay_before_drop_table_sec; extern const ServerSettingsUInt64 database_catalog_drop_error_cooldown_sec; - extern const ServerSettingsUInt64 database_catalog_unused_dir_cleanup_period_sec; - extern const ServerSettingsUInt64 database_catalog_unused_dir_hide_timeout_sec; - extern const ServerSettingsUInt64 database_catalog_unused_dir_rm_timeout_sec; } namespace ErrorCodes @@ -236,13 +233,6 @@ void DatabaseCatalog::initializeAndLoadTemporaryDatabase() void DatabaseCatalog::createBackgroundTasks() { /// It has to be done before databases are loaded (to avoid a race condition on initialization) - if (Context::getGlobalContextInstance()->getApplicationType() == Context::ApplicationType::SERVER && getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_cleanup_period_sec]) - { - auto cleanup_task_holder - = getContext()->getSchedulePool().createTask(StorageID::createEmpty(), "DatabaseCatalogCleanupStoreDirectoryTask", [this]() { this->cleanupStoreDirectoryTask(); }); - cleanup_task = std::make_unique(std::move(cleanup_task_holder)); - } - auto drop_task_holder = getContext()->getSchedulePool().createTask(StorageID::createEmpty(), "DatabaseCatalogDropTableTask", [this](){ this->dropTableDataTask(); }); drop_task = std::make_unique(std::move(drop_task_holder)); @@ -252,14 +242,6 @@ void DatabaseCatalog::createBackgroundTasks() void DatabaseCatalog::startupBackgroundTasks() { - /// And it has to be done after all databases are loaded, otherwise cleanup_task may remove something that should not be removed - if (cleanup_task) - { - (*cleanup_task)->activate(); - /// Do not start task immediately on server startup, it's not urgent. - (*cleanup_task)->scheduleAfter(static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_hide_timeout_sec]) * 1000); - } - (*drop_task)->activate(); std::lock_guard lock{tables_marked_dropped_mutex}; if (!tables_marked_dropped.empty()) @@ -271,9 +253,6 @@ void DatabaseCatalog::shutdownImpl(std::function shutdown_system_logs) is_shutting_down = true; wait_table_finally_dropped.notify_all(); - if (cleanup_task) - (*cleanup_task)->deactivate(); - if (drop_task) (*drop_task)->deactivate(); @@ -1186,8 +1165,6 @@ DatabaseAndTable DatabaseCatalog::tryGetDatabaseAndTable(const StorageID & table void DatabaseCatalog::loadMarkedAsDroppedTables() { - assert(!cleanup_task); - auto component_guard = Coordination::setCurrentComponent("DatabaseCatalog::loadMarkedAsDroppedTables"); // Because some DBs might have a `disk` setting defining the disk to store the table metadata files, // we need to check the dropped metadata on these disks, not just the default database disk. @@ -1957,128 +1934,6 @@ void DatabaseCatalog::checkTablesCanBeExchangedWithNoCyclicDependencies(const St check(loading_dependencies); } -void DatabaseCatalog::cleanupStoreDirectoryTask() -{ - for (const auto & [disk_name, disk] : getContext()->getDisksMap()) - { - if (!disk->supportsStat() || !disk->supportsChmod()) - continue; - - size_t affected_dirs = 0; - size_t checked_dirs = 0; - for (auto it = disk->iterateDirectory("store"); it->isValid(); it->next()) - { - String prefix = it->name(); - bool expected_prefix_dir = disk->existsDirectory(it->path()) && prefix.size() == 3 && isHexDigit(prefix[0]) && isHexDigit(prefix[1]) - && isHexDigit(prefix[2]); - - if (!expected_prefix_dir) - { - LOG_WARNING(log, "Found invalid directory {} on disk {}, will try to remove it", it->path(), disk_name); - checked_dirs += 1; - affected_dirs += maybeRemoveDirectory(disk_name, disk, it->path()); - continue; - } - - for (auto jt = disk->iterateDirectory(it->path()); jt->isValid(); jt->next()) - { - String uuid_str = jt->name(); - UUID uuid; - bool parsed = tryParse(uuid, uuid_str); - - bool expected_dir = disk->existsDirectory(jt->path()) && parsed && uuid != UUIDHelpers::Nil && uuid_str.starts_with(prefix); - - if (!expected_dir) - { - LOG_WARNING(log, "Found invalid directory {} on disk {}, will try to remove it", jt->path(), disk_name); - checked_dirs += 1; - affected_dirs += maybeRemoveDirectory(disk_name, disk, jt->path()); - continue; - } - - /// Order is important - if (!hasUUIDMapping(uuid)) - { - /// We load uuids even for detached and permanently detached tables, - /// so it looks safe enough to remove directory if we don't have uuid mapping for it. - /// No table or database using this directory should concurrently appear, - /// because creation of new table would fail with "directory already exists". - checked_dirs += 1; - affected_dirs += maybeRemoveDirectory(disk_name, disk, jt->path()); - } - } - } - - if (affected_dirs) - LOG_INFO(log, "Cleaned up {} directories from store/ on disk {}", affected_dirs, disk_name); - if (checked_dirs == 0) - LOG_TEST(log, "Nothing to clean up from store/ on disk {}", disk_name); - } - - (*cleanup_task)->scheduleAfter(static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_cleanup_period_sec]) * 1000); -} - -bool DatabaseCatalog::maybeRemoveDirectory(const String & disk_name, const DiskPtr & disk, const String & unused_dir) -{ - /// "Safe" automatic removal of some directory. - /// At first we do not remove anything and only revoke all access right. - /// And remove only if nobody noticed it after, for example, one month. - - try - { - struct stat st = disk->stat(unused_dir); - - if (st.st_uid != geteuid()) - { - /// Directory is not owned by clickhouse, it's weird, let's ignore it (chmod will likely fail anyway). - LOG_WARNING(log, "Found directory {} with unexpected owner (uid={}) on disk {}", unused_dir, st.st_uid, disk_name); - return false; - } - - time_t max_modification_time = std::max({st.st_atime, st.st_mtime, st.st_ctime}); - time_t current_time = time(nullptr); - if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) - { - if (current_time <= max_modification_time + static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_hide_timeout_sec])) - return false; - - LOG_INFO(log, "Removing access rights for unused directory {} from disk {} (will remove it when timeout exceed)", unused_dir, disk_name); - - /// Explicitly update modification time just in case - - disk->setLastModified(unused_dir, Poco::Timestamp::fromEpochTime(current_time)); - - /// Remove all access right - disk->chmod(unused_dir, 0); - - return true; - } - - auto unused_dir_rm_timeout_sec = static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_rm_timeout_sec]); - - if (!unused_dir_rm_timeout_sec) - return false; - - if (current_time <= max_modification_time + unused_dir_rm_timeout_sec) - return false; - - LOG_INFO(log, "Removing unused directory {} from disk {}", unused_dir, disk_name); - - /// We have to set these access rights to make recursive removal work - disk->chmod(unused_dir, S_IRWXU); - - disk->removeRecursive(unused_dir); - - return true; - } - catch (...) - { - tryLogCurrentException(log, fmt::format("Failed to remove unused directory {} from disk {} ({})", - unused_dir, disk->getName(), disk->getPath())); - return false; - } -} - void DatabaseCatalog::reloadDisksTask() { std::set disks; diff --git a/src/Interpreters/DatabaseCatalog.h b/src/Interpreters/DatabaseCatalog.h index ded2f645447d..93de1fdb22da 100644 --- a/src/Interpreters/DatabaseCatalog.h +++ b/src/Interpreters/DatabaseCatalog.h @@ -311,9 +311,6 @@ class DatabaseCatalog : boost::noncopyable, WithMutableContext void dropTablesParallel(std::vector tables); void rescheduleDropTableTask(); - void cleanupStoreDirectoryTask(); - bool maybeRemoveDirectory(const String & disk_name, const DiskPtr & disk, const String & unused_dir); - void reloadDisksTask(); static constexpr size_t reschedule_time_ms = 100; @@ -366,7 +363,6 @@ class DatabaseCatalog : boost::noncopyable, WithMutableContext std::unique_ptr drop_task; std::condition_variable wait_table_finally_dropped; - std::unique_ptr cleanup_task; std::unique_ptr reload_disks_task; std::mutex reload_disks_mutex; @@ -380,7 +376,8 @@ class DatabaseCatalog : boost::noncopyable, WithMutableContext /// This class is useful when creating a table or database. /// Usually we create IStorage/IDatabase object first and then add it to IDatabase/DatabaseCatalog. /// But such object may start using a directory in store/ since its creation. -/// To avoid race with cleanupStoreDirectoryTask() we have to mark UUID as used first. +/// To prevent another table or database from using the same UUID (and so the same directory) +/// concurrently, we have to mark UUID as used first. /// Then we can either add DatabasePtr/StoragePtr to the created UUID mapping /// or remove the lock if creation failed. /// See also addUUIDMapping(...) diff --git a/src/Interpreters/ExternalDictionariesLoader.cpp b/src/Interpreters/ExternalDictionariesLoader.cpp index 94b811e94b8b..5f3157f360fd 100644 --- a/src/Interpreters/ExternalDictionariesLoader.cpp +++ b/src/Interpreters/ExternalDictionariesLoader.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -86,8 +87,16 @@ void ExternalDictionariesLoader::updateObjectFromConfigWithoutReloading(IExterna ExternalDictionariesLoader::DictPtr ExternalDictionariesLoader::getDictionary(const std::string & dictionary_name, ContextPtr local_context) const { - std::string resolved_dictionary_name = resolveDictionaryName(dictionary_name, local_context->getCurrentDatabase()); + return loadDictionary(resolveDictionaryName(dictionary_name, local_context->getCurrentDatabase()), local_context); +} + +ExternalDictionariesLoader::DictPtr ExternalDictionariesLoader::getDictionary(const ResolvedDictionary & dictionary, ContextPtr local_context) const +{ + return loadDictionary(dictionary.getKey(), local_context); +} +ExternalDictionariesLoader::DictPtr ExternalDictionariesLoader::loadDictionary(const std::string & resolved_dictionary_name, ContextPtr local_context) const +{ /// Check if we have a cancellable query context QueryStatusPtr process_list_element; if (local_context->hasQueryContext()) @@ -146,8 +155,16 @@ void ExternalDictionariesLoader::reloadDictionary(const std::string & dictionary DictionaryStructure ExternalDictionariesLoader::getDictionaryStructure(const std::string & dictionary_name, ContextPtr query_context) const { - std::string resolved_name = resolveDictionaryName(dictionary_name, query_context->getCurrentDatabase()); + return getDictionaryStructureByKey(resolveDictionaryName(dictionary_name, query_context->getCurrentDatabase()), dictionary_name); +} + +DictionaryStructure ExternalDictionariesLoader::getDictionaryStructure(const ResolvedDictionary & dictionary) const +{ + return getDictionaryStructureByKey(dictionary.getKey(), dictionary.name); +} +DictionaryStructure ExternalDictionariesLoader::getDictionaryStructureByKey(const std::string & resolved_name, const std::string & dictionary_name) const +{ auto load_result = getLoadResult(resolved_name); if (load_result.object) @@ -162,9 +179,55 @@ DictionaryStructure ExternalDictionariesLoader::getDictionaryStructure(const std return ExternalDictionariesLoader::getDictionaryStructure(*load_result.config); } -void ExternalDictionariesLoader::assertDictionaryStructureExists(const std::string & dictionary_name, ContextPtr query_context) const +const std::string & ExternalDictionariesLoader::ResolvedDictionary::getKey() const +{ + if (key.empty()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary ({}) not found", backQuote(name)); + return key; +} + +ExternalDictionariesLoader::ResolvedDictionary +ExternalDictionariesLoader::resolveDictionary(const std::string & dictionary_name, ContextPtr query_context) const { - getDictionaryStructure(dictionary_name, query_context); + return resolveDictionary(dictionary_name, query_context->getCurrentDatabase(), query_context); +} + +ExternalDictionariesLoader::ResolvedDictionary ExternalDictionariesLoader::resolveDictionary( + const std::string & dictionary_name, const std::string & current_database_name, ContextPtr /*query_context*/) const +{ + auto resolved = resolveDictionaryNameUnchecked(dictionary_name, current_database_name); + + /// One lookup decides whether the dictionary exists, so that a dictionary removed concurrently is reported like any + /// missing one, after the access check. + auto load_result = getLoadResult(resolved.key); + + if (!load_result.object && !load_result.config) + { + /// An empty name names no dictionary at all, so there is nothing to check access to. + if (resolved.qualified_name.table.empty()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary ({}) not found", backQuote(dictionary_name)); + + /// The read that follows the access check reports the missing dictionary to a user with access. + return {dictionary_name, {}, StorageID(resolved.qualified_name.database, resolved.qualified_name.table)}; + } + + if (load_result.object) + { + const auto dictionary = std::static_pointer_cast(load_result.object); + return {dictionary_name, std::move(resolved.key), dictionary->getDictionaryID()}; + } + + auto dictionary_id = StorageID::fromDictionaryConfig(*load_result.config->config, load_result.config->key_in_config); + return {dictionary_name, std::move(resolved.key), std::move(dictionary_id)}; +} + +ExternalDictionariesLoader::ResolvedDictionary +ExternalDictionariesLoader::resolveDictionaryCheckingAccess(const std::string & dictionary_name, ContextPtr query_context) const +{ + auto dictionary = resolveDictionary(dictionary_name, query_context); + query_context->checkAccess( + AccessType::dictGet, IDictionary::getDatabaseOrNoDatabaseTag(dictionary.id), dictionary.id.getTableName()); + return dictionary; } QualifiedTableName ExternalDictionariesLoader::qualifyDictionaryNameWithDatabase(const std::string & dictionary_name, ContextPtr query_context) const @@ -204,6 +267,23 @@ std::string ExternalDictionariesLoader::resolveDictionaryName(const std::string throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary ({}) not found", backQuote(dictionary_name)); } +ExternalDictionariesLoader::ResolvedDictionaryName ExternalDictionariesLoader::resolveDictionaryNameUnchecked(const std::string & dictionary_name, const std::string & current_database_name) const +{ + if (has(dictionary_name)) + return {dictionary_name, QualifiedTableName::tryParseFromString(dictionary_name).value_or(QualifiedTableName{.database = {}, .table = dictionary_name})}; + + /// The name with the database filled in, as `resolveDictionaryNameFromDatabaseCatalog` qualifies it. + auto key = resolveDictionaryNameFromDatabaseCatalog(dictionary_name, current_database_name); + auto qualified_name = QualifiedTableName::tryParseFromString(dictionary_name); + if (!qualified_name) + return {std::move(key), QualifiedTableName{.database = {}, .table = dictionary_name}}; + + if (qualified_name->database.empty()) + qualified_name->database = current_database_name; + + return {std::move(key), std::move(*qualified_name)}; +} + std::string ExternalDictionariesLoader::resolveDictionaryNameFromDatabaseCatalog(const std::string & name, const std::string & current_database_name) const { /// If it's dictionary from Atomic database, then we need to convert qualified name to UUID. @@ -228,6 +308,14 @@ std::string ExternalDictionariesLoader::resolveDictionaryNameFromDatabaseCatalog res = current_database_name + '.' + name; } + /// Only a database with its own tables can contain a DDL dictionary. Do not ask any other database for the table: + /// the name is resolved before access is checked, and e.g. a `PostgreSQL` database would query its remote server. + if (qualified_name->database.empty()) + return res; + auto database = DatabaseCatalog::instance().tryGetDatabase(qualified_name->database); + if (!database || database->isExternal()) + return res; + auto [db, table] = DatabaseCatalog::instance().tryGetDatabaseAndTable( {qualified_name->database, qualified_name->table}, const_pointer_cast(getContext())); diff --git a/src/Interpreters/ExternalDictionariesLoader.h b/src/Interpreters/ExternalDictionariesLoader.h index d474e82f2388..9be39844709a 100644 --- a/src/Interpreters/ExternalDictionariesLoader.h +++ b/src/Interpreters/ExternalDictionariesLoader.h @@ -4,6 +4,7 @@ #include #include #include +#include #include @@ -31,7 +32,35 @@ class ExternalDictionariesLoader : public ExternalLoader, WithContext DictionaryStructure getDictionaryStructure(const std::string & dictionary_name, ContextPtr context) const; - void assertDictionaryStructureExists(const std::string & dictionary_name, ContextPtr context) const; + /// A dictionary name resolved once, so that an access check and the reads after it refer to the same dictionary. + /// The reads go by `key`, which for a dictionary in an `Atomic` database is its UUID and does not change on rename. + /// For an XML dictionary or one in an `Ordinary` database the key is the name. + struct ResolvedDictionary + { + /// The name as the query wrote it. + std::string name; + /// The key the loader stores the dictionary under, empty if there is no such dictionary. + std::string key; + /// The ID to check access rights with, taken from the loaded dictionary if there is one, otherwise from its + /// configuration. For a dictionary that does not exist, the ID it would have, so that a user without access + /// gets the access error and cannot tell a missing dictionary from an existing one. + StorageID id; + + /// Throws if there is no such dictionary. + [[nodiscard]] const std::string & getKey() const; + }; + + /// Resolves the name without loading the dictionary, so that access can be checked before loading. + [[nodiscard]] ResolvedDictionary resolveDictionary(const std::string & dictionary_name, ContextPtr query_context) const; + + /// The same, resolving an unqualified name against the given database rather than the current database of the query. + [[nodiscard]] ResolvedDictionary resolveDictionary(const std::string & dictionary_name, const std::string & current_database_name, ContextPtr query_context) const; + + /// The same, and checks that the user of `query_context` has `dictGet` on the dictionary. + [[nodiscard]] ResolvedDictionary resolveDictionaryCheckingAccess(const std::string & dictionary_name, ContextPtr query_context) const; + + [[nodiscard]] DictPtr getDictionary(const ResolvedDictionary & dictionary, ContextPtr local_context) const; + [[nodiscard]] DictionaryStructure getDictionaryStructure(const ResolvedDictionary & dictionary) const; /// Reloads all previously tried-to-load dictionaries in topological order /// based on their source dependencies (dictionaries sourcing from other dictionaries). @@ -56,6 +85,20 @@ class ExternalDictionariesLoader : public ExternalLoader, WithContext std::string resolveDictionaryName(const std::string & dictionary_name, const std::string & current_database_name) const; + /// Both readings of one resolution: the key the loader stores the dictionary under, and the name as a query refers + /// to it with the database filled in. + struct ResolvedDictionaryName + { + std::string key; + QualifiedTableName qualified_name; + }; + + /// The same as `resolveDictionaryName`, but the key may name no dictionary. + ResolvedDictionaryName resolveDictionaryNameUnchecked(const std::string & dictionary_name, const std::string & current_database_name) const; + + DictPtr loadDictionary(const std::string & key, ContextPtr local_context) const; + DictionaryStructure getDictionaryStructureByKey(const std::string & key, const std::string & dictionary_name) const; + /// Try convert qualified dictionary name to persistent UUID std::string resolveDictionaryNameFromDatabaseCatalog(const std::string & name, const std::string & current_database_name) const; diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index 9976d55c6111..9ef3ed5186d3 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -235,7 +235,9 @@ BlockIO InterpreterAlterQuery::executeToTable(const ASTAlterQuery & alter) return executeDDLQueryOnCluster(query_ptr, getContext(), params); } - getContext()->checkAccess(getRequiredAccess()); + /// The grants of some settings depend on the engine. A table that is not loaded yet is a stand-in without its name. + const String engine = table ? resolveStorageProxyLoading(table)->getName() : String{}; + getContext()->checkAccess(getRequiredAccess(engine)); checkNoRowPolicyForExport(alter, getContext()); if (!table_id) @@ -569,17 +571,19 @@ BlockIO InterpreterAlterQuery::executeToDatabase(const ASTAlterQuery & alter) return res; } -AccessRightsElements InterpreterAlterQuery::getRequiredAccess() const +AccessRightsElements InterpreterAlterQuery::getRequiredAccess(const String & engine) const { AccessRightsElements required_access; const auto & alter = query_ptr->as(); for (const auto & child : alter.command_list->children) - boost::range::push_back(required_access, getRequiredAccessForCommand(child->as(), alter.getDatabase(), alter.getTable())); + boost::range::push_back(required_access, getRequiredAccessForCommand( + child->as(), alter.getDatabase(), alter.getTable(), engine)); return required_access; } -AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand(const ASTAlterCommand & command, const String & database, const String & table) +AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand( + const ASTAlterCommand & command, const String & database, const String & table, const String & engine) { AccessRightsElements required_access; @@ -733,11 +737,14 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand(const AS /// A setting that sends the table's data elsewhere, e.g. the move destination of a queue, is the same data flow as /// `INSERT INTO FUNCTION s3(...) SELECT * FROM
`. The creator of the table supplied its source and credentials, - /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator - /// of `ON CLUSTER` can check them without the table. + /// so the reading part is `SELECT` on the table. For `ON CLUSTER`, `engine` is empty, so the grants can be checked + /// without the table. if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) { - auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + const auto & changes = command.settings_changes->as().changes; + auto export_access = engine.empty() + ? StorageFactory::instance().getExportAccessOfAnyEngine(changes) + : StorageFactory::instance().getExportAccess(changes, engine); if (!export_access.empty()) { required_access.append_range(std::move(export_access)); diff --git a/src/Interpreters/InterpreterAlterQuery.h b/src/Interpreters/InterpreterAlterQuery.h index 17afa140c8e7..604ad24376c6 100644 --- a/src/Interpreters/InterpreterAlterQuery.h +++ b/src/Interpreters/InterpreterAlterQuery.h @@ -22,14 +22,17 @@ class InterpreterAlterQuery : public IInterpreter, WithMutableContext BlockIO execute() override; - static AccessRightsElements getRequiredAccessForCommand(const ASTAlterCommand & command, const String & database, const String & table); + /// `engine` is the engine of the table, empty for `ON CLUSTER`. + static AccessRightsElements getRequiredAccessForCommand( + const ASTAlterCommand & command, const String & database, const String & table, const String & engine = {}); void extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr & ast, ContextPtr context) const override; bool supportsTransactions() const override { return true; } private: - AccessRightsElements getRequiredAccess() const; + /// `engine` is the engine of the table, empty if the table is not known. + AccessRightsElements getRequiredAccess(const String & engine = {}) const; BlockIO executeToTable(const ASTAlterQuery & alter); diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index d4252fbb6082..94b71dc55918 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -41,7 +41,9 @@ #include #include +#include #include +#include #include #include #include @@ -50,6 +52,8 @@ #include #include +#include +#include #include #include #include @@ -1728,7 +1732,10 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) /// Only here is an engine inherited through `AS` known, and nothing is enqueued or created yet. /// A replay of a stored definition was checked when it was created. if (isFreshTableDefinition(mode, create.attach_short_syntax)) + { checkExportAccess(create); + checkDictionaryEngineAccess(create); + } DatabasePtr database; bool need_add_to_database = !create.isTemporary(); @@ -1736,11 +1743,15 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) if (need_add_to_database) database = DatabaseCatalog::instance().tryGetDatabase(database_name); - /// Check type compatible for materialized dest table and select columns - if (create.select && create.is_materialized_view && mode <= LoadingStrictnessLevel::CREATE) + /// Check type compatible for materialized dest table and select columns. + /// A full-definition `ATTACH` by a user is validated like `CREATE`, unlike a replayed one: a follower replica + /// gets `ATTACH` (not `SECONDARY_CREATE`), and the initiator has already validated it before enqueueing. + const bool is_user_full_attach = !internal && mode == LoadingStrictnessLevel::ATTACH && !create.attach_short_syntax + && !is_secondary_query && !is_restore_from_backup && !getContext()->isRecoveryFromStoredMetadata(); + if (create.select && create.is_materialized_view && (mode <= LoadingStrictnessLevel::CREATE || is_user_full_attach)) { // An MV with a flattened nested column in an inner table can never be filled - if (create.is_materialized_view_with_inner_table()) + if (mode <= LoadingStrictnessLevel::CREATE && create.is_materialized_view_with_inner_table()) getContext()->setSetting("flatten_nested", false); validateMaterializedViewColumnsAndEngine(create, properties, database); } @@ -2551,6 +2562,9 @@ BlockIO InterpreterCreateQuery::execute() auto on_cluster_version = getContext()->getSettingsRef()[Setting::distributed_ddl_entry_format_version]; if (is_create_database || on_cluster_version < DDLLogEntry::NORMALIZE_CREATE_ON_INITIATOR_VERSION) { + if (!is_create_database) + checkDictionaryEngineAccess(create); + /// This branch returns before setEngine, and the worker processes AS src without the user's access. if (!create.as_table.empty()) { @@ -2584,6 +2598,7 @@ BlockIO InterpreterCreateQuery::execute() /// the worker inherits the move destination of the source too, and runs with no user checkExportAccess(inherited); + checkDictionaryEngineAccess(inherited); /// A worker copies the source's indices with no user, so declare their transforms here. if (inherited.storage && inherited.storage->engine && endsWith(inherited.storage->engine->name, "MergeTree")) @@ -2715,6 +2730,67 @@ void InterpreterCreateQuery::checkExportAccess(const ASTCreateQuery & create) co getContext()->checkAccess(StorageFactory::instance().getExportAccess(create)); } +void InterpreterCreateQuery::checkDictionaryEngineAccess(ASTCreateQuery & create) const +{ + /// Internal queries (initiated by the server itself) always have access to everything. A replay of `ON CLUSTER` or of a + /// `Replicated` database was checked before it was enqueued, while it still ran as the user, and runs without the user. + if (internal || getContext()->isDDLOrOnClusterInternal()) + return; + + /// An unqualified dictionary name is resolved against the current database of the query that creates the storage + /// and loads the dictionary, so check the dictionary that this query resolves to. + const String & server_default_database = getContext()->getGlobalContext()->getCurrentDatabase(); + String execution_database; + if (!create.cluster.empty()) + { + /// A replay of `ON CLUSTER` runs in the default database of the server. + execution_database = server_default_database; + } + else + { + String database_name = getContext()->resolveDatabase(create.getDatabase()); + auto database = DatabaseCatalog::instance().tryGetDatabase(database_name); + /// A replay in a `Replicated` database runs in that database. + execution_database = database && database->shouldReplicateQuery(getContext(), query_ptr) ? database_name : getContext()->getCurrentDatabase(); + } + + auto check = [&](ASTs & arguments, const String & current_database) + { + /// A wrong number of arguments is reported when the storage is created. + if (arguments.size() != 1) + return; + + /// Keep the name that is checked in the query, so that a replica executing it does not evaluate the argument + /// to another dictionary. + arguments[0] = evaluateConstantExpressionOrIdentifierAsLiteral(arguments[0], getContext()); + auto dictionary_name = checkAndGetLiteralArgument(arguments[0], "dictionary_name"); + const auto & external_loader = getContext()->getExternalDictionariesLoader(); + StorageDictionary::checkDictionaryAccess(external_loader.resolveDictionary(dictionary_name, current_database, getContext()).id, getContext()); + }; + + auto check_engine = [&](ASTStorage & storage) + { + if (storage.engine && storage.engine->name == "Dictionary" && storage.engine->arguments) + check(storage.engine->arguments->children, execution_database); + }; + + if (create.storage) + check_engine(*create.storage); + if (create.targets) + { + for (ASTStorage * inner_engine : create.targets->getInnerEngines()) + check_engine(*inner_engine); + } + + /// `CREATE TABLE ... AS dictionary(...)` creates the storage with the global context, see `doCreateTable`. + if (create.as_table_function) + { + auto & function = create.as_table_function->as(); + if (function.name == "dictionary" && function.arguments) + check(function.arguments->children, server_default_database); + } +} + void InterpreterCreateQuery::extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr &, ContextPtr) const { if (!as_table_saved.empty()) @@ -2836,6 +2912,17 @@ void InterpreterCreateQuery::convertMergeTreeTableIfPossible(ASTCreateQuery & cr else if (!to_replicated) throw Exception(ErrorCodes::INCORRECT_QUERY, "Can not attach table as not replicated, table is already not replicated"); + /// A short `ATTACH` carries no engine of its own, so `getRequiredAccess` requires no `TABLE ENGINE` grant for it, and + /// `getTablePropertiesAndNormalizeCreateQuery` checks the grant for the converted engine only after the side effects + /// below, which cannot be rolled back. So the converted engine is checked here, before them, as a `CREATE` with that + /// engine would be checked. A converted engine that is not registered is refused first: a grant such as + /// `TABLE ENGINE ON *` would cover it, and the rewritten definition could not be attached. + const String converted_engine_name = DatabaseOrdinary::getConvertedMergeTreeEngineName(engine_name, to_replicated); + if (!StorageFactory::instance().getAllStorages().contains(converted_engine_name)) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, + "Table engine conversion is not supported for {}: there is no table engine {}", engine_name, converted_engine_name); + getContext()->checkAccess(AccessType::TABLE_ENGINE, converted_engine_name); + /// Must precede every side effect below: neither the transaction metadata removal nor the /// metadata rewrite can be rolled back. The other direction takes no Keeper path at all. if (to_replicated) @@ -2863,6 +2950,7 @@ void InterpreterCreateQuery::convertMergeTreeTableIfPossible(ASTCreateQuery & cr /// Set new engine DatabaseOrdinary::setMergeTreeEngine(create, getContext(), to_replicated); + chassert(create.storage->engine->name == converted_engine_name); /// Save new metadata auto db_disk = database->getDisk(); diff --git a/src/Interpreters/InterpreterCreateQuery.h b/src/Interpreters/InterpreterCreateQuery.h index 674965cc7e00..36419c8aabd6 100644 --- a/src/Interpreters/InterpreterCreateQuery.h +++ b/src/Interpreters/InterpreterCreateQuery.h @@ -116,6 +116,12 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext /// `setEngine` has resolved an engine inherited through `AS`, which `getRequiredAccess` cannot see. void checkExportAccess(const ASTCreateQuery & create) const; + /// A `Dictionary` table, including the inner table of a materialized view and a table created `AS dictionary(...)`, + /// needs access to the dictionary it reads, see `StorageDictionary::checkDictionaryAccess`. Checked here, while the + /// query still runs as the user: `Replicated` and `ON CLUSTER` replays run with full access, and so does the deferred + /// creation of a table function with an explicit column list. Replaces the dictionary name argument with the evaluated name. + void checkDictionaryEngineAccess(ASTCreateQuery & create) const; + /// Create IStorage and add it to database. If table already exists and IF NOT EXISTS specified, do nothing and return false. bool doCreateTable(ASTCreateQuery & create, const TableProperties & properties, DDLGuardPtr & ddl_guard, LoadingStrictnessLevel mode); BlockIO doCreateOrReplaceTable(ASTCreateQuery & create, const InterpreterCreateQuery::TableProperties & properties, LoadingStrictnessLevel mode); diff --git a/src/Interpreters/InterpreterSystemQuery.cpp b/src/Interpreters/InterpreterSystemQuery.cpp index 5c34792e6493..7aa01d0f1e9f 100644 --- a/src/Interpreters/InterpreterSystemQuery.cpp +++ b/src/Interpreters/InterpreterSystemQuery.cpp @@ -2062,6 +2062,7 @@ void InterpreterSystemQuery::instrumentWithXRay(bool add, ASTSystemQuery & query void InterpreterSystemQuery::syncReplicatedDatabase(ASTSystemQuery & query) { const auto database_name = query.getDatabase(); + getContext()->checkAccess(AccessType::SYSTEM_SYNC_DATABASE_REPLICA, database_name); auto guard = DatabaseCatalog::instance().getDDLGuard(database_name, "", nullptr); auto database = DatabaseCatalog::instance().getDatabase(database_name); diff --git a/src/Interpreters/JoinedTables.cpp b/src/Interpreters/JoinedTables.cpp index 0f00514e8b6a..02335d20015f 100644 --- a/src/Interpreters/JoinedTables.cpp +++ b/src/Interpreters/JoinedTables.cpp @@ -5,13 +5,14 @@ #include #include +#include #include #include #include #include #include #include -#include +#include #include #include @@ -370,26 +371,13 @@ std::shared_ptr JoinedTables::makeTableJoin(const ASTSelectQuery & se } auto storage_dict = std::dynamic_pointer_cast(storage); - if (storage_dict && try_use_direct_join && storage_dict->getDictionary()->getSpecialKeyType() != DictionarySpecialKeyType::Range) + if (storage_dict && try_use_direct_join) { - FunctionDictHelper dictionary_helper(context); - - auto dictionary_name = storage_dict->getDictionaryName(); - auto dictionary = dictionary_helper.getDictionary(dictionary_name); - if (!dictionary) - { - LOG_TRACE(getLogger("JoinedTables"), "Can't use dictionary join: dictionary '{}' was not found", dictionary_name); - return nullptr; - } - if (dictionary->getSpecialKeyType() == DictionarySpecialKeyType::Range) - { - LOG_TRACE(getLogger("JoinedTables"), "Can't use dictionary join: dictionary '{}' is a range dictionary", dictionary_name); - return nullptr; - } - - /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. - auto dictionary_kv = std::dynamic_pointer_cast(dictionary); - table_join->setStorageJoin(dictionary_kv); + /// This runs even if the right table is not read, e.g. for `CREATE VIEW`, so the access must be checked here. + auto dictionary = storage_dict->getDictionary(context); + if (dictionary->getSpecialKeyType() != DictionarySpecialKeyType::Range) + /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. + table_join->setStorageJoin(std::dynamic_pointer_cast(dictionary)); } if (auto storage_kv = castStorage(storage, DeferredTable::Load); storage_kv && try_use_direct_join) diff --git a/src/Interpreters/Session.cpp b/src/Interpreters/Session.cpp index c145b3091a05..4ead0a20dbb2 100644 --- a/src/Interpreters/Session.cpp +++ b/src/Interpreters/Session.cpp @@ -706,7 +706,11 @@ ContextMutablePtr Session::makeQueryContextImpl(const ClientInfo * client_info_t if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::NO_QUERY) query_context->setQueryKind(ClientInfo::QueryKind::INITIAL_QUERY); - if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::INITIAL_QUERY) + if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::INITIAL_QUERY || + /// Some places can send SECONDARY_QUERY with initial_user empty (e.g. dictionaries), and this is OK, + /// it should not block subsequent queries over TCP_INTERSERVER in this session + /// (Connection::sendQuery() forbids forwarding if initial_user != current_user) + (query_context->getClientInfo().initial_user.empty() && !query_context->getClientInfo().current_user.empty())) { query_context->setInitialUserName(query_context->getClientInfo().current_user); query_context->setInitialAddress(*query_context->getClientInfo().current_address); diff --git a/src/Interpreters/TreeOptimizer.cpp b/src/Interpreters/TreeOptimizer.cpp index c7e1fd1164f4..335b512258db 100644 --- a/src/Interpreters/TreeOptimizer.cpp +++ b/src/Interpreters/TreeOptimizer.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include @@ -153,7 +155,19 @@ void optimizeGroupBy(ASTSelectQuery * select_query, ContextPtr context) const auto & dict_name = dict_name_ast->value.safeGet(); const auto & attr_name = attr_name_ast->value.safeGet(); - const auto & dict_ptr = context->getExternalDictionariesLoader().getDictionary(dict_name, context); + const auto & external_loader = context->getExternalDictionariesLoader(); + + /// Do not load the dictionary for a user without access to it, because loading contacts + /// the dictionary source. The query fails later with the proper access error. + auto dictionary = external_loader.resolveDictionary(dict_name, context); + if (!context->getAccess()->isGranted( + AccessType::dictGet, IDictionary::getDatabaseOrNoDatabaseTag(dictionary.id), dictionary.id.getTableName())) + { + ++i; + continue; + } + + const auto & dict_ptr = external_loader.getDictionary(dictionary, context); if (!dict_ptr->isInjective(attr_name)) { ++i; diff --git a/src/Interpreters/WebAssembly/WasmTimeRuntime.cpp b/src/Interpreters/WebAssembly/WasmTimeRuntime.cpp index 2870167f85f6..1761fd44e3e1 100644 --- a/src/Interpreters/WebAssembly/WasmTimeRuntime.cpp +++ b/src/Interpreters/WebAssembly/WasmTimeRuntime.cpp @@ -52,14 +52,16 @@ auto wasmtimeToNative(const wasmtime::Val & val) static_assert(false, "Unsupported WasmValKind"); } -wasmtime::ValKind toWasmTimeValKind(WasmValKind value) +wasmtime::ValType toWasmTimeValType(WasmValKind value) { - #define M(T) \ - if (value == WasmValKind::T) \ - return wasmtime::ValKind::T; - - APPLY_FOR_WASM_TYPES(M) - #undef M + switch (value) + { + case WasmValKind::I32: return wasmtime::ValType::i32(); + case WasmValKind::I64: return wasmtime::ValType::i64(); + case WasmValKind::F32: return wasmtime::ValType::f32(); + case WasmValKind::F64: return wasmtime::ValType::f64(); + case WasmValKind::V128: return wasmtime::ValType::v128(); + } throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported wasm implementation type"); } @@ -74,6 +76,16 @@ WasmValKind fromWasmTimeValKind(wasmtime::ValKind val_type) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported wasm implementation type"); } +WasmValKind fromWasmTimeValType(wasmtime::ValType::Ref ref) +{ + if (ref == wasmtime::ValType::i32()) return WasmValKind::I32; + if (ref == wasmtime::ValType::i64()) return WasmValKind::I64; + if (ref == wasmtime::ValType::f32()) return WasmValKind::F32; + if (ref == wasmtime::ValType::f64()) return WasmValKind::F64; + if (ref == wasmtime::ValType::v128()) return WasmValKind::V128; + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported wasm implementation type"); +} + WasmVal fromWasmTimeValue(const wasmtime::Val & wasm_val) { #define M(T) \ @@ -112,14 +124,14 @@ wasmtime::FuncType toWasmFunctionType(const WasmFunctionDeclaration & host_funct param_types.reserve(argument_types.size()); for (auto & argument_type : argument_types) { - param_types.emplace_back(toWasmTimeValKind(argument_type)); + param_types.emplace_back(toWasmTimeValType(argument_type)); } std::vector result_type; result_type.reserve(1); if (auto return_type = host_function_decl.getReturnType()) { - result_type.emplace_back(toWasmTimeValKind(return_type.value())); + result_type.emplace_back(toWasmTimeValType(return_type.value())); } return wasmtime::FuncType::from_iters(param_types, result_type); @@ -344,14 +356,14 @@ WasmFunctionDeclaration buildFunctionDeclaration(std::string_view module_name, s std::optional return_type; if (function_info.results().size() == 1) { - return_type = fromWasmTimeValKind(function_info.results().begin()->kind()); + return_type = fromWasmTimeValType(*function_info.results().begin()); } std::vector argument_types; argument_types.reserve(function_info.params().size()); for (auto function_argument : function_info.params()) { - argument_types.emplace_back(fromWasmTimeValKind(function_argument.kind())); + argument_types.emplace_back(fromWasmTimeValType(function_argument)); } return WasmFunctionDeclaration(module_name, function_name, std::move(argument_types), return_type); diff --git a/src/Interpreters/loadMetadata.cpp b/src/Interpreters/loadMetadata.cpp index 321991393b9f..8021f60218b8 100644 --- a/src/Interpreters/loadMetadata.cpp +++ b/src/Interpreters/loadMetadata.cpp @@ -554,7 +554,6 @@ static void maybeConvertOrdinaryDatabaseToAtomic(ContextMutablePtr context, cons executeTrivialBlockIO(res, context); /// Unlock UUID mapping, because it will be locked again on database reload. - /// It's safe to do during metadata loading, because cleanup task is not started yet. DatabaseCatalog::instance().removeUUIDMappingFinally(db_uuid); for (const auto & uuid : tables_uuids) DatabaseCatalog::instance().removeUUIDMappingFinally(uuid); diff --git a/src/Parsers/ASTFunctionWithKeyValueArguments.cpp b/src/Parsers/ASTFunctionWithKeyValueArguments.cpp index 24404c581fd2..7455425e083a 100644 --- a/src/Parsers/ASTFunctionWithKeyValueArguments.cpp +++ b/src/Parsers/ASTFunctionWithKeyValueArguments.cpp @@ -14,9 +14,11 @@ namespace /// the custom HTTP headers of the `HTTP` source, whose values often carry API tokens. The headers /// are hidden as a whole, names included: the query is logged before the dictionary source /// validates its structure, so a malformed definition must not leak either. + /// The `url` and `endpoint` of the `HTTP` source are hidden whole: the userinfo, the path or the query can carry credentials. bool isSecretKey(const String & key) { - return key == "password" || key == "headers" || key == "header"; + return key == "password" || key == "headers" || key == "header" + || key == "url" || key == "endpoint"; } } @@ -71,7 +73,16 @@ void ASTPair::formatImpl(WriteBuffer & ostr, const FormatSettings & settings, Fo bool ASTPair::hasSecretParts() const { - return isSecretKey(first) || second->hasSecretParts(); + if (isSecretKey(first)) + return true; + /// The `uri` is a secret part only when it carries a password, see `formatImpl`. + if (first == "uri") + { + String uri = second->formatWithSecretsOneLine(); + if (maskURIPassword(&uri)) + return true; + } + return second->hasSecretParts(); } diff --git a/src/Parsers/FieldFromAST.cpp b/src/Parsers/FieldFromAST.cpp index 4f86b56edbeb..a868ddd42f89 100644 --- a/src/Parsers/FieldFromAST.cpp +++ b/src/Parsers/FieldFromAST.cpp @@ -13,6 +13,7 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; + extern const int ILLEGAL_TYPE_OF_ARGUMENT; } Field createFieldFromAST(ASTPtr ast) @@ -25,6 +26,17 @@ Field createFieldFromAST(ASTPtr ast) throw Exception(ErrorCodes::LOGICAL_ERROR, "Method {} not implemented for {}", method, getTypeName()); } +bool FieldFromASTImpl::operator == (const CustomTypeImpl & rhs) const +{ + if (std::string_view(getTypeName()) != std::string_view(rhs.getTypeName())) + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Comparing custom types with different type names: {} and {}", + getTypeName(), rhs.getTypeName()); + + /// Compare the unmasked text: masking rewrites every credential to `[HIDDEN]`, so two values + /// differing only in a credential would compare equal. + return toString(/*show_secrets=*/ true) == rhs.toString(/*show_secrets=*/ true); +} + bool FieldFromASTImpl::isSecret() const { return isDiskFunction(ast); diff --git a/src/Parsers/FieldFromAST.h b/src/Parsers/FieldFromAST.h index a69c086a1709..7c5eb6a50603 100644 --- a/src/Parsers/FieldFromAST.h +++ b/src/Parsers/FieldFromAST.h @@ -21,7 +21,7 @@ struct FieldFromASTImpl : public CustomType::CustomTypeImpl bool operator <= (const CustomTypeImpl &) const override { throwNotImplemented("<="); } bool operator > (const CustomTypeImpl &) const override { throwNotImplemented(">"); } bool operator >= (const CustomTypeImpl &) const override { throwNotImplemented(">="); } - bool operator == (const CustomTypeImpl &) const override { throwNotImplemented("=="); } + bool operator == (const CustomTypeImpl & rhs) const override; ASTPtr ast; }; diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index e2698652f3fc..a56d79bd68aa 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -401,6 +401,13 @@ void FunctionSecretArgumentsFinder::findOrdinaryFunctionSecretArguments() /// HMAC('mode', 'message', 'key') -> HMAC('mode', 'message', '[HIDDEN]') findHMACSecretArguments(); } + else if ((function->name() == "sipHash64Keyed") || (function->name() == "sipHash128Keyed") + || (function->name() == "sipHash128ReferenceKeyed")) + { + /// sipHash64Keyed(key, data, ...) -> sipHash64Keyed('[HIDDEN]', data, ...) + /// These functions have no named-argument grammar, so the key is always at raw index 0. + markSecretArgument(0); + } else if (function->name() == "url" || function->name() == "urlCluster") { /// url('url', ...) keeps the url at slot 0; urlCluster('cluster', 'url', ...) at slot 1. diff --git a/src/Parsers/tests/gtest_Parser.cpp b/src/Parsers/tests/gtest_Parser.cpp index 429e65d8d125..daf71a85d715 100644 --- a/src/Parsers/tests/gtest_Parser.cpp +++ b/src/Parsers/tests/gtest_Parser.cpp @@ -371,6 +371,6 @@ INSTANTIATE_TEST_SUITE_P( }, { "from matches\nfilter start_date > @2023-05-30 # Some comment here\nderive {\n some_derived_value_1 = a + (b ?? 0), # And there\n some_derived_value_2 = c + some_derived_value\n}\nfilter some_derived_value_2 > 0\ngroup {country, city} (\n aggregate {\n average some_derived_value_2,\n aggr = max some_derived_value_2\n }\n)\nderive place = f\"{city} in {country}\"\nderive country_code = s\"LEFT(country, 2)\"\nsort {aggr, -country}\ntake 1..20", - "WITH\n table_1 AS\n (\n SELECT\n country,\n city,\n c + some_derived_value AS _expr_1\n FROM matches\n WHERE start_date > toDate('2023-05-30')\n ),\n table_0 AS\n (\n SELECT\n country,\n city,\n AVG(_expr_1) AS _expr_0,\n MAX(_expr_1) AS aggr\n FROM table_1\n WHERE _expr_1 > 0\n GROUP BY\n country,\n city\n )\nSELECT\n country,\n city,\n _expr_0,\n aggr,\n CONCAT(city, ' in ', country) AS place,\n LEFT(country, 2) AS country_code\nFROM table_0\nORDER BY\n aggr ASC,\n country DESC\nLIMIT 20", + "WITH table_0 AS\n (\n SELECT\n country,\n city,\n AVG(c + some_derived_value) AS _expr_0,\n MAX(c + some_derived_value) AS aggr\n FROM matches\n WHERE (start_date > toDate('2023-05-30')) AND ((c + some_derived_value) > 0)\n GROUP BY\n country,\n city\n )\nSELECT\n country,\n city,\n _expr_0,\n aggr,\n CONCAT(city, ' in ', country) AS place,\n LEFT(country, 2) AS country_code\nFROM table_0\nORDER BY\n aggr ASC,\n country DESC\nLIMIT 20", }, }))); diff --git a/src/Planner/PlannerJoinTree.cpp b/src/Planner/PlannerJoinTree.cpp index 372e5225fd82..0ea91c7d9bfb 100644 --- a/src/Planner/PlannerJoinTree.cpp +++ b/src/Planner/PlannerJoinTree.cpp @@ -1839,7 +1839,7 @@ std::tuple buildJoinQueryPlan( if (right_table_has_row_policy) prepared_join_storage = {}; else - trySetStorageInTableJoin(right_table_expression, table_join); + trySetStorageInTableJoin(right_table_expression, table_join, query_context); auto hash_table_stat_cache_key = preCalculateCacheKey(right_table_expression, select_query_info); JoinAlgorithmParams params(*planner_context->getQueryContext()); params.hash_table_key_hash = calculateCacheKey(table_join, hash_table_stat_cache_key); diff --git a/src/Planner/PlannerJoins.cpp b/src/Planner/PlannerJoins.cpp index 5ae2d2d974a6..56e450df1798 100644 --- a/src/Planner/PlannerJoins.cpp +++ b/src/Planner/PlannerJoins.cpp @@ -1013,7 +1013,7 @@ std::optional tryExtractConstantFromJoinNode(const QueryTreeNodePtr & join return tryExtractConstantFromConditionNode(join_node_typed.getJoinExpression()); } -void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::shared_ptr & table_join) +void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::shared_ptr & table_join, const ContextPtr & query_context) { StoragePtr storage; @@ -1032,11 +1032,19 @@ void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::sh if (!table_join->isEnabledAlgorithm(JoinAlgorithm::DIRECT) && !table_join->isEnabledAlgorithm(JoinAlgorithm::DEFAULT)) return; - if (auto storage_dictionary = std::dynamic_pointer_cast(storage); - storage_dictionary && storage_dictionary->getDictionary()->getSpecialKeyType() != DictionarySpecialKeyType::Range) - /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. - table_join->setStorageJoin(std::dynamic_pointer_cast(storage_dictionary->getDictionary())); - else if (auto storage_key_value = castStorage(storage, DeferredTable::Load); storage_key_value) + if (auto storage_dictionary = std::dynamic_pointer_cast(storage)) + { + /// This runs even if the right table is not read, e.g. for `CREATE VIEW`, so the access must be checked here. + auto dictionary = storage_dictionary->getDictionary(query_context); + if (dictionary->getSpecialKeyType() != DictionarySpecialKeyType::Range) + { + /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. + table_join->setStorageJoin(std::dynamic_pointer_cast(dictionary)); + return; + } + } + + if (auto storage_key_value = castStorage(storage, DeferredTable::Load); storage_key_value) table_join->setStorageJoin(storage_key_value); } diff --git a/src/Planner/PlannerJoins.h b/src/Planner/PlannerJoins.h index 14c4e63f2981..93dd64340cc8 100644 --- a/src/Planner/PlannerJoins.h +++ b/src/Planner/PlannerJoins.h @@ -295,6 +295,6 @@ std::set extractJoinTableSidesFromExpression( QueryTreeNodePtr getJoinExpressionFromNode(const JoinNode & join_node); -void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::shared_ptr & table_join); +void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::shared_ptr & table_join, const ContextPtr & query_context); } diff --git a/src/Planner/PlannerJoinsLogical.cpp b/src/Planner/PlannerJoinsLogical.cpp index 5a95afa5a193..5164e0625fb2 100644 --- a/src/Planner/PlannerJoinsLogical.cpp +++ b/src/Planner/PlannerJoinsLogical.cpp @@ -606,12 +606,16 @@ PreparedJoinStorage tryGetStorageInTableJoin(const QueryTreeNodePtr & table_expr if (result.storage_join) return result; - auto storage_dictionary = std::dynamic_pointer_cast(storage); - if (storage_dictionary && storage_dictionary->getDictionary()->getSpecialKeyType() != DictionarySpecialKeyType::Range) + if (auto storage_dictionary = std::dynamic_pointer_cast(storage)) { - /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. - result.storage_key_value = std::dynamic_pointer_cast(storage_dictionary->getDictionary()); - return result; + /// This runs even if the right table is not read, e.g. for `CREATE VIEW`, so the access must be checked here. + auto dictionary = storage_dictionary->getDictionary(planner_context->getQueryContext()); + if (dictionary->getSpecialKeyType() != DictionarySpecialKeyType::Range) + { + /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. + result.storage_key_value = std::dynamic_pointer_cast(dictionary); + return result; + } } result.storage_key_value = castStorage(storage, DeferredTable::Load); diff --git a/src/Processors/Formats/Impl/AvroRowInputFormat.cpp b/src/Processors/Formats/Impl/AvroRowInputFormat.cpp index 84646c754a6c..11ddde702a02 100644 --- a/src/Processors/Formats/Impl/AvroRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/AvroRowInputFormat.cpp @@ -8,11 +8,14 @@ #include #include +#include #include #include #include +#include + #include #include @@ -1125,6 +1128,8 @@ class AvroConfluentRowInputFormat::SchemaRegistry if (!url.getUserInfo().empty()) { + Context::getGlobalContextInstance()->getHTTPHeaderFilter().checkURIUserInfo(url); + Poco::Net::HTTPCredentials http_credentials; Poco::Net::HTTPBasicCredentials http_basic_credentials; diff --git a/src/Processors/Formats/Impl/DWARFBlockInputFormat.cpp b/src/Processors/Formats/Impl/DWARFBlockInputFormat.cpp index 0a079eaafeaa..383961020a27 100644 --- a/src/Processors/Formats/Impl/DWARFBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/DWARFBlockInputFormat.cpp @@ -136,8 +136,53 @@ static size_t getColumnIdx(const std::string & name) return it->second; } -DWARFBlockInputFormat::UnitState::UnitState(llvm::DWARFUnit * u) +/// `tryExtractDIEsIfNeeded` makes LLVM parse the unit DIE. LLVM advances the offset by the length of a block or +/// a fixed-size form without checking it against the section (see `checkAttributeEnd`), so a malformed length +/// made it read past the end of the section on the next attribute. Walk the unit DIE the same way with checks first. +/// `data` is truncated at the end of the unit, so this walk itself does not read the next unit, and LLVM parses +/// the unit DIE only if all its attributes are within the unit. +static void checkUnitDie( + const llvm::DWARFUnit & unit, const llvm::DWARFAbbreviationDeclarationSet & abbrevs, const llvm::DWARFDataExtractor & data, + uint64_t end_offset) +{ + const uint64_t end = data.size(); + uint64_t offset = unit.getOffset() + unit.getHeaderSize(); + /// Leave other errors to LLVM, which reports them. + if (offset >= end) + return; + auto err = llvm::Error::success(); + uint64_t abbrev_code = data.getULEB128(&offset, &err); + if (err) + throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, "Failed to parse the unit entry at offset {}: {}", unit.getOffset(), llvm::toString(std::move(err))); + if (abbrev_code == 0 || abbrev_code > UINT32_MAX) + return; + const auto * abbrev = abbrevs.getAbbreviationDeclaration(static_cast(abbrev_code)); + if (!abbrev) + return; + for (const auto & attr : abbrev->attributes()) + { + const uint64_t attr_offset = offset; + if (auto size = attr.getByteSize(unit)) + offset += *size; + else if (!llvm::DWARFFormValue::skipValue(attr.Form, data, &offset, unit.getFormParams())) + return; + /// `skipValue` does not advance the offset if the string is not terminated within the unit. + if (attr.Form == llvm::dwarf::DW_FORM_string && offset == attr_offset) + throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, + "String attribute {} of the unit entry is not terminated before the end of the unit {}", + llvm::dwarf::AttributeString(attr.Attr).operator std::string_view(), end_offset); + /// A huge length makes the offset wrap around. + if (offset < attr_offset || offset > end) + throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, + "Attribute {} of form {} of the unit entry goes past the end of the unit: offset {}, end of unit {}", + llvm::dwarf::AttributeString(attr.Attr).operator std::string_view(), attr.Form, offset, end_offset); + } +} + +DWARFBlockInputFormat::UnitState::UnitState(llvm::DWARFUnit * u, const llvm::DWARFDataExtractor & section_data) : dwarf_unit(u), end_offset(dwarf_unit->getNextUnitOffset()) + /// Offsets stay relative to the start of the section. + , data(section_data, std::min(end_offset, section_data.size())) , offset(dwarf_unit->getOffset() + dwarf_unit->getHeaderSize()) { /// This call is not thread safe, so we do it during initialization. @@ -145,6 +190,8 @@ DWARFBlockInputFormat::UnitState::UnitState(llvm::DWARFUnit * u) if (abbrevs == nullptr) throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, "Couldn't find abbreviation set for unit at offset {}", dwarf_unit->getOffset()); + checkUnitDie(*u, *abbrevs, data, end_offset); + /// This call initializes some data structures inside DWARFUnit that are needed for parsing attributes. auto err = u->tryExtractDIEsIfNeeded(/*CUDieOnly*/ true); if (err) @@ -285,7 +332,7 @@ void DWARFBlockInputFormat::initializeIfNeeded() dwarf_context = llvm::DWARFContext::create(sections, /*AddrSize*/ 8); for (std::unique_ptr & unit : dwarf_context->info_section_units()) - units_queue.emplace_back(unit.get()); + units_queue.emplace_back(unit.get(), *extractor); LOG_DEBUG(getLogger("DWARF"), "{} units, reading in {} threads", units_queue.size(), num_threads); @@ -353,16 +400,32 @@ static inline void throwIfError(llvm::Error & e, const char * what) throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, "Failed to parse {}: {}", what, llvm::toString(std::move(e))); } +/// LLVM advances the offset by the length of a block or a fixed-size form without checking it against the +/// section (LEB128 decoding checks the offset only with an assertion), so every following read would start +/// past the end of the section. Attributes are read from `UnitState::data`, which ends at the end of the unit, +/// so the bytes of the next unit are never read, and the offset is checked after each attribute. +/// The offset is advanced with plain unsigned addition, so a huge length makes it wrap around to before the start of the attribute. +void DWARFBlockInputFormat::checkAttributeEnd( + const llvm::DWARFAbbreviationDeclaration::AttributeSpec & attr, uint64_t attr_offset, uint64_t offset, const UnitState & unit) const +{ + if (offset < attr_offset || offset > unit.data.size()) + throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, + "Attribute {} of form {} goes past the end of the unit: offset {}, end of unit {}", + llvm::dwarf::AttributeString(attr.Attr).operator std::string_view(), attr.Form, offset, unit.end_offset); +} + llvm::DWARFFormValue DWARFBlockInputFormat::parseAttribute( const llvm::DWARFAbbreviationDeclaration::AttributeSpec & attr, uint64_t * offset, const UnitState & unit) const { + const uint64_t attr_offset = *offset; auto val = llvm::DWARFFormValue::createFromSValue( attr.Form, attr.isImplicitConst() ? attr.getImplicitConstValue() : 0); - if (!val.extractValue(*extractor, offset, unit.dwarf_unit->getFormParams(), unit.dwarf_unit)) + if (!val.extractValue(unit.data, offset, unit.dwarf_unit->getFormParams(), unit.dwarf_unit)) throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, "Failed to parse attribute {} of form {} at offset {}", llvm::dwarf::AttributeString(attr.Attr).operator std::string_view(), attr.Form, *offset); + checkAttributeEnd(attr, attr_offset, *offset, unit); return val; } @@ -379,11 +442,18 @@ void DWARFBlockInputFormat::skipAttribute( } else { + const uint64_t attr_offset = *offset; if (!llvm::DWARFFormValue::skipValue( - attr.Form, *extractor, offset, unit.dwarf_unit->getFormParams())) + attr.Form, unit.data, offset, unit.dwarf_unit->getFormParams())) throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, "Failed to skip attribute {} of form {} at offset {}", llvm::dwarf::AttributeString(attr.Attr).operator std::string_view(), attr.Form, *offset); + /// `skipValue` does not advance the offset if the string is not terminated within the unit. + if (attr.Form == llvm::dwarf::DW_FORM_string && *offset == attr_offset) + throw Exception(ErrorCodes::CANNOT_PARSE_DWARF, + "String attribute {} at offset {} is not terminated before the end of the unit {}", + llvm::dwarf::AttributeString(attr.Attr).operator std::string_view(), attr_offset, unit.end_offset); + checkAttributeEnd(attr, attr_offset, *offset, unit); } } @@ -452,7 +522,7 @@ Chunk DWARFBlockInputFormat::parseEntries(UnitState & unit) col_ancestor_array_offsets->insertValue(col_ancestor_tags->size()); } - uint64_t abbrev_code = extractor->getULEB128(&unit.offset, &err); + uint64_t abbrev_code = unit.data.getULEB128(&unit.offset, &err); throwIfError(err, "DIE header"); if (abbrev_code == 0) diff --git a/src/Processors/Formats/Impl/DWARFBlockInputFormat.h b/src/Processors/Formats/Impl/DWARFBlockInputFormat.h index ef94f98a61f2..92a84d87a822 100644 --- a/src/Processors/Formats/Impl/DWARFBlockInputFormat.h +++ b/src/Processors/Formats/Impl/DWARFBlockInputFormat.h @@ -49,6 +49,8 @@ class DWARFBlockInputFormat : public IInputFormat const llvm::DWARFUnit * dwarf_unit; const llvm::DWARFAbbreviationDeclarationSet * abbrevs; uint64_t end_offset; + /// `.debug_info` truncated at the end of this unit, so that parsing its entries never reads the next unit. + llvm::DWARFDataExtractor data; std::string unit_name; ColumnPtr filename_table; // from .debug_line @@ -64,7 +66,7 @@ class DWARFBlockInputFormat : public IInputFormat bool eof() const { return offset == end_offset; } - explicit UnitState(llvm::DWARFUnit * u); + UnitState(llvm::DWARFUnit * u, const llvm::DWARFDataExtractor & section_data); }; const FormatSettings format_settings; @@ -105,6 +107,9 @@ class DWARFBlockInputFormat : public IInputFormat void parseFilenameTable(UnitState & unit, uint64_t offset); Chunk parseEntries(UnitState & unit); + void checkAttributeEnd( + const llvm::DWARFAbbreviationDeclaration::AttributeSpec & attr, uint64_t attr_offset, uint64_t offset, + const UnitState & unit) const; llvm::DWARFFormValue parseAttribute( const llvm::DWARFAbbreviationDeclaration::AttributeSpec & attr, uint64_t * offset, const UnitState & unit) const; diff --git a/src/Processors/Formats/Impl/NativeFormat.cpp b/src/Processors/Formats/Impl/NativeFormat.cpp index d693d295c998..42edec64ad1d 100644 --- a/src/Processors/Formats/Impl/NativeFormat.cpp +++ b/src/Processors/Formats/Impl/NativeFormat.cpp @@ -17,12 +17,7 @@ class NativeInputFormat final : public IInputFormat public: NativeInputFormat(ReadBuffer & buf, SharedHeader header_, const FormatSettings & settings_) : IInputFormat(header_, &buf) - , reader(std::make_unique( - buf, - *header_, - 0, - settings_, - settings_.defaults_for_omitted_fields ? &block_missing_values : nullptr)) + , reader(makeReader(buf, *header_, settings_, block_missing_values)) , header(header_) , block_missing_values(header->columns()) , settings(settings_) @@ -56,7 +51,7 @@ class NativeInputFormat final : public IInputFormat void setReadBuffer(ReadBuffer & in_) override { - reader = std::make_unique(in_, *header, 0, settings, settings.defaults_for_omitted_fields ? &block_missing_values : nullptr); + reader = makeReader(in_, *header, settings, block_missing_values); IInputFormat::setReadBuffer(in_); } @@ -65,6 +60,19 @@ class NativeInputFormat final : public IInputFormat size_t getApproxBytesReadForChunk() const override { return approx_bytes_read_for_chunk; } private: + /// Revision 0 has no serialization kinds in its layout, so the kind set takes effect only with a non-zero revision. + static std::unique_ptr makeReader( + ReadBuffer & buf, const Block & header_, const FormatSettings & settings_, BlockMissingValues & block_missing_values_) + { + return std::make_unique( + buf, + header_, + 0, + settings_, + settings_.defaults_for_omitted_fields ? &block_missing_values_ : nullptr, + ISerialization::KindSet{ISerialization::Kind::DEFAULT}); + } + std::unique_ptr reader; SharedHeader header; BlockMissingValues block_missing_values; @@ -105,7 +113,7 @@ class NativeSchemaReader : public ISchemaReader NamesAndTypesList readSchema() override { - auto reader = NativeReader(in, 0, settings); + auto reader = NativeReader(in, 0, settings, ISerialization::KindSet{ISerialization::Kind::DEFAULT}); auto block = reader.read(); return block.getNamesAndTypesList(); } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.cpp b/src/Processors/Formats/Impl/Parquet/Decoding.cpp index e52e24dce6a8..66c7de20d5fa 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp +++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp @@ -328,8 +328,9 @@ struct PlainStringDecoder : public PageDecoder { for (size_t i = 0; i < num_values; ++i) { - UInt32 x; - memcpy(&x, data, 4); /// omitting range check because input is padded + requireRemainingBytes(4); + UInt32 x = 0; + memcpy(&x, data, 4); size_t len = 4 + size_t(x); requireRemainingBytes(len); data += len; @@ -350,8 +351,9 @@ struct PlainStringDecoder : public PageDecoder col_str.reserve(col_str.size() + to_reserve); for (size_t i = 0; i < num_values; ++i) { - UInt32 x; - memcpy(&x, data, 4); /// omitting range check because input is padded + requireRemainingBytes(4); + UInt32 x = 0; + memcpy(&x, data, 4); size_t len = 4 + size_t(x); requireRemainingBytes(len); if (!filter || filter[filter_offset + i]) @@ -370,12 +372,7 @@ struct PlainStringDecoder : public PageDecoder num_pass += filter[filter_offset + i]; if (num_pass == 0) { - for (size_t i = 0; i < num_values; ++i) - { - UInt32 x; - memcpy(&x, data, 4); - data += 4 + size_t(x); - } + skip(num_values); return; } chars_buf.reserve(num_pass * 32); // rough estimate @@ -383,7 +380,8 @@ struct PlainStringDecoder : public PageDecoder size_t offset = 0; for (size_t i = 0; i < num_values; ++i) { - UInt32 x; + requireRemainingBytes(4); + UInt32 x = 0; memcpy(&x, data, 4); size_t len = 4 + size_t(x); requireRemainingBytes(len); @@ -405,8 +403,9 @@ struct PlainStringDecoder : public PageDecoder size_t offset = 0; for (size_t i = 0; i < num_values; ++i) { - UInt32 x; - memcpy(&x, data, 4); /// omitting range check because input is padded + requireRemainingBytes(4); + UInt32 x = 0; + memcpy(&x, data, 4); size_t len = 4 + size_t(x); requireRemainingBytes(len); offset += len; diff --git a/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp b/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp index 02e5f79ee3f4..81934e8c20bb 100644 --- a/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp @@ -2,6 +2,8 @@ #if USE_PARQUET +#include +#include #include #include #include @@ -21,6 +23,7 @@ #include #include #include +#include #include @@ -30,6 +33,8 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int CANNOT_READ_ALL_DATA; + extern const int TOO_DEEP_RECURSION; } static NamesAndTypesList getHeaderForParquetMetadata() @@ -127,12 +132,89 @@ void checkHeader(const Block & header) } } +static std::shared_ptr readAt(arrow::io::RandomAccessFile & file, int64_t position, int64_t nbytes) +{ + auto buffer = file.ReadAt(position, nbytes); + if (!buffer.ok()) + throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read Parquet metadata: {}", buffer.status().ToString()); + if ((*buffer)->size() != nbytes) + throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read Parquet metadata: unexpected end of file"); + return *buffer; +} + +/// Arrow builds the schema tree recursively (`parquet::schema::Unflatten`, `parquet::SchemaDescriptor`), +/// so a deeply nested schema exhausts the stack. Unlike the native Parquet reader, which has `checkStackSize` +/// as a backstop, the recursion in Arrow cannot be guarded, so the depth is always limited by this ceiling, +/// even if `max_parser_depth` is raised or set to 0 (unlimited). In a release build, Arrow exhausts +/// an 8 MiB stack at a depth between 30000 and 100000; frames are several times larger in sanitizer +/// and debug builds, and the ceiling leaves a wide margin for them. +static constexpr size_t MAX_SCHEMA_DEPTH_FOR_ARROW = 1000; + +/// Check the nesting depth of the schema with a non-recursive walk before giving the footer to Arrow, +/// with the same limit as the native Parquet reader (`max_parser_depth`), capped by `MAX_SCHEMA_DEPTH_FOR_ARROW`. +static void checkSchemaDepth(arrow::io::RandomAccessFile & file, const FormatSettings & format_settings) +{ + const size_t max_parser_depth = format_settings.max_parser_depth; + const size_t max_depth = (max_parser_depth == 0) ? MAX_SCHEMA_DEPTH_FOR_ARROW : std::min(max_parser_depth, MAX_SCHEMA_DEPTH_FOR_ARROW); + + auto file_size_or_error = file.GetSize(); + if (!file_size_or_error.ok()) + throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read Parquet metadata: {}", file_size_or_error.status().ToString()); + const int64_t file_size = *file_size_or_error; + + /// Leave invalid and encrypted files (with the "PARE" magic) to Arrow, which reports a proper error. + if (file_size < 12) + return; + auto tail = readAt(file, file_size - 8, 8); + if (memcmp(tail->data() + 4, "PAR1", 4) != 0) + return; + const int64_t metadata_size = unalignedLoadLittleEndian(tail->data()); + if (metadata_size > file_size - 8) + return; + + auto footer = readAt(file, file_size - 8 - metadata_size, metadata_size); + Parquet::parq::FileMetaData metadata; + Parquet::deserializeThriftStruct(metadata, reinterpret_cast(footer->data()), footer->size()); + + /// The schema is a depth-first list of elements where a group element is followed by its `num_children` children. + /// The stack holds the number of children still to come for each group the walk is in. + VectorWithMemoryTracking children_left; + for (const auto & element : metadata.schema) + { + while (!children_left.empty() && children_left.back() == 0) + children_left.pop_back(); + if (!children_left.empty()) + --children_left.back(); + else if (&element != &metadata.schema.front()) + break; /// Elements after the root are invalid, Arrow reports it. + + if (element.__isset.num_children && element.num_children > 0) + { + children_left.push_back(element.num_children); + if (children_left.size() > max_depth) + { + if (max_depth == MAX_SCHEMA_DEPTH_FOR_ARROW) + throw Exception( + ErrorCodes::TOO_DEEP_RECURSION, + "Parquet schema is nested deeper than the limit ({}) of the `ParquetMetadata` format", + max_depth); + throw Exception( + ErrorCodes::TOO_DEEP_RECURSION, + "Parquet schema is nested deeper than the limit ({}). It can be raised with the setting " + "'max_parser_depth', but a very deeply nested schema is rarely intentional", + max_depth); + } + } + } +} + static std::shared_ptr getFileMetadata( ReadBuffer & in, const FormatSettings & format_settings, std::atomic & is_stopped) { auto arrow_file = asArrowFile(in, format_settings, is_stopped, "Parquet", PARQUET_MAGIC_BYTES, /* avoid_buffering */ true); + checkSchemaDepth(*arrow_file, format_settings); return parquet::ReadMetaData(arrow_file); } diff --git a/src/Processors/Formats/Impl/TemplateRowInputFormat.cpp b/src/Processors/Formats/Impl/TemplateRowInputFormat.cpp index 332ba774c496..1165e792e628 100644 --- a/src/Processors/Formats/Impl/TemplateRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/TemplateRowInputFormat.cpp @@ -338,6 +338,8 @@ TemplateFormatReader::TemplateFormatReader( format.throwInvalidFormat("XML deserialization is not supported", i); } } + if (!has_data) + format.throwInvalidFormat("${data} must occur in the format string for result set", format.columnsCount()); /// Validate format string for rows for (size_t i = 0; i < row_format.columnsCount(); ++i) diff --git a/src/Processors/QueryPlan/AggregatingStep.cpp b/src/Processors/QueryPlan/AggregatingStep.cpp index 4b99ed3a2383..980acf8393c8 100644 --- a/src/Processors/QueryPlan/AggregatingStep.cpp +++ b/src/Processors/QueryPlan/AggregatingStep.cpp @@ -863,6 +863,8 @@ QueryPlanStepPtr AggregatingStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptions(aggregates, ctx.in); + checkDeserializedAggregateOutputNames(keys, aggregates); + checkDeserializedAggregateArguments(aggregates, *ctx.input_headers.front()); UInt64 stats_key = 0; if (has_stats_key) diff --git a/src/Processors/QueryPlan/BlocksMarshallingStep.cpp b/src/Processors/QueryPlan/BlocksMarshallingStep.cpp index d2858b19fce3..5f843d63ed9e 100644 --- a/src/Processors/QueryPlan/BlocksMarshallingStep.cpp +++ b/src/Processors/QueryPlan/BlocksMarshallingStep.cpp @@ -8,6 +8,11 @@ namespace DB { +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} + static ITransformingStep::Traits getTraits() { return ITransformingStep::Traits @@ -73,7 +78,8 @@ void BlocksMarshallingStep::transformPipeline(QueryPipelineBuilder & pipeline, c QueryPlanStepPtr BlocksMarshallingStep::deserialize(Deserialization & ctx) { - chassert(ctx.input_headers.size() == 1); + if (ctx.input_headers.size() != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, "BlocksMarshallingStep must have exactly one input, got {}", ctx.input_headers.size()); return std::make_unique(ctx.input_headers.front()); } diff --git a/src/Processors/QueryPlan/MaterializingCTEStep.cpp b/src/Processors/QueryPlan/MaterializingCTEStep.cpp index 151d76b4acff..b67140675c16 100644 --- a/src/Processors/QueryPlan/MaterializingCTEStep.cpp +++ b/src/Processors/QueryPlan/MaterializingCTEStep.cpp @@ -36,7 +36,7 @@ constexpr ITransformingStep::Traits getMaterializingCTETraits() MaterializingCTEStep::MaterializingCTEStep( SharedHeader input_header_, - MaterializedCTEPtr materialized_cte_ + MaterializedCTEWeakPtr materialized_cte_ ) : ITransformingStep(std::move(input_header_), std::make_shared(Block{}), getMaterializingCTETraits()) , materialized_cte(std::move(materialized_cte_)) @@ -45,7 +45,12 @@ MaterializingCTEStep::MaterializingCTEStep( void MaterializingCTEStep::transformPipeline(QueryPipelineBuilder & pipeline, const BuildQueryPipelineSettings &) { - pipeline.addMaterializingCTETransform(getOutputHeader(), materialized_cte); + auto cte = materialized_cte.lock(); + if (!cte) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "Materialized CTE was destroyed before a pipeline was built for its plan"); + + pipeline.addMaterializingCTETransform(getOutputHeader(), std::move(cte)); } void MaterializingCTEStep::describeActions([[maybe_unused]] JSONBuilder::JSONMap & map) const @@ -56,8 +61,8 @@ void MaterializingCTEStep::describeActions([[maybe_unused]] FormatSettings & set { } -MaterializingCTEsStep::MaterializingCTEsStep(SharedHeaders input_headers_) - : IQueryPlanStep() +MaterializingCTEsStep::MaterializingCTEsStep(SharedHeaders input_headers_, std::vector ctes_) + : ctes(std::move(ctes_)) { input_headers = std::move(input_headers_); output_header = input_headers.front(); @@ -109,20 +114,25 @@ QueryPipelineBuilderPtr DelayedMaterializingCTEsStep::updatePipeline(QueryPipeli "Cannot build pipeline in DelayedMaterializingCTEs. This step should be optimized out."); } -std::vector> DelayedMaterializingCTEsStep::makePlansForCTEs( +std::vector DelayedMaterializingCTEsStep::makePlansForCTEs( DelayedMaterializingCTEsStep && step, const QueryPlanOptimizationSettings & optimization_settings) { - std::vector> plans; + std::vector claimed; for (auto & materialized_cte : step.ctes) { if (materialized_cte->is_materialization_planned.exchange(true)) continue; materialized_cte->plan->optimize(optimization_settings); - plans.emplace_back(std::move(materialized_cte->plan)); + + /// The CTE handle travels with its plan so that the step which + /// attaches the plan also becomes the CTE's owner: the plan holds + /// only a weak back-reference (`MaterializingCTEStep`), and CTEs + /// claimed elsewhere must stay out of this list. + claimed.push_back({materialized_cte, std::move(materialized_cte->plan)}); } - return plans; + return claimed; } } diff --git a/src/Processors/QueryPlan/MaterializingCTEStep.h b/src/Processors/QueryPlan/MaterializingCTEStep.h index 3c78d99a29d5..2396066a1aaf 100644 --- a/src/Processors/QueryPlan/MaterializingCTEStep.h +++ b/src/Processors/QueryPlan/MaterializingCTEStep.h @@ -14,7 +14,7 @@ class MaterializingCTEStep : public ITransformingStep public: explicit MaterializingCTEStep( SharedHeader input_header_, - MaterializedCTEPtr materialized_cte_ + MaterializedCTEWeakPtr materialized_cte_ ); String getName() const override { return "MaterializingCTE"; } @@ -28,14 +28,19 @@ class MaterializingCTEStep : public ITransformingStep void updateOutputHeader() override {} // Output header should stay empty. - MaterializedCTEPtr materialized_cte; + /// Weak on purpose: this step is appended to `materialized_cte->plan`, so a strong handle + /// would make the CTE keep itself alive with no external holder - and a query dying before + /// `resolveMaterializingCTEs` claims the plan would leak the graph, and the table references + /// it carries, for the life of the process. `StorageMemory::materialized_cte` is weak for + /// the same reason. + MaterializedCTEWeakPtr materialized_cte; }; class MaterializingCTEsStep : public IQueryPlanStep { public: - explicit MaterializingCTEsStep(SharedHeaders input_headers_); + MaterializingCTEsStep(SharedHeaders input_headers_, std::vector ctes_); String getName() const override { return "MaterializingCTEs"; } @@ -43,6 +48,12 @@ class MaterializingCTEsStep : public IQueryPlanStep private: void updateOutputHeader() override { output_header = getInputHeaders().front(); } + + /// This step replaces `DelayedMaterializingCTEsStep` once the CTE plans have been claimed + /// and hung below it, so it takes over that step's role as the owner keeping the CTEs alive + /// until the pipeline is built. Holds exactly the CTEs whose plans hang below this node - + /// a CTE claimed by someone else is owned by whoever attached its plan. + std::vector ctes; }; @@ -66,9 +77,20 @@ class DelayedMaterializingCTEsStep final : public IQueryPlanStep QueryPipelineBuilderPtr updatePipeline(QueryPipelineBuilders, const BuildQueryPipelineSettings &) override; + /// A CTE claimed by `makePlansForCTEs`: the pre-built plan to hang below the + /// `MaterializingCTEsStep` that replaces this step, paired with the strong handle + /// that keeps the CTE alive for as long as that plan exists. The pairing is what + /// lets the replacing step own exactly the CTEs it materializes - the plan itself + /// refers back to the CTE only weakly, see `MaterializingCTEStep::materialized_cte`. + struct ClaimedCTE + { + MaterializedCTEPtr cte; + std::unique_ptr plan; + }; + /// Returns the subset of pre-built CTE plans that still need to be executed, /// atomically marking each as materialized. CTEs already marked are skipped. - static std::vector> makePlansForCTEs( + static std::vector makePlansForCTEs( DelayedMaterializingCTEsStep && step, const QueryPlanOptimizationSettings & optimization_settings); diff --git a/src/Processors/QueryPlan/MergingAggregatedStep.cpp b/src/Processors/QueryPlan/MergingAggregatedStep.cpp index c8062a42ca14..fd75e5f4bf89 100644 --- a/src/Processors/QueryPlan/MergingAggregatedStep.cpp +++ b/src/Processors/QueryPlan/MergingAggregatedStep.cpp @@ -240,6 +240,73 @@ void MergingAggregatedStep::serialize(Serialization & ctx) const writeIntBinary(params.stats_collecting_params.key, ctx.out); } +/// With grouping sets, `MergingAggregatedTransform` removes `__grouping_set` from the input and, for every set, +/// moves its keys to the front (see `makeReorderingActions`) and drops the other keys. Check the layout it merges. +static void checkMergedAggregatesLayout( + const Names & keys, const GroupingSetsParamsList & grouping_sets_params, const AggregateDescriptions & aggregates, const Block & header) +{ + if (grouping_sets_params.empty()) + { + /// `appendGroupingIfNeeded` would copy a `__grouping_set` column of the input into the output header, + /// but the merge without grouping sets does not produce it. + if (header.has("__grouping_set")) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized `MergingAggregated` step without grouping sets has a `__grouping_set` column"); + checkDeserializedMergedAggregatesLayout(keys, aggregates, header.getColumnsWithTypeAndName()); + return; + } + + /// The transform splits the rows by the values of `__grouping_set` read as `ColumnUInt64`, and the output header + /// takes its type from the input. + size_t num_grouping_set_columns = 0; + for (const auto & column : header) + { + if (column.name != "__grouping_set") + continue; + ++num_grouping_set_columns; + if (column.type->getTypeId() != TypeIndex::UInt64) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The `__grouping_set` column in the input of a deserialized `MergingAggregated` step has type {} instead of UInt64", + column.type->getName()); + } + if (num_grouping_set_columns != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized `MergingAggregated` step with grouping sets has {} `__grouping_set` columns instead of one", + num_grouping_set_columns); + + /// The per-set layouts below skip the keys of a set after its used keys, but the output header and the + /// reconstruction of the missing keys (`makeCreatingMissingKeysForGroupingSetDAG`) take every key from the + /// original input by name, i.e. from its first occurrence. So every key must occur at most once there. + NameSet seen_keys; + const NameSet all_keys(keys.begin(), keys.end()); + for (const auto & column : header) + if (all_keys.contains(column.name) && !seen_keys.insert(column.name).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key {} occurs more than once in the input of a deserialized `MergingAggregated` step with grouping sets", + column.name); + + for (const auto & grouping_set : grouping_sets_params) + { + NameSet keys_of_set(grouping_set.used_keys.begin(), grouping_set.used_keys.end()); + keys_of_set.insert(grouping_set.missing_keys.begin(), grouping_set.missing_keys.end()); + + ColumnsWithTypeAndName layout; + for (const auto & key : grouping_set.used_keys) + { + const auto * column = header.findByName(key); + if (!column || key == "__grouping_set") + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key {} of a grouping set is not in the input of a deserialized `MergingAggregated` step", key); + layout.push_back(*column); + } + for (const auto & column : header) + if (column.name != "__grouping_set" && !keys_of_set.contains(column.name)) + layout.push_back(column); + + checkDeserializedMergedAggregatesLayout(grouping_set.used_keys, aggregates, layout); + } +} + QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) { if (ctx.input_headers.size() != 1) @@ -288,10 +355,16 @@ QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptions(aggregates, ctx.in); + checkMergedAggregatesLayout(keys, grouping_sets_params, aggregates, *ctx.input_headers.front()); SortDescription group_by_sort_description; deserializeSortDescription(group_by_sort_description, ctx.in); + /// The memory-bound merge is used with a non-empty sort description, and it does not support grouping sets. + if (memory_bound_merging_of_aggregation_results_enabled && !group_by_sort_description.empty() && !grouping_sets_params.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The memory-bound merging of aggregated results with grouping sets in a serialized query plan"); + UInt64 stats_key = 0; if (has_stats_key) readIntBinary(stats_key, ctx.in); @@ -302,6 +375,12 @@ QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) ctx.settings[QueryPlanSerializationSetting::max_entries_for_hash_table_stats], ctx.settings[QueryPlanSerializationSetting::max_size_to_preallocate_for_aggregation]); + /// The planners never enable the memory-efficient merge with grouping sets, and it does not support them. + const bool memory_efficient_aggregation = ctx.settings[QueryPlanSerializationSetting::distributed_aggregation_memory_efficient]; + if (memory_efficient_aggregation && !grouping_sets_params.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The memory-efficient merging of aggregated results with grouping sets in a serialized query plan"); + const auto & settings = ctx.context->getSettingsRef(); Aggregator::Params params( @@ -318,7 +397,7 @@ QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) std::move(params), std::move(grouping_sets_params), final, - ctx.settings[QueryPlanSerializationSetting::distributed_aggregation_memory_efficient], + memory_efficient_aggregation, settings[Setting::aggregation_memory_efficient_merge_threads], should_produce_results_in_order_of_bucket_number, ctx.settings[QueryPlanSerializationSetting::max_block_size], diff --git a/src/Processors/QueryPlan/Optimizations/addPlansForMaterializingCTEs.cpp b/src/Processors/QueryPlan/Optimizations/addPlansForMaterializingCTEs.cpp index fcc327fd5163..04634801f3e2 100644 --- a/src/Processors/QueryPlan/Optimizations/addPlansForMaterializingCTEs.cpp +++ b/src/Processors/QueryPlan/Optimizations/addPlansForMaterializingCTEs.cpp @@ -19,22 +19,30 @@ void addPlansForMaterializingCTEs( if (!delayed) return; - auto plans = DelayedMaterializingCTEsStep::makePlansForCTEs(std::move(*delayed), optimization_settings); + auto claimed_ctes = DelayedMaterializingCTEsStep::makePlansForCTEs(std::move(*delayed), optimization_settings); SharedHeaders input_headers; - input_headers.reserve(1 + plans.size()); + input_headers.reserve(1 + claimed_ctes.size()); input_headers.push_back(node.children.front()->step->getOutputHeader()); - for (auto & plan : plans) + /// The claimed plans hung below this node reference their CTEs only weakly, so the step + /// replacing the delayed one has to take over the strong handles - for exactly the CTEs + /// it claimed. A CTE claimed by someone else (a recursive `buildSetInplace` that + /// materialized it inplace) has its plan attached elsewhere and is owned there. + std::vector ctes; + ctes.reserve(claimed_ctes.size()); + + for (auto & [cte, plan] : claimed_ctes) { input_headers.push_back(plan->getCurrentHeader()); node.children.push_back(plan->getRootNode()); auto [add_nodes, add_resources] = QueryPlan::detachNodesAndResources(std::move(*plan)); nodes.splice(nodes.end(), std::move(add_nodes)); root_plan.addResources(std::move(add_resources)); + ctes.push_back(std::move(cte)); } - auto materializing_ctes = std::make_unique(std::move(input_headers)); + auto materializing_ctes = std::make_unique(std::move(input_headers), std::move(ctes)); materializing_ctes->setStepDescription("Materialize CTEs before main query execution"); node.step = std::move(materializing_ctes); } diff --git a/src/Processors/QueryPlan/Serialization.cpp b/src/Processors/QueryPlan/Serialization.cpp index 55194bf06ee5..13a8b038f012 100644 --- a/src/Processors/QueryPlan/Serialization.cpp +++ b/src/Processors/QueryPlan/Serialization.cpp @@ -27,6 +27,14 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +const SharedHeader & DeserializedInputHeaders::at(size_t i) const +{ + if (i >= headers.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A step of the serialized query plan has {} input(s), but the input {} is required", headers.size(), i); + return headers[i]; +} + static void serializeHeader(const Block & header, WriteBuffer & out) { /// Write only names and types. @@ -219,11 +227,25 @@ QueryPlanAndSets QueryPlan::deserialize(ReadBuffer & in, const ContextPtr & cont SharedHeaders input_headers; input_headers.reserve(frame.children.size()); for (const auto & child : frame.children) + { + /// A sink (e.g. `GatherSend`) has no output, so it cannot be an input of another step. + if (!child->step->hasOutputHeader()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Deserialized step {} has a child step {} without an output stream", + step_name, child->step->getName()); input_headers.push_back(child->step->getOutputHeader()); + } IQueryPlanStep::Deserialization ctx{in, sets_registry, {}, context, input_headers, output_header, settings}; auto step = step_registry.createStep(step_name, ctx); + /// The plan tree assumes that a step has exactly one input per child, e.g. optimizations iterate + /// over the children and access the input header of each of them. + if (step->getInputHeaders().size() != frame.children.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Deserialized step {} has {} input(s), but the serialized query plan has {} child(ren) of it", + step_name, step->getInputHeaders().size(), frame.children.size()); + if (step->hasOutputHeader()) { assertCompatibleHeader( diff --git a/src/Processors/QueryPlan/Serialization.h b/src/Processors/QueryPlan/Serialization.h index b4e1dfbbb7de..4e9844af63cd 100644 --- a/src/Processors/QueryPlan/Serialization.h +++ b/src/Processors/QueryPlan/Serialization.h @@ -26,6 +26,31 @@ struct IQueryPlanStep::Serialization struct SerializedSetsRegistry; +/// The output headers of the children of a step being deserialized. The number of children comes from +/// the serialized plan, so it may not be what the step expects: accessing a missing child throws +/// instead of reading out of bounds. Converts to `const SharedHeaders &` to pass all of them on. +class DeserializedInputHeaders +{ +public: + DeserializedInputHeaders(const SharedHeaders & headers_) : headers(headers_) {} /// NOLINT(google-explicit-constructor) + /// Only a reference is stored, so a temporary vector would dangle right after the initialization. + DeserializedInputHeaders(SharedHeaders && headers_) = delete; + operator const SharedHeaders &() const { return headers; } /// NOLINT(google-explicit-constructor) + + [[nodiscard]] size_t size() const { return headers.size(); } + [[nodiscard]] bool empty() const { return headers.empty(); } + [[nodiscard]] auto begin() const { return headers.begin(); } + [[nodiscard]] auto end() const { return headers.end(); } + + [[nodiscard]] const SharedHeader & at(size_t i) const; + [[nodiscard]] const SharedHeader & operator[](size_t i) const { return at(i); } + [[nodiscard]] const SharedHeader & front() const { return at(0); } + [[nodiscard]] const SharedHeader & back() const { return at(headers.empty() ? 0 : headers.size() - 1); } + +private: + const SharedHeaders & headers; +}; + /// Deserialization context passed to `IQueryPlanStep::deserialize`. struct IQueryPlanStep::Deserialization { @@ -35,7 +60,7 @@ struct IQueryPlanStep::Deserialization const ContextPtr & context; - const SharedHeaders & input_headers; + DeserializedInputHeaders input_headers; const SharedHeader & output_header; const QueryPlanSerializationSettings & settings; }; diff --git a/src/Processors/QueryPlan/TotalsHavingStep.cpp b/src/Processors/QueryPlan/TotalsHavingStep.cpp index 2695c5ce4349..f6adbdd91a46 100644 --- a/src/Processors/QueryPlan/TotalsHavingStep.cpp +++ b/src/Processors/QueryPlan/TotalsHavingStep.cpp @@ -203,6 +203,7 @@ QueryPlanStepPtr TotalsHavingStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptions(aggregates, ctx.in); + checkDeserializedFinalizedAggregates(aggregates, *ctx.input_headers.front()); std::optional actions_dag; String filter_column_name; diff --git a/src/Processors/QueryPlan/UnionStep.cpp b/src/Processors/QueryPlan/UnionStep.cpp index 84acf947d518..f03f25014376 100644 --- a/src/Processors/QueryPlan/UnionStep.cpp +++ b/src/Processors/QueryPlan/UnionStep.cpp @@ -14,6 +14,7 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; } static SharedHeader checkHeaders(const SharedHeaders & input_headers) @@ -96,6 +97,9 @@ void UnionStep::serialize(Serialization & ctx) const QueryPlanStepPtr UnionStep::deserialize(Deserialization & ctx) { + if (ctx.input_headers.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "UnionStep must have at least one input"); + return std::make_unique(ctx.input_headers); } diff --git a/src/Processors/TTL/TTLColumnAlgorithm.cpp b/src/Processors/TTL/TTLColumnAlgorithm.cpp index 91cb9f5080fe..208ffb08c7a5 100644 --- a/src/Processors/TTL/TTLColumnAlgorithm.cpp +++ b/src/Processors/TTL/TTLColumnAlgorithm.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include namespace DB { @@ -12,12 +15,14 @@ TTLColumnAlgorithm::TTLColumnAlgorithm( const String & column_name_, const ExpressionActionsPtr & default_expression_, const String & default_column_name_, - bool is_compact_part_) + bool is_compact_part_, + bool shares_nested_offsets_) : ITTLAlgorithm(ttl_expressions_, description_, old_ttl_info_, current_time_, force_) , column_name(column_name_) , default_expression(default_expression_) , default_column_name(default_column_name_) , is_compact_part(is_compact_part_) + , shares_nested_offsets(shares_nested_offsets_) { if (!isMinTTLExpired()) { @@ -29,6 +34,14 @@ TTLColumnAlgorithm::TTLColumnAlgorithm( new_ttl_info.ttl_finished = true; } +ColumnPtr TTLColumnAlgorithm::createArraysOfDefaults(const IDataType & type, const IColumn & column_with_sizes) +{ + const auto & column_array = assert_cast(column_with_sizes); + const auto & nested_type = assert_cast(type).getNestedType(); + auto data = nested_type->createColumnConstWithDefaultValue(column_array.getData().size()); + return ColumnArray::create(data->convertToFullColumnIfConst(), column_array.getOffsetsPtr()); +} + void TTLColumnAlgorithm::execute(Block & block) { if (block.empty()) @@ -48,6 +61,17 @@ void TTLColumnAlgorithm::execute(Block & block) /// projections can correctly recalculate using it. if (isMaxTTLExpired() && !is_compact_part) { + /// A `Nested` subcolumn stays in the part, so it has to hold the value a read would return: + /// its `DEFAULT` expression, or arrays of defaults with the sizes shared with the other subcolumns. + if (shares_nested_offsets) + { + auto default_column = executeExpressionAndGetColumn(default_expression, block, default_column_name); + if (!default_column) + default_column = createArraysOfDefaults(*column_with_type.type, *column_with_type.column); + column_with_type.column = default_column->convertToFullColumnIfConst(); + return; + } + auto empty_column = column_with_type.column->cloneEmpty(); empty_column->insertManyDefaults(block.rows()); column_with_type.column = std::move(empty_column); @@ -55,6 +79,8 @@ void TTLColumnAlgorithm::execute(Block & block) } auto default_column = executeExpressionAndGetColumn(default_expression, block, default_column_name); + if (!default_column && shares_nested_offsets) + default_column = createArraysOfDefaults(*column_with_type.type, *column_with_type.column); if (default_column) default_column = default_column->convertToFullColumnIfConst(); @@ -89,7 +115,7 @@ void TTLColumnAlgorithm::finalize(const MutableDataPartPtr & data_part) const { data_part->ttl_infos.columns_ttl[column_name] = new_ttl_info; data_part->ttl_infos.updatePartMinMaxTTL(new_ttl_info); - if (is_fully_empty) + if (is_fully_empty && !shares_nested_offsets) data_part->expired_columns.insert(column_name); } diff --git a/src/Processors/TTL/TTLColumnAlgorithm.h b/src/Processors/TTL/TTLColumnAlgorithm.h index f34dae952d16..6ef19bb98c70 100644 --- a/src/Processors/TTL/TTLColumnAlgorithm.h +++ b/src/Processors/TTL/TTLColumnAlgorithm.h @@ -6,7 +6,8 @@ namespace DB { /// Deletes (replaces to default) values in column according to column's TTL description. -/// If all values in column are replaced with defaults, this column won't be written to part. +/// If all values in column are replaced with defaults, this column won't be written to part, +/// unless it is a `Nested` subcolumn that shares the array sizes with the other subcolumns. class TTLColumnAlgorithm final : public ITTLAlgorithm { public: @@ -19,12 +20,16 @@ class TTLColumnAlgorithm final : public ITTLAlgorithm const String & column_name_, const ExpressionActionsPtr & default_expression_, const String & default_column_name_, - bool is_compact_part_ + bool is_compact_part_, + bool shares_nested_offsets_ ); void execute(Block & block) override; void finalize(const MutableDataPartPtr & data_part) const override; + /// The default of a `Nested` subcolumn keeps the array sizes, which it shares with the other subcolumns. + static ColumnPtr createArraysOfDefaults(const IDataType & type, const IColumn & column_with_sizes); + private: const String column_name; const ExpressionActionsPtr default_expression; @@ -32,6 +37,7 @@ class TTLColumnAlgorithm final : public ITTLAlgorithm bool is_fully_empty = true; bool is_compact_part; + bool shares_nested_offsets; }; } diff --git a/src/Processors/Transforms/AggregatingInOrderTransform.cpp b/src/Processors/Transforms/AggregatingInOrderTransform.cpp index 31a0a213a87f..0643425531b2 100644 --- a/src/Processors/Transforms/AggregatingInOrderTransform.cpp +++ b/src/Processors/Transforms/AggregatingInOrderTransform.cpp @@ -357,7 +357,7 @@ void FinalizeAggregatedTransform::transform(Chunk & chunk) { if (params->final) { - finalizeChunk(chunk, aggregates_mask); + finalizeChunk(chunk, aggregates_mask, getOutputPort().getHeader()); } else if (!chunk.getChunkInfos().get()) { diff --git a/src/Processors/Transforms/CubeTransform.cpp b/src/Processors/Transforms/CubeTransform.cpp index a214a2aa1fc4..5a53a2a1bee2 100644 --- a/src/Processors/Transforms/CubeTransform.cpp +++ b/src/Processors/Transforms/CubeTransform.cpp @@ -53,7 +53,7 @@ Chunk CubeTransform::generate() current_chunk = merge(std::move(chunks), !use_nulls, false); } - finalizeChunk(gen_chunk, aggregates_mask); + finalizeChunk(gen_chunk, aggregates_mask, finalized_header); if (!gen_chunk.empty()) gen_chunk.addColumn(0, ColumnUInt64::create(gen_chunk.getNumRows(), grouping_set++)); return gen_chunk; diff --git a/src/Processors/Transforms/RollupTransform.cpp b/src/Processors/Transforms/RollupTransform.cpp index 203908107c61..07252d6bab44 100644 --- a/src/Processors/Transforms/RollupTransform.cpp +++ b/src/Processors/Transforms/RollupTransform.cpp @@ -10,6 +10,7 @@ GroupByModifierTransform::GroupByModifierTransform(SharedHeader header, Aggregat : IAccumulatingTransform(std::move(header), std::make_shared(generateOutputHeader(params_->getHeader(), params_->params.keys, use_nulls_))) , params(std::move(params_)) , use_nulls(use_nulls_) + , finalized_header(params->getHeader()) { keys.reserve(params->params.keys_size); for (const auto & key : params->params.keys) @@ -107,7 +108,7 @@ Chunk RollupTransform::generate() current_chunk = merge(std::move(chunks), !use_nulls, false); } - finalizeChunk(gen_chunk, aggregates_mask); + finalizeChunk(gen_chunk, aggregates_mask, finalized_header); if (!gen_chunk.empty()) gen_chunk.addColumn(0, ColumnUInt64::create(gen_chunk.getNumRows(), set_counter++)); return gen_chunk; diff --git a/src/Processors/Transforms/RollupTransform.h b/src/Processors/Transforms/RollupTransform.h index 2e8d0452192f..05d1e9054118 100644 --- a/src/Processors/Transforms/RollupTransform.h +++ b/src/Processors/Transforms/RollupTransform.h @@ -30,6 +30,8 @@ struct GroupByModifierTransform : public IAccumulatingTransform std::unique_ptr output_aggregator; Block intermediate_header; + /// The header of a generated chunk after `finalizeChunk`, without `__grouping_set`. + const Block finalized_header; Chunks consumed_chunks; Chunk current_chunk; diff --git a/src/Processors/Transforms/TTLTransform.cpp b/src/Processors/Transforms/TTLTransform.cpp index 1d1154f217ce..e84465cbb661 100644 --- a/src/Processors/Transforms/TTLTransform.cpp +++ b/src/Processors/Transforms/TTLTransform.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -31,6 +32,17 @@ static TTLExpressions getExpressions(const TTLDescription & ttl_descr, PreparedS return {expr.expression, where_expr.expression}; } +/// Returns a stored `Nested` sibling of `name`, whose array sizes a read uses to fill `name`. +static const ColumnWithTypeAndName * findNestedSiblingWithSizes(const Block & block, const String & name, const auto & expired_columns) +{ + auto table_name = Nested::extractTableName(name); + for (const auto & column : block) + if (column.name != name && !expired_columns.contains(column.name) && isArray(column.type) + && Nested::extractTableName(column.name) == table_name) + return &column; + return nullptr; +} + SharedHeader TTLTransform::addExpiredColumnsToBlock(const SharedHeader & header, const NamesAndTypesList & expired_columns_) { if (expired_columns_.empty()) @@ -108,11 +120,18 @@ TTLTransform::TTLTransform( return Result{actions, default_ast->getColumnName()}; }; + /// An `Array` column with a dotted name is a `Nested` subcolumn: it shares the array sizes with its siblings. + auto shares_nested_offsets = [&](const NameAndTypePair & column) + { + return isArray(column.type) && Nested::extractTableName(column.name) != column.name; + }; + for (const auto & expired_column : expired_columns) { auto [default_expression, default_column_name] = build_default_expr(expired_column.name); - expired_columns_data.emplace( - expired_column.name, ExpiredColumnData{expired_column.type, std::move(default_expression), std::move(default_column_name)}); + ExpiredColumnData data{ + expired_column.type, std::move(default_expression), std::move(default_column_name), shares_nested_offsets(expired_column)}; + expired_columns_data.emplace(expired_column.name, std::move(data)); } if (metadata_snapshot_->hasAnyColumnTTL()) @@ -123,6 +142,7 @@ TTLTransform::TTLTransform( if (!expired_columns_map.contains(name)) { auto [default_expression, default_column_name] = build_default_expr(name); + auto physical_column = storage_columns.tryGetPhysical(name); algorithms.emplace_back(std::make_unique( getExpressions(description, subqueries_for_sets, context), description, @@ -132,7 +152,8 @@ TTLTransform::TTLTransform( name, default_expression, default_column_name, - isCompactPart(data_part))); + isCompactPart(data_part), + physical_column && shares_nested_offsets(*physical_column))); } } } @@ -173,6 +194,9 @@ void TTLTransform::consume(Chunk chunk) { auto default_column = ITTLAlgorithm::executeExpressionAndGetColumn(data.default_expression, block, data.default_column_name); + if (!default_column && data.shares_nested_offsets) + if (const auto * sibling = findNestedSiblingWithSizes(block, column, expired_columns_data)) + default_column = TTLColumnAlgorithm::createArraysOfDefaults(*data.type, *sibling->column); if (default_column) default_column = default_column->convertToFullColumnIfConst(); else diff --git a/src/Processors/Transforms/TTLTransform.h b/src/Processors/Transforms/TTLTransform.h index 0fed59119a86..6df494b06482 100644 --- a/src/Processors/Transforms/TTLTransform.h +++ b/src/Processors/Transforms/TTLTransform.h @@ -57,6 +57,7 @@ class TTLTransform : public IAccumulatingTransform DataTypePtr type; ExpressionActionsPtr default_expression; String default_column_name; + bool shares_nested_offsets; }; std::unordered_map expired_columns_data; LoggerPtr log; diff --git a/src/Processors/Transforms/TotalsHavingTransform.cpp b/src/Processors/Transforms/TotalsHavingTransform.cpp index 3eaa3b271d8e..6792b19824f1 100644 --- a/src/Processors/Transforms/TotalsHavingTransform.cpp +++ b/src/Processors/Transforms/TotalsHavingTransform.cpp @@ -167,7 +167,7 @@ void TotalsHavingTransform::transform(Chunk & chunk) auto finalized = chunk.clone(); if (final) - finalizeChunk(finalized, aggregates_mask); + finalizeChunk(finalized, aggregates_mask, finalized_header); total_keys += finalized.getNumRows(); @@ -288,7 +288,7 @@ void TotalsHavingTransform::prepareTotals() } totals = Chunk(std::move(current_totals), 1); - finalizeChunk(totals, aggregates_mask); + finalizeChunk(totals, aggregates_mask, finalized_header); if (expression) { diff --git a/src/Processors/Transforms/WindowTransform.cpp b/src/Processors/Transforms/WindowTransform.cpp index a8eced22f70d..e50194134657 100644 --- a/src/Processors/Transforms/WindowTransform.cpp +++ b/src/Processors/Transforms/WindowTransform.cpp @@ -326,6 +326,7 @@ WindowTransform::WindowTransform(SharedHeader input_header_, aggregate_function->sizeOfData(), aggregate_function->alignOfData()); aggregate_function->create(workspace.aggregate_function_state.data()); + workspace.aggregate_function_state_created = true; workspaces.push_back(std::move(workspace)); } @@ -409,8 +410,8 @@ WindowTransform::~WindowTransform() // Some states may be not created yet if the creation failed. for (auto & ws : workspaces) { - ws.aggregate_function->destroy( - ws.aggregate_function_state.data()); + if (ws.aggregate_function_state_created) + ws.aggregate_function->destroy(ws.aggregate_function_state.data()); } } @@ -1013,8 +1014,13 @@ void WindowTransform::updateAggregationState() if (reset_aggregation) { - a->destroy(buf); + if (ws.aggregate_function_state_created) + { + a->destroy(buf); + ws.aggregate_function_state_created = false; + } a->create(buf); + ws.aggregate_function_state_created = true; } // To achieve better performance, we will have to loop over blocks and @@ -1333,7 +1339,11 @@ void WindowTransform::appendChunk(Chunk & chunk) const auto * a = ws.aggregate_function.get(); auto * buf = ws.aggregate_function_state.data(); - a->destroy(buf); + if (ws.aggregate_function_state_created) + { + a->destroy(buf); + ws.aggregate_function_state_created = false; + } } // Release the arena we use for aggregate function states, so that it @@ -1355,6 +1365,7 @@ void WindowTransform::appendChunk(Chunk & chunk) auto * buf = ws.aggregate_function_state.data(); a->create(buf); + ws.aggregate_function_state_created = true; } } } diff --git a/src/Processors/Transforms/finalizeChunk.cpp b/src/Processors/Transforms/finalizeChunk.cpp index 7fb298c0e826..be64ddd08298 100644 --- a/src/Processors/Transforms/finalizeChunk.cpp +++ b/src/Processors/Transforms/finalizeChunk.cpp @@ -1,11 +1,19 @@ #include +#include #include #include +#include +#include namespace DB { +namespace ErrorCodes +{ + extern const int ILLEGAL_COLUMN; +} + ColumnsMask getAggregatesMask(const Block & header, const AggregateDescriptions & aggregates) { ColumnsMask mask(header.columns()); @@ -14,7 +22,7 @@ ColumnsMask getAggregatesMask(const Block & header, const AggregateDescriptions return mask; } -void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask) +void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask, const Block & finalized_header) { auto num_rows = chunk.getNumRows(); auto columns = chunk.detachColumns(); @@ -25,6 +33,20 @@ void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask) continue; auto & column = columns[i]; + + /// A column is finalized with its own function, which may differ from the one of the type in the header + /// if they share the state representation (like `quantile` and `quantiles`): `DataTypeAggregateFunction::equals` + /// considers such types equal, so such a column can pass through a `Union`. Their result types may differ. + const auto & column_aggregate_function = typeid_cast(*column); + const auto & actual_result_type = column_aggregate_function.getAggregateFunction()->getResultType(); + const auto & expected = finalized_header.getByPosition(i); + if (!actual_result_type->equals(*expected.type)) + throw Exception(ErrorCodes::ILLEGAL_COLUMN, + "Cannot finalize the state of aggregate function {} in column {}: it finalizes to {}, but {} is expected. " + "States of different aggregate functions that share a state representation cannot be finalized together", + column_aggregate_function.getAggregateFunction()->getName(), expected.name, + actual_result_type->getName(), expected.type->getName()); + column = ColumnAggregateFunction::convertToValues(IColumn::mutate(std::move(column))); } diff --git a/src/Processors/Transforms/finalizeChunk.h b/src/Processors/Transforms/finalizeChunk.h index 39a1178e270b..f9e7ba796ac7 100644 --- a/src/Processors/Transforms/finalizeChunk.h +++ b/src/Processors/Transforms/finalizeChunk.h @@ -15,6 +15,7 @@ ColumnsMask getAggregatesMask(const Block & header, const AggregateDescriptions /// Convert ColumnAggregateFunction to real values. /// /// @param aggregates_mask columns to convert (see getAggregatesMask()) -void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask); +/// @param finalized_header the expected header after the conversion; throws if a state finalizes to another type +void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask, const Block & finalized_header); } diff --git a/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp b/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp index 026ee67dedf1..653dd25d0d34 100644 --- a/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp +++ b/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp @@ -57,7 +57,7 @@ InputFormatPtr getInputFormatFromASTInsertQuery( } std::unique_ptr input_buffer = with_buffers - ? getReadBufferFromASTInsertQuery(ast) + ? getReadBufferFromASTInsertQuery(ast, context) : std::make_unique(); const Settings & settings = context->getSettingsRef(); @@ -109,7 +109,7 @@ Pipe getSourceFromASTInsertQuery( return getSourceFromInputFormat(ast, std::move(format), std::move(context), input_function); } -std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast) +std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, const ContextPtr & context) { const auto * insert_query = ast->as(); if (!insert_query) @@ -117,6 +117,10 @@ std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast) if (insert_query->infile) { + /// Checked here, before the file is opened: the asynchronous insert queue reads the data without the format check above. + if (context->getApplicationType() == Context::ApplicationType::SERVER) + throw Exception(ErrorCodes::UNKNOWN_TYPE_OF_QUERY, "Query has infile and was send directly to server"); + /// Data can be from infile const auto & in_file_node = insert_query->infile->as(); const auto in_file = in_file_node.value.safeGet(); diff --git a/src/Processors/Transforms/getSourceFromASTInsertQuery.h b/src/Processors/Transforms/getSourceFromASTInsertQuery.h index 0665269d66d3..4df54c25fd85 100644 --- a/src/Processors/Transforms/getSourceFromASTInsertQuery.h +++ b/src/Processors/Transforms/getSourceFromASTInsertQuery.h @@ -40,6 +40,7 @@ class ReadBuffer; /// Prepares a read buffer, that allows to read inlined data /// from ASTInsertQuert directly, and from tail buffer, if it exists. -std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast); +/// Throws for `INSERT ... FROM INFILE` in the server: the client reads the file, the server must not open the path. +std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, const ContextPtr & context); } diff --git a/src/QueryPipeline/RemoteQueryExecutor.cpp b/src/QueryPipeline/RemoteQueryExecutor.cpp index 3ff9ef0a9827..bc2694ba54e3 100644 --- a/src/QueryPipeline/RemoteQueryExecutor.cpp +++ b/src/QueryPipeline/RemoteQueryExecutor.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -943,6 +944,10 @@ void RemoteQueryExecutor::sendExternalTables() auto builder = plan.buildQueryPipeline(QueryPlanOptimizationSettings(my_context), BuildQueryPipelineSettings(my_context)); + /// The receiver accepts only the default serialization, while a table that is not filled + /// through the insert chain (a materialized CTE) keeps `Sparse` columns. + builder->addSimpleTransform([](const SharedHeader & table_header) { return std::make_shared(table_header); }); + builder->resize(1); builder->addTransform(std::make_shared(builder->getSharedHeader(), limits)); diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index 92be0d801fac..aee3989bac6d 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2389,6 +2389,10 @@ void TCPHandler::processQuery(std::shared_ptr & state) throw exception; /// NOLINT #endif } + /// `TCP_INTERSERVER` passed with `ClientInfo` in a `Query` packet is not trusted: + /// only a connection that uses the cluster secret is interserver. + else if (client_info.interface == ClientInfo::Interface::TCP_INTERSERVER) + client_info.interface = ClientInfo::Interface::TCP; state->query_context = session->makeQueryContext(client_info); @@ -2601,7 +2605,12 @@ bool TCPHandler::skipDataPacket(QueryState & state) else maybe_compressed_in = in; - NativeReader skip_block_in(*maybe_compressed_in, client_tcp_protocol_version); + /// Skipped data is held to the same serialization kinds as data that `initBlockInput` reads. + NativeReader skip_block_in( + *maybe_compressed_in, + client_tcp_protocol_version, + /*format_settings_=*/ std::nullopt, + ISerialization::KindSet{ISerialization::Kind::DEFAULT}); bool has_rows = !skip_block_in.read().empty(); state.at_packet_boundary = true; @@ -2627,11 +2636,15 @@ void TCPHandler::initBlockInput(QueryState & state) else if (state.need_receive_data_for_input) header = state.input_header; + /// Only the default kind: senders materialize, and the consumers `assert_cast` columns to the declared type. + /// No peer is exempt: `query_kind` is declared by the client, and an initiator forwards client data to shards. state.block_in = std::make_unique( *state.maybe_compressed_in, header, client_tcp_protocol_version, - getFormatSettings(state.query_context)); + getFormatSettings(state.query_context), + /*block_missing_values_=*/ nullptr, + ISerialization::KindSet{ISerialization::Kind::DEFAULT}); } } diff --git a/src/Storages/IStorage.h b/src/Storages/IStorage.h index e10d484de8b3..d935301914f5 100644 --- a/src/Storages/IStorage.h +++ b/src/Storages/IStorage.h @@ -196,8 +196,9 @@ class IStorage : public std::enable_shared_from_this, public TypePromo using ColumnSizeByName = std::unordered_map; virtual ColumnSizeByName getColumnSizes() const { return {}; } - /// Same as getColumnSizes() but may return nullopt in some specific engines like Merge/Alias - virtual std::optional tryGetColumnSizes() const { return getColumnSizes(); } + /// Same as getColumnSizes() but may return nullopt in some specific engines like Merge/Alias, + /// and covers only the data visible to the user of `query_context`. + virtual std::optional tryGetColumnSizes(const ContextPtr & /*query_context*/) const { return getColumnSizes(); } /// Optional size information of each secondary index. /// Valid only for MergeTree family. diff --git a/src/Storages/Kafka/KafkaConfigLoader.cpp b/src/Storages/Kafka/KafkaConfigLoader.cpp index 5825b9ad0b97..d8c6be6434f6 100644 --- a/src/Storages/Kafka/KafkaConfigLoader.cpp +++ b/src/Storages/Kafka/KafkaConfigLoader.cpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include namespace CurrentMetrics { @@ -40,6 +42,7 @@ namespace KafkaSetting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; } @@ -160,12 +163,157 @@ template struct KafkaInterceptors; namespace { -void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & key, const String & value) +/// librdkafka reads the name as a C string, so it must not contain a null character. +void checkKafkaPropertyName(const String & key) { + if (key.contains('\0')) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Kafka property name {} contains a null character", backQuote(key)); +} + +String toKafkaPropertyName(const String & key) +{ + checkKafkaPropertyName(key); /// "log_level" has valid underscore, the remaining librdkafka setting use dot.separated.format which isn't acceptable for XML. /// See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md - const String setting_name_in_kafka_config = (key == "log_level") ? key : boost::replace_all_copy(key, "_", "."); - kafka_config.set(setting_name_in_kafka_config, value); + return (key == "log_level") ? key : boost::replace_all_copy(key, "_", "."); +} + +/// Only properties reviewed for use without access to server-local resources may be set from SQL. +/// Match the exact name passed to librdkafka, including any `topic.` prefix. +void checkSQLKafkaProperty(const String & name, const String & value) +{ + static constexpr std::string_view allowed_properties[] = { + "acks", + "allow.auto.create.topics", + "api.version.request", + "auto.commit.interval.ms", + "auto.offset.reset", + "batch.num.messages", + "batch.size", + "bootstrap.servers", + "broker.address.family", + "broker.address.ttl", + "check.crcs", + "client.id", + "client.rack", + "compression.codec", + "compression.level", + "compression.type", + "connections.max.idle.ms", + "coordinator.query.interval.ms", + "debug", + "delivery.timeout.ms", + "enable.auto.commit", + "enable.auto.offset.store", + "enable.idempotence", + "enable.partition.eof", + "fetch.error.backoff.ms", + "fetch.max.bytes", + "fetch.message.max.bytes", + "fetch.min.bytes", + "fetch.queue.backoff.ms", + "fetch.wait.max.ms", + "group.id", + "group.instance.id", + "group.protocol", + "group.remote.assignor", + "heartbeat.interval.ms", + "https.ca.pem", + "isolation.level", + "linger.ms", + "log.connection.close", + "log_level", + "max.in.flight", + "max.in.flight.requests.per.connection", + "max.partition.fetch.bytes", + "max.poll.interval.ms", + "message.max.bytes", + "message.send.max.retries", + "message.timeout.ms", + "metadata.broker.list", + "metadata.max.age.ms", + "partition.assignment.strategy", + "partitioner", + "queue.buffering.backpressure.threshold", + "queue.buffering.max.kbytes", + "queue.buffering.max.messages", + "queue.buffering.max.ms", + "queued.max.messages.kbytes", + "queued.min.messages", + "receive.message.max.bytes", + "reconnect.backoff.max.ms", + "reconnect.backoff.ms", + "request.required.acks", + "request.timeout.ms", + "retries", + "retry.backoff.max.ms", + "retry.backoff.ms", + "sasl.mechanism", + "sasl.mechanisms", + "sasl.oauthbearer.assertion.private.key.pem", + "sasl.password", + "sasl.username", + "security.protocol", + "session.timeout.ms", + "socket.connection.setup.timeout.ms", + "socket.keepalive.enable", + "socket.receive.buffer.bytes", + "socket.send.buffer.bytes", + "socket.timeout.ms", + "ssl.ca.pem", + "ssl.certificate.pem", + "ssl.key.password", + "ssl.key.pem", + "statistics.interval.ms", + "topic.acks", + "topic.auto.offset.reset", + "topic.compression.codec", + "topic.compression.level", + "topic.compression.type", + "topic.delivery.timeout.ms", + "topic.message.timeout.ms", + "topic.metadata.refresh.interval.ms", + "topic.partitioner", + "topic.request.required.acks", + "topic.request.timeout.ms", + }; + static_assert(std::ranges::is_sorted(allowed_properties)); + if (std::ranges::binary_search(allowed_properties, std::string_view(name))) + return; + + /// `probe` is not a path: librdkafka searches a fixed list of the standard locations of CA certificates. + if (value == "probe" && (name == "ssl.ca.location" || name == "https.ca.location")) + return; + + static constexpr std::pair pem_alternatives[] = { + {"ssl.key.location", "ssl.key.pem"}, + {"ssl.certificate.location", "ssl.certificate.pem"}, + {"ssl.ca.location", "ssl.ca.pem"}, + {"https.ca.location", "https.ca.pem"}, + {"sasl.oauthbearer.assertion.private.key.file", "sasl.oauthbearer.assertion.private.key.pem"}, + }; + for (const auto & [path_property, pem_property] : pem_alternatives) + if (name == path_property) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Kafka property `{}` can only be specified in a named collection defined in the server configuration file. " + "Pass the contents of the file in the property `{}` instead", + name, + pem_property); + + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Kafka property `{}` can only be specified in a named collection defined in the server configuration file", + name); +} + +void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & key, const String & value, bool from_sql_collection) +{ + const String name = toKafkaPropertyName(key); + if (from_sql_collection) + checkSQLKafkaProperty(name, value); + + kafka_config.set(name, value); } void loadConfigProperty( @@ -177,17 +325,47 @@ void loadConfigProperty( const String property_path = config_prefix + "." + tag; const String property_value = config.getString(property_path); - setKafkaConfigValue(kafka_config, tag, property_value); + setKafkaConfigValue(kafka_config, tag, property_value, /*from_sql_collection=*/false); +} + +bool isNamedTopicSection(std::string_view tag) +{ + return tag == KafkaConfigLoader::CONFIG_KAFKA_TOPIC_TAG || tag.starts_with("kafka_topic["); +} + +/// Return the key within its configuration section. Dots in the property itself are significant. +std::string_view namedCollectionPropertyKey(std::string_view key) +{ + static constexpr std::string_view prefix = "kafka."; + if (!key.starts_with(prefix)) + return {}; /// The collection has no properties below `kafka`. + key.remove_prefix(prefix.size()); + if (key.starts_with("consumer.") || key.starts_with("producer.")) + key.remove_prefix(key.find('.') + 1); + + /// Both `kafka_` and `kafka_topic` (possibly indexed) are topic sections. + if (const auto dot = key.find('.'); dot != std::string_view::npos && key.starts_with("kafka_")) + { + const auto section = key.substr(0, dot); + key.remove_prefix(dot + 1); + if (isNamedTopicSection(section) && key == KafkaConfigLoader::CONFIG_NAME_TAG) + return {}; /// Topic selector, not a librdkafka property. + } + return key; } -void loadNamedCollectionConfig(cppkafka::Configuration & kafka_config, const String & collection_name, const String & config_prefix) +void loadNamedCollectionConfig(cppkafka::Configuration & kafka_config, const NamedCollection & collection, const String & config_prefix) { - const auto & collection = NamedCollectionFactory::instance().get(collection_name); - for (const auto & key : collection->getKeys(-1, config_prefix)) + for (const auto & key : collection.getKeys(-1, config_prefix)) { - // Cut prefix with '.' before actual config tag. - const auto param_name = key.substr(config_prefix.size() + 1); - setKafkaConfigValue(kafka_config, param_name, collection->get(key)); + const auto property_key = namedCollectionPropertyKey(key); + if (property_key.empty() || key.size() != config_prefix.size() + 1 + property_key.size()) + continue; /// Subsections are loaded separately. + const String param_name(property_key); + const auto value = collection.get(key); + /// The check when the table is created or loaded is not sufficient: the collection is read again here, + /// and `ALTER NAMED COLLECTION` can add a property while the table exists. + setKafkaConfigValue(kafka_config, param_name, value, collection.getSourceId() != NamedCollection::SourceId::CONFIG); } } @@ -199,7 +377,12 @@ void loadLegacyTopicConfig( { if (!collection_name.empty()) { - loadNamedCollectionConfig(kafka_config, collection_name, config_prefix); + const auto collection = NamedCollectionFactory::instance().get(collection_name); + /// For a topic called `topic`, the legacy section is also called `kafka_topic`. + /// If it has a `name`, the topic selector must be matched by `loadFromConfig`. + if (config_prefix == "kafka.kafka_topic" && collection->has(config_prefix + ".name")) + return; + loadNamedCollectionConfig(kafka_config, *collection, config_prefix); return; } @@ -212,43 +395,15 @@ void loadLegacyTopicConfig( } } -/// Read server configuration into cppkafa configuration, used by new per-topic configuration -void loadTopicConfig( - cppkafka::Configuration & kafka_config, - const Poco::Util::AbstractConfiguration & config, - const String & collection_name, - const String & config_prefix, - const String & topic) +/// Read a matching per-topic section of the server configuration. +void loadTopicConfig(cppkafka::Configuration & kafka_config, const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { - if (!collection_name.empty()) - { - const auto topic_prefix = fmt::format("{}.{}", config_prefix, KafkaConfigLoader::CONFIG_KAFKA_TOPIC_TAG); - const auto & collection = NamedCollectionFactory::instance().get(collection_name); - for (const auto & key : collection->getKeys(1, config_prefix)) - { - /// Only consider key . Multiple occurrences given as "kafka_topic", "kafka_topic[1]", etc. - if (!key.starts_with(topic_prefix)) - continue; - - const String kafka_topic_path = config_prefix + "." + key; - const String kafka_topic_name_path = kafka_topic_path + "." + KafkaConfigLoader::CONFIG_NAME_TAG; - if (topic == collection->get(kafka_topic_name_path)) - /// Found it! Now read the per-topic configuration into cppkafka. - loadNamedCollectionConfig(kafka_config, collection_name, kafka_topic_path); - } - } - else + Poco::Util::AbstractConfiguration::Keys tags; + config.keys(config_prefix, tags); + for (const auto & tag : tags) { - /// Read all tags one level below - Poco::Util::AbstractConfiguration::Keys tags; - config.keys(config_prefix, tags); - - for (const auto & tag : tags) - { - if (tag == KafkaConfigLoader::CONFIG_NAME_TAG) - continue; // ignore , it is used to match topic configurations + if (tag != KafkaConfigLoader::CONFIG_NAME_TAG) loadConfigProperty(kafka_config, config, config_prefix, tag); - } } } @@ -258,7 +413,16 @@ void loadFromConfig( { if (!params.collection_name.empty()) { - loadNamedCollectionConfig(kafka_config, params.collection_name, config_prefix); + const auto collection = NamedCollectionFactory::instance().get(params.collection_name); + loadNamedCollectionConfig(kafka_config, *collection, config_prefix); + for (const auto & key : collection->getKeys(0, config_prefix)) + { + if (key.size() <= config_prefix.size() || !isNamedTopicSection(std::string_view(key).substr(config_prefix.size() + 1))) + continue; + const String name_key = key + "." + KafkaConfigLoader::CONFIG_NAME_TAG; + if (collection->has(name_key) && std::ranges::contains(params.topics, collection->get(name_key))) + loadNamedCollectionConfig(kafka_config, *collection, key); + } return; } @@ -299,7 +463,7 @@ void loadFromConfig( if (topic_name != topic) continue; - loadTopicConfig(kafka_config, params.config, params.collection_name, kafka_topic_path, topic); + loadTopicConfig(kafka_config, params.config, kafka_topic_path); } continue; } @@ -568,4 +732,18 @@ KafkaConfigLoader::getProducerConfiguration(StorageKafka & storage template cppkafka::Configuration KafkaConfigLoader::getProducerConfiguration(StorageKafka2 & storage, const ProducerConfigParams & params); +void KafkaConfigLoader::checkNamedCollection(const NamedCollection & collection) +{ + if (collection.getSourceId() == NamedCollection::SourceId::CONFIG) + return; + + for (const auto & key : collection.getKeys(-1, CONFIG_KAFKA_TAG)) + { + checkKafkaPropertyName(key); + const auto property_key = namedCollectionPropertyKey(key); + if (!property_key.empty()) + checkSQLKafkaProperty(toKafkaPropertyName(String(property_key)), collection.get(key)); + } +} + } diff --git a/src/Storages/Kafka/KafkaConfigLoader.h b/src/Storages/Kafka/KafkaConfigLoader.h index 9fd04c3750e9..52c332e7483c 100644 --- a/src/Storages/Kafka/KafkaConfigLoader.h +++ b/src/Storages/Kafka/KafkaConfigLoader.h @@ -11,6 +11,7 @@ namespace DB { struct KafkaSettings; +class NamedCollection; class VirtualColumnsDescription; struct KafkaConfigLoader @@ -53,5 +54,10 @@ struct KafkaConfigLoader template static cppkafka::Configuration getProducerConfiguration(TKafkaStorage & storage, const ProducerConfigParams & params); + + /// Throws if a named collection created with SQL sets a librdkafka property that is not explicitly allowed. + /// The same check is done when the configuration of a consumer or a producer is loaded, because the named + /// collection can change while the table exists. + static void checkNamedCollection(const NamedCollection & collection); }; } diff --git a/src/Storages/Kafka/StorageKafkaUtils.cpp b/src/Storages/Kafka/StorageKafkaUtils.cpp index af22807a2eaa..44e594f00c95 100644 --- a/src/Storages/Kafka/StorageKafkaUtils.cpp +++ b/src/Storages/Kafka/StorageKafkaUtils.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -116,6 +117,10 @@ void registerStorageKafka(StorageFactory & factory) &args.table_id, args.storage_def->settings)) { + /// The named collection is checked every time, also when the definition is read back from metadata + /// (server startup, short `ATTACH`): the collection can change after the table is created. + KafkaConfigLoader::checkNamedCollection(*named_collection); + kafka_settings->loadFromNamedCollection(named_collection); collection_name = assert_cast(args.engine_args[0].get())->name(); } diff --git a/src/Storages/MergeTree/MergeTask.cpp b/src/Storages/MergeTree/MergeTask.cpp index 28f143aa3808..b16bc11ac5fa 100644 --- a/src/Storages/MergeTree/MergeTask.cpp +++ b/src/Storages/MergeTree/MergeTask.cpp @@ -426,8 +426,9 @@ void MergeTask::ExecuteAndFinalizeHorizontalPart::extractMergingAndGatheringColu /// TODO: also force "summing" and "aggregating" columns to make Horizontal merge only for such columns - /// For vertical merge with TTL delete optimization, include columns needed by - /// TTL expressions in the horizontal phase so the TTL filter can be evaluated. + /// The TTL step runs over the merged stream, so every TTL expression it evaluates must read + /// from a merged column - a gathered one is missing from the block and the expression throws. + /// Place the inputs of every TTL the step builds an algorithm for, not just the deleting ones. if (ctx->need_remove_expired_values && canVerticalTTLDelete(*global_ctx)) { auto add_ttl_expression_columns = [&](const TTLDescription & ttl_descr) @@ -443,6 +444,12 @@ void MergeTask::ExecuteAndFinalizeHorizontalPart::extractMergingAndGatheringColu for (const auto & where_ttl : global_ctx->metadata_snapshot->getRowsWhereTTLs()) add_ttl_expression_columns(where_ttl); + + for (const auto & move_ttl : global_ctx->metadata_snapshot->getMoveTTLs()) + add_ttl_expression_columns(move_ttl); + + for (const auto & recompression_ttl : global_ctx->metadata_snapshot->getRecompressionTTLs()) + add_ttl_expression_columns(recompression_ttl); } for (const auto & column : global_ctx->storage_columns) diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index 3ce663084320..a73264c06dd3 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -4110,6 +4110,12 @@ void MergeTreeData::dropAllData() if (disk->existsDirectory(fs::path(relative_data_path) / MOVING_DIR_NAME)) disk->removeRecursive(fs::path(relative_data_path) / MOVING_DIR_NAME); + if ((*settings_ptr)[MergeTreeSetting::table_disk]) + { + LOG_INFO(log, "dropAllData: the table directory is the root of disk {}, it is kept", disk->getName()); + continue; + } + try { if (!isSharedStorage() && !disk->isDirectoryEmpty(relative_data_path) @@ -8767,10 +8773,8 @@ Block MergeTreeData::getMinMaxCountProjectionBlock( { auto func = column.getAggregateFunction(); Arena & arena = column.createOrGetArena(); - size_t size_of_state = func->sizeOfData(); - size_t align_of_state = func->alignOfData(); - auto * place = arena.alignedAlloc(size_of_state, align_of_state); - func->create(place); + column.insertDefault(); + auto * place = column.getData().back(); if (const AggregateFunctionCount * /*agg_count*/ _ = typeid_cast(func.get())) AggregateFunctionCount::set(place, value.safeGet()); else @@ -8779,7 +8783,6 @@ Block MergeTreeData::getMinMaxCountProjectionBlock( const auto * value_column_ptr = value_column.get(); func->add(place, &value_column_ptr, 0, &arena); } - column.insertFrom(place); }; Block virtual_columns_block; diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index a2490c3ec29e..50b3e0be1265 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include namespace DB @@ -343,8 +344,10 @@ struct ReplicatedMergeTreeCleanupThread::NodeWithStat Int64 ctime = 0; Int64 czxid = 0; Int32 version = 0; + Int32 num_children = 0; - NodeWithStat(String node_, Int64 ctime_, Int64 czxid_, Int32 version_) : node(std::move(node_)), ctime(ctime_), czxid(czxid_), version(version_) {} + NodeWithStat(String node_, Int64 ctime_, Int64 czxid_, Int32 version_, Int32 num_children_) + : node(std::move(node_)), ctime(ctime_), czxid(czxid_), version(version_), num_children(num_children_) {} /// Sort by (ctime, czxid) rather than (ctime, node_name) to ensure consistent ordering /// across different deduplication directories (blocks/, deduplication_hashes/). @@ -379,7 +382,7 @@ size_t ReplicatedMergeTreeCleanupThread::clearOldBlocks( current_time - static_cast(1000 * window_seconds)); /// Virtual node, all nodes that are "greater" than this one will be deleted - NodeWithStat block_threshold{{}, time_threshold, 0, 0}; + NodeWithStat block_threshold{{}, time_threshold, 0, 0, 0}; size_t current_deduplication_window = std::min(timed_blocks.size(), window_size); auto first_outdated_block_fixed_threshold = timed_blocks.begin() + current_deduplication_window; @@ -396,6 +399,44 @@ size_t ReplicatedMergeTreeCleanupThread::clearOldBlocks( first_outdated_block->node, first_outdated_block->ctime, last_outdated_block->node, last_outdated_block->ctime); + /// A node without children is removed with `TryRemove` in a `Multi` batch: it ignores a node that is already + /// removed by another cleaner or has another version, so concurrent cleaners cannot fail the batch. + if (zookeeper.isFeatureEnabled(DB::KeeperFeatureFlag::TRY_REMOVE)) + { + std::vector multi_futures; + Coordination::Requests batch; + for (auto it = first_outdated_block; it != timed_blocks.end(); ++it) + { + cached_block_stats.erase(it->node); + + String path = zookeeper_path + "/" + blocks_dir_name + "/" + it->node; + if (it->num_children > 0) + { + /// `TryRemove` skips nodes with children (leftovers of previous server versions). + /// Another cleaner can remove the node at the same time, so `ZNONODE` is fine. + const auto rc = zookeeper.tryRemoveRecursive(path); + if (rc != Coordination::Error::ZOK && rc != Coordination::Error::ZNONODE) + throw zkutil::KeeperException::fromPath(rc, path); + continue; + } + + batch.push_back(zkutil::makeRemoveRequest(path, it->version, /*try_remove=*/ true)); + if (batch.size() == zkutil::MULTI_BATCH_SIZE) + { + multi_futures.push_back(zookeeper.asyncMulti(batch)); + batch.clear(); + } + } + if (!batch.empty()) + multi_futures.push_back(zookeeper.asyncMulti(batch)); + + for (auto & future : multi_futures) + static_cast(future.get()); /// Throws if the `Multi` failed. + + LOG_TRACE(log_, "Cleared {} old blocks from ZooKeeper", num_nodes_to_delete); + return num_nodes_to_delete; + } + zkutil::AsyncResponses try_remove_futures; for (auto it = first_outdated_block; it != timed_blocks.end(); ++it) { @@ -479,7 +520,7 @@ void ReplicatedMergeTreeCleanupThread::getBlocksSortedByTime( { /// Cached block const auto & entry = it->second; - timed_blocks.emplace_back(block, entry.ctime, entry.czxid, entry.version); + timed_blocks.emplace_back(block, entry.ctime, entry.czxid, entry.version, entry.num_children); } } @@ -493,8 +534,8 @@ void ReplicatedMergeTreeCleanupThread::getBlocksSortedByTime( if (status.error != Coordination::Error::ZNONODE) { auto node_name = fs::path(exists_paths[i]).filename(); - cached_block_stats.emplace(node_name, NodeCacheEntry{status.stat.ctime, status.stat.czxid, status.stat.version}); - timed_blocks.emplace_back(node_name, status.stat.ctime, status.stat.czxid, status.stat.version); + cached_block_stats.emplace(node_name, NodeCacheEntry{status.stat.ctime, status.stat.czxid, status.stat.version, status.stat.numChildren}); + timed_blocks.emplace_back(node_name, status.stat.ctime, status.stat.czxid, status.stat.version, status.stat.numChildren); } } diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h index 2a6d4b82d3d4..29309c6ad107 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h @@ -26,6 +26,8 @@ class ReplicatedMergeTreeCleanupThread : public IMergeTreeCleanupThread Int64 ctime = 0; Int64 czxid = 0; Int32 version = 0; + /// Block nodes never get children after creation, so the cached value stays valid. + Int32 num_children = 0; }; using NodeCTimeAndVersionCache = std::map; /// Remove old block hashes from ZooKeeper. This is done by the leader replica. Returns the number of removed blocks diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 08aa8818f4a3..7438cf1a85f3 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -109,6 +109,11 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURLWithoutQuery()) / connection_params.getContainer(); } StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; + String getConnectionURLWithoutQuery() const + { + return connection_params.endpoint.sas_auth.empty() ? connection_params.getConnectionURLWithoutQuery() : connection_params.endpoint.storage_account_url; + } + void check(ContextPtr context) override; ObjectStoragePtr createObjectStorage(ContextPtr context, bool is_readonly, CredentialsConfigurationCallback refresh_credentials_callback) override; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/ExpressionVisitor.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/ExpressionVisitor.cpp index 930eda932ba1..f6d5c56a3f14 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/ExpressionVisitor.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/ExpressionVisitor.cpp @@ -4,10 +4,10 @@ #if USE_DELTA_KERNEL_RS #include +#include #include #include #include -#include #include #include #include @@ -501,6 +501,8 @@ class ExpressionVisitor MULTIPLY, DIVIDE, TO_JSON, + PARSE_JSON, + MAP_TO_STRUCT, COALESCE, }; static ffi::EngineExpressionVisitor createVisitor(ExpressionVisitorData & data) @@ -515,7 +517,7 @@ class ExpressionVisitor .visit_literal_float = &visitSimpleLiteral, .visit_literal_double = &visitSimpleLiteral, .visit_literal_string = &visitStringLiteral, - .visit_literal_bool = &visitSimpleLiteral, + .visit_literal_bool = &visitBoolLiteral, .visit_literal_timestamp = &visitTimestampLiteral, .visit_literal_timestamp_ntz = &visitTimestampNtzLiteral, .visit_literal_date = &visitDateLiteral, @@ -530,6 +532,8 @@ class ExpressionVisitor .visit_not = &visitFunction, .visit_is_null = &visitFunction, .visit_to_json = &throwNotImplemented, + .visit_parse_json = &throwNotImplementedParseJSON, + .visit_map_to_struct = &throwNotImplemented, .visit_lt = &throwNotImplemented, .visit_gt = &throwNotImplemented, .visit_eq = &throwNotImplemented, @@ -590,6 +594,25 @@ class ExpressionVisitor }); } + static void throwNotImplementedParseJSON( + void * data, + uintptr_t sibling_list_id, + uintptr_t child_list_id, + ffi::SharedSchema * output_schema) + { + UNUSED(sibling_list_id); + UNUSED(child_list_id); + ffi::free_schema(output_schema); + + ExpressionVisitorData * state = static_cast(data); + visitorImpl(*state, [&]() + { + throw DB::Exception( + DB::ErrorCodes::NOT_IMPLEMENTED, + "Method ParseJSON not implemented"); + }); + } + static void throwNotImplementedOpaqueExpression( void * data, uintptr_t sibling_list_id, @@ -726,6 +749,20 @@ class ExpressionVisitor }); } + /// `boolean` maps to ClickHouse `Bool` in the schema, so the literal must carry `Bool` too; + /// a plain `DataTypeUInt8` would mismatch a `Nullable(Bool)` partition column's advertised type. + static void visitBoolLiteral(void * data, uintptr_t sibling_list_id, bool value) + { + ExpressionVisitorData * state = static_cast(data); + visitorImpl(*state, [&]() + { + if (state->enableLogging()) + LOG_TEST(state->logger(), "List id: {}, type: Bool", sibling_list_id); + + state->addLiteral(sibling_list_id, static_cast(value), DB::DataTypeFactory::instance().get("Bool")); + }); + } + static void visitDecimalLiteral( void * data, uintptr_t sibling_list_id, @@ -815,22 +852,62 @@ class ExpressionVisitor LOG_TEST(state->logger(), "List id: {}, type: Binary", sibling_list_id); std::string value(reinterpret_cast(buffer), len); - state->addLiteral(sibling_list_id, value, std::make_shared(len)); + state->addLiteral(sibling_list_id, value, std::make_shared()); }); } - static void visitNullLiteral(void * data, uintptr_t sibling_list_id) + /// Maps a null `type_tag` (see `NullTypeTag` in `ffi/src/expressions/kernel_visitor.rs`) to the + /// matching ClickHouse type for `Nullable(T)`; tag 12 carries precision/scale, 255/unknown can't. + static DB::DataTypePtr nullInnerTypeForTag(uint8_t type_tag, uint8_t precision, uint8_t scale) + { + switch (type_tag) + { + case 0: return DB::DataTypeFactory::instance().get("Bool"); /// boolean (schema maps boolean -> Bool) + case 1: return std::make_shared(); /// byte + case 2: return std::make_shared(); /// short + case 3: return std::make_shared(); /// integer + case 4: return std::make_shared(); /// long + case 5: return std::make_shared(); /// float + case 6: return std::make_shared(); /// double + case 7: return std::make_shared(); /// string + case 8: return std::make_shared(); /// binary (schema maps binary -> String) + case 9: return std::make_shared(); /// date + case 10: return std::make_shared(6); /// timestamp + case 11: return std::make_shared(6); /// timestamp_ntz + case 12: /// decimal + if (precision <= DB::DecimalUtils::max_precision) + return std::make_shared(precision, scale); + if (precision <= DB::DecimalUtils::max_precision) + return std::make_shared(precision, scale); + if (precision <= DB::DecimalUtils::max_precision) + return std::make_shared(precision, scale); + throw DB::Exception( + DB::ErrorCodes::NOT_IMPLEMENTED, + "Unsupported decimal precision {} for null literal", precision); + default: + throw DB::Exception( + DB::ErrorCodes::NOT_IMPLEMENTED, + "Unsupported null literal type tag {}", type_tag); + } + } + + static void visitNullLiteral( + void * data, + uintptr_t sibling_list_id, + uint8_t type_tag, + uint8_t precision, + uint8_t scale) { ExpressionVisitorData * state = static_cast(data); visitorImpl(*state, [&]() { if (state->enableLogging()) - LOG_TEST(state->logger(), "List id: {}, type: Null", sibling_list_id); + LOG_TEST(state->logger(), "List id: {}, type: Null (tag {})", sibling_list_id, type_tag); state->addLiteral( sibling_list_id, DB::Null(), - std::make_shared(std::make_shared())); + std::make_shared(nullInnerTypeForTag(type_tag, precision, scale))); }); } diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.cpp index f74553d2aa8e..e8b8287a0dc3 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.cpp @@ -46,7 +46,8 @@ namespace DB::ColumnsDescription getPartitionColumnsDescription( const DB::Names & partition_columns, - const DB::NamesAndTypesList & table_schema) + const DB::NamesAndTypesList & table_schema, + bool keep_nullable) { DB::NamesAndTypesList names_and_types; for (const auto & column_name : partition_columns) @@ -54,7 +55,7 @@ namespace auto column = table_schema.tryGetByName(column_name); if (!column.has_value()) throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Not found partition column in schema: {}", column_name); - names_and_types.emplace_back(column_name, removeNullable(column->type)); + names_and_types.emplace_back(column_name, keep_nullable ? column->type : removeNullable(column->type)); } return DB::ColumnsDescription(names_and_types); } @@ -70,17 +71,24 @@ PartitionPruner::PartitionPruner( { if (!partition_columns_.empty()) { - const auto partition_columns_description = getPartitionColumnsDescription(partition_columns_, table_schema_); + const auto partition_columns_description + = getPartitionColumnsDescription(partition_columns_, table_schema_, /* keep_nullable */ false); const auto partition_key_ast = createPartitionKeyAST(partition_columns_); partition_key = DB::KeyDescription::getKeyFromAST( partition_key_ast, partition_columns_description, context); + nullable_partition_key = DB::KeyDescription::getKeyFromAST( + partition_key_ast, + getPartitionColumnsDescription(partition_columns_, table_schema_, /* keep_nullable */ true), + context); DB::ActionsDAGWithInversionPushDown inverted_dag(filter_dag.getOutputs().front(), context); key_condition.emplace( inverted_dag, context, partition_key.column_names, partition_key.expression, true /* single_point */); + nullable_key_condition.emplace( + inverted_dag, context, nullable_partition_key.column_names, nullable_partition_key.expression, true /* single_point */); } if (!physical_names_map_.empty()) { @@ -109,20 +117,28 @@ bool PartitionPruner::canBePruned(const DB::ObjectInfo & object_info) const DB::Row partition_key_values; partition_key_values.reserve(partition_values.size()); + bool holds_null = false; for (auto && value : partition_values) { if (value.isNull()) + { + holds_null = true; partition_key_values.push_back(DB::POSITIVE_INFINITY); /// NULL_LAST + } else partition_key_values.push_back(std::move(value)); } + /// The key without Nullable drops the NULL elements of a set, so it is exact only for a tuple without NULL. + const auto & key = holds_null ? nullable_partition_key : partition_key; + const auto & condition = holds_null ? *nullable_key_condition : *key_condition; + std::vector partition_key_values_ref(partition_key_values.begin(), partition_key_values.end()); - bool can_be_true = key_condition->mayBeTrueInRange( + bool can_be_true = condition.mayBeTrueInRange( partition_key_values_ref.size(), partition_key_values_ref.data(), partition_key_values_ref.data(), - partition_key.data_types); + key.data_types); return !can_be_true; } diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.h b/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.h index 1ff9e2e5559b..ef89f33852bc 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.h +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/PartitionPruner.h @@ -32,6 +32,9 @@ class PartitionPruner private: std::optional key_condition; DB::KeyDescription partition_key; + /// The same key over the schema's Nullable types, for a partition tuple that holds NULL. + std::optional nullable_key_condition; + DB::KeyDescription nullable_partition_key; DB::Names physical_partition_columns; }; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableChanges.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableChanges.cpp index 385b16dfec72..d2f6c1457e95 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableChanges.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableChanges.cpp @@ -2,6 +2,7 @@ #include #if USE_DELTA_KERNEL_RS +#include #include #include #include @@ -77,7 +78,7 @@ DB::NamesAndTypesList TableChanges::getSchemaUnlocked() const using KernelSharedSchema = KernelPointerWrapper; KernelSharedSchema kernel_schema(ffi::table_changes_schema(getTableChanges().get())); - schema = convertToClickHouseSchema(kernel_schema.get()); + schema = convertToClickHouseSchema(kernel_schema.get(), engine.get()); LOG_TRACE(log, "Table schema: {}, source header: {}", schema->toString(), header.dumpNames()); return schema.value(); @@ -150,16 +151,19 @@ DB::Chunk TableChanges::next() { std::lock_guard lock(mutex); - ffi::ArrowFFIData ffi_arrow_data = KernelUtils::unwrapResult( + ffi::ArrowFFIData * ffi_arrow_data = KernelUtils::unwrapResult( ffi::scan_table_changes_next(getTableChangesScanIterator().get()), "scan_table_changes_next"); - if (ffi_arrow_data.array.length == 0) + if (!ffi_arrow_data) + return {}; + SCOPE_EXIT({ ffi::free_arrow_ffi_data(ffi_arrow_data); }); + if (ffi_arrow_data->array.length == 0) return {}; auto record_batch = arrow::ImportRecordBatch( - reinterpret_cast(&ffi_arrow_data.array), - reinterpret_cast(&ffi_arrow_data.schema)); + reinterpret_cast(&ffi_arrow_data->array), + reinterpret_cast(&ffi_arrow_data->schema)); if (!record_batch.ok()) { diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp index cac54224ac17..765cc380c31c 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp @@ -528,8 +528,28 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator void * engine_context, ffi::SharedScanMetadata * scan_metadata) { - ffi::visit_scan_metadata(scan_metadata, engine_context, Iterator::scanCallback); - ffi::free_scan_metadata(scan_metadata); + auto * iter = static_cast(engine_context); + /// Release the handle on all exit paths to avoid leaking it. + SCOPE_EXIT({ + ffi::free_scan_metadata(scan_metadata); + }); + /// Runs inside Rust's `scan_metadata_next`: a C++ exception must not cross the `extern "C"` + /// frame, so store it (like `scanCallback`) and let `scanDataFunc` rethrow after it returns. + try + { + KernelUtils::unwrapResult( + ffi::visit_scan_metadata( + scan_metadata, + iter->kernel_snapshot_state->engine.get(), + engine_context, + Iterator::scanCallback), + "visit_scan_metadata"); + } + catch (...) // Ok: exception saved via setScanException, rethrown by scanDataFunc + { + iter->setScanException(); + iter->data_files_cv.notify_all(); + } } static bool scanCallback( @@ -765,10 +785,16 @@ TableSnapshot::SnapshotStats TableSnapshot::getSnapshotStatsImpl() const struct StatsVisitor { + explicit StatsVisitor(ffi::SharedExternEngine * engine_) : engine(engine_) {} + + ffi::SharedExternEngine * const engine; size_t total_data_files = 0; size_t total_bytes = 0; /// Not all writers add rows count to metadata std::optional total_rows = 0; + /// Set when `visitData` catches an exception; rethrown by the caller after + /// `scan_metadata_next` returns (the callback runs inside a Rust `extern "C"` frame). + std::exception_ptr exception; static bool visit( ffi::NullableCvoid engine_context, @@ -801,12 +827,31 @@ TableSnapshot::SnapshotStats TableSnapshot::getSnapshotStatsImpl() const static void visitData(void * engine_context, ffi::SharedScanMetadata * scan_metadata) { - ffi::visit_scan_metadata(scan_metadata, engine_context, StatsVisitor::visit); - ffi::free_scan_metadata(scan_metadata); + auto * visitor = static_cast(engine_context); + /// Release the handle on all exit paths to avoid leaking it. + SCOPE_EXIT({ + ffi::free_scan_metadata(scan_metadata); + }); + /// Runs inside Rust's `scan_metadata_next`: a C++ exception must not cross the + /// `extern "C"` frame, so store it and let the caller rethrow after the call returns. + try + { + KernelUtils::unwrapResult( + ffi::visit_scan_metadata( + scan_metadata, + visitor->engine, + engine_context, + StatsVisitor::visit), + "visit_scan_metadata"); + } + catch (...) + { + visitor->exception = std::current_exception(); + } } }; - StatsVisitor visitor; + StatsVisitor visitor(state->engine.get()); while (true) { @@ -817,6 +862,10 @@ TableSnapshot::SnapshotStats TableSnapshot::getSnapshotStatsImpl() const StatsVisitor::visitData), "scan_metadata_next"); + /// Rethrow only now that `scan_metadata_next` has returned to C++ (see `visitData`). + if (visitor.exception) + std::rethrow_exception(visitor.exception); + if (!have_scan_data) break; } @@ -928,23 +977,24 @@ TableSnapshot::KernelSnapshotState::KernelSnapshotState(const IKernelHelper & he auto * engine_builder = helper_.createBuilder(); engine = KernelUtils::unwrapResult(ffi::builder_build(engine_builder), "builder_build"); + + using KernelSnapshotBuilder = KernelPointerWrapper; + KernelSnapshotBuilder snapshot_builder(KernelUtils::unwrapResult( + ffi::get_snapshot_builder( + KernelUtils::toDeltaString(helper_.getTableLocation()), + engine.get()), + "get_snapshot_builder")); if (snapshot_version_.has_value()) { - snapshot = KernelUtils::unwrapResult( - ffi::snapshot_at_version( - KernelUtils::toDeltaString(helper_.getTableLocation()), - engine.get(), - snapshot_version_.value()), - "snapshot"); - } - else - { - snapshot = KernelUtils::unwrapResult( - ffi::snapshot( - KernelUtils::toDeltaString(helper_.getTableLocation()), - engine.get()), - "snapshot"); + auto * builder_handle = snapshot_builder.get(); + ffi::snapshot_builder_set_version(&builder_handle, snapshot_version_.value()); } + /// `snapshot_builder_build` consumes the handle, so release() prevents the RAII destructor + /// from double-freeing on success. The destructor still frees on early exception paths. + snapshot = KernelUtils::unwrapResult( + ffi::snapshot_builder_build(snapshot_builder.release()), + "snapshot_builder_build"); + snapshot_version = ffi::version(snapshot.get()); scan = KernelUtils::unwrapResult( ffi::scan(snapshot.get(), engine.get(), /* predicate */{}, /* engine_schema */nullptr), @@ -998,12 +1048,12 @@ void TableSnapshot::initOrUpdateSchemaIfChanged() const if (!schema.has_value()) { auto state = getKernelSnapshotState(); - auto [table_schema, physical_names_map] = getTableSchemaFromSnapshot(state->snapshot.get()); + auto [table_schema, physical_names_map] = getTableSchemaFromSnapshot(state->snapshot.get(), state->engine.get()); if (table_schema.empty()) throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "Table schema cannot be empty"); - auto read_schema = getReadSchemaFromSnapshot(state->scan.get()); + auto read_schema = getReadSchemaFromSnapshot(state->scan.get(), state->engine.get()); auto partition_columns = getPartitionColumnsFromSnapshot(state->snapshot.get()); LOG_TRACE( diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp index dc22ef8c5954..b99598ac05d9 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp @@ -145,7 +145,7 @@ const std::string & WriteTransaction::getDataPath() const return path_prefix; } -void WriteTransaction::create() +void WriteTransaction::create(const DB::Names & partition_columns, const DB::NamesAndTypesList & table_schema) { auto * engine_builder = kernel_helper->createBuilder(); engine = DeltaLake::KernelUtils::unwrapResult(ffi::builder_build(engine_builder), "builder_build"); @@ -162,16 +162,28 @@ void WriteTransaction::create() engine.get()), "with_engine_info"); - write_context = ffi::get_write_context(transaction.get()); - write_schema = DeltaLake::getWriteSchema(write_context.get()); - - auto * write_path_raw = static_cast( - ffi::get_write_path(write_context.get(), DeltaLake::KernelUtils::allocateString)); - if (!write_path_raw) - throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Failed to get write path"); - - write_path = *write_path_raw; - delete write_path_raw; + if (partition_columns.empty()) + { + /// Unpartitioned tables: let the kernel build the write context. + unpartitioned_write_context = DeltaLake::KernelUtils::unwrapResult( + ffi::get_unpartitioned_write_context(transaction.get(), engine.get()), + "get_unpartitioned_write_context"); + write_schema = DeltaLake::getWriteSchema(unpartitioned_write_context.get(), engine.get()); + + std::unique_ptr write_path_raw(static_cast( + ffi::get_write_path(unpartitioned_write_context.get(), DeltaLake::KernelUtils::allocateString))); + if (!write_path_raw) + throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Failed to get write path"); + + write_path = *write_path_raw; + } + else + { + /// delta-kernel exposes no partitioned write context via FFI (TODO(#2355)), so derive the + /// write schema and path directly; per-partition values are handled when committing. + write_schema = table_schema; + write_path = kernel_helper->getTableLocation(); + } auto pos = write_path.find("://"); if (pos == std::string::npos) @@ -280,7 +292,12 @@ void WriteTransaction::commit(const std::vector & files) ffi::add_files(transaction.get(), engine_data.release()); } - auto version = DeltaLake::KernelUtils::unwrapResult(ffi::commit(transaction.release(), engine.get()), "commit"); + using KernelCommittedTransaction = DeltaLake::KernelPointerWrapper; + KernelCommittedTransaction committed(DeltaLake::KernelUtils::unwrapResult( + ffi::commit(transaction.release(), engine.get()), + "commit")); + auto * committed_handle = committed.get(); + auto version = ffi::committed_transaction_version(&committed_handle); LOG_TEST(log, "Commit version: {}", version); } diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.h b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.h index db783658b2da..ad4645855247 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.h +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.h @@ -16,8 +16,9 @@ class WriteTransaction const std::string & getDataPath() const; - /// Create a transcation. - void create(); + /// Create a transaction for the target table. `table_schema` is the table's logical schema; + /// see the implementation for how partitioned vs unpartitioned tables derive the write context. + void create(const DB::Names & partition_columns, const DB::NamesAndTypesList & table_schema); struct CommitFile { @@ -46,7 +47,7 @@ class WriteTransaction KernelExternEngine engine; KernelTransaction transaction; - KernelWriteContext write_context; + KernelWriteContext unpartitioned_write_context; DB::NamesAndTypesList write_schema; void assertTransactionCreated() const; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.cpp index da4fcec929d5..4e5275582b9d 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.cpp @@ -81,6 +81,10 @@ class SchemaVisitorData friend class SchemaVisitor; public: + /// `engine` is required by FFI helpers such as `ffi::get_from_string_map`. Pass `nullptr` only + /// for visit paths that make no engine-bound FFI calls (e.g. partition column extraction). + explicit SchemaVisitorData(ffi::SharedExternEngine * engine_) : engine(engine_) {} + struct SchemaResult { DB::NamesAndTypesList names_and_types; @@ -140,6 +144,8 @@ class SchemaVisitorData /// because they are not stored in the actual data, /// but instead in data paths directories. DB::Names partition_columns; + /// Engine handle required by v0.23.0 FFI helpers such as `ffi::get_from_string_map`. + ffi::SharedExternEngine * engine; const LoggerPtr log = getLogger("SchemaVisitor"); @@ -241,12 +247,17 @@ class SchemaVisitor return id; } - static std::unique_ptr extractPhysicalName(const ffi::CStringMap * metadata) + static std::unique_ptr extractPhysicalName( + const ffi::CStringMap * metadata, + SchemaVisitorData * state) { - std::string * physical_name = static_cast(ffi::get_from_string_map( - metadata, - KernelUtils::toDeltaString("delta.columnMapping.physicalName"), - KernelUtils::allocateString)); + std::string * physical_name = static_cast(KernelUtils::unwrapResult( + ffi::get_from_string_map( + metadata, + KernelUtils::toDeltaString("delta.columnMapping.physicalName"), + KernelUtils::allocateString, + state->engine), + "get_from_string_map")); return physical_name ? std::unique_ptr(physical_name) : nullptr; } @@ -268,7 +279,7 @@ class SchemaVisitor } const std::string column_name(name.ptr, name.len); - const auto physical_name_ptr = extractPhysicalName(metadata); + const auto physical_name_ptr = extractPhysicalName(metadata, state); const std::string physical_name = physical_name_ptr ? *physical_name_ptr : ""; LOG_TEST( @@ -301,7 +312,7 @@ class SchemaVisitor } const std::string column_name(name.ptr, name.len); - const auto physical_name_ptr = extractPhysicalName(metadata); + const auto physical_name_ptr = extractPhysicalName(metadata, state); const std::string physical_name = physical_name_ptr ? *physical_name_ptr : ""; LOG_TEST( @@ -367,7 +378,7 @@ class SchemaVisitor } const std::string column_name(name.ptr, name.len); - const auto physical_name_ptr = extractPhysicalName(metadata); + const auto physical_name_ptr = extractPhysicalName(metadata, state); const std::string physical_name = physical_name_ptr ? *physical_name_ptr : ""; LOG_TEST( @@ -501,38 +512,40 @@ DB::NamesAndTypesList SchemaVisitorData::getNamesAndTypesFromList( return names_and_types; } -std::pair getTableSchemaFromSnapshot(ffi::SharedSnapshot * snapshot) +std::pair getTableSchemaFromSnapshot( + ffi::SharedSnapshot * snapshot, ffi::SharedExternEngine * engine) { - SchemaVisitorData data; + SchemaVisitorData data(engine); SchemaVisitor::visitTableSchema(snapshot, data); auto result = data.getSchemaResult(); return {result.names_and_types, result.physical_names_map}; } -DB::NamesAndTypesList getReadSchemaFromSnapshot(ffi::SharedScan * scan) +DB::NamesAndTypesList getReadSchemaFromSnapshot(ffi::SharedScan * scan, ffi::SharedExternEngine * engine) { - SchemaVisitorData data; + SchemaVisitorData data(engine); SchemaVisitor::visitReadSchema(scan, data); return data.getSchemaResult().names_and_types; } -DB::NamesAndTypesList getWriteSchema(ffi::SharedWriteContext * write_context) +DB::NamesAndTypesList getWriteSchema(ffi::SharedWriteContext * write_context, ffi::SharedExternEngine * engine) { - SchemaVisitorData data; + SchemaVisitorData data(engine); SchemaVisitor::visitWriteSchema(write_context, data); return data.getSchemaResult().names_and_types; } DB::Names getPartitionColumnsFromSnapshot(ffi::SharedSnapshot * snapshot) { - SchemaVisitorData data; + /// Partition column extraction makes no engine-bound FFI calls, so no engine is needed. + SchemaVisitorData data(nullptr); SchemaVisitor::visitPartitionColumns(snapshot, data); return data.getPartitionColumns(); } -DB::NamesAndTypesList convertToClickHouseSchema(ffi::SharedSchema * schema) +DB::NamesAndTypesList convertToClickHouseSchema(ffi::SharedSchema * schema, ffi::SharedExternEngine * engine) { - SchemaVisitorData data; + SchemaVisitorData data(engine); SchemaVisitor::visitSchema(schema, data); return data.getSchemaResult().names_and_types; } diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.h b/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.h index 22c223503851..b48d7a9927cc 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.h +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.h @@ -19,20 +19,23 @@ namespace DeltaLake /// Get table schema and physical column map (logical name to physical name mapping). /// Represents table schema from DeltaLake metadata. /// Contains partition columns. -std::pair getTableSchemaFromSnapshot(ffi::SharedSnapshot * snapshot); +/// `engine` is required by `ffi::get_from_string_map` (v0.23.0). +std::pair getTableSchemaFromSnapshot( + ffi::SharedSnapshot * snapshot, + ffi::SharedExternEngine * engine); /// Get read schema. /// Represents read schema based on data files. -DB::NamesAndTypesList getReadSchemaFromSnapshot(ffi::SharedScan * scan); +DB::NamesAndTypesList getReadSchemaFromSnapshot(ffi::SharedScan * scan, ffi::SharedExternEngine * engine); -DB::NamesAndTypesList getWriteSchema(ffi::SharedWriteContext * write_context); +DB::NamesAndTypesList getWriteSchema(ffi::SharedWriteContext * write_context, ffi::SharedExternEngine * engine); /// Get list of partition columns. /// Read schema does not contain partition columns, /// therefore partition columns are passed separately. DB::Names getPartitionColumnsFromSnapshot(ffi::SharedSnapshot * snapshot); -DB::NamesAndTypesList convertToClickHouseSchema(ffi::SharedSchema * schema); +DB::NamesAndTypesList convertToClickHouseSchema(ffi::SharedSchema * schema, ffi::SharedExternEngine * engine); } diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp index 201f2ca83f09..166d0ae25a0f 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp @@ -37,6 +37,7 @@ namespace ErrorCodes extern const int SUPPORT_IS_DISABLED; extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; + extern const int NOT_IMPLEMENTED; } namespace FailPoints @@ -599,10 +600,17 @@ ReadFromFormatInfo DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat( info.format_header.insert(ColumnWithTypeAndName{result_name_and_type.type, result_name_and_type.name}); } - for (const auto & name_and_type : info.columns_description) - info.columns_description.rename( - name_and_type.name, - DeltaLake::getPhysicalName(name_and_type.name, physical_names_map)); + /// Build a new description rather than rename in place: the physical name of a column may be the logical name of + /// another column that is not renamed yet (`k` renamed to `k_old` under column mapping keeps the physical name `k`), + /// and `ColumnsDescription::rename` to an existing name erases the column, under the iteration over the description. + ColumnsDescription physical_columns_description; + for (const auto & column : info.columns_description) + { + ColumnDescription physical_column = column; + physical_column.name = DeltaLake::getPhysicalName(column.name, physical_names_map); + physical_columns_description.add(std::move(physical_column)); + } + info.columns_description = std::move(physical_columns_description); LOG_TEST(log, "Format header: {}", info.format_header.dumpStructure()); LOG_TEST(log, "Source header: {}", info.source_header.dumpStructure()); @@ -631,8 +639,17 @@ SinkToStoragePtr DeltaLakeMetadataDeltaKernel::write( auto snapshot = getTableSnapshot(snapshot_version); Names partition_columns = snapshot->getPartitionColumns(); + /// Reject column-mapped tables (snapshot exposes physical names): the writer emits logical + /// names, not the required physical field names/ids. TODO: support it (delta-kernel-rs#1124). + if (!snapshot->getPhysicalNamesMap().empty()) + { + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Writing to DeltaLake tables with column mapping enabled is not supported"); + } + auto delta_transaction = std::make_shared(kernel_helper); - delta_transaction->create(); + delta_transaction->create(partition_columns, snapshot->getTableSchema()); if (partition_columns.empty()) { diff --git a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp index 8f1fa65d198a..c5526e732243 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp @@ -107,7 +107,10 @@ void StorageObjectStorageConfiguration::initialize( if (!disk_name.empty()) configuration_to_initialize.fromDisk(disk_name, engine_args, local_context, with_table_structure); else if (auto named_collection = tryGetNamedCollectionWithOverrides(engine_args, local_context, true, nullptr, table_id)) + { configuration_to_initialize.fromNamedCollection(*named_collection, local_context); + configuration_to_initialize.initialized_from_named_collection = true; + } else configuration_to_initialize.fromAST(engine_args, local_context, with_table_structure); diff --git a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h index 94a402f65613..60c7a675e90b 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h @@ -290,6 +290,9 @@ class StorageObjectStorageConfiguration bool partition_columns_in_data_file = true; std::shared_ptr partition_strategy; + /// Set by `initialize` when the arguments come from a named collection. + bool initialized_from_named_collection = false; + protected: void checkFormat() const; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp index d3e842d386b4..b0a584b674b5 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp @@ -44,6 +44,7 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; + extern const int METADATA_MISMATCH; extern const int REPLICA_ALREADY_EXISTS; extern const int SUPPORT_IS_DISABLED; extern const int TIMEOUT_EXCEEDED; @@ -359,7 +360,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, Coordination::Stat stat; auto metadata_str = zookeeper->get(fs::path(zookeeper_path) / "metadata", &stat); auto metadata_from_zk = ObjectStorageQueueTableMetadata::parse(metadata_str); - auto new_table_metadata{table_metadata}; + auto new_table_metadata{metadata_from_zk}; for (const auto & change : changes) { @@ -385,7 +386,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (change.name == "processing_threads_num") { const auto value = change.value.safeGet(); - if (table_metadata.processing_threads_num == value) + if (new_table_metadata.processing_threads_num == value) { LOG_TRACE(log, "Setting `processing_threads_num` already equals {}. " "Will do nothing", value); @@ -396,7 +397,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "loading_retries") { const auto value = change.value.safeGet(); - if (table_metadata.loading_retries == value) + if (new_table_metadata.loading_retries == value) { LOG_TRACE(log, "Setting `loading_retries` already equals {}. " "Will do nothing", value); @@ -407,7 +408,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "after_processing") { const auto value = ObjectStorageQueueTableMetadata::actionFromString(change.value.safeGet()); - if (table_metadata.after_processing == value) + if (new_table_metadata.after_processing == value) { LOG_TRACE(log, "Setting `after_processing` already equals {}. " "Will do nothing", value); @@ -418,7 +419,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "tracked_files_limit") { const auto value = change.value.safeGet(); - if (table_metadata.tracked_files_limit == value) + if (new_table_metadata.tracked_files_limit == value) { LOG_TRACE(log, "Setting `tracked_files_limit` already equals {}. " "Will do nothing", value); @@ -429,7 +430,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "tracked_file_ttl_sec") { const auto value = change.value.safeGet(); - if (table_metadata.tracked_files_ttl_sec == value) + if (new_table_metadata.tracked_files_ttl_sec == value) { LOG_TRACE(log, "Setting `tracked_file_ttl_sec` already equals {}. " "Will do nothing", value); @@ -458,6 +459,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (table_metadata.buckets == value) { LOG_TRACE(log, "Setting `buckets` already equals {}. Will do nothing", value); + new_table_metadata.buckets = value; continue; } if (table_metadata.buckets > 1) @@ -486,7 +488,10 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (is_initial_query) zookeeper->set(table_metadata_path, new_metadata_str, stat.version); - table_metadata.syncChangeableSettings(new_table_metadata); + NameSet changed_names; + for (const auto & change : changes) + changed_names.insert(change.name); + table_metadata.syncChangeableSettings(new_table_metadata, changed_names); } void ObjectStorageQueueMetadata::migrateToBucketsInKeeper(size_t value) @@ -510,10 +515,11 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( const ColumnsDescription & columns, const std::string & format, const ContextPtr & context, - bool is_attach, + const ObjectStorageQueueTableMetadata::Source & source, + bool strict, LoggerPtr log) { - ObjectStorageQueueTableMetadata table_metadata(settings, columns, format); + ObjectStorageQueueTableMetadata table_metadata(settings, columns, format, source); std::vector metadata_paths; size_t buckets_num = 0; @@ -550,16 +556,38 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( { auto zk_client = getZooKeeper(log, zookeeper_name); std::optional metadata_from_zk; + Coordination::Stat stat; if (zk_client->exists(table_metadata_path)) { - const auto metadata_str = zk_client->get(table_metadata_path); + const auto metadata_str = zk_client->get(table_metadata_path, &stat); LOG_TRACE(log, "Metadata in keeper: {}", metadata_str); metadata_from_zk.emplace(ObjectStorageQueueTableMetadata::parse(metadata_str)); } if (metadata_from_zk.has_value()) { table_metadata.adjustFromKeeper(metadata_from_zk.value()); + /// A named collection can change without an `ALTER` of the table, so its source is always checked. + if (!strict && !source.from_named_collection && !metadata_from_zk->source_hash.empty() + && table_metadata.source_hash != metadata_from_zk->source_hash) + { + LOG_WARNING(log, "The source of this table differs from the source of the queue"); + table_metadata.source_hash = metadata_from_zk->source_hash; + } table_metadata.checkEquals(metadata_from_zk.value()); + if (metadata_from_zk->source_hash.empty()) + { + if (strict) + throw Exception( + ErrorCodes::METADATA_MISMATCH, + "Existing table metadata in ZooKeeper has no source, as an older version wrote it. " + "Attach the main table (following the same `keeper_path`) of this queue on an upgraded server, or use another `keeper_path`"); + + if (!table_metadata.source_hash.empty()) + { + metadata_from_zk->source_hash = table_metadata.source_hash; + code = zk_client->trySet(table_metadata_path, metadata_from_zk->toString(), stat.version); + } + } return; } @@ -572,7 +600,7 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( "either `buckets`>1 or `processing_threads_num`>1 (works as `buckets` if it's not specified) " "will not work properly. Please specify them in the CREATE query. See documentation for more details."; - if (is_attach) + if (!strict) { LOG_WARNING(log, "{}", message); warned = true; @@ -637,6 +665,9 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( *code, exception.getPathForFirstFailedOp(), zookeeper_path.string()); continue; } + /// Keeper was changed after the metadata was read, for example by another server, so start again. + if (*code == Coordination::Error::ZBADVERSION || *code == Coordination::Error::ZNONODE) + continue; if (*code != Coordination::Error::ZOK) zkutil::KeeperMultiException::check(*code, requests, responses); } diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h index 9bcc7d620ead..9273f42b2f82 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h @@ -99,6 +99,8 @@ class ObjectStorageQueueMetadata /// - adjust, if needed and allowed, passed queue settings according to /// what is in keeper (for example, processing_threads_num is adjustable, /// because its default depends on the CPU cores on the server); + /// - if not `strict` or from a named collection, a table is loaded even if its source differs from keeper; + /// - if keeper has no `source` (metadata written by an older version), save the table's `source` there; static ObjectStorageQueueTableMetadata syncWithKeeper( const String & zookeeper_name, const fs::path & zookeeper_path, @@ -106,7 +108,8 @@ class ObjectStorageQueueMetadata const ColumnsDescription & columns, const std::string & format, const ContextPtr & context, - bool is_attach, + const ObjectStorageQueueTableMetadata::Source & source, + bool strict, LoggerPtr log); /// Alter settings in keeper metadata /// (rewrites what we write in syncWithKeeper()). diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp index e845fa34a6c0..ef8eb6e38554 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -57,16 +57,24 @@ bool isEmptyValue(const Field & value) return value.getType() == Field::Types::String && value.safeGet().empty(); } +bool changesSourceObjects(const SettingChange & change) +{ + /// `after_processing` other than `keep` modifies the source files. + return (change.name == "after_processing" || change.name == "s3queue_after_processing") + && change.value.safeGet() != "keep"; +} + /// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. -AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind, bool own_engine) { const bool sets_destination = std::ranges::any_of( changes, [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); - if (!sets_destination) + if (!sets_destination && !(own_engine && std::ranges::any_of(changes, changesSourceObjects))) return {}; /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For `after_processing`, the URL of the table is not known here either. /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). @@ -78,14 +86,14 @@ AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, M } -AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine) { - return getMoveDestinationAccess(changes, MoveDestinationKind::S3); + return getMoveDestinationAccess(changes, MoveDestinationKind::S3, own_engine); } -AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine) { - return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure, own_engine); } void checkObjectStorageQueueS3MoveDestinationHost( diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h index 40601b4b1145..6cb036e19b27 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -21,8 +21,10 @@ class RemoteHostFilter; /// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy /// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. /// An empty value disables the move destination, so it is not a destination and needs no grant. -AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); -AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); +/// If `own_engine` (the table has this engine, or its engine is not known, as for `ON CLUSTER`), `after_processing` +/// other than `keep` needs the same unfiltered `WRITE`. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine); /// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. /// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp index fa60b7b66327..4293fa10f335 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace DB @@ -59,7 +60,8 @@ namespace ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata( const ObjectStorageQueueSettings & engine_settings, const ColumnsDescription & columns_, - const std::string & format_) + const std::string & format_, + const Source & source) : format_name(format_) , columns(columns_.toString(true)) , mode(engine_settings[ObjectStorageQueueSetting::mode].toString()) @@ -76,6 +78,7 @@ ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata( , tracked_files_limit(engine_settings[ObjectStorageQueueSetting::tracked_files_limit]) , tracked_files_ttl_sec(engine_settings[ObjectStorageQueueSetting::tracked_file_ttl_sec]) , buckets(engine_settings[ObjectStorageQueueSetting::buckets]) + , source_hash(source.getHash()) { processing_threads_num_changed = engine_settings[ObjectStorageQueueSetting::processing_threads_num].changed; if (!processing_threads_num_changed && engine_settings[ObjectStorageQueueSetting::processing_threads_num] <= 1) @@ -118,6 +121,7 @@ String ObjectStorageQueueTableMetadata::toString() const json.set("partitioning_mode", partitioning_mode); json.set("partition_regex", partition_regex); json.set("partition_component", partition_component); + json.set("source_hash", source_hash); std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM oss.exceptions(std::ios::failbit); @@ -209,6 +213,7 @@ ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata(const Poco::JSO , tracked_files_limit(getOrDefault(json, "tracked_files_limit", "s3queue_", 0ULL)) , tracked_files_ttl_sec(getOrDefault(json, "tracked_files_ttl_sec", "", getOrDefault(json, "tracked_file_ttl_sec", "s3queue_", 0ULL))) , buckets(getOrDefault(json, "buckets", "", 0ULL)) + , source_hash(getOrDefault(json, "source_hash", "", "")) { validateMode(mode); } @@ -220,6 +225,21 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueTableMetadata::parse(const Str return ObjectStorageQueueTableMetadata(json); } +String ObjectStorageQueueTableMetadata::Source::getHash() const +{ + if (empty()) + return {}; + + /// With the lengths, bucket `ab` with path `c/*` and bucket `a` with path `bc/*` have different hashes. + SipHash hash; + for (const auto & part : {type, endpoint, bucket, path_pattern}) + { + hash.update(part.size()); + hash.update(part); + } + return getHexUIntLowercase(hash.get128()); +} + void ObjectStorageQueueTableMetadata::adjustFromKeeper(const ObjectStorageQueueTableMetadata & from_zk) { if (processing_threads_num != from_zk.processing_threads_num) @@ -261,6 +281,11 @@ void ObjectStorageQueueTableMetadata::checkImmutableFieldsEquals(const ObjectSto from_zk.mode, mode); + if (!from_zk.source_hash.empty() && source_hash != from_zk.source_hash) + throw Exception( + ErrorCodes::METADATA_MISMATCH, + "Existing table metadata in ZooKeeper differs in source (storage type, endpoint, bucket or path)"); + if (bucketing_mode != from_zk.bucketing_mode) throw Exception( ErrorCodes::METADATA_MISMATCH, diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h index f06cfe473a9c..6af691e8b105 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -19,6 +20,20 @@ class ReadBuffer; */ struct ObjectStorageQueueTableMetadata { + /// Where the queue reads files from, without credentials. Tables with the same `keeper_path` must have the same + /// source, because processed files are tracked only by their path. + struct Source + { + String type; + String endpoint; + String bucket; + String path_pattern; + bool from_named_collection = false; + + [[nodiscard]] bool empty() const { return endpoint.empty(); } + [[nodiscard]] String getHash() const; + }; + /// Non-changeable settings. const String format_name; const String columns; @@ -38,11 +53,13 @@ struct ObjectStorageQueueTableMetadata std::atomic buckets; bool processing_threads_num_changed = false; + String source_hash; ObjectStorageQueueTableMetadata( const ObjectStorageQueueSettings & engine_settings, const ColumnsDescription & columns_, - const std::string & format_); + const std::string & format_, + const Source & source); ObjectStorageQueueTableMetadata(const ObjectStorageQueueTableMetadata & other) : format_name(other.format_name) @@ -60,16 +77,22 @@ struct ObjectStorageQueueTableMetadata , tracked_files_limit(other.tracked_files_limit.load()) , tracked_files_ttl_sec(other.tracked_files_ttl_sec.load()) , buckets(other.buckets.load()) + , source_hash(other.source_hash) { } - void syncChangeableSettings(const ObjectStorageQueueTableMetadata & other) + void syncChangeableSettings(const ObjectStorageQueueTableMetadata & other, const NameSet & names) { - after_processing = other.after_processing.load(); - loading_retries = other.loading_retries.load(); - processing_threads_num = other.processing_threads_num.load(); - tracked_files_limit = other.tracked_files_limit.load(); - tracked_files_ttl_sec = other.tracked_files_ttl_sec.load(); + if (names.contains("after_processing")) + after_processing = other.after_processing.load(); + if (names.contains("loading_retries")) + loading_retries = other.loading_retries.load(); + if (names.contains("processing_threads_num")) + processing_threads_num = other.processing_threads_num.load(); + if (names.contains("tracked_files_limit")) + tracked_files_limit = other.tracked_files_limit.load(); + if (names.contains("tracked_file_ttl_sec")) + tracked_files_ttl_sec = other.tracked_files_ttl_sec.load(); } explicit ObjectStorageQueueTableMetadata(const Poco::JSON::Object::Ptr & json); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 718da1abc8cf..8b60165d8f1b 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -287,6 +287,8 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( std::optional format_settings_, ASTStorage * engine_args, LoadingStrictnessLevel mode, + ObjectStorageQueueTableMetadata::Source source, + bool strict_metadata_check, bool keep_data_in_keeper_) : IStorage(table_id_) , WithContext(context_) @@ -403,6 +405,11 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( &zookeeper_name); LOG_INFO(log, "Using zookeeper path: {}", zk_path.string()); + if (strict_metadata_check && source.empty()) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Cannot identify the source of the queue: the Azure endpoint is not an `http://` or `https://` URL"); + auto table_metadata = ObjectStorageQueueMetadata::syncWithKeeper( zookeeper_name, zk_path, @@ -410,7 +417,8 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( storage_metadata.getColumns(), configuration_->format, context_, - is_attach, + source, + strict_metadata_check, log); ObjectStorageType storage_type = engine_name == "S3Queue" ? ObjectStorageType::S3 : ObjectStorageType::Azure; @@ -1460,10 +1468,40 @@ void StorageObjectStorageQueue::alter( SettingsChanges changed_settings; std::set new_settings_set; + std::set settings_in_query; + for (const auto & command : alter_commands) + { + for (const auto & change : command.settings_changes) + settings_in_query.insert(change.name); + settings_in_query.insert(command.settings_resets.begin(), command.settings_resets.end()); + } + const auto mode = getTableMetadata().getMode(); const size_t dependencies_count = getDependencies(); bool requires_detached_mv = false; + auto read_settings_in_keeper = [this]() + { + String metadata_in_keeper; + ObjectStorageQueueMetadata::getKeeperRetriesControl(log).retryLoop( + [&] { metadata_in_keeper = getZooKeeper()->get(zk_path / "metadata"); }); + const auto table_metadata_in_keeper = ObjectStorageQueueTableMetadata::parse(metadata_in_keeper); + return getSettings(&table_metadata_in_keeper); + }; + /// Shared by all tables with this `keeper_path` on this server, can differ from this table's `old_settings`. + auto local_shared_metadata_settings = getSettings(&getTableMetadata()); + std::optional settings_in_keeper; + auto differs_from_queue = [&](const SettingChange & setting) + { + if (!ObjectStorageQueueTableMetadata::isStoredInKeeper(setting.name) || !isSettingChangeable(setting.name, mode)) + return false; + if (local_shared_metadata_settings.get(setting.name) != setting.value) + return true; + if (!settings_in_keeper) + settings_in_keeper.emplace(read_settings_in_keeper()); + return settings_in_keeper->get(setting.name) != setting.value; + }; + for (auto & setting : new_settings) { LOG_TEST(log, "New setting {}: {}", setting.name, setting.value); @@ -1479,7 +1517,8 @@ void StorageObjectStorageQueue::alter( old_settings->begin(), old_settings->end(), [&](const SettingChange & change) { return change.name == setting.name; }); - setting_changed = it == old_settings->end() || it->value != setting.value; + setting_changed = it == old_settings->end() || it->value != setting.value + || (settings_in_query.contains(setting.name) && differs_from_queue(setting)); } if (!setting_changed) continue; @@ -1649,7 +1688,7 @@ StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const Ac shutdown_called); } -ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const +ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings(const ObjectStorageQueueTableMetadata * table_metadata_) const { /// We do not store queue settings /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), @@ -1657,14 +1696,14 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const ObjectStorageQueueSettings settings; /// If startup() for a table was not called, just use the default queue settings. /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. - if (!startup_finished) + if (!startup_finished && !table_metadata_) return settings; auto metadata = tryGetFilesMetadata(); if (!metadata) return settings; - const auto & table_metadata = metadata->getTableMetadata(); + const auto & table_metadata = table_metadata_ ? *table_metadata_ : metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index 902ec55b54bf..923579ae718b 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -33,6 +33,8 @@ class StorageObjectStorageQueue : public IStorage, WithContext std::optional format_settings_, ASTStorage * engine_args, LoadingStrictnessLevel mode, + ObjectStorageQueueTableMetadata::Source source, + bool strict_metadata_check, bool keep_data_in_keeper_); String getName() const override { return engine_name; } @@ -64,7 +66,7 @@ class StorageObjectStorageQueue : public IStorage, WithContext zkutil::ZooKeeperPtr getZooKeeper() const; - ObjectStorageQueueSettings getSettings() const; + ObjectStorageQueueSettings getSettings(const ObjectStorageQueueTableMetadata * table_metadata = nullptr) const; /// Can setting be changed via ALTER TABLE MODIFY SETTING query. static bool isSettingChangeable(const std::string & name, ObjectStorageQueueMode mode); diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index d7ddf6e5d128..e6deb4bb7e7c 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -4,6 +4,10 @@ #include #include #include +#include +#if CLICKHOUSE_CLOUD +#include +#endif #include #include #include @@ -11,6 +15,7 @@ #include #include #include +#include #if USE_AWS_S3 #include @@ -41,6 +46,40 @@ namespace ObjectStorageQueueSetting extern const ObjectStorageQueueSettingsBool use_hive_partitioning; } +namespace +{ + +#if USE_AWS_S3 +ObjectStorageQueueTableMetadata::Source getQueueSource(const StorageS3Configuration & configuration, const ContextPtr &) +{ + /// `S3::URI` keeps the user info in the endpoint or the bucket name, so such a URL is parsed again without it. + auto url = configuration.url; + if (!url.uri.getUserInfo().empty()) + { + Poco::URI uri = url.uri; + uri.setUserInfo(""); + url = S3::URI( + uri.toString(), + /*allow_archive_path_syntax*/ false, + /*keep_presigned_query_parameters*/ true); + } + return {configuration.getTypeName(), url.endpoint, url.bucket, configuration.getRawPath().path}; +} +#endif + +#if USE_AZURE_BLOB_STORAGE +ObjectStorageQueueTableMetadata::Source getQueueSource(const StorageAzureConfiguration & configuration, const ContextPtr &) +{ + String endpoint = configuration.getConnectionURLWithoutQuery(); + const Poco::URI uri(endpoint); + if (uri.getScheme() != "http" && uri.getScheme() != "https") + return {}; + return {configuration.getTypeName(), std::move(endpoint), configuration.getNamespace(), configuration.getRawPath().path}; +} +#endif + +} + template StoragePtr createQueueStorage(const StorageFactory::Arguments & args) { @@ -80,8 +119,13 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) if (!allow_uuid_macro) info.table_id.uuid = UUIDHelpers::Nil; - /// Make sure that {uuid} macro is allowed, if present. - args.getContext()->getMacros()->expand(path, info); + { + /// Some fields (e.g.: level) in MacroExpansionInfo are modified during macro expansion. + /// Let's make a copy, so the next call won't interfere with this one. + auto info_copy = info; + /// Make sure that {uuid} macro is allowed, if present. + args.getContext()->getMacros()->expand(path, info_copy); + } /// Actually expand all the macros except {uuid} macro. info.expand_special_macros_only = true; @@ -116,6 +160,20 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) } } + auto source = getQueueSource(*configuration, args.getLocalContext()); + source.from_named_collection = configuration->initialized_from_named_collection; + + /// Another replica of a `Replicated` database replays the definition that its initiator has checked. + const auto metadata_txn = args.getLocalContext()->getZooKeeperMetadataTransaction(); + bool is_secondary_ddl_replay = metadata_txn && !metadata_txn->isInitialQuery(); +#if CLICKHOUSE_CLOUD + is_secondary_ddl_replay |= args.getLocalContext()->getClientInfo().is_shared_catalog_internal + && !SharedDatabaseCatalog::isInitialQuery(args.getLocalContext()); +#endif + const bool is_replayed_definition = !isFreshTableDefinition(args.mode, args.query.attach_short_syntax) + || is_secondary_ddl_replay || args.getLocalContext()->isRecoveryFromStoredMetadata(); + const bool strict_metadata_check = (args.is_restore_from_backup && !is_secondary_ddl_replay) || !is_replayed_definition; + return std::make_shared( std::move(queue_settings), std::move(configuration), @@ -127,6 +185,8 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) format_settings, args.storage_def, args.mode, + std::move(source), + strict_metadata_check, /* keep_data_in_keeper */ false); } diff --git a/src/Storages/RabbitMQ/RabbitMQProducer.cpp b/src/Storages/RabbitMQ/RabbitMQProducer.cpp index 99b14ab4fa24..68651da9323f 100644 --- a/src/Storages/RabbitMQ/RabbitMQProducer.cpp +++ b/src/Storages/RabbitMQ/RabbitMQProducer.cpp @@ -152,13 +152,11 @@ void RabbitMQProducer::setupChannel() void RabbitMQProducer::removeRecord(UInt64 received_delivery_tag, bool multiple, bool republish) { - auto record_iter = delivery_record.find(received_delivery_tag); - assert(record_iter != delivery_record.end()); - + /// The delivery tag comes from the broker, so it may refer to a message that is not (or no longer) in `delivery_record`. if (multiple) { /// If multiple is true, then all delivery tags up to and including current are confirmed (with ack or nack). - ++record_iter; + auto record_iter = delivery_record.upper_bound(received_delivery_tag); if (republish) for (auto record = delivery_record.begin(); record != record_iter; ++record) @@ -170,6 +168,13 @@ void RabbitMQProducer::removeRecord(UInt64 received_delivery_tag, bool multiple, } else { + auto record_iter = delivery_record.find(received_delivery_tag); + if (record_iter == delivery_record.end()) + { + LOG_WARNING(log, "Received {} for unknown delivery tag {}, ignoring it", republish ? "nack" : "ack", received_delivery_tag); + return; + } + if (republish) if (!returned.push(record_iter->second)) throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); diff --git a/src/Storages/RabbitMQ/RabbitMQProducer.h b/src/Storages/RabbitMQ/RabbitMQProducer.h index cc335e48e9e9..765dd5eb0ec7 100644 --- a/src/Storages/RabbitMQ/RabbitMQProducer.h +++ b/src/Storages/RabbitMQ/RabbitMQProducer.h @@ -29,6 +29,8 @@ class RabbitMQProducer : public AsynchronousMessageProducer void cancel() noexcept override; private: + friend class RabbitMQProducerTest; + String getProducingTaskName() const override { return "RabbitMQProducingTask"; } struct Payload diff --git a/src/Storages/StorageAlias.h b/src/Storages/StorageAlias.h index 99a9167dd58d..800eb6755a80 100644 --- a/src/Storages/StorageAlias.h +++ b/src/Storages/StorageAlias.h @@ -246,13 +246,13 @@ class StorageAlias final : public IStorage, WithContext } ColumnSizeByName getColumnSizes() const override { return getTargetTable()->getColumnSizes(); } - std::optional tryGetColumnSizes() const override + std::optional tryGetColumnSizes(const ContextPtr & query_context) const override { auto target = tryGetTargetTable(); if (!target) return std::nullopt; - return target->getColumnSizes(); + return target->tryGetColumnSizes(query_context); } IndexSizeByName getSecondaryIndexSizes() const override { return getTargetTable()->getSecondaryIndexSizes(); } diff --git a/src/Storages/StorageDictionary.cpp b/src/Storages/StorageDictionary.cpp index 3def96884bc0..0b11325fb4b2 100644 --- a/src/Storages/StorageDictionary.cpp +++ b/src/Storages/StorageDictionary.cpp @@ -186,27 +186,33 @@ Pipe StorageDictionary::read( const size_t max_block_size, const size_t threads) { - auto registered_dictionary_name = location == Location::SameDatabaseAndNameAsDictionary ? getStorageID().getInternalDictionaryName() : dictionary_name; - auto dictionary = getContext()->getExternalDictionariesLoader().getDictionary(registered_dictionary_name, local_context); + auto dictionary = getDictionary(local_context); + return dictionary->read(column_names, max_block_size, threads); +} +void StorageDictionary::checkDictionaryAccess(const StorageID & dictionary_id, const ContextPtr & local_context) +{ /** * For backward compatibility reasons we require either SELECT or dictGet permission to read directly from the dictionary. * If none of these conditions are met - we ask to grant a dictGet. */ - bool has_dict_get = local_context->getAccess()->isGranted( - AccessType::dictGet, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - bool has_select = local_context->getAccess()->isGranted( - AccessType::SELECT, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - if (!has_dict_get && !has_select) - local_context->checkAccess(AccessType::dictGet, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - - return dictionary->read(column_names, max_block_size, threads); + auto dictionary_database = IDictionary::getDatabaseOrNoDatabaseTag(dictionary_id); + const auto & access = local_context->getAccess(); + if (!access->isGranted(AccessType::dictGet, dictionary_database, dictionary_id.getTableName()) + && !access->isGranted(AccessType::SELECT, dictionary_database, dictionary_id.getTableName())) + local_context->checkAccess(AccessType::dictGet, dictionary_database, dictionary_id.getTableName()); } -std::shared_ptr StorageDictionary::getDictionary() const +std::shared_ptr StorageDictionary::getDictionary(const ContextPtr & query_context) const { auto registered_dictionary_name = location == Location::SameDatabaseAndNameAsDictionary ? getStorageID().getInternalDictionaryName() : dictionary_name; - return getContext()->getExternalDictionariesLoader().getDictionary(registered_dictionary_name, getContext()); + const auto & external_loader = getContext()->getExternalDictionariesLoader(); + + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and load the dictionary that passed the check. + auto dictionary = external_loader.resolveDictionary(registered_dictionary_name, query_context); + checkDictionaryAccess(dictionary.id, query_context); + return external_loader.getDictionary(dictionary, query_context); } void StorageDictionary::shutdown(bool) @@ -389,7 +395,13 @@ void registerStorageDictionary(StorageFactory & factory) if (args.mode <= LoadingStrictnessLevel::CREATE) { - const auto & dictionary = args.getContext()->getExternalDictionariesLoader().getDictionary(dictionary_name, args.getContext()); + /// The user creating the table must be allowed to read the dictionary. Check it before loading the dictionary, + /// because loading contacts the dictionary source. The name is resolved with the query context, + /// like when the table is read. + const auto & external_loader = local_context->getExternalDictionariesLoader(); + auto resolved_dictionary = external_loader.resolveDictionary(dictionary_name, local_context); + StorageDictionary::checkDictionaryAccess(resolved_dictionary.id, local_context); + const auto & dictionary = external_loader.getDictionary(resolved_dictionary, local_context); const DictionaryStructure & dictionary_structure = dictionary->getStructure(); checkNamesAndTypesCompatibleWithDictionary(dictionary_name, args.columns, dictionary_structure); } diff --git a/src/Storages/StorageDictionary.h b/src/Storages/StorageDictionary.h index b59931b987be..74d832c06d54 100644 --- a/src/Storages/StorageDictionary.h +++ b/src/Storages/StorageDictionary.h @@ -78,10 +78,15 @@ friend class TableFunctionDictionary; /// count() can return wrong result, see test_dictionaries_redis/test_long.py::test_redis_dict_long bool parallelizeOutputAfterReading(ContextPtr) const override { return false; } - std::shared_ptr getDictionary() const; + /// Loads the dictionary after checking that the user of `query_context` may read it, see `checkDictionaryAccess`. + [[nodiscard]] std::shared_ptr getDictionary(const ContextPtr & query_context) const; static NamesAndTypesList getNamesAndTypes(const DictionaryStructure & dictionary_structure, bool validate_id_type); + /// Checks the access needed to read the dictionary with the given ID as a table. + /// Must be called before the dictionary is loaded or its definition is read. + static void checkDictionaryAccess(const StorageID & dictionary_id, const ContextPtr & local_context); + bool isDictionary() const override { return true; } bool supportsTruncate() const override { return false; } void shutdown(bool is_drop) override; diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 4ced2fa21aa6..0f0e1ef7056e 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -279,7 +279,7 @@ AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & crea return; auto it = storages.find(storage.engine->name); if (it != storages.end() && it->second.features.get_export_access_fn) - res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes, /* own_engine */ true)); }; if (create.storage) @@ -292,13 +292,24 @@ AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & crea return res; } +AccessRightsElements StorageFactory::getExportAccess(const SettingsChanges & changes, const String & engine) const +{ + AccessRightsElements res; + for (const auto & [name, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes, name == engine)); + } + return res; +} + AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const { AccessRightsElements res; for (const auto & [_, creator] : storages) { if (creator.features.get_export_access_fn) - res.append_range(creator.features.get_export_access_fn(changes)); + res.append_range(creator.features.get_export_access_fn(changes, /* own_engine */ true)); } return res; } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index 6babf823c358..69e5da3abae7 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -37,7 +37,8 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. - using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + /// If `own_engine`, also the grants for settings that modify the source files, e.g. `after_processing` of a queue. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes, bool own_engine); struct Arguments { @@ -151,6 +152,8 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` /// table. An unknown engine needs nothing here: creating it fails later. AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// For `changes` of a table with `engine`: the destinations of every engine, as below, and the source files of `engine` only. + AccessRightsElements getExportAccess(const SettingsChanges & changes, const String & engine) const; /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; diff --git a/src/Storages/StorageMerge.cpp b/src/Storages/StorageMerge.cpp index a70dd5e4659b..ac485c38a801 100644 --- a/src/Storages/StorageMerge.cpp +++ b/src/Storages/StorageMerge.cpp @@ -288,6 +288,25 @@ StoragePtr StorageMerge::traverseTablesUntilImpl(const ContextPtr & query_contex return {}; } +template +StoragePtr StorageMerge::traverseVisibleTablesUntil(const ContextPtr & query_context, F && predicate) const +{ + auto access = query_context->getAccess(); + std::optional last_database; + bool granted_show_on_all_tables = false; + return traverseTablesUntilImpl(query_context, this, database_name_or_regexp, [&](const StoragePtr & table) + { + auto id = table->getStorageID(); + if (id.database_name != last_database) + { + last_database = id.database_name; + granted_show_on_all_tables = access->isGranted(AccessType::SHOW_TABLES, id.database_name); + } + return (granted_show_on_all_tables || access->isGranted(AccessType::SHOW_TABLES, id.database_name, id.table_name)) + && predicate(table); + }); +} + template void StorageMerge::forEachTable(F && func) const { @@ -1792,11 +1811,27 @@ IStorage::ColumnSizeByName StorageMerge::getColumnSizes() const return column_sizes; } -std::optional StorageMerge::tryGetColumnSizes() const +std::optional StorageMerge::tryGetColumnSizes(const ContextPtr & query_context) const { try { - return getColumnSizes(); + auto access = query_context->getAccess(); + ColumnSizeByName column_sizes; + auto first_table_without_sizes = traverseVisibleTablesUntil(query_context, [&](const auto & table) + { + auto sizes = table->tryGetColumnSizes(query_context); + if (!sizes) + return true; + auto id = table->getStorageID(); + bool show_all_columns = access->isGranted(AccessType::SHOW_COLUMNS, id.database_name, id.table_name); + for (const auto & [name, size] : *sizes) + if (show_all_columns || access->isGranted(AccessType::SHOW_COLUMNS, id.database_name, id.table_name, name)) + column_sizes[name].add(size); + return false; + }); + if (first_table_without_sizes) + return std::nullopt; + return column_sizes; } catch (const Exception & e) { @@ -1834,24 +1869,44 @@ bool StorageMerge::supportsTrivialCountOptimization(const StorageSnapshotPtr &, { /// Here we actually need storage snapshot of all nested tables. /// But to avoid complexity pass nullptr to make more lightweight check in MergeTreeData. - return traverseTablesUntil([&](const auto & table) { return !table->supportsTrivialCountOptimization(nullptr, ctx); }) == nullptr; + auto access = ctx->getAccess(); + return traverseVisibleTablesUntil(ctx, [&](const auto & table) + { + /// Like a direct `SELECT count()`, counting a child needs `SELECT` on at least one of its columns. + auto id = table->getStorageID(); + bool has_select_access = access->isGranted(AccessType::SELECT, id.database_name); + if (!has_select_access) + { + const auto metadata = table->getInMemoryMetadataPtr(); + for (const auto & column : metadata->getColumns()) + { + if (access->isGranted(AccessType::SELECT, id.database_name, id.table_name, column.name)) + { + has_select_access = true; + break; + } + } + } + + return !has_select_access || !table->supportsTrivialCountOptimization(nullptr, ctx); + }) == nullptr; } std::optional StorageMerge::totalRows(ContextPtr query_context) const { - return totalRowsOrBytes([&](const auto & table) { return table->totalRows(query_context); }); + return totalRowsOrBytes(query_context, [&](const auto & table) { return table->totalRows(query_context); }); } std::optional StorageMerge::totalBytes(ContextPtr query_context) const { - return totalRowsOrBytes([&](const auto & table) { return table->totalBytes(query_context); }); + return totalRowsOrBytes(query_context, [&](const auto & table) { return table->totalBytes(query_context); }); } template -std::optional StorageMerge::totalRowsOrBytes(F && func) const +std::optional StorageMerge::totalRowsOrBytes(const ContextPtr & query_context, F && func) const { UInt64 total_rows_or_bytes = 0; - auto first_table = traverseTablesUntil([&](const auto & table) + auto first_table = traverseVisibleTablesUntil(query_context, [&](const auto & table) { if (auto rows_or_bytes = func(table)) { diff --git a/src/Storages/StorageMerge.h b/src/Storages/StorageMerge.h index 948a5f50694f..cff0cfb4a1fb 100644 --- a/src/Storages/StorageMerge.h +++ b/src/Storages/StorageMerge.h @@ -134,6 +134,9 @@ class StorageMerge final : public IStorage, WithContext template StoragePtr traverseTablesUntil(F && predicate) const; + template + StoragePtr traverseVisibleTablesUntil(const ContextPtr & query_context, F && predicate) const; + template void forEachTable(F && func) const; @@ -149,7 +152,7 @@ class StorageMerge final : public IStorage, WithContext ColumnSizeByName getColumnSizes() const override; - std::optional tryGetColumnSizes() const override; + std::optional tryGetColumnSizes(const ContextPtr & query_context) const override; ColumnsDescription getColumnsDescriptionFromSourceTables(const ContextPtr & context) const; @@ -158,7 +161,7 @@ class StorageMerge final : public IStorage, WithContext bool tableSupportsPrewhere() const; template - std::optional totalRowsOrBytes(F && func) const; + std::optional totalRowsOrBytes(const ContextPtr & query_context, F && func) const; friend class ReadFromMerge; }; diff --git a/src/Storages/StorageURL.cpp b/src/Storages/StorageURL.cpp index b021c408324a..ee242fee1f44 100644 --- a/src/Storages/StorageURL.cpp +++ b/src/Storages/StorageURL.cpp @@ -303,7 +303,7 @@ size_t StorageURLSource::DisclosedGlobIterator::size() return pimpl->size(); } -void StorageURLSource::setCredentials(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & request_uri) +void StorageURLSource::setCredentials(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & request_uri, const HTTPHeaderFilter & header_filter) { const auto & user_info = request_uri.getUserInfo(); if (!user_info.empty()) @@ -315,6 +315,8 @@ void StorageURLSource::setCredentials(Poco::Net::HTTPBasicCredentials & credenti credentials.setPassword(user_info.substr(n + 1)); } } + + header_filter.checkBasicCredentials(credentials); } StorageURLSource::StorageURLSource( @@ -341,7 +343,7 @@ StorageURLSource::StorageURLSource( , columns_description(info.columns_description) , requested_columns(info.requested_columns) , need_headers_virtual_column(info.requested_virtual_columns.contains("_headers")) - , requested_virtual_columns(info.requested_virtual_columns.eraseNames({"_headers"})) + , requested_virtual_columns(info.requested_virtual_columns) , block_for_format(info.format_header) , uri_iterator(uri_iterator_) , format(format_) @@ -391,7 +393,9 @@ StorageURLSource::StorageURLSource( QueryPipelineBuilder builder; std::optional num_rows_from_cache = std::nullopt; - if (need_only_count && getContext()->getSettingsRef()[Setting::use_cache_for_count_from_files]) + /// The number of rows from the cache is returned without a request for the data, while the `_headers` + /// virtual column is the headers of the response to that request. Do the request when `_headers` is requested. + if (need_only_count && !need_headers_virtual_column && getContext()->getSettingsRef()[Setting::use_cache_for_count_from_files]) num_rows_from_cache = tryGetNumRowsFromCache(curr_uri.toString(), last_mod_time); if (num_rows_from_cache) @@ -489,30 +493,25 @@ Chunk StorageURLSource::generate() path); } + chassert(dynamic_cast(read_buf.get())); + if (need_headers_virtual_column && !http_response_headers_initialized) + { + http_response_headers = dynamic_cast(read_buf.get())->getResponseHeaders(); + http_response_headers_initialized = true; + } + + /// `_headers` is added along with the other virtual columns, in the order they are requested in, + /// which is the order of the columns in the header of the source. VirtualColumnUtils::addRequestedFileLikeStorageVirtualsToChunk( chunk, requested_virtual_columns, { .path = curr_uri.getPath(), .size = current_file_size, + .http_response_headers = need_headers_virtual_column ? &http_response_headers : nullptr, }, getContext()); - chassert(dynamic_cast(read_buf.get())); - if (need_headers_virtual_column) - { - if (!http_response_headers_initialized) - { - http_response_headers = dynamic_cast(read_buf.get())->getResponseHeaders(); - http_response_headers_initialized = true; - } - - auto type = std::make_shared( - std::make_shared(std::make_shared()), - std::make_shared(std::make_shared())); - - chunk.addColumn(type->createColumnConst(chunk.getNumRows(), http_response_headers)->convertToFullColumnIfConst()); - } return chunk; } @@ -556,7 +555,8 @@ std::pair> StorageURLSource: for (const auto & [param, value] : params) request_uri.addQueryParameter(param, value); - setCredentials(credentials, request_uri); + /// Not inside the `try` below: a forbidden option must fail the read, not fall through to the next one. + setCredentials(credentials, request_uri, context_->getHTTPHeaderFilter()); const auto & settings = context_->getSettingsRef(); diff --git a/src/Storages/StorageURL.h b/src/Storages/StorageURL.h index 379a923ba032..6195b5b50b53 100644 --- a/src/Storages/StorageURL.h +++ b/src/Storages/StorageURL.h @@ -28,6 +28,7 @@ struct ConnectionTimeouts; class NamedCollection; struct StorageID; class PullingPipelineExecutor; +class HTTPHeaderFilter; /** * This class represents table engine for external urls. @@ -206,7 +207,8 @@ class StorageURLSource : public ISource, WithContext void onFinish() override { parser_shared_resources->finishStream(); } - static void setCredentials(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & request_uri); + /// Throws if `header_filter` forbids the `Authorization` header, which sends the credentials, and they have a username. + static void setCredentials(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & request_uri, const HTTPHeaderFilter & header_filter); static std::pair> getFirstAvailableURIAndReadBuffer( std::vector::const_iterator & option, diff --git a/src/Storages/StorageURLCluster.cpp b/src/Storages/StorageURLCluster.cpp index 18ed46e9e005..4c8ec79f4c78 100644 --- a/src/Storages/StorageURLCluster.cpp +++ b/src/Storages/StorageURLCluster.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -40,6 +41,7 @@ namespace ErrorCodes namespace Setting { + extern const SettingsBool enable_url_encoding; extern const SettingsUInt64 glob_expansion_max_elements; extern const SettingsBool use_hive_partitioning; } @@ -136,11 +138,20 @@ RemoteQueryExecutor::Extension StorageURLCluster::getTaskIteratorExtension( auto iterator = std::make_shared( uri, context->getSettingsRef()[Setting::glob_expansion_max_elements], predicate, getVirtualsList(), hive_partition_columns_to_read_from_file_path, context); - auto next_callback = [iter = std::move(iterator)](size_t) mutable -> ClusterFunctionReadTaskResponsePtr + auto next_callback = [iter = std::move(iterator), context](size_t) mutable -> ClusterFunctionReadTaskResponsePtr { auto url = iter->next(); if (url.empty()) return std::make_shared(); + + /// The workers check the credentials under their own configuration, which can differ from this one. + const auto & settings = context->getSettingsRef(); + for (const auto & option : parseRemoteDescription(url, 0, url.size(), '|', settings[Setting::glob_expansion_max_elements])) + { + Poco::Net::HTTPBasicCredentials credentials; + StorageURLSource::setCredentials(credentials, Poco::URI(option, settings[Setting::enable_url_encoding]), context->getHTTPHeaderFilter()); + } + return std::make_shared(std::move(url)); }; auto callback = std::make_shared(std::move(next_callback)); diff --git a/src/Storages/System/StorageSystemColumns.cpp b/src/Storages/System/StorageSystemColumns.cpp index 3b0d34cdb366..bfa8091244a7 100644 --- a/src/Storages/System/StorageSystemColumns.cpp +++ b/src/Storages/System/StorageSystemColumns.cpp @@ -94,18 +94,19 @@ class ColumnsSource : public ISource ColumnPtr databases_, ColumnPtr tables_, Storages storages_, - ContextPtr context) + ContextPtr context_) : ISource(header_) , columns_mask(std::move(columns_mask_)) , max_block_size(max_block_size_) , databases(std::move(databases_)) , tables(std::move(tables_)) , storages(std::move(storages_)) - , client_info_interface(context->getClientInfo().interface) + , client_info_interface(context_->getClientInfo().interface) , total_tables(tables->size()) - , access(context->getAccess()) - , query_id(context->getCurrentQueryId()) - , lock_acquire_timeout(std::chrono::milliseconds(context->getSettingsRef()[Setting::lock_acquire_timeout].totalMilliseconds())) + , access(context_->getAccess()) + , query_id(context_->getCurrentQueryId()) + , lock_acquire_timeout(std::chrono::milliseconds(context_->getSettingsRef()[Setting::lock_acquire_timeout].totalMilliseconds())) + , context(std::move(context_)) { need_to_check_access_for_tables = !access->isGranted(AccessType::SHOW_COLUMNS); } @@ -153,7 +154,7 @@ class ColumnsSource : public ISource /// Certain information about a table - should be calculated only when the corresponding columns are queried. if (columns_mask[7] || columns_mask[8] || columns_mask[9]) { - if (auto sizes = storage->tryGetColumnSizes()) + if (auto sizes = storage->tryGetColumnSizes(context)) column_sizes = std::move(*sizes); } @@ -348,6 +349,7 @@ class ColumnsSource : public ISource bool need_to_check_access_for_tables; String query_id; std::chrono::milliseconds lock_acquire_timeout; + ContextPtr context; }; class ReadFromSystemColumns : public SourceStepWithFilter diff --git a/src/Storages/System/StorageSystemContributors.generated.cpp b/src/Storages/System/StorageSystemContributors.generated.cpp index df41b2727110..15c78e06d58d 100644 --- a/src/Storages/System/StorageSystemContributors.generated.cpp +++ b/src/Storages/System/StorageSystemContributors.generated.cpp @@ -937,6 +937,7 @@ const char * auto_contributors[] { "Maruth Goyal", "Marvin Taschenberger", "Masha", + "Matheus Nerone", "Mathieu Rey", "Matt Klein", "Matt Woenker", @@ -1098,6 +1099,7 @@ const char * auto_contributors[] { "NikitaEvs", "Nikolai Fedorovskikh", "Nikolai Kochetov", + "Nikolai Ovchinnikov", "Nikolai Ryzhov", "Nikolai Sorokin", "Nikolay", @@ -1297,6 +1299,7 @@ const char * auto_contributors[] { "Sami Kerola", "Samuel Chou", "Samuel Colvin", + "Samuel Krempaský", "Samuel Warfield", "Samuele Guerrini", "San", diff --git a/src/Storages/System/StorageSystemRemoteDataPaths.cpp b/src/Storages/System/StorageSystemRemoteDataPaths.cpp index de4a0f7b421e..f143222b0ff3 100644 --- a/src/Storages/System/StorageSystemRemoteDataPaths.cpp +++ b/src/Storages/System/StorageSystemRemoteDataPaths.cpp @@ -34,7 +34,6 @@ namespace ErrorCodes extern const int DIRECTORY_DOESNT_EXIST; } - class SystemRemoteDataPathsSource : public ISource { public: @@ -48,10 +47,8 @@ class SystemRemoteDataPathsSource : public ISource , context(std::move(context_)) { for (const auto & disk : disks_) - { - if (disk.second->isRemote()) + if (isDiskObjectStorage(disk.second)) disks.push_back(disk); - } auto component_guard = Coordination::setCurrentComponent("SystemRemoteDataPathsSource::SystemRemoteDataPathsSource"); /// Position at the first disk diff --git a/src/Storages/VirtualColumnUtils.cpp b/src/Storages/VirtualColumnUtils.cpp index c07e2e4b712b..c2ecd03f6e90 100644 --- a/src/Storages/VirtualColumnUtils.cpp +++ b/src/Storages/VirtualColumnUtils.cpp @@ -469,6 +469,12 @@ void addRequestedFileLikeStorageVirtualsToChunk( /// Row numbers not known, _row_number = NULL. chunk.addColumn(virtual_column.type->createColumnConstWithDefaultValue(chunk.getNumRows())->convertToFullColumnIfConst()); } + else if (virtual_column.name == "_headers" && virtual_values.http_response_headers) + { + /// Added here, in its place among the requested virtual columns, and not by the caller after the other ones: + /// the columns of the chunk must go in the order of the header of the source, which is the requested order. + chunk.addColumn(virtual_column.type->createColumnConst(chunk.getNumRows(), *virtual_values.http_response_headers)->convertToFullColumnIfConst()); + } else if (auto it = hive_map.find(virtual_column.getNameInStorage()); it != hive_map.end()) { chunk.addColumn( diff --git a/src/Storages/VirtualColumnUtils.h b/src/Storages/VirtualColumnUtils.h index 631ab9250d26..eb8956bca967 100644 --- a/src/Storages/VirtualColumnUtils.h +++ b/src/Storages/VirtualColumnUtils.h @@ -11,6 +11,7 @@ namespace DB { +struct Map; class Block; class Chunk; class NamesAndTypesList; @@ -140,6 +141,8 @@ struct VirtualsForFileLikeStorage const String * etag { nullptr }; const std::map * tags { nullptr }; std::optional data_lake_snapshot_version { std::nullopt }; + /// The HTTP response headers of the read: the value of the `_headers` virtual column of the storages which read over HTTP. + const Map * http_response_headers { nullptr }; }; void addRequestedFileLikeStorageVirtualsToChunk( diff --git a/src/Storages/tests/gtest_rabbitmq_publisher.cpp b/src/Storages/tests/gtest_rabbitmq_publisher.cpp new file mode 100644 index 000000000000..60c13d1b5473 --- /dev/null +++ b/src/Storages/tests/gtest_rabbitmq_publisher.cpp @@ -0,0 +1,118 @@ +#include +#include + +#if USE_AMQPCPP + +#include +#include + +#include + +namespace DB +{ + +/// Drives the publisher confirms handler `RabbitMQProducer::removeRecord` directly. The delivery tag +/// of an ack or nack comes from the broker, so it is not guaranteed to be in `delivery_record`. +/// The producer is never started, so no connection to a broker is made. +class RabbitMQProducerTest : public ::testing::Test +{ +protected: + RabbitMQProducerTest() + : publisher(RabbitMQConfiguration{}, Names{"key"}, "exchange", AMQP::ExchangeType::direct, 0, false, shutdown_called, getLogger("RabbitMQProducerTest")) + { + } + + void addRecords(std::initializer_list tags) + { + for (UInt64 tag : tags) + publisher.delivery_record.emplace(tag, RabbitMQProducer::Payload{"message_" + std::to_string(tag), tag}); + } + + void removeRecord(UInt64 tag, bool multiple, bool republish) { publisher.removeRecord(tag, multiple, republish); } + + std::vector pendingTags() const + { + std::vector result; + for (const auto & [tag, _] : publisher.delivery_record) + result.push_back(tag); + return result; + } + + std::vector returnedIds() + { + std::vector result; + RabbitMQProducer::Payload payload; + while (publisher.returned.tryPop(payload)) + result.push_back(payload.id); + return result; + } + + std::atomic shutdown_called{false}; + RabbitMQProducer publisher; +}; + +TEST_F(RabbitMQProducerTest, SingleAckRemovesOnlyItsRecord) +{ + addRecords({1, 2, 3}); + removeRecord(2, /* multiple = */ false, /* republish = */ false); + EXPECT_EQ(pendingTags(), (std::vector{1, 3})); + EXPECT_TRUE(returnedIds().empty()); +} + +TEST_F(RabbitMQProducerTest, UnknownSingleAckOrNackIsIgnored) +{ + addRecords({1, 3}); + removeRecord(2, /* multiple = */ false, /* republish = */ false); + removeRecord(2, /* multiple = */ false, /* republish = */ true); + removeRecord(10, /* multiple = */ false, /* republish = */ true); + EXPECT_EQ(pendingTags(), (std::vector{1, 3})); + EXPECT_TRUE(returnedIds().empty()); +} + +TEST_F(RabbitMQProducerTest, RepeatedSingleNackRequeuesOnce) +{ + addRecords({1, 2}); + removeRecord(1, /* multiple = */ false, /* republish = */ true); + removeRecord(1, /* multiple = */ false, /* republish = */ true); + EXPECT_EQ(pendingTags(), (std::vector{2})); + EXPECT_EQ(returnedIds(), (std::vector{1})); +} + +TEST_F(RabbitMQProducerTest, MultipleAckWithMissingBoundaryTag) +{ + addRecords({1, 2, 4, 5}); + removeRecord(3, /* multiple = */ true, /* republish = */ false); + EXPECT_EQ(pendingTags(), (std::vector{4, 5})); + EXPECT_TRUE(returnedIds().empty()); +} + +TEST_F(RabbitMQProducerTest, MultipleNackWithMissingBoundaryTagRequeuesOnce) +{ + addRecords({1, 2, 4, 5}); + removeRecord(3, /* multiple = */ true, /* republish = */ true); + removeRecord(3, /* multiple = */ true, /* republish = */ true); + EXPECT_EQ(pendingTags(), (std::vector{4, 5})); + EXPECT_EQ(returnedIds(), (std::vector{1, 2})); +} + +TEST_F(RabbitMQProducerTest, MultipleNackBeyondAllRecords) +{ + addRecords({1, 2}); + removeRecord(100, /* multiple = */ true, /* republish = */ true); + EXPECT_TRUE(pendingTags().empty()); + EXPECT_EQ(returnedIds(), (std::vector{1, 2})); +} + +TEST_F(RabbitMQProducerTest, ConfirmsOnEmptyRecord) +{ + removeRecord(1, /* multiple = */ true, /* republish = */ false); + removeRecord(1, /* multiple = */ true, /* republish = */ true); + removeRecord(1, /* multiple = */ false, /* republish = */ false); + removeRecord(1, /* multiple = */ false, /* republish = */ true); + EXPECT_TRUE(pendingTags().empty()); + EXPECT_TRUE(returnedIds().empty()); +} + +} + +#endif diff --git a/src/TableFunctions/TableFunctionDictionary.cpp b/src/TableFunctions/TableFunctionDictionary.cpp index db8dec240b66..9832ea3ba6c4 100644 --- a/src/TableFunctions/TableFunctionDictionary.cpp +++ b/src/TableFunctions/TableFunctionDictionary.cpp @@ -49,8 +49,13 @@ void TableFunctionDictionary::parseArguments(const ASTPtr & ast_function, Contex ColumnsDescription TableFunctionDictionary::getActualTableStructure(ContextPtr context, bool /*is_insert_query*/) const { const ExternalDictionariesLoader & external_loader = context->getExternalDictionariesLoader(); - std::string resolved_name = external_loader.resolveDictionaryName(dictionary_name, context->getCurrentDatabase()); - auto load_result = external_loader.load(resolved_name); + + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and read the dictionary that passed the check. + auto resolved_dictionary = external_loader.resolveDictionary(dictionary_name, context); + StorageDictionary::checkDictionaryAccess(resolved_dictionary.id, context); + + auto load_result = external_loader.load(resolved_dictionary.getKey()); if (load_result) { /// for regexp tree dictionary, the table structure will be different with dictionary structure. it is: @@ -73,7 +78,7 @@ ColumnsDescription TableFunctionDictionary::getActualTableStructure(ContextPtr c } /// otherwise, we get table structure by dictionary structure. - auto dictionary_structure = external_loader.getDictionaryStructure(dictionary_name, context); + auto dictionary_structure = external_loader.getDictionaryStructure(resolved_dictionary); return ColumnsDescription(StorageDictionary::getNamesAndTypes(dictionary_structure, false)); } diff --git a/tests/config/config.d/database_atomic.xml b/tests/config/config.d/database_atomic.xml index a551e710ca37..b3f51d51a79a 100644 --- a/tests/config/config.d/database_atomic.xml +++ b/tests/config/config.d/database_atomic.xml @@ -1,8 +1,3 @@ 60 - - - 0 - 5 - 10 diff --git a/tests/config/config.d/named_collection.xml b/tests/config/config.d/named_collection.xml index 555c3b7f65ba..60341fc98ed2 100644 --- a/tests/config/config.d/named_collection.xml +++ b/tests/config/config.d/named_collection.xml @@ -49,5 +49,17 @@ http://127.0.0.1:8123?query=select+1 RawBLOB + + + 127.0.0.1:1 + topic + group + JSONEachRow + + /etc/clickhouse-server/server.crt + + diff --git a/tests/integration/test_allowed_url_from_config/test.py b/tests/integration/test_allowed_url_from_config/test.py index b43422300bba..6bd65cbe2c0a 100644 --- a/tests/integration/test_allowed_url_from_config/test.py +++ b/tests/integration/test_allowed_url_from_config/test.py @@ -51,6 +51,37 @@ def test_config_with_hosts(start_cluster): node1.query("DROP TABLE table_test_1_2") +@pytest.mark.parametrize( + "query, secret", + [ + ( + "SELECT * FROM url('http://leakuser:pw_userinfo_canary@host:123/', CSV, 'x UInt8')", + "pw_userinfo_canary", + ), + ( + "SELECT * FROM url('http://host:123/v1/chat?access_token=pw_access_token_canary', CSV, 'x UInt8')", + "pw_access_token_canary", + ), + ( + "SELECT * FROM url('http://host:123/pw_path_canary/f.csv', CSV, 'x UInt8')", + "pw_path_canary", + ), + ], + ids=["userinfo", "access_token", "secret_in_path"], +) +def test_rejected_url_credentials_masked(start_cluster, query, secret): + error = node1.query_and_get_error(query) + # The client echoes the submitted query after the exception, so only the exception line is checked. + rejections = [ + line + for line in error.splitlines() + if "is not allowed in configuration file" in line + ] + assert len(rejections) == 1, error + assert 'URL "host:123"' in rejections[0], error + assert secret not in rejections[0], error + + @pytest.mark.parametrize( "query", [ diff --git a/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml b/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml index 22fe3a73a9cc..7d771893ee43 100644 --- a/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml +++ b/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml @@ -16,6 +16,7 @@ + /local_plain/ backup_disk_s3_plain backup_disk_local_plain diff --git a/tests/integration/test_backward_compatibility/test.py b/tests/integration/test_backward_compatibility/test.py index 1f50921bcc57..ef90e43ba0a0 100644 --- a/tests/integration/test_backward_compatibility/test.py +++ b/tests/integration/test_backward_compatibility/test.py @@ -17,6 +17,14 @@ with_zookeeper=True, use_old_analyzer=True, ) +# The oldest tested version (`CLICKHOUSE_CI_MIN_TESTED_VERSION`) in this branch does not send its settings +# in `Hello` yet, so the test of the settings received from the server needs a newer old server. +node3 = cluster.add_instance( + "node3", + image="clickhouse/clickhouse-server", + tag="25.3", + with_installed_binary=True, +) @pytest.fixture(scope="module") @@ -42,3 +50,17 @@ def test_backward_compatability1(start_cluster): node1.query("SYSTEM SYNC REPLICA t", timeout=10) assert node1.query("SELECT count() FROM t") == "1\n" + + +def test_new_client_and_initiator_with_negative_seconds_in_old_server_profile(start_cluster): + node3.query("DROP USER IF EXISTS u_negative_seconds") + node3.query("CREATE USER u_negative_seconds IDENTIFIED WITH no_password SETTINGS max_execution_time = -1") + node3.query("GRANT SELECT ON system.one TO u_negative_seconds") + try: + # `node3.query*` runs the tested client against the old server; the client warns about the value it skips. + out, err = node3.query_and_get_answer_with_error("SELECT 1", user="u_negative_seconds") + assert out == "1\n" + assert "Cannot parse the value of setting `max_execution_time`, skipping it" in err + assert node2.query("SELECT count() FROM remote('node3', system.one, 'u_negative_seconds', '')") == "1\n" + finally: + node3.query("DROP USER IF EXISTS u_negative_seconds") diff --git a/tests/integration/test_distributed_inter_server_secret/test.py b/tests/integration/test_distributed_inter_server_secret/test.py index 5bffac440cfb..57f3c0b320e6 100644 --- a/tests/integration/test_distributed_inter_server_secret/test.py +++ b/tests/integration/test_distributed_inter_server_secret/test.py @@ -424,20 +424,33 @@ def test_per_user_protocol_settings_secure_cluster(user, password): def test_secure_cluster_distributed_over_distributed_different_users_remote(): - # This works because we will have initial_user='default' + # With the local-replica optimization the read runs in new_user's session while remote() + # stamps initial_user='default', so forwarding it over the cluster secret is rejected. + error = n1.query_and_get_error( + "SELECT * FROM remote('n1', currentDatabase(), dist_secure)", + user="new_user", + settings={"prefer_localhost_replica": 1}, + ) + assert "Refusing to forward a query over the cluster secret" in error + + # With the optimization off, remote() opens a real connection that authenticates 'default', + # so initial_user==current_user=='default' and the query runs as 'default'. n1.query( - "SELECT * FROM remote('n1', currentDatabase(), dist_secure)", user="new_user" + "SELECT * FROM remote('n1', currentDatabase(), dist_secure)", + user="new_user", + settings={"prefer_localhost_replica": 0}, + ) + + # new_user exists only on n1, so the secret forward to n2 fails there -- deeper than our + # guard, with no stable error text, so only assert the query is rejected. + assert n2.query_and_get_error( + "SELECT * FROM remote('n1', currentDatabase(), dist_secure, 'new_user')" + ) + + # Also rejected: dist-over-dist on the secure cluster (new_user is still missing on n2). + assert n1.query_and_get_error( + "SELECT * FROM dist_over_dist_secure", user="new_user" ) - # While this is broken because now initial_user='new_user', and n2 does not has it - with pytest.raises(QueryRuntimeException): - n2.query( - "SELECT * FROM remote('n1', currentDatabase(), dist_secure, 'new_user')" - ) - # And this is still a problem, let's assume that this is OK, since we are - # expecting that in case of dist-over-dist the clusters are the same (users - # and stuff). - with pytest.raises(QueryRuntimeException): - n1.query("SELECT * FROM dist_over_dist_secure", user="new_user") def test_secure_cluster_distributed_over_distributed_different_users_cluster(): diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml new file mode 100644 index 000000000000..e3aa7b4a4f21 --- /dev/null +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml @@ -0,0 +1,26 @@ + + + + + interserver_secret_for_test + + + 127.0.0.1 + 9000 + + + + + + + + + 127.0.0.1 + 9000 + + + + + diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/configs/users.d/profiles.xml b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/users.d/profiles.xml new file mode 100644 index 000000000000..3feeedf7c9e1 --- /dev/null +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/users.d/profiles.xml @@ -0,0 +1,10 @@ + + + + + 0 + + + diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/test.py b/tests/integration/test_interserver_marker_requires_cluster_secret/test.py new file mode 100644 index 000000000000..e19b9a9be2a0 --- /dev/null +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/test.py @@ -0,0 +1,213 @@ +"""Regression tests for forged `SECONDARY_QUERY` impersonation over cluster secrets.""" + +import socket + +import pytest + +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) +node = cluster.add_instance( + "node", + main_configs=[ + "configs/config.d/clusters.xml", + ], + user_configs=[ + "configs/users.d/profiles.xml", + ], +) + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def encode_varuint(n): + """Encode an integer as a VarUInt (7 bits per byte, MSB continuation).""" + buf = bytearray() + while n >= 0x80: + buf.append((n & 0x7F) | 0x80) + n >>= 7 + buf.append(n & 0x7F) + return bytes(buf) + + +def encode_string(s): + """Encode a string as VarUInt length prefix + UTF-8 bytes.""" + if isinstance(s, str): + s = s.encode("utf-8") + return encode_varuint(len(s)) + s + + +def send_forged_secondary_query(user, password, query, forged_initial_user): + """Send one query over a plain (non-interserver) connection, forging query_kind=SECONDARY_QUERY + and a client-chosen initial_user. Return the raw bytes the server sends back.""" + # A revision accepted by the server but below DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS + # (54470): new enough for the quota-key addendum field, old enough to avoid chunked framing and + # its negotiation, so the Hello, addendum, Query and Data packets are plain back-to-back bytes. + client_revision = 54462 + + # A regular (non-interserver) Hello: authenticates as a normal user with a password. + hello = b"".join( + [ + encode_varuint(0), # Client::Hello + encode_string(b"test"), # client_name + encode_varuint(24), # version_major + encode_varuint(1), # version_minor + encode_varuint(client_revision), + encode_string(b""), # default database + encode_string(user), + encode_string(password), + ] + ) + addendum = encode_string(b"") # quota key + + # A Query packet that claims to be a SECONDARY_QUERY on behalf of another initial_user. + client_info = b"".join( + [ + b"\x02", # query_kind = SECONDARY_QUERY + encode_string(forged_initial_user), # forged initial_user + encode_string(b""), # initial_query_id + encode_string(b"127.0.0.1:9000"), # initial_address + (0).to_bytes(8, "little"), # initial_query_start_time_microseconds + b"\x01", # interface = TCP + encode_string(b""), # os_user + encode_string(b""), # client_hostname + encode_string(b"test"), # client_name + encode_varuint(24), # version_major + encode_varuint(1), # version_minor + encode_varuint(client_revision), # client_tcp_protocol_version + encode_string(b""), # quota_key + encode_varuint(0), # distributed_depth + encode_varuint(0), # version_patch + b"\x00", # no OpenTelemetry trace context + encode_varuint(0), # collaborate_with_initiator + encode_varuint(0), # obsolete_count_participating_replicas + encode_varuint(0), # number_of_current_replica + ] + ) + query_packet = b"".join( + [ + encode_varuint(1), # Client::Query + encode_string(b""), # query_id + client_info, + encode_string(b""), # end of settings + encode_string(b"\x00" * 32), # interserver hash (ignored without the secret handshake) + encode_varuint(2), # stage = Complete + encode_varuint(0), # compression disabled + encode_string(query), + encode_string(b""), # end of parameters + ] + ) + + # An empty Data block signals end of input, so the server runs the query to completion. + data_block = b"".join( + [ + encode_varuint(2), # Client::Data + encode_string(b""), # temporary table name + encode_varuint(1), # BlockInfo field: is_overflows + b"\x00", # is_overflows = false + encode_varuint(2), # BlockInfo field: bucket_num + (-1).to_bytes(4, "little", signed=True), # bucket_num = -1 + encode_varuint(0), # end of BlockInfo + encode_varuint(0), # columns + encode_varuint(0), # rows + ] + ) + + packet = hello + addendum + query_packet + data_block + response = b"" + with socket.create_connection((node.ip_address, 9000), timeout=20) as connection: + connection.settimeout(5) + connection.sendall(packet) + # The server keeps the connection open after the result, so read until it goes idle. + try: + while True: + chunk = connection.recv(65536) + if not chunk: + break + response += chunk + except (socket.timeout, ConnectionResetError, BrokenPipeError): + pass + return response + + +def test_forged_secondary_query_cannot_impersonate_on_secret_cluster(started_cluster): + """A user forges a SECONDARY_QUERY and reads a Distributed table over a secret cluster. The attacker + never gets the admin-only data: a query impersonating 'admin' is not forwarded, and an empty + initial_user means the authenticated user (the shard would otherwise authenticate it as no user, + i.e. with full access).""" + try: + # A table only `admin` may read, exposed through a Distributed table over the secret cluster. + node.query( + "CREATE TABLE default.secret_data (secret String) ENGINE = MergeTree ORDER BY secret" + ) + node.query("INSERT INTO default.secret_data VALUES ('TOP_SECRET_ADMIN_ONLY')") + node.query( + "CREATE TABLE default.secret_dist AS default.secret_data " + "ENGINE = Distributed(secret_cluster, default, secret_data)" + ) + node.query("CREATE USER admin IDENTIFIED WITH no_password HOST ANY") + node.query("GRANT SELECT ON default.secret_data TO admin") + # The attacker may read only the Distributed table, never the secret table directly. + node.query("CREATE USER attacker IDENTIFIED WITH no_password HOST ANY") + node.query("GRANT SELECT ON default.secret_dist TO attacker") + + for forged_initial_user, expected_error in [ + # Another user's name is refused at the interserver-secret boundary. + (b"admin", b"Refusing to forward a query over the cluster secret"), + # An empty name means the authenticated user, which has no access on the shard. + (b"", b"attacker: Not enough privileges"), + ]: + response = send_forged_secondary_query( + user=b"attacker", + password=b"", + query="SELECT secret FROM default.secret_dist", + forged_initial_user=forged_initial_user, + ) + + # The attacker must not obtain the admin-only data. + assert b"TOP_SECRET_ADMIN_ONLY" not in response + assert expected_error in response + finally: + node.query("DROP TABLE IF EXISTS default.secret_dist SYNC") + node.query("DROP TABLE IF EXISTS default.secret_data SYNC") + node.query("DROP USER IF EXISTS attacker, admin") + + +def test_mixed_secret_and_insecure_cluster_rejected(started_cluster): + """A non-secret Distributed table whose shard re-forwards over a secret one leaves the shard with + initial_user != current_user, so the fix rejects it instead of laundering an unverified + initiator (the non-secret hop cannot vouch for it).""" + try: + node.query( + "CREATE TABLE default.mixed_data (secret String) ENGINE = MergeTree ORDER BY secret" + ) + node.query("INSERT INTO default.mixed_data VALUES ('TOP_SECRET_ADMIN_ONLY')") + # A non-secret Distributed table (outer) whose shard reads a secret Distributed table (inner). + node.query( + "CREATE TABLE default.mixed_inner_dist AS default.mixed_data " + "ENGINE = Distributed(secret_cluster, default, mixed_data)" + ) + node.query( + "CREATE TABLE default.mixed_outer_dist AS default.mixed_data " + "ENGINE = Distributed(insecure_cluster, default, mixed_inner_dist)" + ) + # A non-default user, so the shard sees initial_user (mixed_user) != current_user (default). + node.query("CREATE USER mixed_user IDENTIFIED WITH no_password HOST ANY") + node.query("GRANT SELECT ON default.* TO mixed_user") + + error = node.query_and_get_error( + "SELECT secret FROM default.mixed_outer_dist", user="mixed_user" + ) + assert "Refusing to forward a query over the cluster secret" in error + finally: + node.query("DROP TABLE IF EXISTS default.mixed_outer_dist SYNC") + node.query("DROP TABLE IF EXISTS default.mixed_inner_dist SYNC") + node.query("DROP TABLE IF EXISTS default.mixed_data SYNC") + node.query("DROP USER IF EXISTS mixed_user") diff --git a/tests/integration/test_keeper_persistent_watches/test.py b/tests/integration/test_keeper_persistent_watches/test.py index 51eacd351e82..d11c077eaaf2 100644 --- a/tests/integration/test_keeper_persistent_watches/test.py +++ b/tests/integration/test_keeper_persistent_watches/test.py @@ -6,6 +6,7 @@ import os import threading import re +import struct import helpers.keeper_utils as keeper_utils from helpers.cluster import ClickHouseCluster @@ -343,3 +344,57 @@ def cb(_): destroy_zk_client(client) data = keeper_utils.send_4lw_cmd(cluster, node1, cmd="mntr") assert "zk_watch_count\t0" in data + +CHECK_WATCH, REMOVE_WATCH, ADD_WATCH = 17, 18, 106 +ZOK, ZBADARGUMENTS, ZNOWATCHER = 0, -8, -121 +# (opnum, type or mode, expected error): types are 1..5 and modes 0..1, so the last request of each op is valid. +UNKNOWN_TYPE_REQUESTS = [ + (CHECK_WATCH, 0, ZBADARGUMENTS), + (CHECK_WATCH, 6, ZBADARGUMENTS), + (CHECK_WATCH, 1, ZNOWATCHER), + (REMOVE_WATCH, 0, ZBADARGUMENTS), + (REMOVE_WATCH, 6, ZBADARGUMENTS), + (REMOVE_WATCH, 1, ZNOWATCHER), + (ADD_WATCH, -1, ZBADARGUMENTS), + (ADD_WATCH, 2, ZBADARGUMENTS), + (ADD_WATCH, 0, ZOK), +] + +def recv_exactly(sock, size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise EOFError("Keeper closed the connection") + data += chunk + return data + +def send_unknown_type_requests(): + with get_keeper_socket(node1.name) as sock: + handshake = struct.pack(">iqiqi16s", 0, 0, 30000, 0, 16, b"\0" * 16) + sock.sendall(struct.pack(">i", len(handshake)) + handshake) + reply = recv_exactly(sock, struct.unpack(">i", recv_exactly(sock, 4))[0]) + assert struct.unpack(">q", reply[8:16])[0] != 0 + path = b"/testUnknownWatchType" + for xid, (opnum, value, expected) in enumerate(UNKNOWN_TYPE_REQUESTS, start=1): + body = struct.pack(">iii", xid, opnum, len(path)) + path + struct.pack(">i", value) + sock.sendall(struct.pack(">i", len(body)) + body) + reply = recv_exactly(sock, struct.unpack(">i", recv_exactly(sock, 4))[0]) + reply_xid, _, error = struct.unpack(">iqi", reply[:16]) + assert (reply_xid, error) == (xid, expected), (opnum, value) + +def test_watch_requests_with_unknown_type(started_cluster): + # Through Raft (`quorum_reads`), then a restart that replays the logged requests, then through the local read path. + config = "/etc/clickhouse-server/config.d/keeper_config1.xml" + try: + node1.replace_in_config(config, "", "1") + node1.restart_clickhouse() + keeper_utils.wait_until_connected(cluster, node1) + assert "quorum_reads=true" in keeper_utils.send_4lw_cmd(cluster, node1, cmd="conf") + send_unknown_type_requests() + finally: + node1.replace_in_config(config, "1", "") + node1.restart_clickhouse(kill=True) + keeper_utils.wait_until_connected(cluster, node1) + assert "quorum_reads=false" in keeper_utils.send_4lw_cmd(cluster, node1, cmd="conf") + send_unknown_type_requests() diff --git a/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml b/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml new file mode 100644 index 000000000000..f2632aa4fb13 --- /dev/null +++ b/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml @@ -0,0 +1,16 @@ + + + + + /handler_with_user + GET,POST + + predefined_query_handler + SELECT currentUser() + http_handler_user + + + + + diff --git a/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml b/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml new file mode 100644 index 000000000000..23888f3dcef6 --- /dev/null +++ b/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/tests/integration/test_ldap_external_user_directory/test.py b/tests/integration/test_ldap_external_user_directory/test.py index 9ffdaf00f25b..9f153e673c10 100644 --- a/tests/integration/test_ldap_external_user_directory/test.py +++ b/tests/integration/test_ldap_external_user_directory/test.py @@ -1,4 +1,5 @@ import logging +import uuid import pytest @@ -12,7 +13,12 @@ instance1 = cluster.add_instance( "instance1", - main_configs=["configs/ldap_with_role_mapping.xml", "configs/remote_servers.xml"], + main_configs=[ + "configs/ldap_with_role_mapping.xml", + "configs/memory_user_directory.xml", + "configs/http_handler_with_user.xml", + "configs/remote_servers.xml", + ], user_configs=["configs/users.xml"], macros={"shard": 1, "replica": "instance1"}, stay_alive=True, @@ -229,3 +235,154 @@ def test_remote_query_user_does_not_exist_locally(ldap_cluster): instance2.query("DROP USER IF EXISTS non_local", user="common_user", password="qwerty") instance2.query("DROP TABLE IF EXISTS test_table SYNC", user="common_user", password="qwerty") + + +def add_ldap_user(ldap_cluster, user_cn, password): + code, (stdout, stderr) = ldap_cluster.ldap_container.exec_run( + [ + "sh", + "-c", + """echo "dn: cn={user_cn},ou=users,dc=example,dc=org +objectClass: inetOrgPerson +cn: {user_cn} +sn: {user_cn} +userPassword: {password}" | \ +ldapadd -H ldap://{host}:{port} -D "{admin_bind_dn}" -x -w {admin_password} + """.format( + host=ldap_cluster.ldap_host, + port=ldap_cluster.ldap_port, + admin_bind_dn=LDAP_ADMIN_BIND_DN, + admin_password=LDAP_ADMIN_PASSWORD, + user_cn=user_cn, + password=password, + ), + ], + demux=True, + ) + logging.debug( + f"test_ldap_external_user_directory code:{code} stdout:{stdout}, stderr:{stderr}" + ) + assert code == 0 + + +def delete_ldap_user(ldap_cluster, user_cn): + code, (stdout, stderr) = ldap_cluster.ldap_container.exec_run( + [ + "sh", + "-c", + """ldapdelete 'cn={user_cn},ou=users,dc=example,dc=org' \ +-H ldap://{host}:{port} -D "{admin_bind_dn}" -x -w {admin_password} + """.format( + host=ldap_cluster.ldap_host, + port=ldap_cluster.ldap_port, + admin_bind_dn=LDAP_ADMIN_BIND_DN, + admin_password=LDAP_ADMIN_PASSWORD, + user_cn=user_cn, + ), + ], + demux=True, + ) + logging.debug( + f"test_ldap_external_user_directory code:{code} stdout:{stdout}, stderr:{stderr}" + ) + assert code == 0 + + +def user_storages(name): + return instance1.query( + f"SELECT storage FROM system.users WHERE name = '{name}' ORDER BY storage", + user="common_user", + password="qwerty", + ).split() + + +def test_same_name_user_in_other_directory(ldap_cluster): + """ + A user authenticated by LDAP must not share its name with a user from another user directory. + The `memory` directory follows the LDAP one, so a login by LDAP credentials would reach LDAP first + if the user were not looked up in all directories before. + """ + # A unique name, so that the LDAP user is not yet known to the server even if the test is retried. + name = f"same_name_{uuid.uuid4().hex[:8]}" + add_ldap_user(ldap_cluster, name, "ldap_password") + + try: + instance1.query( + f"CREATE USER {name} IDENTIFIED WITH plaintext_password BY 'local_password' IN memory", + user="common_user", + password="qwerty", + ) + + # The LDAP user is not known yet, so there is no conflict. + assert instance1.query( + "SELECT currentUser()", user=name, password="local_password" + ) == TSV([[name]]) + assert user_storages(name) == ["memory"] + + # The LDAP directory would recognize the user, but the name is already used in the `memory` directory, + # so only that directory authenticates the user, and LDAP does not introduce a second user with this name. + assert f"{name}: Authentication failed" in instance1.query_and_get_error( + "SELECT currentUser()", user=name, password="ldap_password" + ) + assert user_storages(name) == ["memory"] + + # The local user can still log in. + assert instance1.query( + "SELECT currentUser()", user=name, password="local_password" + ) == TSV([[name]]) + + instance1.query( + f"DROP USER {name} FROM memory", + user="common_user", + password="qwerty", + ) + + # Now the LDAP user can log in. + assert instance1.query( + "SELECT currentUser()", user=name, password="ldap_password" + ) == TSV([[name]]) + assert user_storages(name) == ["ldap"] + + # A new user with the same name cannot be created in another directory, whether it is specified or not. + for query in [ + f"CREATE USER {name}", + f"CREATE USER {name} IN memory", + f"CREATE USER OR REPLACE {name} IN memory", + ]: + assert "ACCESS_ENTITY_ALREADY_EXISTS" in instance1.query_and_get_error( + query, user="common_user", password="qwerty" + ) + finally: + for storage in ["memory", "local_directory"]: + instance1.query( + f"DROP USER IF EXISTS {name} FROM {storage}", + user="common_user", + password="qwerty", + ) + delete_ldap_user(ldap_cluster, name) + + +def test_same_name_user_in_other_directory_always_allow_credentials(ldap_cluster): + """ + An HTTP handler with a configured user authenticates it with `AlwaysAllowCredentials`, which the LDAP directory + accepts without contacting the LDAP server. If the user exists in another directory, LDAP must not introduce + a second user with the same name. + """ + name = "http_handler_user" + try: + instance1.query( + f"CREATE USER {name} IN memory", + user="common_user", + password="qwerty", + ) + for _ in range(2): + response = instance1.http_request("handler_with_user") + assert response.status_code == 200, response.text + assert response.text.strip() == name + assert user_storages(name) == ["memory"] + finally: + instance1.query( + f"DROP USER IF EXISTS {name} FROM memory", + user="common_user", + password="qwerty", + ) diff --git a/tests/integration/test_mask_sensitive_info/test.py b/tests/integration/test_mask_sensitive_info/test.py index 7f17c145e335..4410fc7ba573 100644 --- a/tests/integration/test_mask_sensitive_info/test.py +++ b/tests/integration/test_mask_sensitive_info/test.py @@ -885,7 +885,7 @@ def test_create_dictionary(): f"LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())" ) - for toggle, secret in enumerate(["[HIDDEN]", password]): + for toggle, (secret, url) in enumerate([("[HIDDEN]", "[HIDDEN]"), (password, "http://localhost:8123/dict.tsv")]): assert ( node.query(f"SHOW CREATE TABLE dict1 {show_secrets}={toggle}") == f"CREATE DICTIONARY default.dict1\\n(\\n `n` int DEFAULT 0,\\n `m` int DEFAULT 1\\n)\\nPRIMARY KEY n\\nSOURCE(CLICKHOUSE(HOST \\'localhost\\' PORT 9000 USER \\'user1\\' TABLE \\'test\\' PASSWORD \\'{secret}\\' DB \\'default\\'))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" @@ -893,12 +893,12 @@ def test_create_dictionary(): assert ( node.query(f"SHOW CREATE TABLE dict2 {show_secrets}={toggle}") - == f"CREATE DICTIONARY default.dict2\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\'))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" + == f"CREATE DICTIONARY default.dict2\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\'))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" ) assert ( node.query(f"SHOW CREATE TABLE dict3 {show_secrets}={toggle}") - == f"CREATE DICTIONARY default.dict3\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\')))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" + == f"CREATE DICTIONARY default.dict3\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\')))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" ) assert ( @@ -907,8 +907,8 @@ def test_create_dictionary(): ) == ( f"CREATE DICTIONARY default.dict1 (`n` int DEFAULT 0, `m` int DEFAULT 1) PRIMARY KEY n SOURCE(CLICKHOUSE(HOST \\'localhost\\' PORT 9000 USER \\'user1\\' TABLE \\'test\\' PASSWORD \\'{secret}\\' DB \\'default\\')) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" - f"CREATE DICTIONARY default.dict2 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\')) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" - f"CREATE DICTIONARY default.dict3 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\'))) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" + f"CREATE DICTIONARY default.dict2 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\')) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" + f"CREATE DICTIONARY default.dict3 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\'))) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" ) ) @@ -919,11 +919,11 @@ def test_create_dictionary(): "LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())", "CREATE DICTIONARY dict2 (`n` int DEFAULT 0) PRIMARY KEY n " - "SOURCE(HTTP(URL 'http://localhost:8123/dict.tsv' FORMAT 'TabSeparated' USER 'huser' PASSWORD '[HIDDEN]')) " + "SOURCE(HTTP(URL '[HIDDEN]' FORMAT 'TabSeparated' USER 'huser' PASSWORD '[HIDDEN]')) " "LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())", "CREATE DICTIONARY dict3 (`n` int DEFAULT 0) PRIMARY KEY n " - "SOURCE(HTTP(URL 'http://localhost:8123/dict.tsv' FORMAT 'TabSeparated' CREDENTIALS (USER 'huser' PASSWORD '[HIDDEN]'))) " + "SOURCE(HTTP(URL '[HIDDEN]' FORMAT 'TabSeparated' CREDENTIALS (USER 'huser' PASSWORD '[HIDDEN]'))) " "LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())", ], must_not_contain=[password], diff --git a/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml b/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml index 7196958c2186..631687cd269e 100644 --- a/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml +++ b/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml @@ -168,8 +168,4 @@ 131072 11 - - 0 - 60 - 1 diff --git a/tests/integration/test_readonly_restricts_set_role/test.py b/tests/integration/test_readonly_restricts_set_role/test.py index c36af86fa720..a640267ad01f 100644 --- a/tests/integration/test_readonly_restricts_set_role/test.py +++ b/tests/integration/test_readonly_restricts_set_role/test.py @@ -25,6 +25,11 @@ def started_cluster(): "CREATE USER probe IDENTIFIED WITH plaintext_password BY 'x';" "GRANT ro_role, other_role TO probe;" "ALTER USER probe DEFAULT ROLE ro_role;" + # A separate user for `SET DEFAULT ROLE`, so that the cases changing its default roles + # do not affect the ones above, which expect `probe` to start with `ro_role`. + "CREATE USER default_role_probe IDENTIFIED WITH plaintext_password BY 'x';" + "GRANT ro_role, other_role TO default_role_probe;" + "ALTER USER default_role_probe DEFAULT ROLE ro_role;" ) yield cluster @@ -114,3 +119,44 @@ def post(sql, **extra): answer, error = post("SELECT currentRoles()") assert error is None assert answer.strip() == "['ro_role']" + + +def default_roles(node): + return node.query( + "SELECT default_roles_list FROM system.users WHERE name = 'default_role_probe'" + ).strip() + + +@pytest.mark.parametrize( + "readonly, statement", + [ + # `TO CURRENT_USER` requires no grant, so it is not refused by the access check. + (1, "SET DEFAULT ROLE other_role TO CURRENT_USER"), + (1, "SET DEFAULT ROLE ALL TO CURRENT_USER"), + (1, "SET DEFAULT ROLE ALL EXCEPT ro_role TO CURRENT_USER"), + (1, "SET DEFAULT ROLE NONE TO CURRENT_USER"), + (2, "SET DEFAULT ROLE other_role TO CURRENT_USER"), + ], +) +def test_set_default_role_refused_when_enabled(readonly, statement): + _, error = node_on.query_and_get_answer_with_error( + statement, user="default_role_probe", password="x", settings={"readonly": readonly} + ) + assert "READONLY" in error + assert default_roles(node_on) == "['ro_role']" + # The next session starts with the same role. + answer = node_on.query( + "SELECT currentRoles()", user="default_role_probe", password="x" + ) + assert answer.strip() == "['ro_role']" + + +def test_set_default_role_allowed_at_default_settings(): + _, error = node_off.query_and_get_answer_with_error( + "SET DEFAULT ROLE other_role TO CURRENT_USER", + user="default_role_probe", + password="x", + settings={"readonly": 1}, + ) + assert error == "" + assert default_roles(node_off) == "['other_role']" diff --git a/tests/integration/test_replicated_database/test.py b/tests/integration/test_replicated_database/test.py index 783121399dc0..e94a85137f17 100644 --- a/tests/integration/test_replicated_database/test.py +++ b/tests/integration/test_replicated_database/test.py @@ -2044,3 +2044,32 @@ def test_alias_with_dropped_target(started_cluster): # Cleanup for node in [main_node, dummy_node]: node.query(f"DROP DATABASE IF EXISTS {db_name} SYNC") + + +def test_attach_mv_replays_on_replica_without_source(started_cluster): + # The initiator validates a full-definition ATTACH MATERIALIZED VIEW, a follower replays it as is. + main_node.query("CREATE DATABASE attach_mv_src") + main_node.query("CREATE TABLE attach_mv_src.src (n Int32) ENGINE = MergeTree ORDER BY n") + for i, node in enumerate([main_node, dummy_node]): + node.query( + f"CREATE DATABASE attach_mv_db ENGINE = Replicated('/test/attach_mv_db', 'shard1', 'replica{i + 1}')" + ) + main_node.query( + "CREATE TABLE attach_mv_db.dst (n Int32) ENGINE = ReplicatedMergeTree ORDER BY n" + ) + main_node.query( + "ATTACH MATERIALIZED VIEW attach_mv_db.mv UUID '5a2b6c61-7e43-4d6f-9b4b-1ad7b9b33d71' " + "TO attach_mv_db.dst (n Int32) AS SELECT n FROM attach_mv_src.src", + settings={"database_replicated_allow_explicit_uuid": 1}, + ) + dummy_node.query("SYSTEM SYNC DATABASE REPLICA attach_mv_db", timeout=60) + assert ( + dummy_node.query( + "SELECT count() FROM system.tables WHERE database = 'attach_mv_db' AND name = 'mv'" + ) + == "1\n" + ) + + for node in [main_node, dummy_node]: + node.query("DROP DATABASE attach_mv_db SYNC") + main_node.query("DROP DATABASE attach_mv_src SYNC") diff --git a/tests/integration/test_scheduler/test.py b/tests/integration/test_scheduler/test.py index 26cba12cc368..777671a8274d 100644 --- a/tests/integration/test_scheduler/test.py +++ b/tests/integration/test_scheduler/test.py @@ -11,6 +11,7 @@ from helpers.client import QueryRuntimeException from helpers.cluster import ClickHouseCluster from helpers.network import PartitionManager +from helpers.test_tools import assert_eq_with_retry cluster = ClickHouseCluster(__file__) @@ -1097,6 +1098,38 @@ def check_consistency(): check_consistency() +def test_drop_does_not_remove_entity_of_other_kind(): + node.query( + """ + create resource io_read (read disk s3_no_resource); + create workload all; + create workload development in all; + create user drop_workload_user not identified; + grant drop workload on *.* to drop_workload_user; + create user drop_resource_user not identified; + grant drop resource on *.* to drop_resource_user; + """ + ) + try: + assert "doesn't exist" in node.query_and_get_error("drop workload io_read", user="drop_workload_user") + node.query("drop workload if exists io_read", user="drop_workload_user") + assert "doesn't exist" in node.query_and_get_error("drop resource development", user="drop_resource_user") + node.query("drop resource if exists development", user="drop_resource_user") + + definitions = node.query( + "select value from system.zookeeper where path = '/clickhouse/workload' and name = 'definitions.sql'" + ) + assert "CREATE RESOURCE io_read" in definitions + assert "CREATE WORKLOAD development" in definitions + assert node.query("select count() from system.resources where name = 'io_read'") == "1\n" + assert node.query("select count() from system.workloads where name in ('all', 'development')") == "2\n" + + node.query("drop workload development", user="drop_workload_user") + node.query("drop resource io_read", user="drop_resource_user") + finally: + node.query("drop user if exists drop_workload_user; drop user if exists drop_resource_user") + + def test_throw_on_unknown_workload(): node.query( f""" @@ -1236,3 +1269,49 @@ def test_config_based_workloads_and_resources(): # Make sure it's possible to clean the config without "Logical error: 'Removing workload 'all' with children" node.query("DROP WORKLOAD development") + + +def test_workload_entity_keeper_storage_session_renewal(): + # A query that renews the expired Keeper session of `node` must not overwrite what `node2` wrote meanwhile + definitions = "select value from system.zookeeper where path = '/clickhouse/workload' and name = 'definitions.sql'" + + def expire_keeper_session_of_node(sync_workload): + # The watching thread of `node` refreshes on this change and then sleeps for up to 10 seconds + node2.query(f"create workload {sync_workload} in all") + assert_eq_with_retry( + node, + f"select count() from system.workloads where name = '{sync_workload}'", + "1", + retry_count=100, + sleep_time=0.1, + ) + # The watch dies with the session, so `node` does not see the next change of `node2` + node.query("system reconnect zookeeper") + + node.query("create workload all; create workload development in all") + try: + assert_eq_with_retry( + node2, + "select count() from system.workloads where name = 'development'", + "1", + retry_count=100, + sleep_time=0.1, + ) + + expire_keeper_session_of_node("admin") + node2.query("create workload production in development") + assert "cannot be dropped" in node.query_and_get_error( + "drop workload development" + ) + assert "production" in node2.query(definitions) + + expire_keeper_session_of_node("prod_merges") + node2.query("create workload dev_merges in all") + node.query("create workload prod_mutations in all") + result = node2.query(definitions) + assert "dev_merges" in result and "prod_mutations" in result + finally: + node.query( + "drop workload if exists prod_mutations; drop workload if exists dev_merges; drop workload if exists prod_merges; " + "drop workload if exists production; drop workload if exists admin; drop workload if exists development; drop workload if exists all" + ) diff --git a/tests/integration/test_storage_delta/test.py b/tests/integration/test_storage_delta/test.py index 3521ddabe30b..cfbeb18f4042 100644 --- a/tests/integration/test_storage_delta/test.py +++ b/tests/integration/test_storage_delta/test.py @@ -1640,6 +1640,134 @@ def check_pruned(count, query_id): check_pruned(num_files - 1, query_id) +def test_partition_by_nullable_bool(started_cluster): + # Nullable(Bool) partition column with true / false / NULL in separate files, exercising + # both the Bool literal visitor and the null visitor; all must yield Nullable(Bool). + node = started_cluster.instances["node1"] + table_name = randomize_table_name("test_partition_by_nullable_bool") + + schema = pa.schema( + [ + ("id", pa.int32()), + ("flag", pa.bool_()), + ] + ) + data = [ + pa.array([1, 2, 3], type=pa.int32()), + pa.array([True, False, None], type=pa.bool_()), + ] + + storage_options = { + "AWS_ENDPOINT_URL": f"http://{started_cluster.minio_ip}:{started_cluster.minio_port}", + "AWS_ACCESS_KEY_ID": minio_access_key, + "AWS_SECRET_ACCESS_KEY": minio_secret_key, + "AWS_ALLOW_HTTP": "true", + "AWS_S3_ALLOW_UNSAFE_RENAME": "true", + } + path = f"s3://root/{table_name}" + table = pa.Table.from_arrays(data, schema=schema) + + write_deltalake_with_retry( + path, table, storage_options=storage_options, partition_by=["flag"] + ) + + delta_function = f""" + deltaLake( + 'http://{started_cluster.minio_ip}:{started_cluster.minio_port}/root/{table_name}', + '{minio_access_key}', + '{minio_secret_key}') + """ + + # The partition column must be advertised as Nullable(Bool), not Nullable(UInt8). + assert ( + "id\tNullable(Int32)\t\t\t\t\t\n" + "flag\tNullable(Bool)" + == node.query( + f"DESCRIBE TABLE {delta_function}", + settings={"allow_experimental_delta_kernel_rs": 1}, + ).strip() + ) + + # true / false / NULL are materialized correctly across the separate data files. + assert ( + "1\ttrue\n2\tfalse\n3\t\\N" + == node.query( + f"SELECT id, flag FROM {delta_function} ORDER BY id", + settings={ + "allow_experimental_delta_kernel_rs": 1, + "use_hive_partitioning": 0, + }, + ).strip() + ) + + +def test_partition_by_binary(started_cluster): + # Delta `binary` partition column with two non-NULL values and a NULL in separate files, + # exercising both the binary literal visitor and the null visitor. `binary` is advertised as + # Nullable(String), so every per-file transform must yield Nullable(String); a stray FixedString + # on the non-NULL files would fail to unify with the schema's Nullable(String). + node = started_cluster.instances["node1"] + table_name = randomize_table_name("test_partition_by_binary") + + schema = pa.schema( + [ + ("id", pa.int32()), + ("data", pa.binary()), + ] + ) + data = [ + pa.array([1, 2, 3], type=pa.int32()), + pa.array([b"aa", b"bb", None], type=pa.binary()), + ] + + storage_options = { + "AWS_ENDPOINT_URL": f"http://{started_cluster.minio_ip}:{started_cluster.minio_port}", + "AWS_ACCESS_KEY_ID": minio_access_key, + "AWS_SECRET_ACCESS_KEY": minio_secret_key, + "AWS_ALLOW_HTTP": "true", + "AWS_S3_ALLOW_UNSAFE_RENAME": "true", + } + path = f"s3://root/{table_name}" + table = pa.Table.from_arrays(data, schema=schema) + + write_deltalake_with_retry( + path, table, storage_options=storage_options, partition_by=["data"] + ) + + delta_function = f""" + deltaLake( + 'http://{started_cluster.minio_ip}:{started_cluster.minio_port}/root/{table_name}', + '{minio_access_key}', + '{minio_secret_key}') + """ + + # The partition column must be advertised as Nullable(String), not Nullable(FixedString(N)). + assert ( + "id\tNullable(Int32)\t\t\t\t\t\n" + "data\tNullable(String)" + == node.query( + f"DESCRIBE TABLE {delta_function}", + settings={"allow_experimental_delta_kernel_rs": 1}, + ).strip() + ) + + # The non-NULL and NULL partition files must unify: the transform type is Nullable(String) for + # every file. We assert the runtime type and null-ness rather than the exact bytes, since delta-rs + # escapes binary partition values in the log. + assert ( + "1\tNullable(String)\t0\n" + "2\tNullable(String)\t0\n" + "3\tNullable(String)\t1" + == node.query( + f"SELECT id, toTypeName(data), isNull(data) FROM {delta_function} ORDER BY id", + settings={ + "allow_experimental_delta_kernel_rs": 1, + "use_hive_partitioning": 0, + }, + ).strip() + ) + + @pytest.mark.parametrize( "column_mapping", ["", "name"] ) # "id" is not supported by delta-kernel at the moment @@ -3589,6 +3717,62 @@ def test_column_mapping_id(started_cluster): ) +@pytest.mark.parametrize("column_mapping", ["name", "id"]) +def test_column_mapping_write_rejected(started_cluster, column_mapping): + # Writing to a column-mapped table must be rejected: ClickHouse writes logical + # Parquet field names, not the physical names/ids that a Delta reader expects, + # so committing an AddFile would produce an unreadable data file. + node = started_cluster.instances["node1"] + table_name = randomize_table_name(f"test_column_mapping_write_{column_mapping}") + spark = started_cluster.spark_session + minio_client = started_cluster.minio_client + bucket = started_cluster.minio_bucket + path = f"/{table_name}" + + schema = StructType( + [ + StructField("id", IntegerType(), True), + StructField("name", StringType(), True), + ] + ) + data = [(1, "Alice"), (2, "Bob")] + df = spark.createDataFrame(data, schema=schema) + df.write.format("delta").option("delta.minReaderVersion", "2").option( + "delta.minWriterVersion", "5" + ).option("delta.columnMapping.mode", column_mapping).save(path) + upload_directory(minio_client, bucket, path, "") + + def list_objects(): + return sorted( + obj.object_name + for obj in minio_client.list_objects(bucket, table_name, recursive=True) + ) + + objects_before = list_objects() + + delta_function = f""" +deltaLake( + 'http://{started_cluster.minio_ip}:{started_cluster.minio_port}/root/{table_name}', + '{minio_access_key}', + '{minio_secret_key}') + """ + + error = node.query_and_get_error( + f"INSERT INTO TABLE FUNCTION {delta_function} SELECT 3 AS id, 'Carol' AS name" + ) + assert "NOT_IMPLEMENTED" in error + assert "column mapping" in error + + # Nothing was committed: no new parquet data file and no new _delta_log entry. + assert objects_before == list_objects() + + # The table is still readable and its data is unchanged. + assert ( + "1\tAlice\n2\tBob" + == node.query(f"SELECT * FROM {delta_function} ORDER BY all").strip() + ) + + @pytest.mark.parametrize("column_mapping", ["", "name"]) def test_subcolumns(started_cluster, column_mapping): node = started_cluster.instances["node1"] diff --git a/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml b/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml new file mode 100644 index 000000000000..7f6c26058269 --- /dev/null +++ b/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml @@ -0,0 +1,25 @@ + + + + + kerberized_kafka1:19092 + kafka_json_as_string_named_collection + 1 + kafka_json_as_string_named_collection + JSONAsString + 1000 + + SASL_PLAINTEXT + GSSAPI + kafka + /tmp/keytab/clickhouse.keytab + anotherkafkauser/instance@TEST.CLICKHOUSE.TECH + security + false + + + + diff --git a/tests/integration/test_storage_kerberized_kafka/test.py b/tests/integration/test_storage_kerberized_kafka/test.py index 0fb5f39dbdaf..702909aafdb8 100644 --- a/tests/integration/test_storage_kerberized_kafka/test.py +++ b/tests/integration/test_storage_kerberized_kafka/test.py @@ -26,7 +26,7 @@ cluster = ClickHouseCluster(__file__) instance = cluster.add_instance( "instance", - main_configs=["configs/kafka.xml"], + main_configs=["configs/kafka.xml", "configs/named_collections.xml"], user_configs=["configs/users.xml"], with_kerberized_kafka=True, clickhouse_path_dir="clickhouse_path", @@ -246,7 +246,9 @@ def test_kafka_json_as_string_no_kdc(kafka_cluster): assert instance.contains_in_log("KerberosInit failure:") -def test_kafka_config_from_sql_named_collection(kafka_cluster): +def test_kafka_config_from_named_collection(kafka_cluster): + # The named collection `kafka_config` is in `configs/named_collections.xml`: a named collection created with SQL + # cannot set `kafka.sasl_kerberos_keytab`, because it is a path on the server. kafka_produce( kafka_cluster, "kafka_json_as_string_named_collection", @@ -258,26 +260,6 @@ def test_kafka_config_from_sql_named_collection(kafka_cluster): ], ) - instance.query( - """ - DROP NAMED COLLECTION IF EXISTS kafka_config; - CREATE NAMED COLLECTION kafka_config AS - kafka.security_protocol = 'SASL_PLAINTEXT', - kafka.sasl_mechanism = 'GSSAPI', - kafka.sasl_kerberos_service_name = 'kafka', - kafka.sasl_kerberos_keytab = '/tmp/keytab/clickhouse.keytab', - kafka.sasl_kerberos_principal = 'anotherkafkauser/instance@TEST.CLICKHOUSE.TECH', - kafka.debug = 'security', - kafka.api_version_request = 'false', - - kafka_broker_list = 'kerberized_kafka1:19092', - kafka_topic_list = 'kafka_json_as_string_named_collection', - kafka_commit_on_select = 1, - kafka_group_name = 'kafka_json_as_string_named_collection', - kafka_format = 'JSONAsString', - kafka_flush_interval_ms=1000; - """ - ) instance.query( """ CREATE TABLE test.kafka (field String) diff --git a/tests/integration/test_storage_postgresql/test.py b/tests/integration/test_storage_postgresql/test.py index b60c3bded396..f17170279670 100644 --- a/tests/integration/test_storage_postgresql/test.py +++ b/tests/integration/test_storage_postgresql/test.py @@ -518,6 +518,30 @@ def test_postgres_ndim(started_cluster): cursor.execute("DROP SCHEMA ndim_schema CASCADE") +def test_postgres_ndim_out_of_range(started_cluster): + cursor = started_cluster.postgres_conn.cursor() + + cursor.execute("DROP TABLE IF EXISTS arr_bad_ndim") + cursor.execute("CREATE TABLE arr_bad_ndim (a integer[])") + cursor.execute("INSERT INTO arr_bad_ndim SELECT '{{1}, {2}}'") + + def query_type(): + return node1.query_and_get_error( + f"""SELECT toTypeName(a) FROM postgresql('postgres1:5432', 'postgres', 'arr_bad_ndim', 'postgres', '{pg_pass}')""" + ) + + # PostgreSQL never reports more than 6 dimensions by itself, so emulate a misbehaving server + # by editing the catalog directly (the connection is a superuser). + cursor.execute( + "UPDATE pg_attribute SET attndims = 30000 WHERE attrelid = 'arr_bad_ndim'::regclass AND attname = 'a'" + ) + error = query_type() + assert "INCORRECT_DATA" in error, error + assert "unsupported number of dimensions" in error, error + + cursor.execute("DROP TABLE arr_bad_ndim") + + def test_postgres_on_conflict(started_cluster): cursor = started_cluster.postgres_conn.cursor() table = "test_conflict" diff --git a/tests/integration/test_storage_s3_queue/test_0.py b/tests/integration/test_storage_s3_queue/test_0.py index 7216375fe5a8..7662c1a38204 100644 --- a/tests/integration/test_storage_s3_queue/test_0.py +++ b/tests/integration/test_storage_s3_queue/test_0.py @@ -91,6 +91,16 @@ def started_cluster(): stay_alive=True, ) + cluster.add_instance( + "instance_old", + with_zookeeper=True, + image="clickhouse/clickhouse-server", + # A release older than this one that is no longer supported, so it never gets the source hash in a backport. + tag="25.10", + with_installed_binary=True, + stay_alive=True, + ) + logging.info("Starting cluster...") cluster.start() logging.info("Cluster started") @@ -960,6 +970,43 @@ def test_multiple_tables_meta_mismatch(started_cluster): ) +def test_source_hash_after_upgrade(started_cluster): + """A queue that an older version created gets the hash of its source in Keeper after the upgrade.""" + node = started_cluster.instances["instance_old"] + keeper_path = f"/clickhouse/test_upgrade_{generate_random_string()}" + + def create_queue(name, bucket): + return f""" + CREATE TABLE {name} (x String) + ENGINE = S3Queue('http://localhost:11111/{bucket}/upgrade/*', NOSIGN, 'CSV') + SETTINGS mode = 'unordered', keeper_path = '{keeper_path}' + """ + + def get_source_hash(): + return node.query( + f"SELECT JSONExtractString(value, 'source_hash') FROM system.zookeeper " + f"WHERE path = '{keeper_path}' AND name = 'metadata'" + ).strip() + + try: + node.query(create_queue("queue", "test")) + assert get_source_hash() == "" + + node.restart_with_latest_version() + # Tables are loaded in the background, and a query to a table waits until it is loaded. + node.query("DESCRIBE TABLE queue") + assert get_source_hash() != "" + + # Now the source is checked: a queue of another bucket cannot use this `keeper_path`. + error = node.query_and_get_error(create_queue("other", "other")) + assert "differs in source" in error + node.query(create_queue("same", "test")) + finally: + node.query("DROP TABLE IF EXISTS queue SYNC") + node.query("DROP TABLE IF EXISTS same SYNC") + node.restart_with_original_version() + + def test_virtual_columns(started_cluster): start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") node = started_cluster.instances["instance"] diff --git a/tests/integration/test_storage_url/configs/conf.xml b/tests/integration/test_storage_url/configs/conf.xml index 8fa71e356822..a342efc6bdc0 100644 --- a/tests/integration/test_storage_url/configs/conf.xml +++ b/tests/integration/test_storage_url/configs/conf.xml @@ -2,6 +2,9 @@ 1 + +
X-Forbidden-Placeholder
+
@@ -34,6 +37,14 @@ + + + + node2 + 9000 + + + diff --git a/tests/integration/test_storage_url/test.py b/tests/integration/test_storage_url/test.py index fa68686b1f67..c346f8482f26 100644 --- a/tests/integration/test_storage_url/test.py +++ b/tests/integration/test_storage_url/test.py @@ -4,7 +4,7 @@ import os from helpers.cluster import ClickHouseCluster -from helpers.test_tools import TSV +from helpers.test_tools import TSV, assert_eq_with_retry from helpers.mock_servers import start_mock_servers cluster = ClickHouseCluster(__file__) @@ -14,6 +14,8 @@ user_configs=["configs/users.xml"], with_nginx=True, ) +# The worker of `test_cluster_node2`; `forbidden_authorization` changes only node1's configuration. +node2 = cluster.add_instance("node2", main_configs=["configs/conf.xml"]) @pytest.fixture(scope="module", autouse=True) def setup_node(): @@ -158,3 +160,185 @@ def test_file_formats(file_format): expected_result += f"{i}\t{i + 1}\t{i + 2}\n" assert result == expected_result + + +CONF_PATH = "/etc/clickhouse-server/config.d/conf.xml" +FORBIDDEN_HEADER = "
X-Forbidden-Placeholder
" + + +class forbidden_authorization: + """Forbids the `Authorization` header in `http_forbid_headers` for the duration of the block.""" + + def __enter__(self): + node1.replace_in_config( + CONF_PATH, FORBIDDEN_HEADER, FORBIDDEN_HEADER + "
Authorization
" + ) + node1.query("SYSTEM RELOAD CONFIG") + + def __exit__(self, *args): + node1.replace_in_config(CONF_PATH, "
Authorization
", "") + node1.query("SYSTEM RELOAD CONFIG") + + +def server_part_of_error(error): + # The client appends "(query: ...)" with the query text as sent, credentials included. + return error.split("(query: ")[0] + + +def assert_authorization_forbidden(error, secret="user:pass"): + assert 'HTTP header "Authorization" is forbidden' in error, error + assert secret not in server_part_of_error(error), error + + +@pytest.mark.parametrize( + "query", + [ + pytest.param( + "SELECT sum(column1) FROM url('http://user:pass@nginx:80/test_1', 'TSV', " + "'column1 UInt32, column2 UInt32, column3 UInt32')", + id="userinfo", + ), + # The first option is unreachable, so the read moves on to the second one. + pytest.param( + "SELECT sum(column1) FROM url(" + "'http://127.0.0.1:1/test_1|http://user:pass@nginx:80/test_1', " + "'TSV', 'column1 UInt32, column2 UInt32, column3 UInt32') SETTINGS http_max_tries = 1", + id="failover", + ), + # The second option is usable, so the read must not move on to it. + pytest.param( + "SELECT sum(column1) FROM url(" + "'http://user:pass@nginx:80/test_1|http://nginx:80/test_1', " + "'TSV', 'column1 UInt32, column2 UInt32, column3 UInt32') SETTINGS http_max_tries = 1", + id="failover_first", + ), + pytest.param( + "SELECT sum(column1) FROM urlCluster('test_cluster_two_shards', " + "'http://user:pass@nginx:80/test_1', 'TSV', 'column1 UInt32, column2 UInt32, column3 UInt32')", + id="url_cluster", + ), + ], +) +def test_url_userinfo_with_forbidden_authorization(query): + # The userinfo is sent as Basic credentials in the `Authorization` header. + assert node1.query(query) == "3\n" + + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) + + +def test_url_cluster_userinfo_refused_by_initiator(): + # node1 refuses the URL before node2, which does not forbid the header, gets it. The userinfo is in the second + # failover option, so the URL as a whole has none. + query = ( + "SELECT sum(column1) FROM urlCluster('test_cluster_node2', " + "'http://127.0.0.1:1/test_1|http://user:pass@nginx:80/test_1', " + "'TSV', 'column1 UInt32, column2 UInt32, column3 UInt32') SETTINGS http_max_tries = 1" + ) + assert node1.query(query) == "3\n" + + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) + + +def test_url_userinfo_without_username_with_forbidden_authorization(): + # Credentials without a username are not sent, so they are not refused. + with forbidden_authorization(): + assert ( + node1.query( + "SELECT sum(column1) FROM url('http://:pass@nginx:80/test_1', 'TSV', " + "'column1 UInt32, column2 UInt32, column3 UInt32')" + ) + == "3\n" + ) + + +def test_stored_url_table_with_forbidden_authorization(): + # A stored table loads after the header is forbidden, but its reads do not send the userinfo. + table_name = "url_userinfo" + node1.query(f"DROP TABLE IF EXISTS {table_name}") + node1.query( + f"CREATE TABLE {table_name} (column1 UInt32, column2 UInt32, column3 UInt32) " + "ENGINE = URL('http://user:pass@nginx:80/test_1', 'TSV')" + ) + try: + assert node1.query(f"SELECT sum(column1) FROM {table_name}") == "3\n" + + with forbidden_authorization(): + node1.query(f"DETACH TABLE {table_name}") + node1.query(f"ATTACH TABLE {table_name}") + assert_authorization_forbidden(node1.query_and_get_error(f"SELECT sum(column1) FROM {table_name}")) + finally: + node1.query(f"DROP TABLE IF EXISTS {table_name}") + + +def test_http_dictionary_credentials_with_forbidden_authorization(): + def create_dictionary(name): + node1.query( + f"CREATE DICTIONARY {name} (column1 UInt64, column2 UInt32, column3 UInt32) PRIMARY KEY column1 " + "SOURCE(HTTP(url 'http://nginx:80/test_1' format 'TabSeparated' " + "credentials(user 'user' password 'dict_secret_pw'))) " + "LIFETIME(0) LAYOUT(FLAT())" + ) + + allowed, forbidden = "http_credentials_allowed", "http_credentials_forbidden" + try: + create_dictionary(allowed) + assert node1.query(f"SELECT dictGet('{allowed}', 'column2', toUInt64(3))") == "2\n" + + with forbidden_authorization(): + create_dictionary(forbidden) + assert_authorization_forbidden( + node1.query_and_get_error(f"SELECT dictGet('{forbidden}', 'column2', toUInt64(3))"), + secret="dict_secret_pw", + ) + finally: + node1.query(f"DROP DICTIONARY IF EXISTS {allowed}") + node1.query(f"DROP DICTIONARY IF EXISTS {forbidden}") + + +def test_loaded_http_dictionary_credentials_with_forbidden_authorization(): + # A loaded dictionary keeps its source across its updates, so the credentials are checked per request. + name = "http_credentials_loaded" + node1.query( + f"CREATE DICTIONARY {name} (column1 UInt64, column2 UInt32, column3 UInt32) PRIMARY KEY column1 " + "SOURCE(HTTP(url 'http://nginx:80/test_1' format 'TabSeparated' " + "credentials(user 'user' password 'dict_secret_pw'))) " + "LIFETIME(MIN 1 MAX 1) LAYOUT(FLAT())" + ) + try: + assert node1.query(f"SELECT dictGet('{name}', 'column2', toUInt64(3))") == "2\n" + + with forbidden_authorization(): + assert_eq_with_retry( + node1, + f"SELECT last_exception LIKE '%Authorization%is forbidden%' FROM system.dictionaries WHERE name = '{name}'", + "1", + retry_count=60, + sleep_time=0.5, + ) + finally: + node1.query(f"DROP DICTIONARY IF EXISTS {name}") + + +@pytest.mark.parametrize( + "registry_url", + [ + pytest.param("http://user:pass@nginx:80/", id="userinfo"), + # Without an authority the URL has no userinfo, but the schema is requested from + # `http://user:pass@nginx:80/schemas/ids/1`, which its path resolves to. + pytest.param("http:http://user:pass@nginx:80/", id="without_authority"), + ], +) +def test_avro_schema_registry_userinfo_with_forbidden_authorization(registry_url): + # The data is the magic byte and the schema id 1, so the schema is requested. The server has no + # schema registry, so the request fails anyway: only whether it is refused matters. + query = ( + "SELECT * FROM format(AvroConfluent, 'a UInt8', '\\x00\\x00\\x00\\x00\\x01') " + f"SETTINGS format_avro_schema_registry_url = '{registry_url}'" + ) + error = node1.query_and_get_error(query) + assert 'HTTP header "Authorization" is forbidden' not in error, error + + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) diff --git a/tests/integration/test_store_cleanup/__init__.py b/tests/integration/test_store_cleanup/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/integration/test_store_cleanup/configs/store_cleanup.xml b/tests/integration/test_store_cleanup/configs/store_cleanup.xml deleted file mode 100644 index 5fbe87cce006..000000000000 --- a/tests/integration/test_store_cleanup/configs/store_cleanup.xml +++ /dev/null @@ -1,11 +0,0 @@ - - 0 - 60 - 1 - - - - testkeeper - - \ No newline at end of file diff --git a/tests/integration/test_store_cleanup/test.py b/tests/integration/test_store_cleanup/test.py deleted file mode 100644 index 6ed52880752f..000000000000 --- a/tests/integration/test_store_cleanup/test.py +++ /dev/null @@ -1,221 +0,0 @@ -import pytest - -from helpers.cluster import ClickHouseCluster - -cluster = ClickHouseCluster(__file__) - -node1 = cluster.add_instance( - "node1", - stay_alive=True, - main_configs=["configs/store_cleanup.xml"], - with_remote_database_disk=False, # The test checks data on the local disk -) - -path_to_data = "/var/lib/clickhouse/" - - -@pytest.fixture(scope="module") -def started_cluster(): - try: - cluster.start() - yield cluster - - finally: - cluster.shutdown() - - -def test_store_cleanup(started_cluster): - sync_drop = {"database_atomic_wait_for_drop_and_detach_synchronously": True} - - node1.query("DROP DATABASE IF EXISTS db", settings=sync_drop) - node1.query("DROP DATABASE IF EXISTS db2", settings=sync_drop) - node1.query("DROP DATABASE IF EXISTS db3", settings=sync_drop) - - node1.query("CREATE DATABASE db UUID '10000000-1000-4000-8000-000000000001'") - node1.query( - "CREATE TABLE db.log UUID '10000000-1000-4000-8000-000000000002' ENGINE=Log AS SELECT 1" - ) - node1.query( - "CREATE TABLE db.mt UUID '10000000-1000-4000-8000-000000000003' ENGINE=MergeTree ORDER BY tuple() AS SELECT 1" - ) - node1.query( - "CREATE TABLE db.mem UUID '10000000-1000-4000-8000-000000000004' ENGINE=Memory AS SELECT 1" - ) - - node1.query("CREATE DATABASE db2 UUID '20000000-1000-4000-8000-000000000001'") - node1.query( - "CREATE TABLE db2.log UUID '20000000-1000-4000-8000-000000000002' ENGINE=Log AS SELECT 1" - ) - node1.query("DETACH DATABASE db2", settings=sync_drop) - - node1.query("CREATE DATABASE db3 UUID '30000000-1000-4000-8000-000000000001'") - node1.query( - "CREATE TABLE db3.log UUID '30000000-1000-4000-8000-000000000002' ENGINE=Log AS SELECT 1" - ) - node1.query( - "CREATE TABLE db3.log2 UUID '30000000-1000-4000-8000-000000000003' ENGINE=Log AS SELECT 1" - ) - node1.query("DETACH TABLE db3.log") - node1.query("DETACH TABLE db3.log2 PERMANENTLY") - - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store"] - ) - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/100"] - ) - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/200"] - ) - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/300"] - ) - - node1.stop_clickhouse(kill=True) - # All dirs related to `db` will be removed - node1.exec_in_container(["rm", f"{path_to_data}/metadata/db.sql"]) - - node1.exec_in_container(["mkdir", f"{path_to_data}/store/kek"]) - node1.exec_in_container(["touch", f"{path_to_data}/store/12"]) - try: - node1.exec_in_container(["mkdir", f"{path_to_data}/store/456"]) - except Exception as e: - print("Failed to create 456/:", str(e)) - node1.exec_in_container(["mkdir", f"{path_to_data}/store/456/testgarbage"]) - node1.exec_in_container( - ["mkdir", f"{path_to_data}/store/456/30000000-1000-4000-8000-000000000003"] - ) - node1.exec_in_container( - ["touch", f"{path_to_data}/store/456/45600000-1000-4000-8000-000000000003"] - ) - node1.exec_in_container( - ["mkdir", f"{path_to_data}/store/456/45600000-1000-4000-8000-000000000004"] - ) - - node1.start_clickhouse() - node1.query("DETACH DATABASE db2", settings=sync_drop) - node1.query("DETACH TABLE db3.log") - - node1.wait_for_log_line( - "Removing access rights for unused directory", - timeout=60, - look_behind_lines=1000000, - ) - node1.wait_for_log_line( - "directories from store", timeout=60, look_behind_lines=1000000 - ) - - store = node1.exec_in_container(["ls", f"{path_to_data}/store"]) - assert "100" in store - assert "200" in store - assert "300" in store - assert "456" in store - assert "kek" in store - assert "12" in store - assert "d---------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store"] - ) - assert "d---------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/456"] - ) - - # Metadata is removed, so store/100 contains garbage - store100 = node1.exec_in_container(["ls", f"{path_to_data}/store/100"]) - assert "10000000-1000-4000-8000-000000000001" in store100 - assert "10000000-1000-4000-8000-000000000002" in store100 - assert "10000000-1000-4000-8000-000000000003" in store100 - assert "d---------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/100"] - ) - - # Database is detached, nothing to clean up - store200 = node1.exec_in_container(["ls", f"{path_to_data}/store/200"]) - assert "20000000-1000-4000-8000-000000000001" in store200 - assert "20000000-1000-4000-8000-000000000002" in store200 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/200"] - ) - - # Tables are detached, nothing to clean up - store300 = node1.exec_in_container(["ls", f"{path_to_data}/store/300"]) - assert "30000000-1000-4000-8000-000000000001" in store300 - assert "30000000-1000-4000-8000-000000000002" in store300 - assert "30000000-1000-4000-8000-000000000003" in store300 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/300"] - ) - - # Manually created garbage - store456 = node1.exec_in_container(["ls", f"{path_to_data}/store/456"]) - assert "30000000-1000-4000-8000-000000000003" in store456 - assert "45600000-1000-4000-8000-000000000003" in store456 - assert "45600000-1000-4000-8000-000000000004" in store456 - assert "testgarbage" in store456 - assert "----------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/456"] - ) - - node1.wait_for_log_line( - "Removing unused directory", timeout=90, look_behind_lines=1000000 - ) - node1.wait_for_log_line( - "directories from store", timeout=90, look_behind_lines=1000000 - ) - node1.wait_for_log_line( - "Nothing to clean up from store/", timeout=90, look_behind_lines=1000000 - ) - - store = node1.exec_in_container(["ls", f"{path_to_data}/store"]) - assert "100" in store - assert "200" in store - assert "300" in store - assert "456" in store - assert "kek" not in store # changed - assert "\n12\n" not in store # changed - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store"] - ) # changed - - # Metadata is removed, so store/100 contains garbage - store100 = node1.exec_in_container(["ls", f"{path_to_data}/store/100"]) # changed - assert "10000000-1000-4000-8000-000000000001" not in store100 # changed - assert "10000000-1000-4000-8000-000000000002" not in store100 # changed - assert "10000000-1000-4000-8000-000000000003" not in store100 # changed - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/100"] - ) # changed - - # Database is detached, nothing to clean up - store200 = node1.exec_in_container(["ls", f"{path_to_data}/store/200"]) - assert "20000000-1000-4000-8000-000000000001" in store200 - assert "20000000-1000-4000-8000-000000000002" in store200 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/200"] - ) - - # Tables are detached, nothing to clean up - store300 = node1.exec_in_container(["ls", f"{path_to_data}/store/300"]) - assert "30000000-1000-4000-8000-000000000001" in store300 - assert "30000000-1000-4000-8000-000000000002" in store300 - assert "30000000-1000-4000-8000-000000000003" in store300 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/300"] - ) - - # Manually created garbage - store456 = node1.exec_in_container(["ls", f"{path_to_data}/store/456"]) - assert "30000000-1000-4000-8000-000000000003" not in store456 # changed - assert "45600000-1000-4000-8000-000000000003" not in store456 # changed - assert "45600000-1000-4000-8000-000000000004" not in store456 # changed - assert "testgarbage" not in store456 # changed - assert "---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/456"] - ) # changed - - node1.query("ATTACH TABLE db3.log2") - node1.query("ATTACH DATABASE db2") - node1.query("ATTACH TABLE db3.log") - - assert "1\n" == node1.query("SELECT * FROM db3.log") - assert "1\n" == node1.query("SELECT * FROM db3.log2") - assert "1\n" == node1.query("SELECT * FROM db2.log") diff --git a/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py b/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py new file mode 100644 index 000000000000..8642b61ce073 --- /dev/null +++ b/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 + +""" +A fake MongoDB server that answers `find` and `getMore` with hand-encoded cursor replies. + +The collection name of the `find` command selects the reply, see `SCENARIOS`. +The cursor ID of the `getMore` command selects the next batch. + +The server listens on a free port that the kernel selects, and writes the port number to the port file. + +Usage: malformed_cursor_batch_server.py +""" + +import os +import socketserver +import struct +import sys + + +# Encode BSON directly so the server can send malformed embedded documents. +def document(*elements): + body = b"".join(elements) + return struct.pack(" (first batch, cursor ID, next batch). +# A nonzero cursor ID keeps the cursor open. Each open cursor has a different ID. +# If the next batch is `None`, the server does not expect `getMore`. +SCENARIOS = { + "valid": ([VALID, VALID], 0, None), + "empty": ([], 0, None), + # Neither a short length nor a missing NUL terminator must abort the process. + "short": ([SHORT], 0, None), + "nonnul": ([NONNUL], 0, None), + # A bad document after a valid one, while the cursor is still open. + "after_valid": ([VALID, SHORT], 1, None), + # A bad document in a `getMore` reply. + "next_batch": ([VALID], 2, [NONNUL]), +} +NEXT_BATCHES = { + cursor_id: (collection, next_batch) + for collection, (_, cursor_id, next_batch) in SCENARIOS.items() + if cursor_id != 0 +} + + +def cursor_reply(collection, documents, batch, cursor_id): + return document( + element( + 0x03, + "cursor", + document( + element(0x12, "id", struct.pack(" /var/log/clickhouse-server/malformed_cursor_batch_server.log 2>&1", + ], + detach=True, + ) + # The server binds to port 0 in the container of `node`, and writes the port to the port file when it listens. + port = wait_condition( + lambda: node.exec_in_container( + ["bash", "-c", f"cat {port_file} 2>/dev/null"], nothrow=True + ).strip(), + lambda reply: reply.isdigit(), + max_attempts=40, + delay=0.5, + ) + return f"127.0.0.1:{port}" + + +def test_malformed_cursor_batch(started_cluster, malformed_cursor_batch_server): + # A MongoDB server that returned a malformed document in a cursor batch used to abort the ClickHouse server + # (`BSON_ASSERT` in `_mongoc_cursor_response_read` of the C driver). Now the query fails with an exception. + # The fake MongoDB server answers `find` and `getMore` with hand-encoded replies. + # The collection name selects the reply. + node = started_cluster.instances["node"] + + def select(collection): + return ( + f"SELECT * FROM mongodb('{malformed_cursor_batch_server}', 'db', '{collection}', '', '', 'v String', " + "'serverSelectionTimeoutMS=30000&socketTimeoutMS=30000')" + ) + + # The fake server is good enough for the driver when all documents are valid. + assert node.query(select("valid")) == "hello\nhello\n" + assert node.query(select("empty")) == "" + + for collection in [ + # Neither a short length nor a missing NUL terminator must abort the process. + "short", + "nonnul", + # Reject a bad document after reading a valid one, even when the cursor is still open. + "after_valid", + # The same validation must apply to a `getMore` reply. + "next_batch", + ]: + error = node.query_and_get_error(select(collection)) + assert "Invalid BSON document in cursor reply." in error, (collection, error) + assert node.query("SELECT 1") == "1\n", collection diff --git a/tests/queries/0_stateless/01601_detach_permanently.sql b/tests/queries/0_stateless/01601_detach_permanently.sql index c5d5a37ee37b..090598697dce 100644 --- a/tests/queries/0_stateless/01601_detach_permanently.sql +++ b/tests/queries/0_stateless/01601_detach_permanently.sql @@ -33,8 +33,7 @@ SELECT 'can still show the create statement'; SHOW CREATE TABLE test1601_detach_permanently_atomic.test_name_reuse FORMAT Vertical; SELECT 'can not attach with bad uuid'; --- STD_EXCEPTION occurred when running flaky test, the table directory's access right was removed. Refer `DatabaseCatalog::maybeRemoveDirectory`. -ATTACH TABLE test1601_detach_permanently_atomic.test_name_reuse UUID '00000000-0000-0000-0000-000000001601' (`number` UInt64 ) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8192 ; -- { serverError TABLE_ALREADY_EXISTS, STD_EXCEPTION } +ATTACH TABLE test1601_detach_permanently_atomic.test_name_reuse UUID '00000000-0000-0000-0000-000000001601' (`number` UInt64 ) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8192 ; -- { serverError TABLE_ALREADY_EXISTS } SELECT 'can attach with short syntax'; ATTACH TABLE test1601_detach_permanently_atomic.test_name_reuse; diff --git a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference index a51336301866..f797556ac550 100644 --- a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference +++ b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference @@ -6,10 +6,8 @@ Using storage policy: s3_cache (0,808110) READ_FROM_CACHE Using storage policy: local_cache (0,519) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE (0,808110) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE (0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_CACHE Using storage policy: azure_cache (0,519) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE (0,808110) READ_FROM_CACHE diff --git a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh index 6b34813159f6..37a65e926dab 100755 --- a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh +++ b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh @@ -1,5 +1,9 @@ #!/usr/bin/env bash -# Tags: long, no-fasttest, no-parallel, no-object-storage, no-random-settings +# Tags: long, no-fasttest, no-parallel, no-object-storage, no-random-settings, no-flaky-check +# Tag no-flaky-check: the test reads through the shared `s3_cache`, `local_cache` and `azure_cache` caches +# and expects exact cache hit/miss sequences. Repeated runs start while background merges of `test.hits_s3` +# are still writing through `s3_cache` with `cache_on_write_operations`, which fills the whole cache with +# non-releasable segments, so reads bypass the cache or re-download. # set -x diff --git a/tests/queries/0_stateless/02294_decimal_second_errors.reference b/tests/queries/0_stateless/02294_decimal_second_errors.reference index a9e2f17562ae..98fb6a686563 100644 --- a/tests/queries/0_stateless/02294_decimal_second_errors.reference +++ b/tests/queries/0_stateless/02294_decimal_second_errors.reference @@ -2,5 +2,3 @@ 1 1 1 -1 -1 diff --git a/tests/queries/0_stateless/02294_decimal_second_errors.sql b/tests/queries/0_stateless/02294_decimal_second_errors.sql index b9b6d0a62238..b7cb062d20fa 100644 --- a/tests/queries/0_stateless/02294_decimal_second_errors.sql +++ b/tests/queries/0_stateless/02294_decimal_second_errors.sql @@ -1,11 +1,11 @@ SELECT 1 SETTINGS max_execution_time=NaN; -- { clientError CANNOT_PARSE_NUMBER } SELECT 1 SETTINGS max_execution_time=Infinity; -- { clientError CANNOT_PARSE_NUMBER }; SELECT 1 SETTINGS max_execution_time=-Infinity; -- { clientError CANNOT_PARSE_NUMBER }; +SELECT 1 SETTINGS max_execution_time=-0.5; -- { clientError BAD_ARGUMENTS } +SELECT 1 SETTINGS max_execution_time=-1; -- { clientError BAD_ARGUMENTS } -- Ok values -SELECT 1 SETTINGS max_execution_time=-0.5; SELECT 1 SETTINGS max_execution_time=5.5; -SELECT 1 SETTINGS max_execution_time=-1; SELECT 1 SETTINGS max_execution_time=0.0; SELECT 1 SETTINGS max_execution_time=-0.0; SELECT 1 SETTINGS max_execution_time=10; diff --git a/tests/queries/0_stateless/02466_distributed_query_profiler.sql b/tests/queries/0_stateless/02466_distributed_query_profiler.sql index 171cc2a75638..3f50b79f7277 100644 --- a/tests/queries/0_stateless/02466_distributed_query_profiler.sql +++ b/tests/queries/0_stateless/02466_distributed_query_profiler.sql @@ -7,8 +7,6 @@ select * from remote('127.{2,4}', view( -- LIMIT is to activate query cancellation in case of enough rows already read. limit 10 settings - -- This is to avoid draining in background and got the exception during query execution - drain_timeout=-1, -- This is to activate as much signals as possible to trigger EINTR query_profiler_real_time_period_ns=1, -- This is to use MultiplexedConnections diff --git a/tests/queries/0_stateless/02477_invalid_reads.sql b/tests/queries/0_stateless/02477_invalid_reads.sql index f2f10296426a..bee4120396e4 100644 --- a/tests/queries/0_stateless/02477_invalid_reads.sql +++ b/tests/queries/0_stateless/02477_invalid_reads.sql @@ -65,6 +65,11 @@ SELECT finalizeAggregation(CAST(unhex('0F000000000000803F'), SELECT finalizeAggregation(CAST(unhex('01080000000000000000'), 'AggregateFunction(groupUniqArray, Tuple(String))')); -- { serverError INCORRECT_DATA } +-- LowCardinality(String) interns through ColumnUnique. Its arena record has a trailing byte, so an +-- encoded size of zero must be rejected instead of becoming SIZE_MAX at the hash input. +SELECT finalizeAggregation(CAST(unhex('0109000000000000000000'), + 'AggregateFunction(groupUniqArray, Tuple(Variant(LowCardinality(String))))')); -- { serverError INCORRECT_DATA } + -- uniq stores skip_degree as the first byte and thins hashes by 2 ^ skip_degree. Thinning cannot -- raise the degree beyond one past its budget, so a larger one is rejected. The last accepted -- degree still admits a count that saturates the hash space, which size() reports as its maximum. diff --git a/tests/queries/0_stateless/02714_local_object_storage.sh b/tests/queries/0_stateless/02714_local_object_storage.sh index fb44697ddeee..3f0698ebb8f6 100755 --- a/tests/queries/0_stateless/02714_local_object_storage.sh +++ b/tests/queries/0_stateless/02714_local_object_storage.sh @@ -12,13 +12,6 @@ settings=( --local_filesystem_read_method='pread' ) -server_path=$(${CLICKHOUSE_CLIENT} -q "SELECT path FROM system.disks WHERE name = 'default'") - -if [ "${server_path:0:1}" != "/" ]; then - echo "path should be absolute (path: $path)" >&2 - exit 1 -fi - $CLICKHOUSE_CLIENT "${settings[@]}" -nm -q " DROP TABLE IF EXISTS test; @@ -26,7 +19,7 @@ $CLICKHOUSE_CLIENT "${settings[@]}" -nm -q " ENGINE = MergeTree() ORDER BY tuple() SETTINGS disk = disk( type = 'local_blob_storage', - path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/'); + path = '${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/'); INSERT INTO test SELECT 1, 'test'; SELECT * FROM test; @@ -39,7 +32,7 @@ $CLICKHOUSE_CLIENT "${settings[@]}" -nm -q " type = 'cache', max_size = '10Mi', path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/', - disk = disk(type='local_blob_storage', path='${server_path}/disks/${CLICKHOUSE_TEST_UNIQUE_NAME}/')); + disk = disk(type='local_blob_storage', path='${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/')); INSERT INTO test SELECT 1, 'test'; SELECT * FROM test; diff --git a/tests/queries/0_stateless/02888_obsolete_settings.reference b/tests/queries/0_stateless/02888_obsolete_settings.reference index 2fdd7718009b..34b913779b8d 100644 --- a/tests/queries/0_stateless/02888_obsolete_settings.reference +++ b/tests/queries/0_stateless/02888_obsolete_settings.reference @@ -1,5 +1,8 @@ -- Obsolete server settings allow_impersonate_user +database_catalog_unused_dir_cleanup_period_sec +database_catalog_unused_dir_hide_timeout_sec +database_catalog_unused_dir_rm_timeout_sec storage_metadata_write_full_object_key -- Obsolete general settings 1 diff --git a/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sql b/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh old mode 100644 new mode 100755 similarity index 88% rename from tests/queries/0_stateless/02963_test_flexible_disk_configuration.sql rename to tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh index 6b285d423e79..bdcbf491dcf2 --- a/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sql +++ b/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh @@ -1,12 +1,19 @@ --- Tags: no-fasttest +#!/usr/bin/env bash +# Tags: no-fasttest + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +$CLICKHOUSE_CLIENT -q " drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() -settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='./02963_test1/'); +settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='${CLICKHOUSE_DISKS_FILES}/02963_test1/'); drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() -settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='./02963_test2/'); -- { serverError BAD_ARGUMENTS } +settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='${CLICKHOUSE_DISKS_FILES}/02963_test2/'); -- { serverError BAD_ARGUMENTS } drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() @@ -26,7 +33,7 @@ settings disk='s3_disk_02963'; drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() -settings disk=disk(name='s3_disk_02963', type = object_storage, object_storage_type = local_blob_storage, path='./02963_test2/'); -- { serverError BAD_ARGUMENTS } +settings disk=disk(name='s3_disk_02963', type = object_storage, object_storage_type = local_blob_storage, path='${CLICKHOUSE_DISKS_FILES}/02963_test2/'); -- { serverError BAD_ARGUMENTS } drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() @@ -96,3 +103,4 @@ settings disk=disk(name='test7', endpoint = 'http://localhost:11111/test/common/', access_key_id = clickhouse, secret_access_key = clickhouse); -- { serverError UNKNOWN_ELEMENT_IN_CONFIG } +" diff --git a/tests/queries/0_stateless/03000_too_big_max_execution_time_setting.sql b/tests/queries/0_stateless/03000_too_big_max_execution_time_setting.sql index 7aa86891b42d..c123ba16ce8d 100644 --- a/tests/queries/0_stateless/03000_too_big_max_execution_time_setting.sql +++ b/tests/queries/0_stateless/03000_too_big_max_execution_time_setting.sql @@ -1,2 +1,3 @@ select 1 settings max_execution_time = 9223372036854775808; -- {clientError BAD_ARGUMENTS} +select 1 settings max_execution_time = 9223372036854.775; -- {clientError BAD_ARGUMENTS} diff --git a/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh b/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh index e835186ddfb4..9ef3b3895ede 100755 --- a/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh +++ b/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh @@ -18,7 +18,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/03362/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/03362/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query " @@ -30,7 +30,7 @@ SETTINGS table_disk = true, refresh_parts_interval = 1, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/03362/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/03362/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query "INSERT INTO writer VALUES ('Hello')"; diff --git a/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh b/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh index f18d0b9e3eff..9402ab467686 100755 --- a/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh +++ b/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh @@ -14,7 +14,7 @@ $CLICKHOUSE_CLIENT -q " CREATE TABLE test_local_blob_log (a Int32, b String) ENGINE = MergeTree() ORDER BY a - SETTINGS disk = disk(type = 'local_blob_storage', path = '03776_test_local_blob_log/'); + SETTINGS disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_DISKS_FILES}/03776_test_local_blob_log/'); INSERT INTO test_local_blob_log VALUES (1, 'test1'), (2, 'test2'), (3, 'test3'); diff --git a/tests/queries/0_stateless/04300_deltalake_ffi_panic_guard.sh b/tests/queries/0_stateless/04300_deltalake_ffi_panic_guard.sh index 3e2cf2522ab9..1a4f885c2e36 100755 --- a/tests/queries/0_stateless/04300_deltalake_ffi_panic_guard.sh +++ b/tests/queries/0_stateless/04300_deltalake_ffi_panic_guard.sh @@ -8,9 +8,11 @@ # A NUL byte is valid UTF-8, so it passes the option decoding, but it is an invalid HTTP header # value. While signing the S3 request, `object_store` does `.unwrap()` on the resulting # `InvalidHeaderValue` and panics on a `TokioBackgroundExecutor` worker; the kernel executor then -# panics on the calling thread inside `ffi::snapshot`. Because the FFI is `extern "C"` (nounwind), -# that panic used to reach `panic_cannot_unwind` and abort the server. The FFI now wraps `snapshot` -# and `builder_build` in `catch_unwind`, converting the panic into a `DELTA_KERNEL_ERROR` exception. +# panics on the calling thread inside `ffi::snapshot_builder_build`. Because the FFI is `extern "C"` +# (nounwind), that panic used to reach `panic_cannot_unwind` and abort the server. The FFI now wraps +# `snapshot_builder_build` (the snapshot builder API ClickHouse calls) -- along with `snapshot`, its +# variants and `builder_build` -- in `catch_unwind`, converting the panic into a `DELTA_KERNEL_ERROR` +# exception. # # Written as a `.sh` test through `clickhouse-local`: on the unfixed binary the process aborts, so # stdout is empty and mismatches the reference (clean FAIL); on the fixed binary the guarded panic diff --git a/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh b/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh index a9ba7bd33bcb..64c015304592 100755 --- a/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh +++ b/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh @@ -22,7 +22,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04421/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04421/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query " @@ -34,7 +34,7 @@ SETTINGS table_disk = true, refresh_parts_interval = 1, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04421/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04421/${CLICKHOUSE_DATABASE}/') " # Sanity check: the background refresh picks up the first part. diff --git a/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh b/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh index 6d8a269bc8a0..8cf55a313ecb 100755 --- a/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh +++ b/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh @@ -16,7 +16,7 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS writer SYNC" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS reader SYNC" -disk_path="disks/04545/${CLICKHOUSE_DATABASE}/" +disk_path="${CLICKHOUSE_DISKS_FILES}/04545/${CLICKHOUSE_DATABASE}/" # Writer: a read-write plain_rewritable object-storage disk. ${CLICKHOUSE_CLIENT} --query " @@ -67,7 +67,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = local, - path = 'disks/04545_local/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04545_local/${CLICKHOUSE_DATABASE}/') " 2>&1 | grep -qF "requires metadata stored on the object storage" && echo "local metadata read-only disk rejected for table_disk" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS reader_local SYNC" diff --git a/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python b/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python index b9aac4e38b04..5e976535fc97 100644 --- a/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python +++ b/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python @@ -5,7 +5,7 @@ # # A crafted `REPLICATED`-serialized column can trigger the same out-of-bounds read # (nested_column[index]) via two independent paths that SerializationReplicated must -# reject with INCORRECT_DATA (code 117), while the server stays alive: +# reject with INCORRECT_DATA (code 117): # # 1. out-of-bounds index: per-row indexes point past the nested ("elements") column. # Before the fix, only the index row count was validated, not the index values. @@ -16,15 +16,26 @@ # ColumnReplicated, not the nested column size), so without an explicit post-read # size check the nested column would silently end up smaller than num_elements. # -# The client speaks the raw native protocol pinned to revision 54482 +# Only a server may choose the `REPLICATED` kind, so the crafted columns arrive the way a real +# one does: in a result block, sent to clickhouse-client by a fake server. A block that a client +# sends to the server accepts only the default kind, so there such a column is rejected by its +# kind, before SerializationReplicated reads it, and the server must stay alive (the last scenario). +# +# Both sides speak the raw native protocol pinned to revision 54482 # (DBMS_MIN_REVISION_WITH_REPLICATED_SERIALIZATION, the minimum that enables REPLICATED), # so the set of exchanged, revision-gated fields is fixed and does not drift. import os import socket import struct +import sys import uuid +CURDIR = os.path.dirname(os.path.realpath(__file__)) +sys.path.insert(0, os.path.join(CURDIR, "helpers")) + +from fake_native_server import runClientAgainstFakeServer + CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") @@ -251,13 +262,17 @@ def readHeader(s): readKindStack(s) -def sendCraftedReplicatedBlock(s): +CLIENT_DATA = 2 +SERVER_DATA = 1 + + +def craftedReplicatedBlock(packet_type): limit = 4 num_elements = 1 oob_index = 0xFFFFFFFF ba = bytearray() - writeVarUInt(2, ba) # Data + writeVarUInt(packet_type, ba) # Data writeStringBinary("", ba) # table name serializeBlockInfo(ba) writeVarUInt(1, ba) # columns @@ -278,7 +293,7 @@ def sendCraftedReplicatedBlock(s): for _ in range(num_elements): ba.extend(struct.pack("&1 | grep -oF 'TOO_MANY_QUERY_PLAN_OPTIMIZATIONS' | head -n 1 + +timeout 30 $CLICKHOUSE_CLIENT -q "DROP TABLE t_04700 SYNC" && echo "dropped" || echo "STUCK" diff --git a/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python b/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python new file mode 100644 index 000000000000..db56872e4742 --- /dev/null +++ b/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# `ClientInfo::read` stores the reported `interface` and `http_method` bytes without checking that +# they name an enumerator, so `system.query_log` and `system.processes` must be able to render any +# byte a client sends. This script speaks the raw native protocol to report values outside both +# enums. +# +# The queries are sent as `SECONDARY_QUERY`. That is the query kind whose reported interface is +# allowed to differ from the receiving session's: a query forwarded to a shard carries the +# initiator's interface, so an HTTP initiator forwarding over a native TCP connection reports +# `HTTP` on a TCP session, and `validateClientInfo` exempts it. An `INITIAL_QUERY` reporting +# anything but the session's own interface is refused with `CLIENT_INFO_DOES_NOT_MATCH` wherever +# `validate_tcp_client_information` is on, which includes the stateless-test server. +# +# The revision is pinned to 54484, the newest one whose `ClientInfo` layout is fully written below +# (`client_agent` is added at 54485), so the set of exchanged fields is fixed and does not drift. + +import os +import socket +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") +CLIENT_NAME = "interface enum poc" + +REVISION = 54484 + +INTERFACE_TCP = 1 +INTERFACE_HTTP = 2 +# Each `*_LOW` byte is the smallest value its own enum does not name, so a projection keyed on a +# threshold instead of on membership either passes it through, and rendering then throws, or has +# already remapped a named value that `03258_refreshable_mv_misc` and `04306_create_handler_http` +# pin. 200 narrows to -56, keeping the negative `Int8` class armed. Adding an enumerator to either +# enum moves that field's `*_LOW` byte: it is the next value that enum would allocate. +INTERFACE_UNMAPPED_LOW = 12 +HTTP_METHOD_UNMAPPED_LOW = 7 +UNMAPPED_HIGH_BIT = 200 + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") if isinstance(s, str) else s + writeVarUInt(len(b), ba) + ba.extend(b) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt(s, size=1): + res = readStrict(s, size) + val = 0 + for i in range(len(res)): + val += res[i] << (i * 8) + return val + + +def readVarUInt(s): + x = 0 + for i in range(9): + byte = readStrict(s)[0] + x |= (byte & 0x7F) << (7 * i) + if not byte & 0x80: + return x + return x + + +def readStringBinary(s): + size = readVarUInt(s) + return readStrict(s, size).decode("utf-8") + + +def sendHello(s): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeStringBinary(CLICKHOUSE_DATABASE, ba) + writeStringBinary("default", ba) # user + writeStringBinary("", ba) # password + s.sendall(ba) + + +def receiveHello(s): + assert readVarUInt(s) == 0 # Hello + readStringBinary(s) # server name + readVarUInt(s) # major + readVarUInt(s) # minor + readVarUInt(s) # revision + readVarUInt(s) # parallel replicas protocol version (>= 54471) + readStringBinary(s) # timezone (>= 54058) + readStringBinary(s) # display name (>= 54372) + readVarUInt(s) # version patch (>= 54401) + readStringBinary(s) # proto_send chunked (>= 54470) + readStringBinary(s) # proto_recv chunked (>= 54470) + for _ in range(readVarUInt(s)): # password complexity rules (>= 54461) + readStringBinary(s) + readStringBinary(s) + readStrict(s, 8) # nonce, UInt64 (>= 54462) + while True: # server settings in STRINGS_WITH_FLAGS format (>= 54474) + if readStringBinary(s) == "": + break + readVarUInt(s) # flags + readStringBinary(s) # value + readVarUInt(s) # query plan serialization version (>= 54477) + readVarUInt(s) # cluster function protocol version (>= 54479) + + +def sendAddendum(s): + ba = bytearray() + writeStringBinary("", ba) # quota key (>= 54458) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # parallel replicas protocol version (>= 54471) + s.sendall(ba) + + +def serializeClientInfo(ba, query_id, interface, http_method): + ba.append(2) # SECONDARY_QUERY + writeStringBinary("default", ba) # initial_user + writeStringBinary(query_id, ba) # initial_query_id + writeStringBinary("127.0.0.1:9000", ba) # initial_address + ba.extend([0] * 8) # initial_query_start_time_microseconds (>= 54449) + ba.append(interface) + if interface == INTERFACE_TCP: + writeStringBinary("os_user", ba) + writeStringBinary("client_hostname", ba) + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # client major + writeVarUInt(9, ba) # client minor + writeVarUInt(REVISION, ba) # client tcp protocol version + elif interface == INTERFACE_HTTP: + ba.append(http_method) + writeStringBinary(CLIENT_NAME, ba) # http_user_agent + writeStringBinary("", ba) # forwarded_for (>= 54443) + writeStringBinary("", ba) # http_referer (>= 54447) + writeStringBinary("", ba) # quota key (>= 54060) + writeVarUInt(0, ba) # distributed_depth (>= 54448) + if interface == INTERFACE_TCP: + writeVarUInt(1, ba) # client version patch (>= 54401) + ba.append(0) # opentelemetry: no trace id (>= 54442) + writeVarUInt(0, ba) # parallel replicas: collaborate_with_initiator (>= 54453) + writeVarUInt(0, ba) # parallel replicas: obsolete count + writeVarUInt(0, ba) # parallel replicas: number_of_current_replica + writeVarUInt(0, ba) # script query number (>= 54475) + writeVarUInt(0, ba) # script line number (>= 54475) + ba.append(0) # jwt: none (>= 54476) + + +def sendQuery(s, query, interface, http_method, query_id, settings): + ba = bytearray() + writeVarUInt(1, ba) # Query + writeStringBinary(query_id, ba) + serializeClientInfo(ba, query_id, interface, http_method) + for key, value in settings.items(): + writeStringBinary(key, ba) + writeVarUInt(1, ba) # is_important + writeStringBinary(str(value), ba) + writeStringBinary("", ba) # end of per-query settings + writeStringBinary("", ba) # interserver externally granted roles (>= 54472) + writeStringBinary("", ba) # interserver secret (>= 54441) + writeVarUInt(2, ba) # stage = Complete + ba.append(0) # no compression + writeStringBinary(query, ba) + writeStringBinary("", ba) # query parameters terminator (>= 54459) + s.sendall(ba) + + +def sendEmptyBlock(s): + ba = bytearray() + writeVarUInt(2, ba) # Data + writeStringBinary("", ba) + writeVarUInt(1, ba) # block info field 1 + ba.append(0) # is_overflows = false + writeVarUInt(2, ba) # block info field 2 + ba.extend((-1).to_bytes(4, "little", signed=True)) # bucket_num = -1 + writeVarUInt(0, ba) # end of block info + writeVarUInt(0, ba) # columns + writeVarUInt(0, ba) # rows + s.sendall(ba) + + +def expectQueryAccepted(s): + # Any first packet other than an `Exception` proves the server accepted the reported client info: + # a `SELECT` answers with its result header once the query has started, and a completed + # `INSERT ... SELECT` run with `interactive_delay = 0` answers only after its commit. The rest of + # the stream is not read. + packet_type = readVarUInt(s) + if packet_type == 2: # Exception + readUInt(s, 4) # code + readStringBinary(s) # name + raise RuntimeError("Unexpected exception: {}".format(readStringBinary(s))) + + +def runQuery(label, query, interface, http_method, query_id=None, settings=None): + query_id = query_id or uuid.uuid4().hex + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(30) + s.connect((CLICKHOUSE_HOST, CLICKHOUSE_PORT)) + sendHello(s) + receiveHello(s) + sendAddendum(s) + sendQuery(s, query, interface, http_method, query_id, settings or {}) + sendEmptyBlock(s) + expectQueryAccepted(s) + print("{}: query accepted".format(label)) + + +def observeSelfInProcesses(label, interface, http_method): + # `system.processes` is filled from the live process list, so a running query sees its own row + # and can persist what the server renders for it. That is the only way to assert on + # `system.processes`: it holds nothing once the query has ended. + query_id = uuid.uuid4().hex + # With `interactive_delay = 0` the server runs a completed pipeline without a periodic progress + # callback, so the first packet it sends is the one after the INSERT has committed. A client that + # disconnects while such a pipeline is still running has its query cancelled, losing the row. + runQuery( + label, + "INSERT INTO processes_snapshot " + "SELECT toString(interface), toString(http_method) " + "FROM system.processes WHERE query_id = '{}'".format(query_id), + interface, + http_method, + query_id, + settings={"interactive_delay": 0}, + ) + + +def main(): + runQuery( + "reported interface out of domain", + "SELECT 1 SETTINGS log_comment = 'interface_enum_unknown'", + INTERFACE_UNMAPPED_LOW, + 0, + ) + runQuery( + "reported http_method out of domain", + "SELECT 2 SETTINGS log_comment = 'http_method_enum_unknown'", + INTERFACE_HTTP, + UNMAPPED_HIGH_BIT, + ) + # Two queries, because one cannot report an out-of-domain value for both columns at once: + # `http_method` is only read off the wire when the reported interface is `HTTP`. + # The `system.processes` probes carry the other byte of each pair, so both projections are + # reported both classes across their two call sites. + observeSelfInProcesses("processes: reported interface out of domain", UNMAPPED_HIGH_BIT, 0) + observeSelfInProcesses( + "processes: reported http_method out of domain", INTERFACE_HTTP, HTTP_METHOD_UNMAPPED_LOW + ) + + +if __name__ == "__main__": + main() diff --git a/tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.reference b/tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.reference new file mode 100644 index 000000000000..dce6fe983969 --- /dev/null +++ b/tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.reference @@ -0,0 +1,22 @@ +87 +87 +87 +21.75 +4 +13 +91 +87 +1 +2 +1 +1 +1 +1 +1 +0 +force_enable +1 +0 +1 +disable +1 diff --git a/tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.sql b/tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.sql new file mode 100644 index 000000000000..4892d394b77e --- /dev/null +++ b/tests/queries/0_stateless/05137_rewrite_aggregate_function_with_if_short_circuit.sql @@ -0,0 +1,60 @@ +-- https://github.com/ClickHouse/ClickHouse/issues/85784 +-- https://github.com/ClickHouse/ClickHouse/issues/118625 + +-- At short_circuit_function_evaluation = 'disable' the un-rewritten queries throw as well, so every +-- expected value below requires short-circuit evaluation to be on. +-- optimize_if_chain_to_multiif is pinned off: it flattens the nested `if` below into `multiIf` before +-- this pass runs, and the pass matches only `if`, so the nested witness would stop exercising it. +SET enable_analyzer = 1, optimize_rewrite_aggregate_function_with_if = 1, + optimize_rewrite_sum_if_to_count_if = 0, short_circuit_function_evaluation = 'enable', + optimize_if_chain_to_multiif = 0; + +SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5); +SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5) SETTINGS optimize_rewrite_aggregate_function_with_if = 0; +SELECT sum(if(number != 0, intDiv(42, number), 0)) FROM numbers(5); +SELECT avg(if(number = 0, NULL, intDiv(42, number))) FROM numbers(5); +SELECT count(if(number = 0, NULL, intDiv(42, number))) FROM numbers(5); + +SELECT sum(if((number = 0) OR ((number % 6) = 0), 0, intDiv(6, number))) FROM numbers(6); +SELECT sum(if(number = 0, 0, intDiv(42, number) + 1)) FROM numbers(5); +SELECT sum(if(number = 0, 0, if(number > 100, 0, intDiv(42, number)))) FROM numbers(5); +-- A conversion is protected at 'enable' too: the guard asks the generic suitability predicate, not a +-- list of arithmetic functions. +SELECT count(if(s = 'bad', NULL, toDate(s))) FROM (SELECT arrayJoin(['2020-01-01', 'bad']) AS s); + +-- A subquery on the right of IN is not an expression: it has no result type, and laziness does not +-- reach inside it. +SELECT sum(if(number = 0, 0, number IN (SELECT 1 UNION ALL SELECT 2))) FROM numbers(5); +SELECT count() > 0 FROM ( + EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, number IN (SELECT intDiv(42, number) FROM numbers(1, 5)))) FROM numbers(5) +) WHERE explain LIKE '%sumIf%'; +SELECT count() > 0 FROM ( + EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, number IN (SELECT intDiv(42, number) FROM numbers(1, 5) UNION ALL SELECT 1))) FROM numbers(5) +) WHERE explain LIKE '%sumIf%'; + +-- The rewrite is still applied when the lifted branch was never evaluated lazily. +SELECT count() > 0 FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, number)) FROM numbers(5)) WHERE explain LIKE '%sumIf%'; +SELECT count() > 0 FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, number, 0)) FROM numbers(5)) WHERE explain LIKE '%sumIf%'; +SELECT count() > 0 FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, number * 2)) FROM numbers(5)) WHERE explain LIKE '%sumIf%'; +SELECT count() FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5)) WHERE explain LIKE '%sumIf%'; + +SELECT 'force_enable'; +-- addDate reports no short-circuit suitability, so only forced laziness protects it. +SELECT count(if(s = 'bad', NULL, addDate(s, INTERVAL 1 DAY))) +FROM (SELECT arrayJoin(['2020-01-01', 'bad']) AS s) +SETTINGS short_circuit_function_evaluation = 'force_enable'; +-- The same query throws at 'enable': nothing was protected there, so the rewrite changes nothing. +SELECT count(if(s = 'bad', NULL, addDate(s, INTERVAL 1 DAY))) +FROM (SELECT arrayJoin(['2020-01-01', 'bad']) AS s); -- { serverError CANNOT_PARSE_DATETIME } +SELECT count() FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, number * 2)) FROM numbers(5)) +WHERE explain LIKE '%sumIf%' +SETTINGS short_circuit_function_evaluation = 'force_enable'; +-- A bare column is still rewritten at forced laziness: the guard declines only for a function. +SELECT count() > 0 FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, number)) FROM numbers(5)) +WHERE explain LIKE '%sumIf%' +SETTINGS short_circuit_function_evaluation = 'force_enable'; + +SELECT 'disable'; +SELECT count() > 0 FROM (EXPLAIN QUERY TREE SELECT sum(if(number = 0, 0, intDiv(42, number))) FROM numbers(5)) +WHERE explain LIKE '%sumIf%' +SETTINGS short_circuit_function_evaluation = 'disable'; diff --git a/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference b/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference index 42de9969ea9e..62c38917df43 100644 --- a/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference +++ b/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference @@ -1,4 +1,4 @@ -CREATE DICTIONARY default.d_05141\n(\n `id` UInt64,\n `v` String\n)\nPRIMARY KEY id\nSOURCE(HTTP(URL \'http://localhost:11111/x.tsv\' FORMAT \'TabSeparated\' CREDENTIALS (USER \'user\' PASSWORD \'[HIDDEN]\') HEADERS (\'[HIDDEN]\')))\nLIFETIME(MIN 0 MAX 0)\nLAYOUT(FLAT()) +CREATE DICTIONARY default.d_05141\n(\n `id` UInt64,\n `v` String\n)\nPRIMARY KEY id\nSOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'TabSeparated\' CREDENTIALS (USER \'user\' PASSWORD \'[HIDDEN]\') HEADERS (\'[HIDDEN]\')))\nLIFETIME(MIN 0 MAX 0)\nLAYOUT(FLAT()) 0 0 1 d_05141_flat HEADERS \'[HIDDEN]\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) d_05141_foo HEADERS (\'[HIDDEN]\'))) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) diff --git a/tests/queries/0_stateless/05153_prefer_column_name_to_alias_ambiguous_join.reference b/tests/queries/0_stateless/05153_prefer_column_name_to_alias_ambiguous_join.reference new file mode 100644 index 000000000000..e063858fc003 --- /dev/null +++ b/tests/queries/0_stateless/05153_prefer_column_name_to_alias_ambiguous_join.reference @@ -0,0 +1,18 @@ +1 1 +2 2 +1 1 +2 2 +11 1 +12 2 +2 200 +2 200 +11 11 +12 12 +12 12 +11 1 +12 2 +12 2 +1 buyer 1 +buyer 2 buyer 1 +100 pubA +200 pubB diff --git a/tests/queries/0_stateless/05153_prefer_column_name_to_alias_ambiguous_join.sql b/tests/queries/0_stateless/05153_prefer_column_name_to_alias_ambiguous_join.sql new file mode 100644 index 000000000000..2b0defaa2a3c --- /dev/null +++ b/tests/queries/0_stateless/05153_prefer_column_name_to_alias_ambiguous_join.sql @@ -0,0 +1,101 @@ +-- An unqualified column name that is ambiguous between three or more joined tables +-- resolves to the alias with the same name under prefer_column_name_to_alias = 1, +-- as the old analyzer did. + +SET enable_analyzer = 1; +SET prefer_column_name_to_alias = 1; + +DROP TABLE IF EXISTS ranged_items; +DROP TABLE IF EXISTS product; +DROP TABLE IF EXISTS store; + +CREATE TABLE ranged_items (SNO Int32, skuID Int32) ENGINE = Memory; +CREATE TABLE product (PIN Int32) ENGINE = Memory; +CREATE TABLE store (SNO Int32) ENGINE = Memory; +INSERT INTO ranged_items VALUES (1, 10), (2, 20), (2, 20); +INSERT INTO product VALUES (10), (20); +INSERT INTO store VALUES (1), (2); + +-- comma join, alias name used in ORDER BY +SELECT ranged_items.SNO AS SNO, count() AS c +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO +GROUP BY ranged_items.SNO ORDER BY SNO; + +-- comma join, alias name used in GROUP BY and ORDER BY +SELECT ranged_items.SNO AS SNO, count() AS c +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO +GROUP BY SNO ORDER BY SNO; + +-- alias points at the last table +SELECT store.SNO + 10 AS SNO, count() AS c +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO +GROUP BY SNO ORDER BY SNO; + +-- alias name used in WHERE and inside a SELECT expression +SELECT ranged_items.SNO AS SNO, SNO * 100 AS SNO100 +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO AND SNO = 2 +ORDER BY SNO100; + +-- without an alias the identifier is still ambiguous +SELECT ranged_items.SNO AS s, count() +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO +GROUP BY SNO; -- { serverError AMBIGUOUS_IDENTIFIER } + +-- an alias whose expression is the ambiguous identifier itself cannot take over +SELECT SNO AS SNO +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO; -- { serverError AMBIGUOUS_IDENTIFIER } + +-- three tables: the alias is used +SELECT ranged_items.SNO + 10 AS SNO, SNO AS x +FROM ranged_items, product, store +WHERE ranged_items.skuID = product.PIN AND ranged_items.SNO = store.SNO +ORDER BY x; + +-- two tables: the left table's column wins, the alias is not used +SELECT ranged_items.SNO + 10 AS SNO, SNO AS x +FROM ranged_items, store +WHERE ranged_items.SNO = store.SNO +ORDER BY x; + +DROP TABLE ranged_items; +DROP TABLE product; +DROP TABLE store; + +DROP TABLE IF EXISTS drl; +DROP TABLE IF EXISTS ap; +DROP TABLE IF EXISTS ab; + +CREATE TABLE drl (BuyerID String, PublisherID Int32) ENGINE = Memory; +CREATE TABLE ap (PublisherID Int32, PublisherName String) ENGINE = Memory; +CREATE TABLE ab (BuyerID Int32, BuyerName String) ENGINE = Memory; +INSERT INTO drl VALUES ('1', 100), ('2', 200); +INSERT INTO ap VALUES (100, 'pubA'), (200, 'pubB'); +INSERT INTO ab VALUES (1, 'buyer 1'), (2, 'buyer 2'); + +-- LEFT JOIN chain, alias name used in WHERE +SELECT drl.BuyerID AS BuyerID, ab.BuyerName AS BuyerName +FROM drl LEFT JOIN ap ON drl.PublisherID = ap.PublisherID + LEFT JOIN ab ON drl.BuyerID = toString(ab.BuyerID) +WHERE BuyerID IN ('1'); + +-- ambiguity in the nested JOIN, the column of the outer right table must not win over the alias +SELECT ab0.BuyerName AS BuyerName, ab2.BuyerName +FROM ab AS ab0 LEFT JOIN ab AS ab1 ON ab0.BuyerID = ab1.BuyerID + LEFT JOIN ab AS ab2 ON ab0.BuyerID = ab2.BuyerID + 1 +WHERE BuyerName = 'buyer 2'; + +-- alias name used in an ON clause resolves to the alias as well +SELECT drl.PublisherID AS PublisherID, ap.PublisherName +FROM drl LEFT JOIN ab ON drl.BuyerID = toString(ab.BuyerID) + LEFT JOIN ap ON PublisherID = ap.PublisherID +ORDER BY PublisherID; + +DROP TABLE drl; +DROP TABLE ap; +DROP TABLE ab; diff --git a/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.reference b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.reference new file mode 100644 index 000000000000..2c3e1cbad3a7 --- /dev/null +++ b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.reference @@ -0,0 +1,5 @@ +1 1 +1 +1 +identical value accepted under readonly +1 diff --git a/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.sh b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.sh new file mode 100755 index 000000000000..42cf354af3b6 --- /dev/null +++ b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A custom setting (enabled by `custom_settings_prefixes`) can hold an AST rather than a literal, e.g. +# `custom_x = disk(type = 's3', ...)`. Assigning such a setting a second time compares the new value +# with the one the session already holds, and both sides being AST-valued is the only way to reach +# that comparison. `custom_x` lives for the lifetime of an HTTP session, so every statement below runs +# in one session. + +SESSION="05153_$CLICKHOUSE_DATABASE" + +# A successful SET writes nothing, so no request below is redirected: an exception body would land in +# the output and no longer match the reference. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153first', secret_access_key = 'c05153secret')" + +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153second', secret_access_key = 'c05153secret')" + +# The second value wins. `name` is one of the arguments the credential masker leaves visible. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SELECT + position(value, 'c05153second') > 0, + position(value, 'c05153first') = 0 + FROM system.settings WHERE name = 'custom_x'" + +# Re-assigning the identical value is accepted too. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153second', secret_access_key = 'c05153secret')" +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SELECT position(value, 'c05153second') > 0 FROM system.settings WHERE name = 'custom_x'" + +# A nested SETTINGS clause is clamped against the session value rather than refused, which reaches the +# same comparison through a different caller. The inner scope sees the nested value. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SELECT * FROM ( + SELECT position(value, 'c05153nested') > 0 + FROM system.settings WHERE name = 'custom_x' + SETTINGS custom_x = disk(type = 's3', name = 'c05153nested') + )" + +# Under `readonly = 1` a setting change is refused, but an assignment the constraint check judges +# unchanged returns before that check (`SettingsConstraints.cpp:362`), so the comparison's verdict is +# observable: an exact repeat stays silent, while a value differing only in its credential is refused. +# `readonly = 1` also refuses the settings the test runner appends to the URL, so this session's URL +# carries nothing but the session id. +RO_SESSION="05153_ro_$CLICKHOUSE_DATABASE" +RO_URL="${CLICKHOUSE_URL%%\?*}?session_id=$RO_SESSION" + +${CLICKHOUSE_CURL} -sS "$RO_URL" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153ro', secret_access_key = 'c05153secret')" +${CLICKHOUSE_CURL} -sS "$RO_URL" --data-binary "SET readonly = 1" + +${CLICKHOUSE_CURL} -sS "$RO_URL" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153ro', secret_access_key = 'c05153secret')" +echo 'identical value accepted under readonly' + +${CLICKHOUSE_CURL} -sS "$RO_URL" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153ro', secret_access_key = 'c05153other')" 2>&1 \ + | grep -c "Cannot modify 'custom_x' setting in readonly mode" diff --git a/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.reference b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.reference new file mode 100644 index 000000000000..f61a1ae7dddc --- /dev/null +++ b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.reference @@ -0,0 +1,11 @@ +data path outside, disk registered 0 +data path outside, directory not created +metadata path outside, disk registered 0 +s3 metadata path outside, disk registered 0 +escaping name, disk registered 0 +nested data path outside, disk registered 0 +encrypted path outside wrapped disk, disk registered 0 +encrypted over local disk outside base directory, disk registered 0 +data path inside 2 +s3 with default metadata path 2 +cache over config disk 2 diff --git a/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.sh b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.sh new file mode 100755 index 000000000000..dd311cc0bfc3 --- /dev/null +++ b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-distributed-cache +# no-fasttest: the S3 cases need the minio instance. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +name="${CLICKHOUSE_TEST_UNIQUE_NAME}" +server_path=$(${CLICKHOUSE_CLIENT} -q "SELECT path FROM system.disks WHERE name = 'default'") +inside="${CLICKHOUSE_DISKS_FILES}/${name}" +outside="${server_path}${name}_outside" +s3_args="endpoint = 'http://localhost:11111/test/${name}/', access_key_id = 'clickhouse', secret_access_key = 'clickhouse'" + +${CLICKHOUSE_CLIENT} -q " +CREATE TABLE t_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_outside', type = 'local_blob_storage', path = '${outside}/'); -- { serverError BAD_ARGUMENTS } +SELECT 'data path outside, disk registered', count() FROM system.disks WHERE name = '${name}_outside'; +" +test -d "${outside}" && echo "data path outside, directory created" || echo "data path outside, directory not created" + +${CLICKHOUSE_CLIENT} -q " +CREATE TABLE t_meta_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_meta_outside', type = 'local_blob_storage', path = '${inside}_meta/', metadata_path = '${outside}_meta/'); -- { serverError BAD_ARGUMENTS } +SELECT 'metadata path outside, disk registered', count() FROM system.disks WHERE name = '${name}_meta_outside'; + +CREATE TABLE t_s3_meta_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_s3_meta_outside', type = 's3', ${s3_args}, metadata_path = '${outside}_s3/'); -- { serverError BAD_ARGUMENTS } +SELECT 's3 metadata path outside, disk registered', count() FROM system.disks WHERE name = '${name}_s3_meta_outside'; + +CREATE TABLE t_escaping_name (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '../${name}_escape', type = 's3', ${s3_args}); -- { serverError BAD_ARGUMENTS } +SELECT 'escaping name, disk registered', count() FROM system.disks WHERE name = '../${name}_escape'; + +CREATE TABLE t_cache_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = cache, name = '${name}_cache_outside', path = '${name}_cache_outside', max_size = '10Mi', + disk = disk(name = '${name}_nested_outside', type = 'local_blob_storage', path = '${outside}_nested/')); -- { serverError BAD_ARGUMENTS } +SELECT 'nested data path outside, disk registered', count() FROM system.disks WHERE name = '${name}_nested_outside'; + +CREATE TABLE t_encrypted_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = encrypted, name = '${name}_encrypted_outside', disk = 'local_disk', path = '../../${name}_escape/', key = '1234567812345678'); -- { serverError BAD_ARGUMENTS } +SELECT 'encrypted path outside wrapped disk, disk registered', count() FROM system.disks WHERE name = '${name}_encrypted_outside'; + +CREATE TABLE t_encrypted_default (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = encrypted, name = '${name}_encrypted_default', disk = 'default', path = '${name}_encrypted/', key = '1234567812345678'); -- { serverError BAD_ARGUMENTS } +SELECT 'encrypted over local disk outside base directory, disk registered', count() FROM system.disks WHERE name = '${name}_encrypted_default'; + +CREATE TABLE t_inside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_inside', type = 'local_blob_storage', path = '${inside}/'); +INSERT INTO t_inside VALUES (1), (2); +SELECT 'data path inside', count() FROM t_inside; + +CREATE TABLE t_s3 (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_s3', type = 's3', ${s3_args}); +INSERT INTO t_s3 VALUES (1), (2); +SELECT 's3 with default metadata path', count() FROM t_s3; + +CREATE TABLE t_cache (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = cache, name = '${name}_cache', path = '${name}_cache', max_size = '10Mi', disk = 'local_disk'); +INSERT INTO t_cache VALUES (1), (2); +SELECT 'cache over config disk', count() FROM t_cache; +" diff --git a/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.reference b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.reference new file mode 100644 index 000000000000..2672ec645c5f --- /dev/null +++ b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.reference @@ -0,0 +1,6 @@ +count 100 +expired_left 0 +ids 1 199 100 +cols 150 150 150 +parts 1 +algo Vertical diff --git a/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.sql b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.sql new file mode 100644 index 000000000000..a504e087125a --- /dev/null +++ b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.sql @@ -0,0 +1,75 @@ +-- Tags: no-object-storage +-- An object-storage policy has no disk `default`, so the move TTL below could not be created there. + +-- A vertical TTL merge evaluates every TTL family's expression against the merged block, so the +-- inputs of the move and recompression TTLs must be merged too, not gathered. Without that the +-- merge throws `NOT_FOUND_COLUMN_IN_BLOCK` and the parts never merge. +-- +-- The rows TTL reads `d`, the recompression TTL reads `e` and the move TTL reads `f`: three +-- different columns, so none of them rides into the merged stream on another TTL's back. + +SET optimize_throw_if_noop = 0; + +DROP TABLE IF EXISTS t_ttl_vert_families; + +CREATE TABLE t_ttl_vert_families +( + id UInt64, + d DateTime, + e DateTime, + f DateTime, + c1 UInt64, + c2 UInt64, + c3 UInt64 +) +ENGINE = MergeTree +ORDER BY id +TTL d + INTERVAL 1 DAY DELETE, + e + INTERVAL 1 MONTH RECOMPRESS CODEC(ZSTD(1)), + f + INTERVAL 2 MONTH TO DISK 'default' +SETTINGS + min_bytes_for_wide_part = 0, + min_bytes_for_full_part_storage = 0, + enable_block_number_column = 0, + enable_block_offset_column = 0, + vertical_merge_algorithm_min_rows_to_activate = 1, + vertical_merge_algorithm_min_columns_to_activate = 1, + vertical_merge_optimize_ttl_delete = 1, + max_bytes_to_merge_at_max_space_in_pool = 1, + merge_with_ttl_timeout = 100000, + ratio_of_defaults_for_sparse_serialization = 1.0; + +-- Two parts, so the merge reads from the merging algorithm rather than short-circuiting a single +-- part. Even rows are expired by the rows TTL. `max_bytes_to_merge_at_max_space_in_pool = 1` keeps +-- the background pool off regular merges and the TTL blocker off TTL merges until both parts exist, +-- so the `OPTIMIZE` is the first merge logged. +SYSTEM STOP TTL MERGES t_ttl_vert_families; + +INSERT INTO t_ttl_vert_families +SELECT number, if(number % 2, now() + INTERVAL 1 YEAR, '2000-01-01 00:00:00'), now(), now(), 1, 1, 1 +FROM numbers(100); + +INSERT INTO t_ttl_vert_families +SELECT number + 100, if(number % 2, now() + INTERVAL 1 YEAR, '2000-01-01 00:00:00'), now(), now(), 2, 2, 2 +FROM numbers(100); + +SYSTEM START TTL MERGES t_ttl_vert_families; + +OPTIMIZE TABLE t_ttl_vert_families FINAL; + +SELECT 'count', count() FROM t_ttl_vert_families; +SELECT 'expired_left', count() FROM t_ttl_vert_families WHERE d + INTERVAL 1 DAY <= now(); +SELECT 'ids', min(id), max(id), countIf(id % 2 = 1) FROM t_ttl_vert_families; +SELECT 'cols', sum(c1), sum(c2), sum(c3) FROM t_ttl_vert_families; +SELECT 'parts', count() FROM system.parts + WHERE database = currentDatabase() AND table = 't_ttl_vert_families' AND active; + +SYSTEM FLUSH LOGS part_log; +-- Exclude `TTLDropMerge`: a part whose rows are all expired is dropped by a short-circuit that +-- always uses the `Horizontal` algorithm. +SELECT 'algo', merge_algorithm FROM system.part_log + WHERE database = currentDatabase() AND table = 't_ttl_vert_families' AND event_type = 'MergeParts' + AND merge_reason != 'TTLDropMerge' + ORDER BY event_time_microseconds LIMIT 1; + +DROP TABLE t_ttl_vert_families; diff --git a/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference new file mode 100644 index 000000000000..290dcff21a62 --- /dev/null +++ b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference @@ -0,0 +1,20 @@ +--- SHOW GRANTS +GRANT SELECT ON *.* TO grantor WITH GRANT OPTION +REVOKE SELECT ON d.t1 FROM grantor +REVOKE GRANT OPTION FOR SELECT ON d.t2 FROM grantor +REVOKE GRANT OPTION FOR SELECT ON d.zt2 FROM grantor +REVOKE SELECT ON db1.* FROM grantor +REVOKE GRANT OPTION FOR SELECT ON db2.* FROM grantor +REVOKE GRANT OPTION FOR SELECT ON zdb2.* FROM grantor +--- system.grants +d t1 SELECT 0 1 +d t2 SELECT 1 1 +d zt2 SELECT 1 1 +db1 \N SELECT 0 1 +db2 \N SELECT 1 1 +zdb2 \N SELECT 1 1 +\N \N SELECT 1 0 +--- the grant option cannot be passed on for a database whose grant option was revoked +GRANT SELECT ON db2.* TO victim1 +--- positive control: a database that was never revoked is still passed on with grant option +GRANT SELECT ON db3.* TO victim2 WITH GRANT OPTION diff --git a/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh new file mode 100755 index 000000000000..b6bd0e6c58d6 --- /dev/null +++ b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tests that "REVOKE GRANT OPTION FOR" is listed by SHOW GRANTS and by system.grants, and that the +# user can no longer pass the grant option on, also when another revoked database or table name +# shares a prefix with it. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +grantor="user05255_1_${CLICKHOUSE_DATABASE}_$RANDOM" +victim1="user05255_2_${CLICKHOUSE_DATABASE}_$RANDOM" +victim2="user05255_3_${CLICKHOUSE_DATABASE}_$RANDOM" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS $grantor, $victim1, $victim2" +${CLICKHOUSE_CLIENT} --query "CREATE USER $grantor, $victim1, $victim2" + +${CLICKHOUSE_CLIENT} --query "GRANT SELECT ON *.* TO $grantor WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "REVOKE SELECT ON db1.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON db2.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON zdb2.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE SELECT ON d.t1 FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON d.t2 FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON d.zt2 FROM $grantor" + +echo "--- SHOW GRANTS" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $grantor" | sed "s/$grantor/grantor/g" + +echo "--- system.grants" +${CLICKHOUSE_CLIENT} --query " + SELECT database, table, access_type, grant_option, is_partial_revoke + FROM system.grants WHERE user_name = '$grantor' ORDER BY database, table, access_type" + +echo "--- the grant option cannot be passed on for a database whose grant option was revoked" +${CLICKHOUSE_CLIENT} --user "$grantor" --query "GRANT CURRENT GRANTS(SELECT ON db2.*) TO $victim1 WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $victim1" | sed "s/$victim1/victim1/g" + +echo "--- positive control: a database that was never revoked is still passed on with grant option" +${CLICKHOUSE_CLIENT} --user "$grantor" --query "GRANT CURRENT GRANTS(SELECT ON db3.*) TO $victim2 WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $victim2" | sed "s/$victim2/victim2/g" + +${CLICKHOUSE_CLIENT} --query "DROP USER $grantor, $victim1, $victim2" diff --git a/tests/queries/0_stateless/05291_dictionary_access_check_before_load.reference b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.reference new file mode 100644 index 000000000000..365f397217bb --- /dev/null +++ b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.reference @@ -0,0 +1,119 @@ +NOT_LOADED +--- no grants +SELECT * FROM dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +DESCRIBE TABLE dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +SELECT dictGet('db.d', 'value', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT dictHas('db.d', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT count() FROM numbers(1) GROUP BY dictGet('db.d', 'value', number) SETTINGS enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +SELECT * FROM dictionary('d') +ACCESS_DENIED +NOT_LOADED +DESCRIBE TABLE dictionary('d') +ACCESS_DENIED +NOT_LOADED +SELECT dictGet('d', 'value', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT dictHas('d', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT count() FROM numbers(1) GROUP BY dictGet('d', 'value', number) SETTINGS enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +--- SELECT on a Dictionary table is not enough without a grant on the dictionary +SELECT * FROM w +ACCESS_DENIED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct' +ACCESS_DENIED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'hash' +ACCESS_DENIED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +EXPLAIN SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 1 +ACCESS_DENIED +NOT_LOADED +CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 1 +ACCESS_DENIED +NOT_LOADED +EXPLAIN SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +--- creating a Dictionary table needs access to the dictionary +CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(d) +ACCESS_DENIED +NOT_LOADED +--- SELECT is enough for the dictionary table function, but not for dictGet +SELECT dictGet('d', 'value', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +DESCRIBE TABLE dictionary('d') +id UInt64 +value String +SELECT * FROM dictionary('d') +1 a +LOADED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct', enable_analyzer = 1 +0 +1 a +LOADED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +0 +1 a +LOADED +--- dictGet +NOT_LOADED +SELECT dictGet('d', 'value', toUInt64(1)) +a +LOADED +NOT_LOADED +SELECT dictHas('db.d', toUInt64(1)) +1 +LOADED +NOT_LOADED +SELECT count() FROM numbers(1) GROUP BY dictGet('d', 'value', number) SETTINGS enable_analyzer = 0 +1 +LOADED +NOT_LOADED +SELECT * FROM dictionary('d') +1 a +LOADED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct' +0 +1 a +LOADED +NOT_LOADED +CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct' + +LOADED +NOT_LOADED +CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(db.d) + +LOADED +CREATE TABLE w_unqualified_by_user (id UInt64, value String) ENGINE = Dictionary(d) + +LOADED +1 a +LOADED diff --git a/tests/queries/0_stateless/05291_dictionary_access_check_before_load.sh b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.sh new file mode 100755 index 000000000000..7aa4a637cd6c --- /dev/null +++ b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Access rights must be checked before a dictionary is loaded, +# so a query without the required grants does not trigger the load. + +username="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +${CLICKHOUSE_CLIENT} -m --query " + DROP USER IF EXISTS ${username}; + CREATE TABLE src (id UInt64, value String) ENGINE = Memory; + INSERT INTO src VALUES (1, 'a'); + CREATE DICTIONARY d (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE TABLE w (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d); + SET check_table_dependencies = 0; + DETACH DICTIONARY d; + ATTACH DICTIONARY d; + CREATE USER ${username} NOT IDENTIFIED; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${username}; +" + +# The queries go over HTTP: starting a client for each of them makes the test too slow. +function query() +{ + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" --data-binary "$1" +} + +function status() +{ + query "SELECT status FROM system.dictionaries WHERE database = currentDatabase() AND name = '${1:-d}'" +} + +# Reattaching the dictionary resets its state to not loaded. The `Dictionary` tables depend on it, which would block +# a permanent detach. +function unload() +{ + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&check_table_dependencies=0" --data-binary "DETACH DICTIONARY d" + query "ATTACH DICTIONARY d" + status +} + +function as_user() +{ + echo "$1" | sed "s/${CLICKHOUSE_DATABASE}/db/g" + local output + output=$(${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&user=${username}" --data-binary "$1" 2>&1) + if grep -q ACCESS_DENIED <<< "${output}" + then + echo ACCESS_DENIED + else + echo "${output}" + fi +} + +status + +echo "--- no grants" +# Both a qualified name and an unqualified one resolved against the current database. +for dict in "${CLICKHOUSE_DATABASE}.d" "d" +do + as_user "SELECT * FROM dictionary('${dict}')" + status + as_user "DESCRIBE TABLE dictionary('${dict}')" + status + as_user "SELECT dictGet('${dict}', 'value', toUInt64(1))" + status + as_user "SELECT dictHas('${dict}', toUInt64(1))" + status + as_user "SELECT count() FROM numbers(1) GROUP BY dictGet('${dict}', 'value', number) SETTINGS enable_analyzer = 0" + status +done + +echo "--- SELECT on a Dictionary table is not enough without a grant on the dictionary" +query "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.w TO ${username}" +as_user "SELECT * FROM w" +status +# A join may use the dictionary directly as a key-value storage, check it is covered as well. +for settings in "join_algorithm = 'direct'" "join_algorithm = 'hash'" "join_algorithm = 'direct', enable_analyzer = 0" +do + as_user "SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS ${settings}" + status +done +# Queries that are only analyzed do not read the right table, but the join planning must not load the dictionary either. +query "GRANT CREATE VIEW ON ${CLICKHOUSE_DATABASE}.* TO ${username}" +for analyzer in 1 0 +do + as_user "EXPLAIN SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = ${analyzer}" + status + as_user "CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = ${analyzer}" + status +done + +echo "--- creating a Dictionary table needs access to the dictionary" +${CLICKHOUSE_CLIENT} -m --query " + GRANT CREATE TABLE ON ${CLICKHOUSE_DATABASE}.* TO ${username}; + GRANT TABLE ENGINE ON Dictionary TO ${username}; +" +as_user "CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d)" +status +# An unqualified name is resolved against the current database, like when the table is read. +as_user "CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(d)" +status + +echo "--- SELECT is enough for the dictionary table function, but not for dictGet" +query "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.d TO ${username}" +as_user "SELECT dictGet('d', 'value', toUInt64(1))" +status +as_user "DESCRIBE TABLE dictionary('d')" +as_user "SELECT * FROM dictionary('d')" +status +# The same rule applies to a direct join against a Dictionary table, with both analyzers. +for analyzer in 1 0 +do + unload + as_user "SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct', enable_analyzer = ${analyzer}" + status +done + +echo "--- dictGet" +${CLICKHOUSE_CLIENT} -m --query " + REVOKE SELECT ON ${CLICKHOUSE_DATABASE}.d FROM ${username}; + GRANT dictGet ON ${CLICKHOUSE_DATABASE}.d TO ${username}; +" +unload +as_user "SELECT dictGet('d', 'value', toUInt64(1))" +status +unload +as_user "SELECT dictHas('${CLICKHOUSE_DATABASE}.d', toUInt64(1))" +status +unload +as_user "SELECT count() FROM numbers(1) GROUP BY dictGet('d', 'value', number) SETTINGS enable_analyzer = 0" +status +unload +as_user "SELECT * FROM dictionary('d')" +status +unload +as_user "SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct'" +status +unload +as_user "CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct'" +status +# With access, creating a Dictionary table loads the dictionary to validate the columns. +unload +as_user "CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d)" +status +as_user "CREATE TABLE w_unqualified_by_user (id UInt64, value String) ENGINE = Dictionary(d)" +status +# Reading the table resolves the same dictionary. +query "SELECT * FROM w_unqualified_by_user" +status + +query "DROP USER ${username}" diff --git a/tests/queries/0_stateless/05292_dictionary_metadata_access_check.reference b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.reference new file mode 100644 index 000000000000..f2546d0a36ff --- /dev/null +++ b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.reference @@ -0,0 +1,47 @@ +--- no grants +SELECT dictGet('d', 'no_such_attribute', toUInt64(1)) +ACCESS_DENIED +DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1))) +ACCESS_DENIED +SELECT dictGet('d', 'value', number) FROM numbers(0) +ACCESS_DENIED +SELECT dictGetOrDefault('d', 'value', toUInt64(1), 'x') +ACCESS_DENIED +SELECT dictGetOrNull('d', 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictGetKeys('d', 'value', 'a') +ACCESS_DENIED +SELECT dictGetKeys('d', 'no_such_attribute', 'a') +ACCESS_DENIED +--- dictGet +DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1))) +dictGet(\'d\', \'value\', toUInt64(1)) String +SELECT dictGet('d', 'no_such_attribute', toUInt64(1)) +No such attribute +SELECT dictGetKeys('d', 'no_such_attribute', 'a') +has no attribute +--- missing dictionary, no grants +SELECT dictGet('no_such_dictionary', 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictGetKeys('no_such_dictionary', 'value', 'a') +ACCESS_DENIED +SELECT * FROM dictionary('no_such_dictionary') +ACCESS_DENIED +--- identifier, no grants +SELECT dictGet(d, 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictGet(no_such_dictionary, 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictHas(no_such_dictionary, toUInt64(1)) +ACCESS_DENIED +SELECT dictGetKeys(no_such_dictionary, 'value', 'a') +ACCESS_DENIED +--- missing dictionary, dictGet +SELECT dictGet('no_such_dictionary', 'value', toUInt64(1)) +not found +SELECT dictGetKeys('no_such_dictionary', 'value', 'a') +not found +SELECT * FROM dictionary('no_such_dictionary') +not found +SELECT dictGet(no_such_dictionary, 'value', toUInt64(1)) +not found diff --git a/tests/queries/0_stateless/05292_dictionary_metadata_access_check.sh b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.sh new file mode 100755 index 000000000000..3a3fbc5ba0f8 --- /dev/null +++ b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Without the `dictGet` grant, the dictionary definition (attributes, layout) must not be revealed, +# even when a query only needs the result type and does not execute the function. + +username="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +${CLICKHOUSE_CLIENT} -m --query " + DROP USER IF EXISTS ${username}; + CREATE TABLE src (id UInt64, value String) ENGINE = Memory; + CREATE DICTIONARY d (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE USER ${username} NOT IDENTIFIED; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${username}; +" + +function as_user() +{ + echo "$1" + local output + output=$(${CLICKHOUSE_CLIENT} --user "${username}" --query "$1" 2>&1) + if grep -q ACCESS_DENIED <<< "${output}" + then + echo ACCESS_DENIED + else + echo "${output}" + fi +} + +echo "--- no grants" +as_user "SELECT dictGet('d', 'no_such_attribute', toUInt64(1))" +as_user "DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1)))" +as_user "SELECT dictGet('d', 'value', number) FROM numbers(0)" +as_user "SELECT dictGetOrDefault('d', 'value', toUInt64(1), 'x')" +as_user "SELECT dictGetOrNull('d', 'value', toUInt64(1))" +as_user "SELECT dictGetKeys('d', 'value', 'a')" +as_user "SELECT dictGetKeys('d', 'no_such_attribute', 'a')" + +echo "--- dictGet" +${CLICKHOUSE_CLIENT} --query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.d TO ${username}" +as_user "DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1)))" +as_user "SELECT dictGet('d', 'no_such_attribute', toUInt64(1))" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|No such attribute|unexpected ACCESS_DENIED" | head -2 +as_user "SELECT dictGetKeys('d', 'no_such_attribute', 'a')" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|has no attribute|unexpected ACCESS_DENIED" | head -2 + +# A missing dictionary must look the same as an existing one without access. +${CLICKHOUSE_CLIENT} --query "REVOKE dictGet ON ${CLICKHOUSE_DATABASE}.d FROM ${username}" +echo "--- missing dictionary, no grants" +as_user "SELECT dictGet('no_such_dictionary', 'value', toUInt64(1))" +as_user "SELECT dictGetKeys('no_such_dictionary', 'value', 'a')" +as_user "SELECT * FROM dictionary('no_such_dictionary')" + +# The dictionary name can also be an identifier, which the analyzer resolves separately. +echo "--- identifier, no grants" +as_user "SELECT dictGet(d, 'value', toUInt64(1))" +as_user "SELECT dictGet(no_such_dictionary, 'value', toUInt64(1))" +as_user "SELECT dictHas(no_such_dictionary, toUInt64(1))" +as_user "SELECT dictGetKeys(no_such_dictionary, 'value', 'a')" + +echo "--- missing dictionary, dictGet" +${CLICKHOUSE_CLIENT} --query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.* TO ${username}" +for query in \ + "SELECT dictGet('no_such_dictionary', 'value', toUInt64(1))" \ + "SELECT dictGetKeys('no_such_dictionary', 'value', 'a')" \ + "SELECT * FROM dictionary('no_such_dictionary')" \ + "SELECT dictGet(no_such_dictionary, 'value', toUInt64(1))" +do + as_user "${query}" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|not found|unexpected ACCESS_DENIED" | head -2 +done + +${CLICKHOUSE_CLIENT} --query "DROP USER ${username}" diff --git a/tests/queries/0_stateless/05296_join_using_alias_outermost_join_only.reference b/tests/queries/0_stateless/05296_join_using_alias_outermost_join_only.reference new file mode 100644 index 000000000000..aba364259c5a --- /dev/null +++ b/tests/queries/0_stateless/05296_join_using_alias_outermost_join_only.reference @@ -0,0 +1,31 @@ +single JOIN: the alias is the key even when the left table has a column with the same name +2 2 7 +inner JOIN of two: the left column is the key +2 3 7 +2 0 +outermost JOIN of two: the alias is the key +2 2 7 +inner USING JOIN below the aliased outermost USING key +2 2 7 +three JOINs: inner keys from the left tables, the outermost key from the alias +110 120 2 2 7 +comma JOIN counts as a level +2 3 +ARRAY JOIN above the JOIN is not a level: the JOIN stays outermost +2 2 1 +2 2 2 +2 3 1 +a matcher inside the aliased key expression expands over the left side +(1,(1)) (1) +(1) (1) +(1) (1) +the key is computed before the joins of the left side: a column retyped by an inner USING keeps the type it is read with +(1) Tuple(UInt16) (1) Tuple(UInt16) +2 UInt32 2 UInt16 +join_use_nulls: the key is computed before the inner RIGHT JOIN makes the left columns nullable +2 Nullable(UInt16) 2 UInt16 +a subquery has its own join tree +2 2 7 +2 3 +the reported query: the projection refers to the right side of the inner JOIN +a x 3 2026-01-01 00:00:00 diff --git a/tests/queries/0_stateless/05296_join_using_alias_outermost_join_only.sql b/tests/queries/0_stateless/05296_join_using_alias_outermost_join_only.sql new file mode 100644 index 000000000000..66cba22d4722 --- /dev/null +++ b/tests/queries/0_stateless/05296_join_using_alias_outermost_join_only.sql @@ -0,0 +1,76 @@ +-- With `analyzer_compatibility_join_using_top_level_identifier` a `JOIN USING` identifier is resolved from an alias of the query. +-- The old analyzer rewrote a query with several JOINs into nested subqueries, so an inner JOIN never saw such an alias and +-- took the key from its left table. Only the outermost JOIN keeps the alias lookup; USING keys at different levels of the +-- join tree follow the same rule. + +SET enable_analyzer = 1; +SET analyzer_compatibility_join_using_top_level_identifier = 1; +SET joined_subquery_requires_alias = 0; + +SELECT 'single JOIN: the alias is the key even when the left table has a column with the same name'; +SELECT a + 1 AS b, t2.b AS right_b, t2.c FROM (SELECT 1 AS a, 3 AS b) t1 JOIN (SELECT 2 AS b, 7 AS c) t2 USING (b); + +SELECT 'inner JOIN of two: the left column is the key'; +SELECT a + 1 AS b, t2.b AS right_b, t2.c FROM (SELECT 1 AS a, 3 AS b) t1 JOIN (SELECT 3 AS b, 7 AS c) t2 USING (b) JOIN (SELECT 1 AS z) t3 ON 1 = 1; +-- The alias value would have matched the right side, the left column does not. +SELECT a + 1 AS b, t2.b AS right_b FROM (SELECT 1 AS a, 3 AS b) t1 LEFT JOIN (SELECT 2 AS b) t2 USING (b) JOIN (SELECT 1 AS z) t3 ON 1 = 1; +-- Without a left column the key of an inner JOIN cannot be resolved. +SELECT a + 1 AS b FROM (SELECT 1 AS a) t1 JOIN (SELECT 2 AS b) t2 USING (b) JOIN (SELECT 1 AS z) t3 ON 1 = 1; -- { serverError UNKNOWN_IDENTIFIER } + +SELECT 'outermost JOIN of two: the alias is the key'; +SELECT a + 1 AS b, t3.b AS right_b, t3.c FROM (SELECT 1 AS a) t1 JOIN (SELECT 1 AS z) t2 ON 1 = 1 JOIN (SELECT 2 AS b, 7 AS c) t3 USING (b); + +SELECT 'inner USING JOIN below the aliased outermost USING key'; +SELECT a + 1 AS b, t3.b AS right_b, t3.c FROM (SELECT 1 AS a, 10 AS k) t1 JOIN (SELECT 10 AS k) t2 USING (k) JOIN (SELECT 2 AS b, 7 AS c) t3 USING (b); + +SELECT 'three JOINs: inner keys from the left tables, the outermost key from the alias'; +SELECT k + 100 AS k, m + 100 AS m, a + 1 AS b, t4.b AS right_b, t4.c +FROM (SELECT 1 AS a, 10 AS k) t1 +JOIN (SELECT 10 AS k, 20 AS m) t2 USING (k) +JOIN (SELECT 20 AS m) t3 USING (m) +JOIN (SELECT 2 AS b, 7 AS c) t4 USING (b); + +SELECT 'comma JOIN counts as a level'; +SELECT a + 1 AS b, t2.b AS right_b FROM (SELECT 1 AS a, 3 AS b) t1 JOIN (SELECT 3 AS b) t2 USING (b), (SELECT 1 AS z) t3; + +SELECT 'ARRAY JOIN above the JOIN is not a level: the JOIN stays outermost'; +SELECT a + 1 AS b, t2.b AS right_b, x FROM (SELECT 1 AS a, 3 AS b, [1, 2] AS arr) t1 JOIN (SELECT 2 AS b) t2 USING (b) ARRAY JOIN arr AS x ORDER BY x; +-- A JOIN below an ARRAY JOIN that is itself below another JOIN is an inner JOIN. +SELECT a + 1 AS b, t2.b AS right_b, x FROM (SELECT 1 AS a, 3 AS b, [1] AS arr) t1 JOIN (SELECT 3 AS b) t2 USING (b) ARRAY JOIN arr AS x JOIN (SELECT 1 AS z) t3 ON 1 = 1; + +SELECT 'a matcher inside the aliased key expression expands over the left side'; +SELECT tuple(*) AS k, t2.k AS right_k FROM (SELECT 1 AS a) t1 JOIN (SELECT tuple(1) AS k) t2 USING (k); +SELECT tuple(t1.*) AS k, t2.k AS right_k FROM (SELECT 1 AS a) t1 JOIN (SELECT tuple(1) AS k) t2 USING (k); +SELECT tuple(t1.*) AS k, t3.k AS right_k FROM (SELECT 1 AS a) t1, (SELECT 1 AS z) t2 JOIN (SELECT tuple(1) AS k) t3 USING (k); + +SELECT 'the key is computed before the joins of the left side: a column retyped by an inner USING keeps the type it is read with'; +SELECT tuple(t1.a) AS k, toTypeName(k), t3.k AS right_k, toTypeName(right_k) +FROM (SELECT toUInt8(1) AS a) t1 JOIN (SELECT toUInt16(1) AS a) t2 USING (a) JOIN (SELECT tuple(toUInt16(1)) AS k) t3 USING (k); +-- An unqualified matcher expands the key column of the inner USING JOIN from both of its tables, as in PREWHERE, +-- so the expression has no single source table and is not a key. +SELECT tuple(*) AS k, toTypeName(k), t3.k AS right_k, toTypeName(right_k) +FROM (SELECT toUInt8(1) AS a) t1 JOIN (SELECT toUInt16(1) AS a) t2 USING (a) JOIN (SELECT tuple(toUInt16(1)) AS k) t3 USING (k); -- { serverError UNKNOWN_IDENTIFIER } +SELECT a + 1 AS b, toTypeName(b), t3.b AS right_b, toTypeName(right_b) +FROM (SELECT toUInt8(1) AS a) t1 JOIN (SELECT toUInt16(1) AS a) t2 USING (a) JOIN (SELECT toUInt16(2) AS b) t3 USING (b); + +SELECT 'join_use_nulls: the key is computed before the inner RIGHT JOIN makes the left columns nullable'; +SET join_use_nulls = 1; +SELECT a + 1 AS b, toTypeName(b), t3.b AS right_b, toTypeName(right_b) +FROM (SELECT 1 AS a, 10 AS x) t1 RIGHT JOIN (SELECT 10 AS x) t2 USING (x) JOIN (SELECT 2 AS b) t3 USING (b); +SET join_use_nulls = 0; + +SELECT 'a subquery has its own join tree'; +SELECT s.b, s.right_b, t.c FROM (SELECT a + 1 AS b, t2.b AS right_b FROM (SELECT 1 AS a, 3 AS b) t1 JOIN (SELECT 2 AS b) t2 USING (b)) s JOIN (SELECT 7 AS c) t ON 1 = 1 JOIN (SELECT 1 AS z) u ON 1 = 1; +SELECT s.b, s.right_b FROM (SELECT a + 1 AS b, t2.b AS right_b FROM (SELECT 1 AS a, 3 AS b) t1 JOIN (SELECT 3 AS b) t2 USING (b) JOIN (SELECT 1 AS z) t3 ON 1 = 1) s; + +SELECT 'the reported query: the projection refers to the right side of the inner JOIN'; +WITH m AS (SELECT 'a' AS symbol, 'x' AS lp, 1 AS pos), + b AS (SELECT 'a' AS symbol, 'x' AS lp, 2 AS net_volume), + dttm AS (SELECT toDateTime('2026-01-01 00:00:00') AS Dttm) +SELECT if(m.symbol = '', b.symbol, m.symbol) AS symbol, + if(m.lp = '', b.lp, m.lp) AS lp, + b.net_volume + m.pos AS pos, + dttm.Dttm AS last_updated +FROM m +FULL OUTER JOIN b USING (symbol, lp) +FULL OUTER JOIN dttm ON 1 = 1; diff --git a/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.reference b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.reference new file mode 100644 index 000000000000..47a0f3741797 --- /dev/null +++ b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.reference @@ -0,0 +1,2 @@ +1 +0 0 1 diff --git a/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.sh b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.sh new file mode 100755 index 000000000000..41f4a0fc8560 --- /dev/null +++ b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The source of an `HTTP` dictionary is shown in `system.dictionaries` without the userinfo of its url. +user="user_${CLICKHOUSE_DATABASE}" +$CLICKHOUSE_CLIENT -q "DROP USER IF EXISTS ${user}" +$CLICKHOUSE_CLIENT -q "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'plain_dictionary_password'" + +url="http://${user}:plain_dictionary_password@${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?query=SELECT+number,toString(number)+FROM+numbers(2)+FORMAT+TabSeparated" +$CLICKHOUSE_CLIENT -q "CREATE DICTIONARY dict_http (key UInt64, value String) PRIMARY KEY key SOURCE(HTTP(URL '${url}' FORMAT 'TabSeparated')) LIFETIME(0) LAYOUT(FLAT())" +$CLICKHOUSE_CLIENT -q "SELECT dictGet('dict_http', 'value', 1)" +$CLICKHOUSE_CLIENT -q "SELECT countSubstrings(source, 'plain_dictionary_password'), countSubstrings(source, '${user}'), countSubstrings(source, '[HIDDEN]') FROM system.dictionaries WHERE database = currentDatabase() AND name = 'dict_http'" + +$CLICKHOUSE_CLIENT -q "DROP DICTIONARY dict_http" +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference new file mode 100644 index 000000000000..a2e64b66af38 --- /dev/null +++ b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference @@ -0,0 +1,27 @@ +2 +3 +1 +1 +1 0 +tq_a delete +tq_b delete +tq_a keep +tq_b keep +tq_a delete +tq_b delete +tq_a keep +tq_b keep +keep +tq_a 1 +tq_b 1 +1 +1 +tq_s1 keep +tq_s2 keep +keep +tag +keep keep +keep keep +5 +2 +1 diff --git a/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql new file mode 100644 index 000000000000..e4850d75a65d --- /dev/null +++ b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql @@ -0,0 +1,234 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` and `AzureQueue` engines are not built in the fast test. +-- zookeeper: the immutable part of the queue metadata lives under `keeper_path` in keeper. + +-- A queue table stores the settings listed in `ObjectStorageQueueTableMetadata::isStoredInKeeper` +-- under its `keeper_path` (docs/reference/engines/table-engines/integrations/s3queue.mdx, section +-- `keeper_path`). A second table pointed at the same path must agree with what is already stored +-- there, so each of the immutable fields below is rejected with `METADATA_MISMATCH` on its own. +-- The object storage is never contacted: the metadata check happens while the engine is built. + +DROP TABLE IF EXISTS tq_base; +DROP TABLE IF EXISTS tq_bucket_base; + +CREATE TABLE tq_base (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +-- `after_processing`: stored as 'keep', local 'delete'. +CREATE TABLE tq1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + after_processing = 'delete'; -- { serverError METADATA_MISMATCH } + +-- `bucketing_mode`: stored as 'path', local 'partition'. A 'partition' bucketing mode hashes the +-- partition key instead of the path, so `bucketing_mode = 'partition'` is rejected outright unless a +-- partitioning mode is set too. To vary `bucketing_mode` alone, a second keeper path already stores +-- `partitioning_mode = 'regex'`, which needs no experimental setting. +CREATE TABLE tq_bucket_base (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_bucket', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', partition_component = 'part', + processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +CREATE TABLE tq2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_bucket', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', partition_component = 'part', + bucketing_mode = 'partition'; -- { serverError METADATA_MISMATCH } + +-- `partitioning_mode`: stored as 'none', local 'regex'. The stored `partition_regex` and +-- `partition_component` differ too, but the partitioning mode is compared first. +CREATE TABLE tq3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', + partition_component = 'part'; -- { serverError METADATA_MISMATCH } + +-- `partition_regex`: stored empty, local set. +CREATE TABLE tq4 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partition_regex = '(?P.+)'; -- { serverError METADATA_MISMATCH } + +-- `partition_component`: stored empty, local set. +CREATE TABLE tq5 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partition_component = 'part'; -- { serverError METADATA_MISMATCH } + +-- `tracked_files_limit`: stored as the default 1000, local 7. +CREATE TABLE tq6 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + tracked_files_limit = 7; -- { serverError METADATA_MISMATCH } + +-- `tracked_files_ttl_sec`: stored as the default 0, local 60. +CREATE TABLE tq7 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + tracked_file_ttl_sec = 60; -- { serverError METADATA_MISMATCH } + +-- `last_processed_path`: stored empty, local set. +CREATE TABLE tq8 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + last_processed_path = 'a.csv'; -- { serverError METADATA_MISMATCH } + +-- `source`: stored path `05366_queue/*`, local path `05366_other/*`. +CREATE TABLE tq9 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_other/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366'; -- { serverError METADATA_MISMATCH } + +-- `source`: bucket `test0` with path `5366_queue/*` is another source than bucket `test` with path `05366_queue/*`. +CREATE TABLE tq10 (x String) ENGINE = S3Queue('http://localhost:11111/test0/5366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366'; -- { serverError METADATA_MISMATCH } + +-- Every mismatching table was rejected, so only the two base tables exist. +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name LIKE 'tq%'; + +-- The check is selective: a table that agrees on all of the immutable fields joins the same path. +CREATE TABLE tq_same (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name LIKE 'tq%'; + +DROP TABLE tq_same; +DROP TABLE tq_bucket_base; +DROP TABLE tq_base; + +-- An `AzureQueue` and an `S3Queue` with the same endpoint, bucket and path read different storages. +CREATE TABLE tq_type_azure (x String) ENGINE = AzureQueue('http://localhost:11111', 'test', '05366_type/*', 'devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_type'; +CREATE TABLE tq_type_s3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_type/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_type'; -- { serverError METADATA_MISMATCH } +DROP TABLE tq_type_azure; + +-- The user info of a URL is not a part of the source. +CREATE TABLE tq_u (x String) ENGINE = S3Queue('http://user:secret@localhost:11111/test/05366_u/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info'; +CREATE TABLE tq_u2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_u/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info'; +DROP TABLE tq_u2; DROP TABLE tq_u; +-- Paths that differ only in a part like `&sig=` are different sources. +CREATE TABLE tq_sig (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_root&sig=a/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sig'; +CREATE TABLE tq_sig_z (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_root&sig=z/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sig'; -- { serverError METADATA_MISMATCH } +DROP TABLE tq_sig; + +-- Azure forms that have a source: a scheme in upper case, and an `abfss` URL with a separate SAS. +CREATE TABLE tq_az_upper (x String) ENGINE = AzureQueue('HTTP://localhost:11111', 'test', '05366_upper/*', 'devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_upper'; +CREATE TABLE tq_az_sas (x String) ENGINE = AzureQueue('abfss://cont@acc.dfs.core.windows.net/05366_sas/*.csv', 'sv=1&sig=2') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sas'; +SELECT JSONExtractString(value, 'source_hash') != '' FROM system.zookeeper WHERE path IN ('/clickhouse/' || currentDatabase() || '/05366_upper', '/clickhouse/' || currentDatabase() || '/05366_sas') AND name = 'metadata' ORDER BY path; +DROP TABLE tq_az_upper; +DROP TABLE tq_az_sas; + +-- `send_logs_level` keeps the warnings of the attached tables, and the errors of the refused queries, out of the test output. +SET send_logs_level = 'fatal'; + +CREATE TABLE tq_a (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_shared/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1; +CREATE TABLE tq_b (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_shared/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1, after_processing = 'keep'; +-- Keeper has only a hash of the source. +SELECT JSONExtractString(value, 'source_hash') != '', value LIKE '%05366_shared%' FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; + +-- Tables with the same `keeper_path` share `after_processing`: after the `ALTER` of `tq_a` both tables have `delete`, +-- while `tq_b` still has `keep` in its definition. +ALTER TABLE tq_a MODIFY SETTING after_processing = 'delete'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +-- Set `keep` in keeper, as the initiator of a `Replicated` database does before this server runs the query: only the copy of +-- this server still has `delete`, and the `ALTER` to `keep` below must still change it. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"delete"', '"after_processing":"keep"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +-- `tq_b` already has `keep` in its definition, but an `ALTER` or a `RESET` to `keep` must still change the queue. +-- The same holds for `tq_a`, whose definition already has `delete`. +ALTER TABLE tq_b MODIFY SETTING after_processing = 'keep'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +ALTER TABLE tq_a MODIFY SETTING after_processing = 'delete'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +ALTER TABLE tq_b RESET SETTING after_processing; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +-- Leave `keep` in the definition of `tq_a` too, so that both tables can be attached again below. +ALTER TABLE tq_a MODIFY SETTING after_processing = 'keep'; +-- The same holds for any setting stored in keeper that an `ALTER` can change, e.g. `processing_threads_num`. +ALTER TABLE tq_a MODIFY SETTING processing_threads_num = 2; +ALTER TABLE tq_b MODIFY SETTING processing_threads_num = 1; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'processing_threads_num' ORDER BY table; + +-- A setting that the mode does not allow to change can still be repeated with the value of the definition, +-- also when the queue uses the value of another table (`tq_o1` uses 4 threads of `tq_o`). +CREATE TABLE tq_o (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_o/*', NOSIGN, 'CSV') SETTINGS mode = 'ordered', keeper_path = '/clickhouse/{database}/05366_o', processing_threads_num = 4; +CREATE TABLE tq_o1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_o/*', NOSIGN, 'CSV') SETTINGS mode = 'ordered', keeper_path = '/clickhouse/{database}/05366_o', processing_threads_num = 1; +ALTER TABLE tq_o MODIFY SETTING processing_threads_num = 4; +ALTER TABLE tq_o1 MODIFY SETTING processing_threads_num = 1, polling_max_timeout_ms = 2000; +SELECT create_table_query LIKE '%processing_threads_num = 1%polling_max_timeout_ms = 2000%' FROM system.tables WHERE database = currentDatabase() AND name = 'tq_o1'; +ALTER TABLE tq_o MODIFY SETTING processing_threads_num = 5; -- { serverError SUPPORT_IS_DISABLED } +DROP TABLE tq_o; +DROP TABLE tq_o1; + +-- `parallel_inserts` is not stored in keeper, so repeating its value next to another setting changes only the other one. +CREATE TABLE tq_p (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_p/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_p', parallel_inserts = 1; +ALTER TABLE tq_p MODIFY SETTING parallel_inserts = 1, polling_max_timeout_ms = 2000; +SELECT create_table_query LIKE '%parallel_inserts = 1%polling_max_timeout_ms = 2000%' FROM system.tables WHERE database = currentDatabase() AND name = 'tq_p'; +DROP TABLE tq_p; + +-- `after_processing` is still checked when a table is attached, as on master. A table that fails to attach cannot be +-- detached again in a `Replicated` database, so this uses an `Atomic` one. +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} ENGINE = Atomic; +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale', after_processing = 'keep'; +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale', after_processing = 'keep'; +-- After the `ALTER` of `tq_s1`, `tq_s2` still has `keep` in its definition and keeper has `delete`. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'delete'; +DETACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; -- { serverError METADATA_MISMATCH } +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'keep'; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() || '_1' AND table IN ('tq_s1', 'tq_s2') AND name = 'after_processing' ORDER BY table; + +-- Set `after_processing` to `keep` directly in keeper, as another server would, while the copy of this server has `delete`. +-- Then a reattached table and a new table fail instead of taking the outdated `delete`. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'delete'; +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2 MODIFY SETTING after_processing = 'delete'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"delete"', '"after_processing":"keep"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +DETACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; -- { serverError METADATA_MISMATCH } +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale'; -- { serverError METADATA_MISMATCH } +-- An `ALTER` of another setting needs no `WRITE` grant, so it must not write the outdated `delete` of this server back to keeper. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING polling_max_timeout_ms = 2000; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +-- An `ALTER` of `after_processing` itself is written to keeper. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'tag', after_processing_tag_key = 'k', after_processing_tag_value = 'v'; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} SYNC; + +-- Set `delete` directly in keeper, as another server would, while the definition and the copy of this server have +-- `keep`. An explicit `keep` must still reach keeper, by a `MODIFY` and by a `RESET`. +CREATE TABLE tq_k (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_k/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_k', after_processing = 'keep'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"keep"', '"after_processing":"delete"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k MODIFY SETTING after_processing = 'keep'; +SELECT JSONExtractString(value, 'after_processing'), (SELECT value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table = 'tq_k' AND name = 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"keep"', '"after_processing":"delete"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k RESET SETTING after_processing; +SELECT JSONExtractString(value, 'after_processing'), (SELECT value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table = 'tq_k' AND name = 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +-- An `ALTER` changes only the settings it names: `loading_retries` set by another server stays in keeper. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"loading_retries":10', '"loading_retries":5') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k MODIFY SETTING polling_max_timeout_ms = 2000; +SELECT JSONExtractUInt(value, 'loading_retries') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +DROP TABLE tq_k; + +-- Change the source in keeper: the tables must still attach, with a warning. +DETACH TABLE tq_a; DETACH TABLE tq_b; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpOne(value, '"source_hash":"[^"]*"', '"source_hash":"00"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +ATTACH TABLE tq_b; ATTACH TABLE tq_a; +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name IN ('tq_a', 'tq_b'); + +-- A named collection can change without an `ALTER` of the table, so a table that uses one must still match the source +-- in keeper when it attaches. Changing the source in keeper has the same effect as changing the collection. +CREATE TABLE tq_nc (x String) ENGINE = S3Queue(s3_conn, filename = '05366_nc/*', format = 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_nc'; +DETACH TABLE tq_nc; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpOne(value, '"source_hash":"[^"]*"', '"source_hash":"00"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_nc' AND name = 'metadata'; +ATTACH TABLE tq_nc; -- { serverError METADATA_MISMATCH } +-- Without a source in keeper, as in metadata of an older version, the table attaches and writes its source there. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpAll(value, ',"source_hash":"[^"]*"', '') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_nc' AND name = 'metadata'; +ATTACH TABLE tq_nc; +DROP TABLE tq_nc; + +-- Remove `source` from keeper, as in metadata of an older version: the first attached table writes it back. +-- A new table must not join such metadata, because it could belong to another source. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpAll(value, ',"source_hash":"[^"]*"', '') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +DETACH TABLE tq_a; DETACH TABLE tq_b; +CREATE TABLE tq_c (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_c/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1; -- { serverError METADATA_MISMATCH } +ATTACH TABLE tq_b; ATTACH TABLE tq_a; +SELECT JSONExtractString(value, 'source_hash') NOT IN ('', '00') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; + +DROP TABLE tq_b; +DROP TABLE tq_a; diff --git a/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.reference b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.reference new file mode 100644 index 000000000000..74d9aa4e2d8f --- /dev/null +++ b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.reference @@ -0,0 +1,70 @@ +1 q 1 +1 \N 1 +2 p 1 +2 \N 1 +\N \N 2 +3 +1 q 1 +1 \N 1 +2 p 1 +2 \N 1 +\N \N 2 +1 [] 1 +1 [3] 1 +2 [] 1 +2 [2] 1 +\N [] 2 +0 q 1 +0 \N 1 +1 q 1 +1 \N 1 +2 p 1 +2 \N 1 +3 q 1 +3 \N 1 +\N \N 4 +0 q +1 q +2 p +3 q +1 +3 +5 +0 +2 +4 +1 u +3 w +5 w +0 y +2 y +4 y +1 +(0) 4 +(1) 3 +(2) 3 +\N 10 +0 (0) +1 (1) +0 \N +1 \N +\N \N +(0) 4 +(1) 3 +(2) 3 +(0) 4 +(0) 10 +(1) 3 +(2) 3 +(0) 4 +(1) 3 +(2) 3 +\N 10 +(0,0) 2 +(0,1) 2 +(0,2) 2 +(1,0) 2 +(1,1) 2 +(1,2) 2 +\N 12 +0 diff --git a/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.sql b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.sql new file mode 100644 index 000000000000..3c72fe4002e1 --- /dev/null +++ b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.sql @@ -0,0 +1,32 @@ +-- An if chain or an ORDER BY tuple that contains a GROUP BY key reads the key from the aggregation result. + +SET enable_analyzer = 1; +SET optimize_if_transform_strings_to_enum = 0; + +-- A constant-condition `if` key nested in an `if` chain (#125803). +SELECT n, if(n = 5, toString(n), if(1, if(n > 1, 'p', 'q'), 'z')) AS e, count() FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(1, if(n > 1, 'p', 'q'), 'z')) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT count() FROM (SELECT n, if(n = 5, toString(n), if(1, if(n > 1, 'p', 'q'), 'z')) AS e FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(1, if(n > 1, 'p', 'q'), 'z')) HAVING e IS NULL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1); + +-- A plain `if` key nested in an `if` chain. +SELECT n, if(n = 5, toString(n), if(n > 1, 'p', 'q')) AS e, count() FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(n > 1, 'p', 'q')) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT n, if(n = 5, [toUInt8(n)], if(n > 1, [2], [3])) AS e, count() FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(n > 1, [2], [3])) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT n, if(n = 5, toString(n), if(m > 1, 'p', 'q')) AS e, count() FROM (SELECT number AS n, number % 3 AS m FROM numbers(4)) GROUP BY ROLLUP(n, if(m > 1, 'p', 'q')) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT n, if(n = 5, toString(n), if(m > 1, 'p', 'q')) AS e FROM (SELECT number AS n, number % 3 AS m FROM numbers(4)) GROUP BY n, if(m > 1, 'p', 'q') ORDER BY n SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 1; + +-- A key whose `then` branch is itself a chain. +SELECT n FROM (SELECT number AS n, number % 2 = 1 AS a, number % 3 = 1 AS p, number % 5 = 1 AS q FROM numbers(6)) GROUP BY n, if(a, if(p, 'u', if(q, 'v', 'w')), 'y') ORDER BY if(n = 5, 'x', if(a, if(p, 'u', if(q, 'v', 'w')), 'y')), n SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 1; +SELECT n, if(a, if(p, 'u', if(q, 'v', 'w')), 'y') AS k FROM (SELECT number AS n, number % 2 = 1 AS a, number % 3 = 1 AS p, number % 5 = 1 AS q FROM numbers(6)) GROUP BY n, k ORDER BY if(n = 5, 'x', k), n SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 1; + +-- A chain without a key is still rewritten. +SELECT count() FROM (EXPLAIN QUERY TREE SELECT n, if(n = 1, 'a', if(n = 2, 'b', 'c')) FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n) SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1) WHERE explain ILIKE '%function_name: multiIf%'; + +-- A tuple key in ORDER BY (#125804). +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY ROLLUP(k) ORDER BY k SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; +SELECT a, if(1, tuple(a), tuple(0)) AS k FROM (SELECT number % 2 AS a FROM numbers(4)) GROUP BY ROLLUP(a, k) ORDER BY k, a SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY k ORDER BY k SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY ROLLUP(k) ORDER BY k SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY CUBE(k) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a, b), tuple(0, 0)) AS k, count() FROM (SELECT number % 2 AS a, number % 3 AS b FROM numbers(12)) GROUP BY GROUPING SETS ((k), ()) ORDER BY k SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; + +-- A tuple of keys that is not itself a key is still split. +SELECT count() FROM (EXPLAIN QUERY TREE SELECT a, b FROM (SELECT number % 2 AS a, number % 3 AS b FROM numbers(12)) GROUP BY ROLLUP(a, b) ORDER BY tuple(a, b) SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0) WHERE explain ILIKE '%function_name: tuple%'; diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference index e5046dab0a10..e1c3ed4e18d6 100644 --- a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -7,6 +7,8 @@ settings that are not a destination: allowed -- ALTER with WRITE on S3 limited by a URL filter -- ALTER with WRITE on S3 destination with WRITE on S3: allowed +after_processing = 'delete' with WRITE on S3: allowed +after_processing = 'delete' in a Replicated database with WRITE on S3: allowed empty destination without WRITE on S3: allowed -- ALTER with WRITE on S3, restricted by a row policy empty destination with a row policy: allowed @@ -26,6 +28,7 @@ table without a destination: created 0 -- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 CREATE AS with WRITE on S3: created +after_processing = 'delete' with WRITE on S3: created materialized view with WRITE on S3: created RESTORE with WRITE on S3: restored RESTORE ON CLUSTER with WRITE on S3: restored diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh index 5699f7262195..1f5f12aad788 100755 --- a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -12,6 +12,7 @@ # `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) # source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. # `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. +# `after_processing` = `delete`, `move` or `tag` modifies the source files, so it also needs `WRITE` on the source. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -25,6 +26,7 @@ src="http://localhost:11111/test/${db}_move_src/" dst="http://localhost:11111/test/${db}_move_dst/" backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +backup_src="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_src')" keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" @@ -33,6 +35,9 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_alias SYNC; DROP TABLE IF EXISTS ${db}.t SYNC; DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_delete SYNC; + DROP TABLE IF EXISTS ${db}.t_src SYNC; + DROP TABLE IF EXISTS ${db}.t_src_other SYNC; DROP TABLE IF EXISTS ${db}.t_as SYNC; DROP TABLE IF EXISTS ${db}.t_as_src SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; @@ -42,6 +47,7 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_backup SYNC; DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP DATABASE IF EXISTS ${db}_replicated SYNC; DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; DROP USER IF EXISTS ${user_alter}, ${user_create}; " @@ -102,6 +108,18 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " -- { serverError ACCESS_DENIED } " +# `delete`, `move` and `tag` modify the source files, so they need `WRITE` on `S3` too. +for action in delete move tag; do + $CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing = '${action}' + -- { serverError ACCESS_DENIED } + " +done +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" + echo "-- ALTER ON CLUSTER is rejected by the initiator" $CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" @@ -109,6 +127,10 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} -- { serverError ACCESS_DENIED } " +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" @@ -143,6 +165,28 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} " && echo "destination with WRITE on S3: allowed" +# `AzureQueue` also has `after_processing`, but an `S3Queue` table needs no grant on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing = 'delete' +" && echo "after_processing = 'delete' with WRITE on S3: allowed" +$CLICKHOUSE_CLIENT -q "ALTER TABLE ${db}.t MODIFY SETTING after_processing = 'keep'" +# With `ON CLUSTER` the table on another host may be an `AzureQueue`, so both grants are needed. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" +# In a `Replicated` database the initiator checks the same grants. +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE DATABASE ${db}_replicated ENGINE = Replicated('/test/05441_${db}', 's1', 'r1'); + CREATE TABLE ${db}_replicated.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_replicated'; + GRANT ALTER SETTINGS, SELECT ON ${db}_replicated.t TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}_replicated.t MODIFY SETTING after_processing = 'delete' +" && echo "after_processing = 'delete' in a Replicated database with WRITE on S3: allowed" +$CLICKHOUSE_CLIENT -q "DROP DATABASE ${db}_replicated SYNC" + # Resetting the destination disables the move, so it needs no grant for a destination. $CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" $CLICKHOUSE_CLIENT --user "${user_alter}" -q " @@ -181,6 +225,10 @@ $CLICKHOUSE_CLIENT -q " ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} -- { serverError NOT_IMPLEMENTED } " +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing = 'delete' + -- { serverError NOT_IMPLEMENTED } +" $CLICKHOUSE_CLIENT -q " ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 " && echo "settings that are not a destination through an alias: allowed" @@ -206,6 +254,15 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -q " after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' -- { serverError ACCESS_DENIED } " +# `CREATE` with `delete`, `move` or `tag` needs `WRITE` on the source too. +for action in delete move tag; do + $CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = '${action}', + after_processing_move_prefix = 'p', after_processing_tag_key = 'k', after_processing_tag_value = 'v' + -- { serverError ACCESS_DENIED } + " +done # The same CREATE without a destination, or with an empty one, needs no grant for it. $CLICKHOUSE_CLIENT --user "${user_create}" -q " @@ -321,6 +378,20 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -m -q " SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; " +# `RESTORE` is checked like `CREATE`: a queue with a different source cannot use an existing `keeper_path`. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_src (x UInt8) ENGINE = S3Queue('${dst}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_src'; + BACKUP TABLE ${db}.t_src TO ${backup_src} FORMAT Null; + DROP TABLE ${db}.t_src SYNC; + CREATE TABLE ${db}.t_src_other (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_src'; +" +$CLICKHOUSE_CLIENT -q " + RESTORE TABLE ${db}.t_src FROM ${backup_src} SETTINGS structure_only = 1 FORMAT Null + -- { serverError METADATA_MISMATCH } +" + echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" # The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. @@ -328,6 +399,10 @@ $CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_create}" $CLICKHOUSE_CLIENT --user "${user_create}" -q " CREATE TABLE ${db}.t_as AS ${db}.t_as_src " && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_delete (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_delete', after_processing = 'delete' +" && echo "after_processing = 'delete' with WRITE on S3: created" $CLICKHOUSE_CLIENT --user "${user_create}" -q " CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', @@ -363,6 +438,9 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_alias SYNC; DROP TABLE IF EXISTS ${db}.t SYNC; DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_delete SYNC; + DROP TABLE IF EXISTS ${db}.t_src SYNC; + DROP TABLE IF EXISTS ${db}.t_src_other SYNC; DROP TABLE IF EXISTS ${db}.t_as SYNC; DROP TABLE IF EXISTS ${db}.t_as_src SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; @@ -372,6 +450,7 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_backup SYNC; DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP DATABASE IF EXISTS ${db}_replicated SYNC; DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; DROP USER IF EXISTS ${user_alter}, ${user_create}; " diff --git a/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.reference b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.reference new file mode 100644 index 000000000000..39f55ad38c86 --- /dev/null +++ b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.reference @@ -0,0 +1,5 @@ +0 +5 +5 +5 +5 diff --git a/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.sh b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.sh new file mode 100755 index 000000000000..c7e3dae2f5e5 --- /dev/null +++ b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database, no-fasttest, no-shared-merge-tree +# no-replicated-database: the explicit ZooKeeper path is used as is +# no-shared-merge-tree: relies on the ZooKeeper layout of ReplicatedMergeTree + +# The cleanup thread removes the expired deduplication entries in batches. Check that +# - more expired entries than fit in one batch are all removed, +# - an expired entry with children (a leftover of previous server versions) is removed too, +# - the entries inside the window are kept, so the inserts that are still in the window are deduplicated. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +CLICKHOUSE_TEST_ZOOKEEPER_PREFIX="${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_DATABASE}" +ZK_PATH="/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_dedup_cleanup_batches" + +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_dedup_cleanup_batches SYNC" +$CLICKHOUSE_CLIENT --query " + CREATE TABLE t_dedup_cleanup_batches (n UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_dedup_cleanup_batches', '{replica}') + ORDER BY n + SETTINGS replicated_deduplication_window = 5, cleanup_delay_period = 1, cleanup_delay_period_random_add = 0, cleanup_thread_preferred_points_per_iteration = 0" + +# Collect the expired entries first, so that the cleanup thread usually removes them in one pass. +# `SYSTEM STOP CLEANUP` does not wait for an iteration that already runs, so the results do not depend on it. +$CLICKHOUSE_CLIENT --query "SYSTEM STOP CLEANUP t_dedup_cleanup_batches" + +# The cleanup only uses the creation order of the entries, so the expired entries can be created directly: +# 250 entries are more than two batches of 100 removals. They are older than the inserts below, so they are expired. +$CLICKHOUSE_CLIENT --async_insert=0 --query " + INSERT INTO system.zookeeper (path, name, value) + SELECT '$ZK_PATH/deduplication_hashes', 'expired_' || toString(number), '' FROM numbers(250)" + +# A leftover entry with a child. +$CLICKHOUSE_CLIENT --async_insert=0 --query "INSERT INTO system.zookeeper (path, name, value) VALUES ('$ZK_PATH/deduplication_hashes', 'leftover', '')" +$CLICKHOUSE_CLIENT --async_insert=0 --query "INSERT INTO system.zookeeper (path, name, value) VALUES ('$ZK_PATH/deduplication_hashes/leftover', 'child', '')" + +# One entry per block: 5 blocks fill the window. +INSERT_SETTINGS=(--insert_keeper_fault_injection_probability=0 --max_insert_threads=1 --max_block_size=1 --min_insert_block_size_rows=1 --min_insert_block_size_bytes=0) +$CLICKHOUSE_CLIENT "${INSERT_SETTINGS[@]}" --insert_deduplication_token=recent --query "INSERT INTO t_dedup_cleanup_batches SELECT number FROM numbers(5)" + +COUNT_EXPIRED="SELECT count() FROM system.zookeeper WHERE path = '$ZK_PATH/deduplication_hashes' AND (name LIKE 'expired\_%' OR name = 'leftover')" +$CLICKHOUSE_CLIENT --query "SYSTEM START CLEANUP t_dedup_cleanup_batches" + +for _ in {1..300} +do + [ "$($CLICKHOUSE_CLIENT --query "$COUNT_EXPIRED")" -eq 0 ] && break + sleep 0.2 +done + +$CLICKHOUSE_CLIENT --query "$COUNT_EXPIRED" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.zookeeper WHERE path = '$ZK_PATH/deduplication_hashes'" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM t_dedup_cleanup_batches" + +# All 5 blocks are still in the window, so they are deduplicated. The insert adds no entries, so the cleanup +# thread that still runs cannot change the result. +$CLICKHOUSE_CLIENT "${INSERT_SETTINGS[@]}" --insert_deduplication_token=recent --query "INSERT INTO t_dedup_cleanup_batches SELECT number FROM numbers(5)" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM t_dedup_cleanup_batches" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.zookeeper WHERE path = '$ZK_PATH/deduplication_hashes'" + +$CLICKHOUSE_CLIENT --query "DROP TABLE t_dedup_cleanup_batches SYNC" diff --git a/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.reference b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.reference new file mode 100644 index 000000000000..d679bc77aff6 --- /dev/null +++ b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.reference @@ -0,0 +1,16 @@ +-- without TABLE ENGINE grants, both directions are refused +TABLE ENGINE ON ReplicatedMergeTree +TABLE ENGINE ON ReplicatedReplacingMergeTree +TABLE ENGINE ON MergeTree +-- the refused queries keep the stored definitions +mt MergeTree +rmt ReplicatedMergeTree +rpl ReplacingMergeTree +-- TABLE ENGINE ON ReplicatedMergeTree allows only the conversion to ReplicatedMergeTree +TABLE ENGINE ON ReplicatedReplacingMergeTree +TABLE ENGINE ON MergeTree +mt ReplicatedMergeTree +1 +-- TABLE ENGINE ON MergeTree allows the conversion back +mt MergeTree +1 diff --git a/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.sh b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.sh new file mode 100755 index 000000000000..9e9189bc4cb2 --- /dev/null +++ b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database, no-ordinary-database, no-shared-merge-tree +# no-replicated-database, no-ordinary-database: `ATTACH TABLE ... AS [NOT] REPLICATED` is supported only for `Atomic` databases. +# no-shared-merge-tree: the tables must keep the engines they are created with. + +# `ATTACH TABLE ... AS [NOT] REPLICATED` requires the `TABLE ENGINE` grant on the engine the table is converted to, +# and a refused conversion leaves the stored definition of the detached table as it was. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A table converted to `ReplicatedMergeTree` has no metadata in ZooKeeper and logs a warning when it is attached. +CLIENT="${CLICKHOUSE_CLIENT} --server_logs_file=/dev/null" +user="user_05494_${CLICKHOUSE_DATABASE}" + +cleanup() +{ + ${CLIENT} --query "DROP USER IF EXISTS ${user}" +} + +trap cleanup EXIT +cleanup + +${CLIENT} <&1 | grep -o -m1 "TABLE ENGINE ON [A-Za-z]*" +} + +echo "-- without TABLE ENGINE grants, both directions are refused" +attach_as_user_denied "ATTACH TABLE mt AS REPLICATED" +attach_as_user_denied "ATTACH TABLE rpl AS REPLICATED" +attach_as_user_denied "ATTACH TABLE rmt AS NOT REPLICATED" + +echo "-- the refused queries keep the stored definitions" +${CLIENT} <&1) + grep -o -m1 -E "ACCESS_DENIED|POSTGRESQL_CONNECTION_FAILURE|Connection refused" <<< "${output}" | head -1 +} + +as_user "SELECT dictHas('${remote_db}.t', toUInt64(1))" +as_user "SELECT dictGet('${remote_db}.t', 'value', toUInt64(1))" +as_user "SELECT dictGet(${remote_db}.t, 'value', toUInt64(1))" +as_user "SELECT * FROM dictionary('${remote_db}.t')" + +${CLICKHOUSE_CLIENT} -m --query " + DROP DATABASE ${remote_db}; + DROP USER ${username}; +" diff --git a/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.reference b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.reference new file mode 100644 index 000000000000..5573d0203026 --- /dev/null +++ b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.reference @@ -0,0 +1,34 @@ +--- ON CLUSTER +CREATE TABLE cluster_db.w_1 ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE cluster_db.w_2 ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE cluster_db.w_default ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +--- inner table of a materialized view +CREATE MATERIALIZED VIEW mv ENGINE = Dictionary(db.d) AS SELECT id, value FROM db.src +ACCESS_DENIED +NOT_LOADED +--- table function +CREATE TABLE w_function (id UInt64, value String) AS dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +0 +CREATE TABLE cluster_db.w_function ON CLUSTER test_shard_localhost (id UInt64, value String) AS dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +0 +--- unqualified name, resolved by ON CLUSTER in the default database of the server +CREATE TABLE cluster_db.w_unqualified ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary('d_unqualified') +ACCESS_DENIED +NOT_LOADED +--- dictionary name given by an expression +CREATE TABLE w_expression (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d')) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE cluster_db.w_expression ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d')) + +1 diff --git a/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.sh b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.sh new file mode 100755 index 000000000000..dbec3f666a76 --- /dev/null +++ b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Creating a `Dictionary` table needs `dictGet` or `SELECT` on the dictionary. `ON CLUSTER` and `Replicated` databases +# execute `CREATE` again with full access, so the access must be checked before, and the dictionary must not be loaded. + +username="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +cluster_db="${CLICKHOUSE_DATABASE}_on_cluster" +# A dictionary with this name exists both in the test database and in `default`. +unqualified="d_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + ${CLICKHOUSE_CLIENT} -m --query " + DROP DATABASE IF EXISTS ${cluster_db}; + DROP DICTIONARY IF EXISTS default.${unqualified}; + DROP USER IF EXISTS ${username}; + " +} +cleanup +trap cleanup EXIT + +${CLICKHOUSE_CLIENT} -m --query " + CREATE TABLE src (id UInt64, value String) ENGINE = Memory; + INSERT INTO src VALUES (1, 'a'); + CREATE DICTIONARY d (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE DICTIONARY ${unqualified} (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE DICTIONARY default.${unqualified} (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE DATABASE ${cluster_db}; + CREATE USER ${username} NOT IDENTIFIED; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${username}; + GRANT dictGet ON ${CLICKHOUSE_DATABASE}.${unqualified} TO ${username}; + GRANT CREATE TABLE, CREATE VIEW ON ${CLICKHOUSE_DATABASE}.* TO ${username}; + GRANT CREATE TABLE ON ${cluster_db}.* TO ${username}; + GRANT SELECT ON ${CLICKHOUSE_DATABASE}.src TO ${username}; + GRANT CLUSTER ON *.* TO ${username}; + GRANT TABLE ENGINE ON Dictionary TO ${username}; +" + +function query() +{ + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" --data-binary "$1" +} + +function status() +{ + query "SELECT status FROM system.dictionaries WHERE database = currentDatabase() AND name = 'd'" +} + +# Reattaching the dictionary resets its state to not loaded. Tables that depend on it would block a permanent detach. +function unload() +{ + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&check_table_dependencies=0" --data-binary "DETACH DICTIONARY ${1:-d}" + query "ATTACH DICTIONARY ${1:-d}" +} + +# Runs a query as the user, with the given extra URL parameters. +function as_user() +{ + echo "$1" | sed -e "s/${username}/user/g" -e "s/${cluster_db}/cluster_db/g" -e "s/${unqualified}/d_unqualified/g" -e "s/${CLICKHOUSE_DATABASE}/db/g" + local output + output=$(${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&user=${username}&distributed_ddl_output_mode=none${2:-}" --data-binary "$1" 2>&1) + if grep -q ACCESS_DENIED <<< "${output}" + then + echo ACCESS_DENIED + else + echo "${output}" | sed -e "s/${cluster_db}/cluster_db/g" -e "s/${CLICKHOUSE_DATABASE}/db/g" + fi +} + +echo "--- ON CLUSTER" +for version in 1 2 "" +do + unload + as_user "CREATE TABLE ${cluster_db}.w_${version:-default} ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d)" "${version:+&distributed_ddl_entry_format_version=${version}}" + status +done + +echo "--- inner table of a materialized view" +unload +as_user "CREATE MATERIALIZED VIEW mv ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d) AS SELECT id, value FROM ${CLICKHOUSE_DATABASE}.src" +status + +echo "--- table function" +unload +as_user "CREATE TABLE w_function (id UInt64, value String) AS dictionary('${CLICKHOUSE_DATABASE}.d')" +status +query "EXISTS TABLE w_function" +unload +as_user "CREATE TABLE ${cluster_db}.w_function ON CLUSTER test_shard_localhost (id UInt64, value String) AS dictionary('${CLICKHOUSE_DATABASE}.d')" "&distributed_ddl_entry_format_version=2" +status +query "EXISTS TABLE ${cluster_db}.w_function" + +echo "--- unqualified name, resolved by ON CLUSTER in the default database of the server" +unload "default.${unqualified}" +as_user "CREATE TABLE ${cluster_db}.w_unqualified ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary('${unqualified}')" +query "SELECT status FROM system.dictionaries WHERE database = 'default' AND name = '${unqualified}'" + +echo "--- dictionary name given by an expression" +unload +as_user "CREATE TABLE w_expression (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d'))" +status +query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.d TO ${username}" +as_user "CREATE TABLE ${cluster_db}.w_expression ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d'))" +# The query sent to the replicas carries the checked name, so a replica does not evaluate the expression again. +query " + SELECT query LIKE '%ENGINE = Dictionary(\\'${CLICKHOUSE_DATABASE}.d\\')%' + FROM system.distributed_ddl_queue + WHERE cluster = 'test_shard_localhost' AND query LIKE '%${cluster_db}.w_expression%' + LIMIT 1" diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference new file mode 100644 index 000000000000..32cc47d3073e --- /dev/null +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference @@ -0,0 +1,8 @@ +wide 1 [NULL,NULL] ['x','y'] +rows 1 ['',''] ['x','y'] +rows 2 ['c'] ['z'] +compact 1 ['',''] ['x','y'] +enum 1 ['ok','ok'] ['x','y'] +enum 2 ['other'] ['z'] +single ['',''] ['',''] 2 2 +added ['a','b'] ['x','y'] ['',''] diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql new file mode 100644 index 000000000000..990fb36db1db --- /dev/null +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql @@ -0,0 +1,82 @@ +-- A column TTL on one `Nested` subcolumn resets it to arrays of defaults of the same size, +-- because its array sizes are shared with the other subcolumns, which keep their values. + +DROP TABLE IF EXISTS t_nested_ttl_wide; +DROP TABLE IF EXISTS t_nested_ttl_rows; +DROP TABLE IF EXISTS t_nested_ttl_compact; +DROP TABLE IF EXISTS t_nested_ttl_enum; +DROP TABLE IF EXISTS t_nested_ttl_single; +DROP TABLE IF EXISTS t_nested_ttl_added; + +-- A Wide part with every row expired, the type change also rewrites the subcolumn. +CREATE TABLE t_nested_ttl_wide (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_wide VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_wide MODIFY COLUMN `n.a` Array(Nullable(String)) TTL ts + INTERVAL 1 DAY; +ALTER TABLE t_nested_ttl_wide MATERIALIZE TTL SETTINGS mutations_sync = 2; +SELECT 'wide', id, `n.a`, `n.b` FROM t_nested_ttl_wide; + +-- Only some rows of the part are expired. +CREATE TABLE t_nested_ttl_rows (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_rows VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']), (2, '2100-01-01 00:00:00', ['c'], ['z']); +ALTER TABLE t_nested_ttl_rows MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_rows FINAL; +SELECT 'rows', id, `n.a`, `n.b` FROM t_nested_ttl_rows ORDER BY id; + +-- A Compact part stores the sizes of each subcolumn separately, but it gets the same default. +CREATE TABLE t_nested_ttl_compact (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000; + +INSERT INTO t_nested_ttl_compact VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_compact MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY; +ALTER TABLE t_nested_ttl_compact MATERIALIZE TTL SETTINGS mutations_sync = 2; +SELECT 'compact', id, `n.a`, `n.b` FROM t_nested_ttl_compact; + +-- The default of an `Enum` element is its first value, not zero. +CREATE TABLE t_nested_ttl_enum (id UInt64, ts DateTime, n Nested(a Enum8('ok' = 1, 'other' = 2), b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_enum VALUES (1, '2020-01-01 00:00:00', ['other', 'other'], ['x', 'y']), (2, '2100-01-01 00:00:00', ['other'], ['z']); +ALTER TABLE t_nested_ttl_enum MODIFY COLUMN `n.a` Array(Enum8('ok' = 1, 'other' = 2)) TTL ts + INTERVAL 1 DAY SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_enum FINAL; +SELECT 'enum', id, `n.a`, `n.b` FROM t_nested_ttl_enum ORDER BY id; + +-- The sizes are kept when every subcolumn expires. +CREATE TABLE t_nested_ttl_single (id UInt64, ts DateTime, n Nested(a String, b String), m UInt64 MATERIALIZED length(`n.a`)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_single VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_single + MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY, + MODIFY COLUMN `n.b` Array(String) TTL ts + INTERVAL 1 DAY +SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_single FINAL; +SELECT 'single', `n.a`, `n.b`, m, length(`n.a`) FROM t_nested_ttl_single; + +-- A subcolumn that no part stores gets the sizes of the other subcolumns, as in a read. +-- A vertical merge does not use the TTL transform for these columns, so it is disabled here. +CREATE TABLE t_nested_ttl_added (id UInt64, n Nested(a String, c String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, enable_vertical_merge_algorithm = 0; + +INSERT INTO t_nested_ttl_added VALUES (1, ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_added ADD COLUMN `n.d` Array(String); +ALTER TABLE t_nested_ttl_added ADD COLUMN ts DateTime DEFAULT '2020-01-01 00:00:00'; +ALTER TABLE t_nested_ttl_added MODIFY TTL ts + INTERVAL 1 DAY WHERE id = 100 SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_added FINAL; +SELECT 'added', `n.a`, `n.c`, `n.d` FROM t_nested_ttl_added; + +DROP TABLE t_nested_ttl_wide; +DROP TABLE t_nested_ttl_rows; +DROP TABLE t_nested_ttl_compact; +DROP TABLE t_nested_ttl_enum; +DROP TABLE t_nested_ttl_single; +DROP TABLE t_nested_ttl_added; diff --git a/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference b/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference new file mode 100644 index 000000000000..e224e8c3e4b8 --- /dev/null +++ b/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference @@ -0,0 +1,14 @@ +t: has([NULL, 1], p) [2] [2] 3 +t: has([NULL, 5], p) [1,2] [1,2] 2 +t: NOT has([NULL, 1], p) [1,3,4] [1,3,4] 0 +t: has([NULL, 1]::Array(Nullable(Int64)), p) [2] [2] 3 +t: NOT has([NULL, 1]::Array(Nullable(Int64)), p) [1,3,4] [1,3,4] 0 +t: p IN (NULL, 1), transform_null_in = 1 [2] [2] 3 +t: p IS NULL, delta_lake_enable_engine_predicate = 0 [2] [2] 3 +t: p = 7, delta_lake_enable_engine_predicate = 0 [3] [3] 3 +t: p < 6, delta_lake_enable_engine_predicate = 0 [1] [1] 3 +t: p IS NOT NULL, delta_lake_enable_engine_predicate = 0 [1,3,4] [1,3,4] 1 +t: has([5, 7], p) [1,3] [1,3] 1 +n: has([NULL, 5], p) [1] [1] 2 +n: NOT has([NULL, 5], p) [3,4] [3,4] 1 +t2: has([NULL, 1], a) [1,2,3] [1,2,3] 0 diff --git a/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.sh b/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.sh new file mode 100755 index 000000000000..25a4b89f88aa --- /dev/null +++ b/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-msan +# Tag no-fasttest: delta-kernel pulls in extra dependencies. +# Tag no-msan: delta-kernel-rs (Rust) is not built under MSan, so DeltaLakeLocal is absent. +# Partition pruning must keep the data file of the NULL partition when the filter's set holds NULL, and prune the other files as before. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e + +ROOT="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_delta_null_set" +trap 'rm -rf "${ROOT}" 2>/dev/null' EXIT +rm -rf "${ROOT}" + +# A hand-written Delta table (a partitioned INSERT of a NULL value is not supported on this branch): a v0 log with protocol + metaData. +bootstrap() { + local table=$1 schema=$2 partition_columns=$3 + mkdir -p "${ROOT}/${table}/_delta_log" + cat > "${ROOT}/${table}/_delta_log/00000000000000000000.json" < : one data file holding only `v`, committed in the v0 log. +add_file() { + local table=$1 dir=$2 values=$3 v=$4 + echo "{\"add\":{\"path\":\"${dir}/data.parquet\",\"partitionValues\":${values},\"size\":1,\"modificationTime\":1700000000000,\"dataChange\":true}}" \ + >> "${ROOT}/${table}/_delta_log/00000000000000000000.json" + QUERIES+=" + INSERT INTO FUNCTION file('${ROOT}/${table}/${dir}/data.parquet', Parquet, 'v Int32') VALUES (${v});" +} + +# One data file per partition. Only t and t2 have a NULL partition (`__HIVE_DEFAULT_PARTITION__`, a JSON null). +add_file t 'p=5' '{"p":"5"}' 1 +add_file t 'p=__HIVE_DEFAULT_PARTITION__' '{"p":null}' 2 +add_file t 'p=7' '{"p":"7"}' 3 +add_file t 'p=8' '{"p":"8"}' 4 +add_file n 'p=5' '{"p":"5"}' 1 +add_file n 'p=7' '{"p":"7"}' 3 +add_file n 'p=8' '{"p":"8"}' 4 +add_file t2 'a=__HIVE_DEFAULT_PARTITION__/b=3' '{"a":null,"b":"3"}' 1 +add_file t2 'a=1/b=3' '{"a":"1","b":"3"}' 2 +add_file t2 'a=1/b=5' '{"a":"1","b":"5"}' 3 + +LABELS=() + +# arm
[settings]: prints the rows read with no filter at the source (LIMIT blocks the push-down), +# the rows read with partition pruning, and the number of data files pruned by the second query. +arm() { + local table=$1 condition=$2 settings=${3:+ SETTINGS $3} + LABELS+=("${table}: ${condition}${3:+, $3}") + QUERIES+=" + SELECT arraySort(groupArray(v)) FROM (SELECT * FROM deltaLakeLocal('${ROOT}/${table}') LIMIT 1000) WHERE ${condition}${settings}; + SELECT sumIf(value, event = 'DeltaLakePartitionPrunedFiles') FROM system.events; + SELECT arraySort(groupArray(v)) FROM deltaLakeLocal('${ROOT}/${table}') WHERE ${condition}${settings}; + SELECT sumIf(value, event = 'DeltaLakePartitionPrunedFiles') FROM system.events;" +} + +arm t "has([NULL, 1], p)" +arm t "has([NULL, 5], p)" +arm t "NOT has([NULL, 1], p)" +arm t "has([NULL, 1]::Array(Nullable(Int64)), p)" +arm t "NOT has([NULL, 1]::Array(Nullable(Int64)), p)" +arm t "p IN (NULL, 1)" "transform_null_in = 1" +# The engine predicate would skip these files before the partition pruner counts them. +arm t "p IS NULL" "delta_lake_enable_engine_predicate = 0" +arm t "p = 7" "delta_lake_enable_engine_predicate = 0" +arm t "p < 6" "delta_lake_enable_engine_predicate = 0" +arm t "p IS NOT NULL" "delta_lake_enable_engine_predicate = 0" +arm t "has([5, 7], p)" +arm n "has([NULL, 5], p)" +arm n "NOT has([NULL, 5], p)" +arm t2 "has([NULL, 1], a)" + +mapfile -t LINES < <(${CLICKHOUSE_LOCAL} --query "${QUERIES}" < /dev/null) +if [[ "${#LINES[@]}" != "$(( 4 * ${#LABELS[@]} ))" ]]; then + printf 'Expected %s lines, got %s:\n%s\n' "$(( 4 * ${#LABELS[@]} ))" "${#LINES[@]}" "$(printf '%s\n' "${LINES[@]}")" >&2 + exit 1 +fi + +for i in "${!LABELS[@]}"; do + printf '%s\t%s\t%s\t%s\n' "${LABELS[$i]}" "${LINES[4 * i]}" "${LINES[4 * i + 2]}" "$(( LINES[4 * i + 3] - LINES[4 * i + 1] ))" +done diff --git a/tests/queries/0_stateless/05616_merge_storage_hidden_tables_metadata.reference b/tests/queries/0_stateless/05616_merge_storage_hidden_tables_metadata.reference new file mode 100644 index 000000000000..aa470e20a575 --- /dev/null +++ b/tests/queries/0_stateless/05616_merge_storage_hidden_tables_metadata.reference @@ -0,0 +1,32 @@ +1 +m 3 +merge() 3 +m_func 3 +a_m 3 +mm 3 +m 3 1 +m id 1 1 +m s 1 1 +a_m 3 1 +a_m id 1 1 +a_m s 1 1 +mm 3 1 +mm id 1 1 +mm s 1 1 +1 +m_show 8 +m_col 10 +u2 t_hidden 0 +u2 m 3 +u2 m 3 +u2 m 3 +m_show id 1 1 +m_show s 1 1 +m_col id 1 1 +m_col s 1 1 +m_alias id 1 1 +m_alias s 1 1 +m_ashow id 1 1 +m_ashow s 1 1 +admin m 1003 +admin m 1003 diff --git a/tests/queries/0_stateless/05616_merge_storage_hidden_tables_metadata.sh b/tests/queries/0_stateless/05616_merge_storage_hidden_tables_metadata.sh new file mode 100755 index 000000000000..a7ef086edbbe --- /dev/null +++ b/tests/queries/0_stateless/05616_merge_storage_hidden_tables_metadata.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +user="u_${CLICKHOUSE_DATABASE}" +user2="u2_${CLICKHOUSE_DATABASE}" +# The settings under which `count()` is answered from metadata (trivial count). +trivial="apply_patch_parts = 0, apply_mutations_on_fly = 0, optimize_trivial_count_query = 1, enable_parallel_replicas = 0, make_distributed_plan = 0, empty_result_for_aggregation_by_empty_set = 0" + +${CLICKHOUSE_CLIENT} --multiline -q " +DROP USER IF EXISTS ${user}; +DROP USER IF EXISTS ${user2}; +SET allow_experimental_alias_table_engine = 1; +CREATE TABLE t_visible (id UInt32, s String) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_hidden (id UInt32, s String) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_show (id UInt32, s String) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_col (id UInt32, s String) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +INSERT INTO t_visible SELECT number, 'v' FROM numbers(3); +INSERT INTO t_hidden SELECT number, repeat('h', 100) FROM numbers(1000); +INSERT INTO t_show SELECT number, 's' FROM numbers(5); +INSERT INTO t_col SELECT number, 'c' FROM numbers(7); +CREATE TABLE m (id UInt32, s String) ENGINE = Merge(currentDatabase(), '^t_(visible|hidden)\$'); +CREATE TABLE m_show (id UInt32, s String) ENGINE = Merge(currentDatabase(), '^t_(visible|show)\$'); +CREATE TABLE m_col (id UInt32, s String) ENGINE = Merge(currentDatabase(), '^t_(visible|col)\$'); +CREATE TABLE m_func AS merge(currentDatabase(), '^t_(visible|hidden)\$'); +CREATE TABLE a_m ENGINE = Alias(currentDatabase(), m); +CREATE TABLE mm (id UInt32, s String) ENGINE = Merge(currentDatabase(), '^m\$'); +CREATE TABLE a_hidden ENGINE = Alias(currentDatabase(), t_hidden); +CREATE TABLE m_alias (id UInt32, s String) ENGINE = Merge(currentDatabase(), '^(t_visible|a_hidden)\$'); +CREATE TABLE a_show ENGINE = Alias(currentDatabase(), t_show); +CREATE TABLE m_ashow (id UInt32, s String) ENGINE = Merge(currentDatabase(), '^(t_visible|a_show)\$'); +CREATE USER ${user} IDENTIFIED WITH plaintext_password BY '${user}'; +GRANT SELECT ON t_visible TO ${user}; +GRANT SELECT ON m TO ${user}; +GRANT SELECT ON m_show TO ${user}; +GRANT SELECT ON m_col TO ${user}; +GRANT SELECT ON m_func TO ${user}; +GRANT SELECT ON a_m TO ${user}; +GRANT SELECT ON mm TO ${user}; +GRANT SHOW TABLES ON t_show TO ${user}; +GRANT SELECT(id) ON t_col TO ${user}; +GRANT SELECT ON a_hidden TO ${user}; +GRANT SELECT ON m_alias TO ${user}; +GRANT SELECT ON a_show TO ${user}; +GRANT SELECT ON m_ashow TO ${user}; +CREATE USER ${user2} IDENTIFIED WITH plaintext_password BY '${user2}'; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.* TO ${user2}; +REVOKE SELECT ON ${CLICKHOUSE_DATABASE}.t_hidden FROM ${user2}; +SELECT min(data_compressed_bytes) > 0 FROM system.columns WHERE database = currentDatabase() AND table = 't_visible'; +" + +# Rows and sizes of a matched table the user cannot see are not reported. +${CLICKHOUSE_CLIENT} --user "${user}" --password "${user}" --multiline -q " +SELECT 'm', count() FROM m SETTINGS ${trivial}; +SELECT 'merge()', count() FROM merge(currentDatabase(), '^t_(visible|hidden)\$') SETTINGS ${trivial}; +SELECT 'm_func', count() FROM m_func; +SELECT 'a_m', count() FROM a_m SETTINGS ${trivial}; +SELECT 'mm', count() FROM mm SETTINGS ${trivial}; +" + +for table in m a_m mm +do + ${CLICKHOUSE_CLIENT} --user "${user}" --password "${user}" --multiline -q " + SELECT '${table}', total_rows, total_bytes = (SELECT total_bytes FROM system.tables WHERE database = currentDatabase() AND name = 't_visible') + FROM system.tables WHERE database = currentDatabase() AND name = '${table}'; + SELECT '${table}', c.name, c.data_compressed_bytes = v.data_compressed_bytes, c.data_uncompressed_bytes = v.data_uncompressed_bytes + FROM system.columns AS c INNER JOIN (SELECT name, data_compressed_bytes, data_uncompressed_bytes FROM system.columns WHERE database = currentDatabase() AND table = 't_visible') AS v USING (name) + WHERE c.database = currentDatabase() AND c.table = '${table}' ORDER BY c.name; + " +done + +# The trivial count is still used for a partially granted user. +${CLICKHOUSE_CLIENT} --user "${user}" --password "${user}" -q "EXPLAIN SELECT count() FROM m SETTINGS ${trivial}" | grep -c 'Optimized trivial count' + +# A visible table the user cannot read is not counted from metadata either. +${CLICKHOUSE_CLIENT} --user "${user}" --password "${user}" --multiline -q " +SELECT count() FROM m_show SETTINGS ${trivial}; -- { serverError ACCESS_DENIED } +SELECT count() FROM m_show; -- { serverError ACCESS_DENIED } +SELECT 'm_show', total_rows FROM system.tables WHERE database = currentDatabase() AND name = 'm_show'; +SELECT 'm_col', count() FROM m_col SETTINGS ${trivial}; +" + +# A table-level revoke inside a database-wide grant hides that table. +${CLICKHOUSE_CLIENT} --user "${user2}" --password "${user2}" --multiline -q " +SELECT 'u2 t_hidden', count() FROM system.tables WHERE database = currentDatabase() AND name = 't_hidden'; +SELECT 'u2 m', count() FROM m; +SELECT 'u2 m', count() FROM m SETTINGS ${trivial}; +SELECT 'u2 m', total_rows FROM system.tables WHERE database = currentDatabase() AND name = 'm'; +" + +# Column sizes of a Merge table are the sums of the column sizes the user sees on its children. +for table_children in "m_show:'t_visible','t_show'" "m_col:'t_visible','t_col'" "m_alias:'t_visible','a_hidden'" "m_ashow:'t_visible','a_show'" +do + table=${table_children%%:*} + ${CLICKHOUSE_CLIENT} --user "${user}" --password "${user}" -q " + SELECT '${table}', c.name, c.data_compressed_bytes = v.compressed, c.data_uncompressed_bytes = v.uncompressed + FROM system.columns AS c INNER JOIN (SELECT name, sum(data_compressed_bytes) AS compressed, sum(data_uncompressed_bytes) AS uncompressed + FROM system.columns WHERE database = currentDatabase() AND table IN (${table_children#*:}) GROUP BY name) AS v USING (name) + WHERE c.database = currentDatabase() AND c.table = '${table}' ORDER BY c.name" +done + +${CLICKHOUSE_CLIENT} --multiline -q " +SELECT 'admin m', count() FROM m SETTINGS ${trivial}; +SELECT 'admin m', total_rows FROM system.tables WHERE database = currentDatabase() AND name = 'm'; +DROP USER IF EXISTS ${user}; +DROP USER IF EXISTS ${user2}; +" diff --git a/tests/queries/0_stateless/05617_async_insert_native_serialization_kind_gate.python b/tests/queries/0_stateless/05617_async_insert_native_serialization_kind_gate.python new file mode 100644 index 000000000000..79174b3929da --- /dev/null +++ b/tests/queries/0_stateless/05617_async_insert_native_serialization_kind_gate.python @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Regression test for post-auth type confusion in asynchronous inserts over the native TCP protocol. +# +# The sender chooses each column's serialization kind. For `INSERT ... FORMAT Native`, choosing +# `Sparse` or `Replicated` puts a `ColumnSparse` / `ColumnReplicated` in the block but keeps the +# column's declared type. With `async_insert = 1`, the block was queued unchanged. The flush used +# `insertRangeFrom` to copy it into a full column. Its `assert_cast` reinterpreted the column. +# `assert_cast` is a plain `static_cast` in release builds. +# +# Senders of these blocks need only the default kind. The server must accept only that kind at +# every nesting depth in all peer blocks: `INSERT` data, external tables and scalars. These +# scenarios send well-formed blocks, so only the kind can cause rejection. All expect +# `INCORRECT_DATA` (code 117) and a server that stays alive. An ordinary block is still inserted. +# +# The client uses the raw native protocol pinned to revision 54482 +# (`DBMS_MIN_REVISION_WITH_REPLICATED_SERIALIZATION`). This keeps the exchanged revision-gated +# fields fixed. + +import os +import socket +import struct +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") +CLIENT_NAME = "async insert serialization kind" + +REVISION = 54482 + +# KindStackBinarySerializationType +KIND_STACK_DEFAULT = 0 +KIND_STACK_SPARSE = 1 +KIND_STACK_REPLICATED = 4 +KIND_STACK_COMBINATION = 5 + +# Protocol::Client +CLIENT_DATA = 2 +CLIENT_SCALAR = 7 + +# Protocol::Server +SERVER_EXCEPTION = 2 +SERVER_PROGRESS = 3 +SERVER_END_OF_STREAM = 5 +SERVER_PROFILE_EVENTS = 14 + +END_OF_GRANULE_FLAG = 1 << 62 + +ROWS = 4 + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") if isinstance(s, str) else s + writeVarUInt(len(b), ba) + ba.extend(b) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt(s, size=1): + res = readStrict(s, size) + val = 0 + for i in range(len(res)): + val += res[i] << (i * 8) + return val + + +def readUInt8(s): + return readUInt(s) + + +def readUInt32(s): + return readUInt(s, 4) + + +def readVarUInt(s): + x = 0 + for i in range(9): + byte = readStrict(s)[0] + x |= (byte & 0x7F) << (7 * i) + if not byte & 0x80: + return x + return x + + +def readStringBinary(s): + size = readVarUInt(s) + return readStrict(s, size).decode("utf-8") + + +def sendHello(s): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeStringBinary(CLICKHOUSE_DATABASE, ba) # database + writeStringBinary("default", ba) # user + writeStringBinary("", ba) # password + s.sendall(ba) + + +def receiveHello(s): + assert readVarUInt(s) == 0 # Hello + readStringBinary(s) # server name + readVarUInt(s) # major + readVarUInt(s) # minor + readVarUInt(s) # revision + readVarUInt(s) # parallel replicas protocol version (>= 54471) + readStringBinary(s) # timezone (>= 54058) + readStringBinary(s) # display name (>= 54372) + readVarUInt(s) # version patch (>= 54401) + readStringBinary(s) # proto_send chunked (>= 54470) + readStringBinary(s) # proto_recv chunked (>= 54470) + for _ in range(readVarUInt(s)): # password complexity rules (>= 54461) + readStringBinary(s) + readStringBinary(s) + readStrict(s, 8) # nonce, UInt64 (>= 54462) + # Server settings in STRINGS_WITH_FLAGS format: (name, flags, value)* terminated + # by an empty name (>= 54474). + while True: + if readStringBinary(s) == "": # setting name + break + readVarUInt(s) # flags + readStringBinary(s) # value + readVarUInt(s) # query plan serialization version (>= 54477) + readVarUInt(s) # cluster function protocol version (>= 54479) + + +def sendAddendum(s): + ba = bytearray() + writeStringBinary("", ba) # quota key (>= 54458) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # parallel replicas protocol version (>= 54471) + s.sendall(ba) + + +def serializeClientInfo(ba, query_id): + ba.append(1) # INITIAL_QUERY + writeStringBinary("default", ba) # initial_user + writeStringBinary(query_id, ba) # initial_query_id + writeStringBinary("127.0.0.1:9000", ba) # initial_address + ba.extend([0] * 8) # initial_query_start_time_microseconds (>= 54449) + ba.append(1) # interface = TCP + writeStringBinary("os_user", ba) + writeStringBinary("client_hostname", ba) + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # client major + writeVarUInt(9, ba) # client minor + writeVarUInt(REVISION, ba) # client tcp protocol version + writeStringBinary("", ba) # quota key (>= 54060) + writeVarUInt(0, ba) # distributed_depth (>= 54448) + writeVarUInt(1, ba) # client version patch (>= 54401) + ba.append(0) # opentelemetry: no trace id (>= 54442) + writeVarUInt(0, ba) # parallel replicas: collaborate_with_initiator (>= 54453) + writeVarUInt(0, ba) # parallel replicas: obsolete count + writeVarUInt(0, ba) # parallel replicas: number_of_current_replica + writeVarUInt(0, ba) # script query number (>= 54475) + writeVarUInt(0, ba) # script line number (>= 54475) + ba.append(0) # jwt: none (>= 54476) + + +def sendQuery(s, query): + ba = bytearray() + query_id = uuid.uuid4().hex + writeVarUInt(1, ba) # Query + writeStringBinary(query_id, ba) + serializeClientInfo(ba, query_id) + # Skip the slow text stack trace symbolization; readException discards the trace anyway. + # It must be a protocol setting: an inline SETTINGS clause does not reach the reply path. + writeStringBinary("calculate_text_stack_trace", ba) + writeVarUInt(1, ba) # is_important + writeStringBinary("0", ba) + writeStringBinary("", ba) # end of per-query settings + writeStringBinary("", ba) # interserver externally granted roles (>= 54472) + writeStringBinary("", ba) # interserver secret (>= 54441) + writeVarUInt(2, ba) # stage = Complete + ba.append(0) # no compression + writeStringBinary(query, ba) + writeStringBinary("", ba) # query parameters terminator (>= 54459) + s.sendall(ba) + + +def serializeBlockInfo(ba): + writeVarUInt(1, ba) # field 1 + ba.append(0) # is_overflows = false + writeVarUInt(2, ba) # field 2 + ba.extend(struct.pack("= 54480) + for _ in range(readVarUInt(s)): + readUInt32(s) + else: + raise RuntimeError("Unknown BlockInfo field {}".format(field_num)) + + +def emptyBlock(): + ba = bytearray() + writeVarUInt(2, ba) # Data + writeStringBinary("", ba) + serializeBlockInfo(ba) + writeVarUInt(0, ba) # columns + writeVarUInt(0, ba) # rows + return bytes(ba) + + +def readException(s): + code = readUInt32(s) + readStringBinary(s) # name + text = readStringBinary(s) + readStringBinary(s) # trace + readUInt8(s) # has_nested + return code, text + + +def readKindStack(s): + kind = readUInt8(s) + if kind == KIND_STACK_COMBINATION: # number of kinds and the kinds themselves + readStrict(s, readVarUInt(s)) + + +def readHeader(s): + packet_type = receiveReply(s) + if packet_type == SERVER_EXCEPTION: + code, text = readException(s) + raise RuntimeError("Unexpected exception {}: {}".format(code, text)) + assert packet_type == 1, "Expected Data (header) packet, got {}".format(packet_type) + readStringBinary(s) # external table name + readBlockInfo(s) + columns = readVarUInt(s) + rows = readVarUInt(s) + assert rows == 0, "Expected an empty header block, got {} rows".format(rows) + # Consume the per-column descriptor so the stream stays aligned. + for _ in range(columns): + readStringBinary(s) # column name + readStringBinary(s) # column type + if readUInt8(s): # has custom serialization (>= 54454) + readKindStack(s) + + +def skipProfileEvents(s): + fixed_sizes = {"DateTime": 4, "UInt64": 8, "Int64": 8} + readStringBinary(s) # external table name + readBlockInfo(s) + columns = readVarUInt(s) + rows = readVarUInt(s) + for _ in range(columns): + readStringBinary(s) # column name + column_type = readStringBinary(s) + assert readUInt8(s) == 0 # has custom serialization (>= 54454) + if column_type == "String": + for _ in range(rows): + readStringBinary(s) + elif column_type.startswith("Enum8("): + readStrict(s, rows) + else: + readStrict(s, rows * fixed_sizes[column_type]) + + +def receiveReply(s): + """Skips the reports of a running `INSERT` and returns the type of the packet that ends it.""" + while True: + packet_type = readVarUInt(s) + if packet_type == SERVER_PROFILE_EVENTS: + skipProfileEvents(s) + elif packet_type == SERVER_PROGRESS: + # read_rows, read_bytes, total_rows_to_read, total_bytes_to_read (>= 54463), + # written_rows, written_bytes (>= 54420), elapsed_ns (>= 54460) + for _ in range(7): + readVarUInt(s) + else: + return packet_type + + +def dataBlockPrefix(column_type, table_name="", packet_type=CLIENT_DATA): + """The beginning of a Data or Scalar packet with one column `x`, up to its serialization kinds.""" + ba = bytearray() + writeVarUInt(packet_type, ba) + writeStringBinary(table_name, ba) # empty for the data of an INSERT + serializeBlockInfo(ba) + writeVarUInt(1, ba) # columns + writeVarUInt(ROWS, ba) + writeStringBinary("x", ba) # column name + writeStringBinary(column_type, ba) + return ba + + +def sparseOffsets(): + """SparseOffsets substream: rows 0 and 1 are non-default, the trailing defaults close the granule.""" + ba = bytearray() + writeVarUInt(0, ba) + writeVarUInt(0, ba) + writeVarUInt((ROWS - 2) | END_OF_GRANULE_FLAG, ba) + return ba + + +def sparseBlock(table_name=""): + ba = dataBlockPrefix("UInt64", table_name) + ba.append(1) # has_custom serialization + ba.append(KIND_STACK_SPARSE) + ba.extend(sparseOffsets()) + ba.extend(struct.pack("<2Q", 42, 43)) # SparseElements substream + return bytes(ba) + + +def replicatedBlock(table_name="", packet_type=CLIENT_DATA): + num_elements = 2 + ba = dataBlockPrefix("UInt64", table_name, packet_type) + ba.append(1) # has_custom serialization + ba.append(KIND_STACK_REPLICATED) + # ReplicatedIndexes substream: row count, index type size, in-range indexes. + writeVarUInt(ROWS, ba) + ba.append(8) # sizeof(UInt64) + for i in range(ROWS): + ba.extend(struct.pack("&1 | grep -qF 'Received error from remote server' && break + sleep 0.1 +done + +# The bridge cannot connect to the DSN and answers with an error, which quotes the request URI. Grep that +# line: the client also echoes the submitted query, which legitimately contains what the user typed. +${CLICKHOUSE_CLIENT} --query_id "${CLICKHOUSE_TEST_UNIQUE_NAME}_tf" --query "SELECT * FROM odbc('DSN=no_such_dsn;PWD=${SECRET}', 'db', 't')" 2>&1 \ + | grep -F 'Received error from remote server' | assert_shape "odbc_table_function" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" +${CLICKHOUSE_CLIENT} --query " + SELECT exception + FROM system.query_log + WHERE event_date >= yesterday() + AND current_database = currentDatabase() + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_tf' + AND type != 'QueryStart'" | assert_shape "query_log" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_odbc (a Int32) ENGINE = ODBC('DSN=no_such_dsn;PWD=${SECRET}', 'db', 't')" +${CLICKHOUSE_CLIENT} --query "INSERT INTO t_odbc VALUES (1)" 2>&1 \ + | grep -F 'Received error from remote server' | assert_shape "odbc_engine_insert" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_odbc" diff --git a/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.reference b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.reference new file mode 100644 index 000000000000..1d5e015fb91f --- /dev/null +++ b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.reference @@ -0,0 +1,2 @@ +Sparse +1000 9500 33 diff --git a/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.sql b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.sql new file mode 100644 index 000000000000..69a2302fc7a9 --- /dev/null +++ b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.sql @@ -0,0 +1,25 @@ +-- A materialized CTE keeps the `Sparse` columns it has read, and the table behind it is sent to the shards +-- as an external table. A shard accepts only the default serialization in the blocks it receives. + +SET enable_materialized_cte = 1; +SET enable_analyzer = 1; + +DROP TABLE IF EXISTS t_sparse; + +CREATE TABLE t_sparse (id UInt64, x UInt64, t Tuple(a UInt64, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS ratio_of_defaults_for_sparse_serialization = 0.1; + +INSERT INTO t_sparse SELECT number, if(number % 50 = 0, number, 0), (if(number % 30 = 0, number, 0), '') FROM numbers(1000); + +SELECT serialization_kind FROM system.parts_columns +WHERE database = currentDatabase() AND table = 't_sparse' AND active AND column = 'x'; + +-- The CTE is referenced twice, otherwise it is inlined. `127.0.0.2` is not a local address: the shard is reached over the network. +WITH m AS MATERIALIZED (SELECT id, x, t FROM t_sparse) +SELECT count(), sum(m.x), countIf(m.t != (0, '')) +FROM remote('127.0.0.2', numbers(1000)) AS r +INNER JOIN m ON r.number = m.id +WHERE m.x IN (SELECT x FROM m); + +DROP TABLE t_sparse; diff --git a/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference new file mode 100644 index 000000000000..d7624b276d3a --- /dev/null +++ b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference @@ -0,0 +1,6 @@ +1 t_05620 x = 1 local_directory +1 t_05620 x = 2 local_directory +1 t_05620 x = 2 memory +1 t_05620 x = 3 local_directory +denied +denied diff --git a/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh new file mode 100755 index 000000000000..4ed4ded7baf2 --- /dev/null +++ b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# Tag no-replicated-database: its replicated access storage replaces the local_directory and memory storages + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="u_05620_${CLICKHOUSE_DATABASE}" +user2="u2_05620_${CLICKHOUSE_DATABASE}" +policy="p_05620_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_05620 (x Int32) ENGINE = MergeTree ORDER BY x" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user}, ${user2} IDENTIFIED WITH no_password" +${CLICKHOUSE_CLIENT} --query "GRANT CLUSTER ON *.* TO ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY ON ${CLICKHOUSE_DATABASE}.* TO ${user}" + +# A bare table name refers to the current database, as it does without ON CLUSTER. +on_cluster() { ${CLICKHOUSE_CLIENT} --user "${user}" --distributed_ddl_output_mode none --query "$1"; } +show() { ${CLICKHOUSE_CLIENT} --query "SELECT database = currentDatabase(), table, select_filter, storage FROM system.row_policies WHERE short_name = '${policy}'"; } + +on_cluster "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost IN local_directory USING x = 1 TO ALL" +show +on_cluster "ALTER ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost USING x = 2" +show +on_cluster "MOVE ROW POLICY ${policy} ON t_05620 TO memory ON CLUSTER test_shard_localhost" +show +on_cluster "DROP ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost" +show + +# On a cluster with , the privileges are also checked on the current database. +on_cluster "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_cluster_two_shards_different_databases USING x = 3 TO ALL" +show +on_cluster "DROP ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost" +show + +# The privileges are checked before the query is queued: on the current database, and globally for ON *. +denied() +{ + if ${CLICKHOUSE_CLIENT} --user "$1" --query "$2" 2>&1 | grep -qF "necessary to have the grant $3"; then echo denied; else echo "not denied"; fi +} +denied "${user2}" "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_cluster_two_shards_different_databases USING 1 TO ALL" "CREATE ROW POLICY ON ${CLICKHOUSE_DATABASE}.t_05620" +denied "${user}" "CREATE ROW POLICY ${policy} ON * ON CLUSTER test_shard_localhost USING 1 TO ALL" "CREATE ROW POLICY ON *.*" +show + +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_05620" diff --git a/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.reference b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.reference new file mode 100644 index 000000000000..67e0669d56c6 --- /dev/null +++ b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.reference @@ -0,0 +1,10 @@ +4 99999 +3 99998 +2 99997 +99999 4 +99998 3 +99997 2 +0 0 0 +1 1 1 +2 2 2 +299995 4999950000 4999950000 diff --git a/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.sh b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.sh new file mode 100755 index 000000000000..4b3b3f2de284 --- /dev/null +++ b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-msan +# Tag no-fasttest: needs Parquet and Delta Lake +# Tag no-msan: delta-kernel-rs (Rust) is not built under MSan, so `deltaLakeLocal` is absent. + +# A Delta Lake table with column mapping where a column is stored under the logical name of another column, read +# with the columns in every order: the renaming of the requested columns to their physical names must not collide +# with a logical name that is not renamed yet (it used to erase the column and read freed memory). + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +DELTA_DIR="${USER_FILES_PATH}/${CLICKHOUSE_DATABASE}_05621" +rm -rf "${DELTA_DIR}" +mkdir -p "${DELTA_DIR}/_delta_log" + +# The data file stores `k` = number % 7, `v` = number and `w` = number: the table's `k_old`, `k` and `w` +# (column mapping enabled on an existing table, then `k` renamed to `k_old` and `v` to `k`). +${CLICKHOUSE_CLIENT} --query " + INSERT INTO FUNCTION file('${DELTA_DIR}/data.parquet', Parquet, 'k Int64, v Int64, w Int64') + SELECT number % 7, number, number FROM numbers(100000)" +DELTA_SCHEMA='{\"type\":\"struct\",\"fields\":[{\"name\":\"k_old\",\"type\":\"long\",\"nullable\":false,\"metadata\":{\"delta.columnMapping.id\":1,\"delta.columnMapping.physicalName\":\"k\"}},{\"name\":\"k\",\"type\":\"long\",\"nullable\":false,\"metadata\":{\"delta.columnMapping.id\":2,\"delta.columnMapping.physicalName\":\"v\"}},{\"name\":\"w\",\"type\":\"long\",\"nullable\":false,\"metadata\":{\"delta.columnMapping.id\":3,\"delta.columnMapping.physicalName\":\"w\"}}]}' +cat > "${DELTA_DIR}/_delta_log/00000000000000000000.json" <&1 | grep -o -m1 -E 'READONLY|QUERY_IS_PROHIBITED' + $CLICKHOUSE_CLIENT $setting -q "ALTER NAMED COLLECTION ${nc}_existing SET key = 'other'" 2>&1 | grep -o -m1 -E 'READONLY|QUERY_IS_PROHIBITED' + $CLICKHOUSE_CLIENT $setting -q "DROP NAMED COLLECTION ${nc}_existing" 2>&1 | grep -o -m1 -E 'READONLY|QUERY_IS_PROHIBITED' +done + +# Nothing was created or dropped. +$CLICKHOUSE_CLIENT -q "SELECT name FROM system.named_collections WHERE name LIKE '${nc}%' ORDER BY name" | sed "s/${nc}/nc/" + +$CLICKHOUSE_CLIENT -q "DROP NAMED COLLECTION ${nc}_existing" diff --git a/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.reference b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.reference new file mode 100644 index 000000000000..94cd23857655 --- /dev/null +++ b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.reference @@ -0,0 +1,5 @@ +UNKNOWN_TYPE_OF_QUERY +UNKNOWN_TYPE_OF_QUERY +UNKNOWN_TYPE_OF_QUERY +UNKNOWN_TYPE_OF_QUERY +0 diff --git a/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.sh b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.sh new file mode 100755 index 000000000000..3acc1e842236 --- /dev/null +++ b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `INSERT ... FROM INFILE` is read by the client. The server must refuse it before it opens the path, +# also for an asynchronous insert: the result must not depend on whether the file exists. + +readable="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.txt" +missing="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_missing.txt" +echo "line" > "${readable}" + +${CLICKHOUSE_CLIENT} -q "CREATE TABLE t_async_infile (line String) ENGINE = Memory" + +for wait in 0 1; do + for path in "${readable}" "${missing}"; do + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&async_insert=1&wait_for_async_insert=${wait}" \ + --data-binary "INSERT INTO t_async_infile FROM INFILE '${path}' FORMAT LineAsString" \ + | grep -o -m1 'UNKNOWN_TYPE_OF_QUERY\|FILE_DOESNT_EXIST\|CANNOT_OPEN_FILE' || echo "accepted" + done +done + +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM t_async_infile" +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_async_infile" +rm -f "${readable}" diff --git a/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.reference b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.reference new file mode 100644 index 000000000000..9337af0e7b78 --- /dev/null +++ b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.reference @@ -0,0 +1,8 @@ +-- huge positive exponent does not fit +\N \N \N +-- exponent sum out of range +\N +-- huge negative exponent rounds to zero +0 0 0 +-- ordinary exponents +1500 1.5 1000000000000000 \N diff --git a/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.sql b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.sql new file mode 100644 index 000000000000..079a8681ece0 --- /dev/null +++ b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.sql @@ -0,0 +1,17 @@ +-- A decimal text exponent close to the `Int32` limits must not wrap around: +-- `1e2147483647` used to pass the "too big" check and read as 0. + +SELECT '-- huge positive exponent does not fit'; +SELECT toDecimal64OrNull('1e2147483647', 2), toDecimal32OrNull('1e2147483647', 0), toDecimal256OrNull('-1e2147483647', 10); +SELECT toDecimal64('1e2147483647', 2); -- { serverError ARGUMENT_OUT_OF_BOUND } +SELECT * FROM format(CSV, 'd Decimal(10, 2)', '1e2147483647'); -- { serverError ARGUMENT_OUT_OF_BOUND } + +SELECT '-- exponent sum out of range'; +SELECT toDecimal64OrNull('0.1e-2147483648', 2); +SELECT toDecimal64('0.1e-2147483648', 2); -- { serverError CANNOT_PARSE_NUMBER } + +SELECT '-- huge negative exponent rounds to zero'; +SELECT toDecimal64OrNull('1e-2147483648', 2), toDecimal64OrNull('1e-2147483647', 2), toDecimal128('-5e-2147483648', 3); + +SELECT '-- ordinary exponents'; +SELECT toDecimal64('1.5e3', 2), toDecimal64('15e-1', 2), toDecimal64('1e15', 2), toDecimal64OrNull('1e16', 2); diff --git a/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference new file mode 100644 index 000000000000..6f1822583bd6 --- /dev/null +++ b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference @@ -0,0 +1,13 @@ +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +memory +1 +1 +ACCESS_ENTITY_ALREADY_EXISTS +0 local_directory +1 memory +1 +1 +0 diff --git a/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh new file mode 100755 index 000000000000..c2526dc6f58e --- /dev/null +++ b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# no-replicated-database: that configuration replaces the user directories, so there is no `memory` storage. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A user name must not be used in more than one user directory. +# `memory` is the last user directory, so `CREATE USER` without `IN` would pick an earlier one. + +user="user_05770_${CLICKHOUSE_DATABASE}" +source_user="user_05770_source_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}, ${source_user}" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'p1' IN memory" + +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user} IN local_directory" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER IF NOT EXISTS ${user}" + +# A replacement is refused if another directory holds the name, but allowed within the same directory. +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2'" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2' IN local_directory" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT storage FROM system.users WHERE name = '${user}'" +${CLICKHOUSE_CLIENT} --user "${user}" --password p1 --query "SELECT currentUser() = '${user}'" +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2' IN memory" +${CLICKHOUSE_CLIENT} --user "${user}" --password p2 --query "SELECT currentUser() = '${user}'" + +# A rename to a name held by another directory is refused, and both users remain usable. +${CLICKHOUSE_CLIENT} --query "CREATE USER ${source_user} IDENTIFIED WITH plaintext_password BY 'p3' IN local_directory" +${CLICKHOUSE_CLIENT} --query "ALTER USER ${source_user} RENAME TO ${user}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT name = '${user}', storage FROM system.users WHERE name IN ('${user}', '${source_user}') ORDER BY storage" +${CLICKHOUSE_CLIENT} --user "${user}" --password p2 --query "SELECT currentUser() = '${user}'" +${CLICKHOUSE_CLIENT} --user "${source_user}" --password p3 --query "SELECT currentUser() = '${source_user}'" + +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}, ${source_user}" +${CLICKHOUSE_CLIENT} --query "SELECT count() FROM system.users WHERE name IN ('${user}', '${source_user}')" diff --git a/tests/queries/0_stateless/05771_template_resultset_without_data.reference b/tests/queries/0_stateless/05771_template_resultset_without_data.reference new file mode 100644 index 000000000000..b98936844069 --- /dev/null +++ b/tests/queries/0_stateless/05771_template_resultset_without_data.reference @@ -0,0 +1,2 @@ +1 +INVALID_TEMPLATE_FORMAT diff --git a/tests/queries/0_stateless/05771_template_resultset_without_data.sh b/tests/queries/0_stateless/05771_template_resultset_without_data.sh new file mode 100755 index 000000000000..43ffdcf70052 --- /dev/null +++ b/tests/queries/0_stateless/05771_template_resultset_without_data.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +# The format string for the result set of the `Template` input format must contain `${data}`. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +dir="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +mkdir -p "$dir" +printf 'prefix ${data}' > "$dir/resultset_ok.format" +printf 'prefix' > "$dir/resultset_without_data.format" +printf '${x:CSV}' > "$dir/row.format" + +printf 'prefix 1' | $CLICKHOUSE_LOCAL --input-format Template --structure 'x UInt64' \ + --format_template_resultset "$dir/resultset_ok.format" --format_template_row "$dir/row.format" -q "SELECT * FROM table" + +printf 'prefix' | $CLICKHOUSE_LOCAL --input-format Template --structure 'x UInt64' \ + --format_template_resultset "$dir/resultset_without_data.format" --format_template_row "$dir/row.format" -q "SELECT * FROM table" 2>&1 \ + | grep -o -m1 'INVALID_TEMPLATE_FORMAT' + +rm -rf "$dir" diff --git a/tests/queries/0_stateless/05772_map_combinator_fixed_string_key_size.reference b/tests/queries/0_stateless/05772_map_combinator_fixed_string_key_size.reference new file mode 100644 index 000000000000..5c8eba139966 --- /dev/null +++ b/tests/queries/0_stateless/05772_map_combinator_fixed_string_key_size.reference @@ -0,0 +1 @@ +{'a':5} diff --git a/tests/queries/0_stateless/05772_map_combinator_fixed_string_key_size.sql b/tests/queries/0_stateless/05772_map_combinator_fixed_string_key_size.sql new file mode 100644 index 000000000000..3431781d8e36 --- /dev/null +++ b/tests/queries/0_stateless/05772_map_combinator_fixed_string_key_size.sql @@ -0,0 +1,5 @@ +-- A serialized state of a -Map aggregate function with a `FixedString(N)` key must have keys of exactly N bytes. + +SELECT anyMapMerge(CAST(unhex('0101610105') AS AggregateFunction(anyMap, Map(FixedString(1), UInt8)))); +SELECT anyMapMerge(CAST(unhex('010261620105') AS AggregateFunction(anyMap, Map(FixedString(1), UInt8)))); -- { serverError INCORRECT_DATA } +SELECT anyMapMerge(CAST(unhex('01000105') AS AggregateFunction(anyMap, Map(FixedString(1), UInt8)))); -- { serverError INCORRECT_DATA } diff --git a/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.reference b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.reference new file mode 100644 index 000000000000..52bebd7dba71 --- /dev/null +++ b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.reference @@ -0,0 +1,4 @@ +1 +TOO_DEEP_RECURSION +TOO_DEEP_RECURSION +TOO_DEEP_RECURSION diff --git a/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.sh b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.sh new file mode 100755 index 000000000000..660f3c111362 --- /dev/null +++ b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: the `ParquetMetadata` format needs Arrow, which is not built in the fast test. + +# The `ParquetMetadata` format limits the nesting depth of the Parquet schema with `max_parser_depth`, +# and always with a hard ceiling, because Arrow builds the schema tree recursively. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Writes a Parquet file without row groups, with a column nested in the given number of groups. +# It is written directly, because ClickHouse does not parse such deep types. +function write_deep_parquet() +{ + python3 -I -c ' +import struct, sys + +def varint(n): + out = b"" + while True: + b = n & 0x7f + n >>= 7 + if not n: + return out + bytes([b]) + out += bytes([b | 0x80]) + +def zigzag(n): + return varint((n << 1) ^ (n >> 63)) + +def field(delta, thrift_type): + return bytes([(delta << 4) | thrift_type]) + +I32, I64, BINARY, LIST, STRUCT = 5, 6, 8, 9, 12 + +def schema_element(name, physical_type=None, repetition=None, num_children=None): + # Field ids: 1 type, 3 repetition_type, 4 name, 5 num_children. + out = b"" + last = 0 + if physical_type is not None: + out += field(1 - last, I32) + zigzag(physical_type) + last = 1 + if repetition is not None: + out += field(3 - last, I32) + zigzag(repetition) + last = 3 + out += field(4 - last, BINARY) + varint(len(name)) + name + last = 4 + if num_children is not None: + out += field(5 - last, I32) + zigzag(num_children) + return out + b"\x00" + +def struct_list(items): + header = bytes([(len(items) << 4) | STRUCT]) if len(items) < 15 else bytes([0xf0 | STRUCT]) + varint(len(items)) + return header + b"".join(items) + +depth = int(sys.argv[1]) +schema = [schema_element(b"schema", num_children=1)] +schema += [schema_element(b"c", repetition=1, num_children=1) for _ in range(depth)] +schema += [schema_element(b"c", physical_type=1, repetition=1)] +# FileMetaData: 1 version, 2 schema, 3 num_rows, 4 row_groups. +metadata = field(1, I32) + zigzag(1) + field(1, LIST) + struct_list(schema) + field(1, I64) + zigzag(0) + field(1, LIST) + struct_list([]) + b"\x00" +sys.stdout.buffer.write(b"PAR1" + metadata + struct.pack(" "$2" +} + +file="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.parquet" + +write_deep_parquet 100 "$file" +$CLICKHOUSE_LOCAL -q "SELECT num_columns FROM file('$file', ParquetMetadata)" +$CLICKHOUSE_LOCAL --max_parser_depth 50 -q "SELECT num_columns FROM file('$file', ParquetMetadata)" 2>&1 | grep -o -m1 'TOO_DEEP_RECURSION' + +# Raising `max_parser_depth` or setting it to 0 (unlimited) does not remove the hard ceiling. +write_deep_parquet 100000 "$file" +$CLICKHOUSE_LOCAL --max_parser_depth 0 -q "SELECT num_columns FROM file('$file', ParquetMetadata)" 2>&1 | grep -o -m1 'TOO_DEEP_RECURSION' +$CLICKHOUSE_LOCAL --max_parser_depth 1000000 -q "SELECT num_columns FROM file('$file', ParquetMetadata)" 2>&1 | grep -o -m1 'TOO_DEEP_RECURSION' + +rm -f "$file" diff --git a/tests/queries/0_stateless/05774_aggregate_function_column_expand_exception.reference b/tests/queries/0_stateless/05774_aggregate_function_column_expand_exception.reference new file mode 100644 index 000000000000..9766475a4185 --- /dev/null +++ b/tests/queries/0_stateless/05774_aggregate_function_column_expand_exception.reference @@ -0,0 +1 @@ +ok diff --git a/tests/queries/0_stateless/05774_aggregate_function_column_expand_exception.sql b/tests/queries/0_stateless/05774_aggregate_function_column_expand_exception.sql new file mode 100644 index 000000000000..3b047fa94e0b --- /dev/null +++ b/tests/queries/0_stateless/05774_aggregate_function_column_expand_exception.sql @@ -0,0 +1,19 @@ +-- Tags: no-parallel, no-fasttest +-- Tag no-parallel: the failpoint is global and would fire in other queries. +-- Tag no-fasttest: failpoints are not available in the fast test build. + +-- `ColumnAggregateFunction::expand` (used by the short-circuit evaluation of `if`) must stay valid when +-- creating an aggregate function state throws, so that the column can be destroyed. + +SYSTEM ENABLE FAILPOINT column_aggregate_function_expand_exception; + +SELECT finalizeAggregation(if(number % 3 = 0, + initializeAggregation('groupArrayState', number), + initializeAggregation('groupArrayState', number + 1))) +FROM numbers(100) +FORMAT Null +SETTINGS short_circuit_function_evaluation = 'force_enable'; -- { serverError MEMORY_LIMIT_EXCEEDED } + +SYSTEM DISABLE FAILPOINT column_aggregate_function_expand_exception; + +SELECT 'ok'; diff --git a/tests/queries/0_stateless/05775_query_plan_step_missing_inputs.reference b/tests/queries/0_stateless/05775_query_plan_step_missing_inputs.reference new file mode 100644 index 000000000000..ccddfbfa32fc --- /dev/null +++ b/tests/queries/0_stateless/05775_query_plan_step_missing_inputs.reference @@ -0,0 +1,5 @@ +Extremes 117 +Limit 117 +Union 117 +Extremes with two children 117 +server alive 1 diff --git a/tests/queries/0_stateless/05775_query_plan_step_missing_inputs.sh b/tests/queries/0_stateless/05775_query_plan_step_missing_inputs.sh new file mode 100755 index 000000000000..490aae1894d4 --- /dev/null +++ b/tests/queries/0_stateless/05775_query_plan_step_missing_inputs.sh @@ -0,0 +1,271 @@ +#!/usr/bin/env bash +# A step of a `QueryPlan` packet (native-protocol packet type 13) needs as many children as it reads input +# headers, but the number of children comes from the packet. Steps used to read the input headers without +# checking it, so a plan with a step lacking its children made the server read out of bounds. Now such a +# plan is rejected with `INCORRECT_DATA` and the server keeps serving. +# +# The packet is only reachable for a query sent with the `QueryPlan` processing stage while the +# server has `process_query_plan_packet` enabled (see tests/config/config.d/process_query_plan_packet.xml). +# The client here speaks the raw native protocol pinned to revision 54482 so the revision-gated +# fields of the handshake are fixed. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +python3 - <<'PYEOF' +import os +import socket +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_USER = os.environ.get("CLICKHOUSE_USER", "default") +CLICKHOUSE_PASSWORD = os.environ.get("CLICKHOUSE_PASSWORD", "") +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") + +CLIENT_NAME = "query plan missing inputs test" +REVISION = 54482 + +# Plan serialization version gates for header fields (see Core/ProtocolDefines.h). +WITH_EXECUTION_LIMITS = 11 # max_threads + concurrency_control +WITH_STEP_VERSIONS = 19 # per-step version + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def varuint(x): + ba = bytearray() + writeVarUInt(x, ba) + return bytes(ba) + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") if isinstance(s, str) else s + writeVarUInt(len(b), ba) + ba.extend(b) + + +def strbin(s): + ba = bytearray() + writeStringBinary(s, ba) + return bytes(ba) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt(s, size=1): + res = readStrict(s, size) + val = 0 + for i in range(len(res)): + val += res[i] << (i * 8) + return val + + +def readUInt32(s): + return readUInt(s, 4) + + +def readVarUInt(s): + x = 0 + for i in range(9): + byte = readStrict(s)[0] + x |= (byte & 0x7F) << (7 * i) + if not byte & 0x80: + return x + return x + + +def readStringBinary(s): + size = readVarUInt(s) + return readStrict(s, size).decode("utf-8") + + +def sendHello(s): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeStringBinary(CLICKHOUSE_DATABASE, ba) + writeStringBinary(CLICKHOUSE_USER, ba) + writeStringBinary(CLICKHOUSE_PASSWORD, ba) + s.sendall(ba) + + +def receiveHello(s): + assert readVarUInt(s) == 0 # Hello + readStringBinary(s) # server name + readVarUInt(s) # major + readVarUInt(s) # minor + readVarUInt(s) # revision + readVarUInt(s) # parallel replicas protocol version + readStringBinary(s) # timezone + readStringBinary(s) # display name + readVarUInt(s) # version patch + readStringBinary(s) # proto_send chunked + readStringBinary(s) # proto_recv chunked + for _ in range(readVarUInt(s)): # password complexity rules + readStringBinary(s) + readStringBinary(s) + readStrict(s, 8) # nonce + while True: # server settings + if readStringBinary(s) == "": + break + readVarUInt(s) + readStringBinary(s) + query_plan_version = readVarUInt(s) # query plan serialization version + readVarUInt(s) # cluster function protocol version + return query_plan_version + + +def sendAddendum(s): + ba = bytearray() + writeStringBinary("", ba) # quota key + writeStringBinary("notchunked", ba) # proto_send chunked + writeStringBinary("notchunked", ba) # proto_recv chunked + writeVarUInt(0, ba) # parallel replicas protocol version + s.sendall(ba) + + +def serializeClientInfo(ba, query_id): + ba.append(1) # INITIAL_QUERY + writeStringBinary(CLICKHOUSE_USER, ba) # initial_user + writeStringBinary(query_id, ba) # initial_query_id + writeStringBinary("127.0.0.1:9000", ba) # initial_address + ba.extend([0] * 8) # initial_query_start_time_microseconds + ba.append(1) # interface = TCP + writeStringBinary("os_user", ba) + writeStringBinary("client_hostname", ba) + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # client major + writeVarUInt(9, ba) # client minor + writeVarUInt(REVISION, ba) # client tcp protocol version + writeStringBinary("", ba) # quota key + writeVarUInt(0, ba) # distributed_depth + writeVarUInt(1, ba) # client version patch + ba.append(0) # opentelemetry: no trace id + writeVarUInt(0, ba) # parallel replicas: collaborate_with_initiator + writeVarUInt(0, ba) # parallel replicas: obsolete count + writeVarUInt(0, ba) # parallel replicas: number_of_current_replica + writeVarUInt(0, ba) # script query number + writeVarUInt(0, ba) # script line number + ba.append(0) # jwt: none + + +def sendQuery(s, query, stage): + ba = bytearray() + query_id = uuid.uuid4().hex + writeVarUInt(1, ba) # Query + writeStringBinary(query_id, ba) + serializeClientInfo(ba, query_id) + writeStringBinary("", ba) # empty per-query settings + writeStringBinary("", ba) # interserver externally granted roles + writeStringBinary("", ba) # interserver secret + writeVarUInt(stage, ba) # query processing stage + ba.append(0) # no compression + writeStringBinary(query, ba) + writeStringBinary("", ba) # query parameters terminator + s.sendall(ba) + + +def buildNode(plan_version, step_name, payload, children): + """Serializes a plan node: its children first, then the step itself with an empty output header.""" + node = bytearray() + writeVarUInt(len(children), node) # num_children + for child in children: + node += child + writeStringBinary(step_name, node) + if plan_version >= WITH_STEP_VERSIONS: + writeVarUInt(0, node) # step_version + writeStringBinary("", node) # step_description + writeVarUInt(0, node) # output header: 0 columns + writeVarUInt(0, node) # settings: 0 changed + node += payload + return bytes(node) + + +def buildTree(plan_version, tree): + """Serializes a plan subtree given as `(step_name, payload, [subtrees of the children])`.""" + step_name, payload, children = tree + return buildNode(plan_version, step_name, payload, [buildTree(plan_version, child) for child in children]) + + +def buildQueryPlanPacket(plan_version, step_name, payload, num_children, children): + body = bytearray() + writeVarUInt(plan_version, body) + if plan_version >= WITH_EXECUTION_LIMITS: + writeVarUInt(0, body) # max_threads + body.append(0) # concurrency_control + # Node tree: a root step with the given children, or with the given number of `ReadFromTable` children. + # `ReadFromTable` payload: table name and no flags; the table is only resolved after deserialization. + if children is None: + children = [("ReadFromTable", strbin("t") + b"\x00", [])] * num_children + body += buildTree(plan_version, (step_name, payload, children)) + + packet = bytearray() + writeVarUInt(13, packet) # Client::QueryPlan + packet += body + return bytes(packet) + + +def readException(s): + code = readUInt32(s) + readStringBinary(s) # name + text = readStringBinary(s) + readStringBinary(s) # trace + readStrict(s) # has_nested + return code, text + + +def sendPlan(step_name, payload, num_children=0, children=None): + """Sends a `QueryPlan` packet with a step having `children` (or `num_children` `ReadFromTable` children) and returns the exception code, or None if the query is not rejected.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(60) + s.connect((CLICKHOUSE_HOST, CLICKHOUSE_PORT)) + sendHello(s) + plan_version = receiveHello(s) + sendAddendum(s) + # Stage 7 == QueryProcessingStage::QueryPlan: the server then expects a QueryPlan packet. + sendQuery(s, "SELECT 1", 7) + s.sendall(buildQueryPlanPacket(plan_version, step_name, payload, num_children, children)) + + # Only the first packet matters: either the exception or the start of the query result. + packet_type = readVarUInt(s) + if packet_type == 2: # Exception + return readException(s)[0] + return None + + +def main(): + # 117 == INCORRECT_DATA + for step_name, payload in [("Extremes", b""), ("Limit", b"\x00\x01\x00"), ("Union", b"")]: + print(step_name, sendPlan(step_name, payload)) + # A step with more children than it has inputs. + print("Extremes with two children", sendPlan("Extremes", b"", num_children=2)) + + +main() +PYEOF + +# The server must still be alive and serving after rejecting the malicious packet. +${CLICKHOUSE_CLIENT} --query "SELECT 'server alive', 1" diff --git a/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.reference b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.reference new file mode 100644 index 000000000000..3749278cffff --- /dev/null +++ b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.reference @@ -0,0 +1 @@ +['{"a":1,"b":2}'] ['{"a":1,"b":2}'] diff --git a/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.sql b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.sql new file mode 100644 index 000000000000..974d00da071d --- /dev/null +++ b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.sql @@ -0,0 +1,39 @@ +-- A serialized value of a `JSON` column in an aggregate state (here of `groupArray`) has every path of a row once, +-- in sorted order. A repeated path must be rejected instead of producing a column with subcolumns of different sizes. + +-- The state of `groupArray` with one row: the number of paths, then the size of the path, the path, +-- the size of the value and the value (Dynamic binary: type `Int64` and the number) for every path. +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '0100000000000000' || hex('b') || '0900000000000000' || '0A0200000000000000' AS path_b, + '013C' || '0200000000000000' AS header +SELECT + finalizeAggregation(CAST(unhex(header || path_a || path_b), 'AggregateFunction(groupArray, JSON)')), + finalizeAggregation(CAST(unhex(header || path_a || path_b), 'AggregateFunction(groupArray, JSON(max_dynamic_paths = 0))')); + +-- The same path twice: into a dynamic path and into shared data. +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '013C' || '0200000000000000' AS header +SELECT finalizeAggregation(CAST(unhex(header || path_a || path_a), 'AggregateFunction(groupArray, JSON)')); -- { serverError INCORRECT_DATA } + +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '013C' || '0200000000000000' AS header +SELECT finalizeAggregation(CAST(unhex(header || path_a || path_a), 'AggregateFunction(groupArray, JSON(max_dynamic_paths = 0))')); -- { serverError INCORRECT_DATA } + +-- Paths out of order in shared data. +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '0100000000000000' || hex('b') || '0900000000000000' || '0A0200000000000000' AS path_b, + '013C' || '0200000000000000' AS header +SELECT finalizeAggregation(CAST(unhex(header || path_b || path_a), 'AggregateFunction(groupArray, JSON(max_dynamic_paths = 0))')); -- { serverError INCORRECT_DATA } + +-- A typed path repeated as a dynamic path or in shared data. Typed paths come first in the serialized value. +SELECT finalizeAggregation(CAST( + unhex('012a0300000000000000010000000000000001000000000000006109000000000000000a0100000000000000'), + 'AggregateFunction(groupArray, JSON(a Int64))')); -- { serverError INCORRECT_DATA } + +SELECT finalizeAggregation(CAST( + unhex('012a0300000000000000010000000000000001000000000000006109000000000000000a0100000000000000'), + 'AggregateFunction(groupArray, JSON(a Int64, max_dynamic_paths = 0))')); -- { serverError INCORRECT_DATA } diff --git a/tests/queries/0_stateless/05791_aggregating_step_argument_types.reference b/tests/queries/0_stateless/05791_aggregating_step_argument_types.reference new file mode 100644 index 000000000000..58e71197a70d --- /dev/null +++ b/tests/queries/0_stateless/05791_aggregating_step_argument_types.reference @@ -0,0 +1,25 @@ +argument type differs from the input INCORRECT_DATA +argument is not in the input INCORRECT_DATA +aggregate is duplicated INCORRECT_DATA +well-formed accepted +merged column is not a state INCORRECT_DATA +merged states are reordered INCORRECT_DATA +merged state is duplicated INCORRECT_DATA +merged key is after the states INCORRECT_DATA +merged state is repeated after the states INCORRECT_DATA +well-formed merge accepted +grouping set column is a String INCORRECT_DATA +grouping set column is duplicated INCORRECT_DATA +memory-efficient grouping sets merge INCORRECT_DATA +grouping set key is repeated after the states INCORRECT_DATA +memory-bound grouping sets merge INCORRECT_DATA +well-formed grouping sets merge accepted +grouping set column without grouping sets INCORRECT_DATA +well-formed merge without grouping sets accepted +finalized column is not a state INCORRECT_DATA +finalized state is not in the input INCORRECT_DATA +finalized state is of another function INCORRECT_DATA +well-formed totals accepted +TotalsHaving of a union with quantile states ILLEGAL_COLUMN +TotalsHaving of a union with quantiles states accepted +3 diff --git a/tests/queries/0_stateless/05791_aggregating_step_argument_types.sh b/tests/queries/0_stateless/05791_aggregating_step_argument_types.sh new file mode 100755 index 000000000000..b4b30bd23e0b --- /dev/null +++ b/tests/queries/0_stateless/05791_aggregating_step_argument_types.sh @@ -0,0 +1,238 @@ +#!/usr/bin/env bash +# The aggregate functions of a deserialized `Aggregating` step are resolved from the argument types written +# in the plan, but they are executed on the input columns of the same names. A plan with other types made a +# function interpret a column of another type. `AggregatingStep::deserialize` (and the steps merging or finalizing +# the states) now check the types against the input header. The steps merging the states read the keys and then the +# states by position, so their input must have them in the order of the plan, without duplicates. +# The well-formed plans are accepted, so the refusals are specific. +# The raw protocol client is the one of 05775_query_plan_step_missing_inputs.sh. The leaves of the plans are +# `ReadFromTable` steps reading the columns of their headers from the tables created below. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +${CLICKHOUSE_CLIENT} --query " + CREATE TABLE t (x UInt64, k UInt64, __grouping_set UInt64, a AggregateFunction(any, UInt64), b AggregateFunction(sum, UInt64)) ENGINE = Memory; + CREATE TABLE q (a AggregateFunction(quantiles(0.5), UInt64)) ENGINE = Memory; +" + +python3 - <<'PYEOF' +import os +import socket +import struct +E = os.environ.get +HOST, PORT = E("CLICKHOUSE_HOST", "127.0.0.1"), int(E("CLICKHOUSE_PORT_TCP", "9000")) +USER, PASSWORD = E("CLICKHOUSE_USER", "default"), E("CLICKHOUSE_PASSWORD", "") +DATABASE = E("CLICKHOUSE_DATABASE", "default") +CLIENT = "aggregating step argument types" +REVISION = 54482 # pinned, so the revision-gated fields of the handshake are fixed +VERSION = 0 # DBMS_QUERY_PLAN_SERIALIZATION_VERSION: no execution limits and no per-step versions +U64, STR = b"\x04", b"\x15" # BinaryTypeIndex +NUL = b"\x00" # a zero flags byte + + +def vu(x): + out = bytearray() + while True: + out.append((x & 0x7F) | (0x80 if x > 0x7F else 0)) + x >>= 7 + if not x: + return bytes(out) + +def sb(s): + return vu(len(s)) + s.encode() + +def rv(f): + x = shift = 0 + while True: + c = f.read(1)[0] + x |= (c & 0x7F) << shift + shift += 7 + if not c & 0x80: + return x + +def skip_hello(f): + assert rv(f) == 0 + for kind in "SVVVVSSVSS": # name, 4 versions, timezone, display name, patch, 2 chunked modes + rv(f) if kind == "V" else f.read(rv(f)) + for _ in range(rv(f) * 2): # password complexity rules, two strings each + f.read(rv(f)) + f.read(8) # nonce + while f.read(rv(f)): # server settings, an empty name terminates + rv(f) + f.read(rv(f)) + rv(f), rv(f) # query plan serialization and cluster function versions + +def header(columns): + return vu(len(columns)) + b"".join(sb(n) + t for n, t in columns) + +def node(step, payload, out_columns, children=(), settings=()): + # The children are read before their parent: the number of children, the children, then the step. + out = vu(len(children)) + b"".join(children) + out += sb(step) + sb("") + header(out_columns) # step name, description, header + out += vu(len(settings)) + for name, value in settings: # the number of changed settings, then name, flags, binary value of each + out += sb(name) + vu(0) + value + return out + payload + +def read_table(columns, table="t"): + return node("ReadFromTable", sb(table) + NUL, columns) # table name, no flags + +def forge(label, payload, children=(), out_columns=(), step="Aggregating", settings=()): + # One `ReadFromTable` child per header of `children`. + forge_tree(label, node(step, payload, out_columns, [read_table(columns) for columns in children], settings)) + +def forge_tree(label, root): + plan = vu(VERSION) + root + vu(0) # version, the nodes, no sets + qid = os.urandom(16).hex() + info = (b"\x01" + sb(USER) + sb(qid) + sb("127.0.0.1:9000") + bytes(8) + b"\x01" + + sb("os_user") + sb("host") + sb(CLIENT) + vu(24) + vu(9) + vu(REVISION) + sb("") + + vu(0) + vu(1) + bytes(7)) # depth, patch, no tracing/replicas/script/jwt + with socket.socket() as s: + s.settimeout(60) + s.connect((HOST, PORT)) + f = s.makefile("rb") + s.sendall(vu(0) + sb(CLIENT) + vu(24) + vu(9) + vu(REVISION) + + sb(DATABASE) + sb(USER) + sb(PASSWORD)) + skip_hello(f) + s.sendall(sb("") + sb("notchunked") + sb("notchunked") + vu(0) # addendum + + vu(1) + sb(qid) + info + sb("") + sb("") + sb("") + + vu(7) + NUL + sb("SELECT 1") + sb("") # 7 == QueryProcessingStage::QueryPlan + + vu(13) + plan + # an empty `Data` block ends the external tables: no table name, the block info, no columns and rows + + vu(2) + sb("") + vu(1) + NUL + vu(2) + struct.pack("= 4: + code = int.from_bytes(data[position - 4:position], "little") + break + s.settimeout(1 if data.endswith(b"\x05") else 60) + names = {117: "INCORRECT_DATA", 48: "NOT_IMPLEMENTED", 44: "ILLEGAL_COLUMN"} + print(label, "accepted" if code is None else names.get(code, code)) + +FINAL = 1 +AF = b"\x25" # BinaryTypeIndex::AggregateFunction + +def state(function, argument_type): # AggregateFunction(function, argument_type), version 0 + return AF + vu(0) + sb(function) + vu(0) + vu(1) + argument_type + +def aggregates_of(aggregates): # name, arguments with their types, function, parameters + out = vu(len(aggregates)) + for name, argument, a_type, function, *parameters in aggregates: + out += sb(name) + vu(1) + sb(argument) + a_type + sb(function) + vu(len(parameters)) + b"".join(parameters) + return out + +def aggregating(flags, argument_type=None, keys=(), aggregates=None): + # Flags, keys, then the aggregates. By default one aggregate `a` = any(x). + if aggregates is None: + aggregates = [("a", "x", argument_type, "any")] + return bytes([flags]) + vu(len(keys)) + b"".join(sb(k) for k in keys) + aggregates_of(aggregates) + +X = [("x", U64)] +A = [("a", U64)] +forge("argument type differs from the input", aggregating(FINAL, STR), [X], A) +forge("argument is not in the input", aggregating(FINAL, U64), [[("k", U64)]], A) +# The output of an ordinary aggregation has a column for every key and aggregate, finalized by name. +forge("aggregate is duplicated", aggregating(FINAL, aggregates=[("a", "x", U64, "groupArray")] * 2), [X], A * 2) +forge("well-formed", aggregating(FINAL, U64), [X], A) + +# The merge reads the keys and then the states by position, so the input must have them in the order of the plan. +ANY_SUM = [("a", "x", U64, "any"), ("b", "x", U64, "sum")] +STATES = [("a", state("any", U64)), ("b", state("sum", U64))] +AB = [("a", U64), ("b", U64)] +def merging(keys, aggregates, flags=FINAL): # flags, keys, aggregates, an empty sort description + return bytes([flags]) + vu(len(keys)) + b"".join(sb(k) for k in keys) + aggregates_of(aggregates) + vu(0) + +forge("merged column is not a state", merging([], ANY_SUM[:1]), [A], A, "MergingAggregated") +forge("merged states are reordered", merging([], ANY_SUM), [STATES[::-1]], AB, "MergingAggregated") +forge("merged state is duplicated", merging([], ANY_SUM[:1] * 2), [STATES[:1] * 2], A * 2, "MergingAggregated") +forge("merged key is after the states", merging(["k"], ANY_SUM[:1]), [STATES[:1] + [("k", U64)]], + [("k", U64), ("a", U64)], "MergingAggregated") +forge("merged state is repeated after the states", merging([], ANY_SUM), [STATES + STATES[:1]], AB, "MergingAggregated") +forge("well-formed merge", merging([], ANY_SUM), [STATES], AB, "MergingAggregated") + +# With grouping sets, the merge splits the rows by `__grouping_set`, read as `UInt64`, and keeps its type in the output. +GROUPING_SETS = 4 +def merging_grouping_sets(keys, sets, aggregates, flags=FINAL | GROUPING_SETS, sort_description=vu(0)): + out = bytes([flags]) + vu(len(keys)) + b"".join(sb(k) for k in keys) + vu(len(sets)) + for used_keys in sets: + out += vu(len(used_keys)) + b"".join(sb(k) for k in used_keys) + return out + aggregates_of(aggregates) + sort_description + +GS = merging_grouping_sets(["k"], [["k"], []], ANY_SUM[:1]) +K_STATE = [("k", U64), STATES[0]] +K_A = [("k", U64), ("a", U64)] +NOT_MEMORY_EFFICIENT = [("distributed_aggregation_memory_efficient", vu(0))] +forge("grouping set column is a String", GS, [[("__grouping_set", STR)] + K_STATE], + [("__grouping_set", STR)] + K_A, "MergingAggregated") +forge("grouping set column is duplicated", GS, [[("__grouping_set", U64)] * 2 + K_STATE], + [("__grouping_set", U64)] + K_A, "MergingAggregated") +# The memory-efficient merge (on by default in the settings of the step) does not support grouping sets. +forge("memory-efficient grouping sets merge", GS, [[("__grouping_set", U64)] + K_STATE], + [("__grouping_set", U64)] + K_A, "MergingAggregated") +# The output header and the reconstruction of the missing keys take every key from the input by name. +forge("grouping set key is repeated after the states", GS, [[("__grouping_set", U64)] + K_STATE + [("k", U64)]], + [("__grouping_set", U64)] + K_A, "MergingAggregated", NOT_MEMORY_EFFICIENT) +# The memory-bound merge (with a non-empty sort description) does not support grouping sets either. +MEMORY_BOUND = 32 +GS_SORTED = merging_grouping_sets(["k"], [["k"], []], ANY_SUM[:1], FINAL | GROUPING_SETS | MEMORY_BOUND, vu(1) + sb("k") + b"\x03") +forge("memory-bound grouping sets merge", GS_SORTED, [[("__grouping_set", U64)] + K_STATE], + [("__grouping_set", U64)] + K_A, "MergingAggregated", NOT_MEMORY_EFFICIENT) +forge("well-formed grouping sets merge", GS, [[("__grouping_set", U64)] + K_STATE], + [("__grouping_set", U64)] + K_A, "MergingAggregated", NOT_MEMORY_EFFICIENT) + +# Without grouping sets, the merge does not produce `__grouping_set`, so the input must not have it. +MERGING = merging(["k"], ANY_SUM[:1]) +forge("grouping set column without grouping sets", MERGING, [K_STATE + [("__grouping_set", U64)]], + [("__grouping_set", U64)] + K_A, "MergingAggregated") +forge("well-formed merge without grouping sets", MERGING, [K_STATE], K_A, "MergingAggregated") + +# `TotalsHaving` finalizes the states it finds in the input by the names of its aggregates. +def totals_having(aggregates): # flags (final), then the aggregates + return bytes([FINAL]) + aggregates_of(aggregates) + +forge("finalized column is not a state", totals_having(ANY_SUM[:1]), [A], A, "TotalsHaving") +forge("finalized state is not in the input", totals_having(ANY_SUM[:1]), [[("b", state("any", U64))]], [("b", U64)], "TotalsHaving") +forge("finalized state is of another function", totals_having(ANY_SUM[:1]), [[("a", state("sum", U64))]], A, "TotalsHaving") +forge("well-formed totals", totals_having(ANY_SUM), [STATES], AB, "TotalsHaving") + +# `DataTypeAggregateFunction::equals` considers the states of `quantile` and `quantiles` equal, so a `Union` +# passes a column of `quantile` states under a header of `quantiles` states. They are finalized with the function +# of the column, to `Float64` instead of `Array(Float64)`. The aggregation without keys of an empty input gives one row. +F64 = b"\x03" # Field::Types::Float64 +HALF = F64 + struct.pack(" "$file" + +S="input_format_parquet_max_block_size = 4096, max_threads = 1" +F="file('$file', 'Parquet', 'k UInt64, g Point')" + +$CLICKHOUSE_LOCAL -q "SELECT count(), sum(g.1), sum(g.2), countIf(g != (toFloat64(k), toFloat64(-k))) FROM $F PREWHERE intDiv(k, 1000) % 2 = 0 SETTINGS $S" +$CLICKHOUSE_LOCAL -q "SELECT k, g FROM $F PREWHERE intDiv(k, 1000) % 2 = 0 AND k % 1000 IN (0, 999) ORDER BY k LIMIT 4 SETTINGS $S" +$CLICKHOUSE_LOCAL -q "SELECT count(), sum(g.1) FROM $F PREWHERE k % 3000 >= 2500 SETTINGS $S" + +# Corrupt the length of the value for k = 5500, which lies in the middle of a range of filtered-out rows, +# so its page is fully filtered while other rows of the block pass (the filter is applied inside the +# decoders starting from the second block). Skipping the values of that page must detect the invalid +# length instead of reading out of bounds. Checksums are not written, so that the corruption is not +# caught by the page checksum. +corrupted="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_corrupted.parquet" +$CLICKHOUSE_LOCAL -q " + SELECT number AS k, (toFloat64(number), toFloat64(-number))::Point AS g + FROM numbers(20000) + FORMAT Parquet + SETTINGS output_format_parquet_geometadata = 1, output_format_parquet_compression_method = 'none', + output_format_parquet_data_page_size = 1024, output_format_parquet_batch_size = 64, + output_format_parquet_write_page_index = 0, output_format_parquet_max_dictionary_size = 0, + output_format_parquet_write_bloom_filter = 0, output_format_parquet_row_group_size = 20000, + output_format_parquet_write_checksums = 0" > "$file" +$CLICKHOUSE_LOCAL -q " + WITH concat(unhex('0101000000'), reinterpretAsFixedString(toFloat64(5500)), reinterpretAsFixedString(toFloat64(-5500))) AS v + SELECT replaceOne(raw, concat(unhex('15000000'), v), concat(unhex('FFFFFF7F'), v)) + FROM file('$file', 'RawBLOB', 'raw String') + FORMAT RawBLOB" > "$corrupted" +cmp -s "$file" "$corrupted" && echo "the file was not corrupted" +F="file('$corrupted', 'Parquet', 'k UInt64, g Point')" +$CLICKHOUSE_LOCAL -q "SELECT count(), sum(g.1) FROM $F PREWHERE intDiv(k, 1000) % 2 = 0 SETTINGS $S" 2>&1 | grep -o -m1 'INCORRECT_DATA' + +rm -f "$corrupted" + +rm -f "$file" diff --git a/tests/queries/0_stateless/05810_dwarf_attribute_past_end_of_section.reference b/tests/queries/0_stateless/05810_dwarf_attribute_past_end_of_section.reference new file mode 100644 index 000000000000..be0a0fd5bdfc --- /dev/null +++ b/tests/queries/0_stateless/05810_dwarf_attribute_past_end_of_section.reference @@ -0,0 +1,13 @@ +compile_unit producer exprloc +compile_unit name exprloc +CANNOT_PARSE_DWARF +CANNOT_PARSE_DWARF +variable location exprloc +variable name exprloc +CANNOT_PARSE_DWARF +CANNOT_PARSE_DWARF +compile_unit a +compile_unit b +CANNOT_PARSE_DWARF +CANNOT_PARSE_DWARF +CANNOT_PARSE_DWARF diff --git a/tests/queries/0_stateless/05810_dwarf_attribute_past_end_of_section.sh b/tests/queries/0_stateless/05810_dwarf_attribute_past_end_of_section.sh new file mode 100755 index 000000000000..6b44a7ba836d --- /dev/null +++ b/tests/queries/0_stateless/05810_dwarf_attribute_past_end_of_section.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-msan +# Tag no-fasttest: the `DWARF` format is not built in the fast test. +# Tag no-msan: the `DWARF` format is not built with MSan. + +# An attribute whose length goes past the end of `.debug_info` must be rejected by the `DWARF` format. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +prefix="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +# A minimal ELF with one compilation unit with two attributes of form DW_FORM_exprloc either in the unit entry +# or in its child. The length of the first expression is either 1 (valid), 0xFFFFFFFF (past the end of the section) +# or 0xFFFFFFFFFFFFFFFF (makes the offset wrap around to before the attribute). +python3 - "$prefix" <<'PYEOF' +import struct +import sys + +ABBREV = bytes([ + # Abbreviation 1: DW_TAG_compile_unit without children, with DW_AT_producer and DW_AT_name, both of form DW_FORM_exprloc. + 0x01, 0x11, 0x00, 0x25, 0x18, 0x03, 0x18, 0x00, 0x00, + # Abbreviation 2: DW_TAG_compile_unit with children and without attributes. + 0x02, 0x11, 0x01, 0x00, 0x00, + # Abbreviation 3: DW_TAG_variable without children, with DW_AT_location and DW_AT_name, both of form DW_FORM_exprloc. + 0x03, 0x34, 0x00, 0x02, 0x18, 0x03, 0x18, 0x00, 0x00, + # Abbreviation 4: DW_TAG_compile_unit without children, with DW_AT_name of form DW_FORM_string. + 0x04, 0x11, 0x00, 0x03, 0x08, 0x00, 0x00, + # Abbreviation 5: DW_TAG_compile_unit without children, with DW_AT_language of form DW_FORM_data4. + 0x05, 0x11, 0x00, 0x13, 0x06, 0x00, 0x00, + # Abbreviation 6: DW_TAG_variable without children, with DW_AT_name of form DW_FORM_string. + 0x06, 0x34, 0x00, 0x03, 0x08, 0x00, 0x00, + 0x00]) + +def make_unit(entries): + header = bytes([0x05, 0x00, 0x01, 0x08, 0, 0, 0, 0]) # version 5, DW_UT_compile, address size 8, abbrev offset 0 + return struct.pack('&1 | grep -o -m1 'CANNOT_PARSE_DWARF' + $CLICKHOUSE_LOCAL -q "SELECT count() FROM file('${prefix}${kind}_wraparound.elf', DWARF)" 2>&1 | grep -o -m1 'CANNOT_PARSE_DWARF' + rm -f "${prefix}${kind}_valid.elf" "${prefix}${kind}_invalid.elf" "${prefix}${kind}_wraparound.elf" +done + +$CLICKHOUSE_LOCAL -q "SELECT tag, name FROM file('${prefix}_two_units_valid.elf', DWARF) ORDER BY offset" +for kind in string data4 nested_string; do + $CLICKHOUSE_LOCAL -q "SELECT count() FROM file('${prefix}_two_units_${kind}.elf', DWARF)" 2>&1 | grep -o -m1 'CANNOT_PARSE_DWARF' +done +rm -f "${prefix}"_two_units_*.elf diff --git a/tests/queries/0_stateless/05811_restore_zip_encrypted_entry_too_short.reference b/tests/queries/0_stateless/05811_restore_zip_encrypted_entry_too_short.reference new file mode 100644 index 000000000000..6ecc93c63ab8 --- /dev/null +++ b/tests/queries/0_stateless/05811_restore_zip_encrypted_entry_too_short.reference @@ -0,0 +1 @@ +CANNOT_UNPACK_ARCHIVE diff --git a/tests/queries/0_stateless/05811_restore_zip_encrypted_entry_too_short.sh b/tests/queries/0_stateless/05811_restore_zip_encrypted_entry_too_short.sh new file mode 100755 index 000000000000..197b385a1325 --- /dev/null +++ b/tests/queries/0_stateless/05811_restore_zip_encrypted_entry_too_short.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: zip archives need minizip, which is not in the fast test build. + +# An encrypted entry of a zip archive whose compressed size is less than the size of the encryption header +# must be rejected when restoring a backup from the archive. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +WORK_DIR=$(cd "${CLICKHOUSE_TMP}" && pwd)/${CLICKHOUSE_TEST_UNIQUE_NAME} +rm -rf "${WORK_DIR}" +mkdir -p "${WORK_DIR}/backups" + +cat > "${WORK_DIR}/config.xml" < + + ${WORK_DIR}/backups + + +CONFIG + +# A zip archive with one stored entry `.backup` encrypted with the traditional PKWARE encryption and the +# password "password". The compressed size of the entry is 1, less than the 12-byte encryption header. +python3 - "${WORK_DIR}/backups/archive.zip" <<'PYEOF' +import struct +import sys + +table = [] +for n in range(256): + c = n + for _ in range(8): + c = (c >> 1) ^ 0xEDB88320 if c & 1 else c >> 1 + table.append(c) + +def crc32_update(crc, b): + return (crc >> 8) ^ table[(crc ^ b) & 0xFF] + +keys = [0x12345678, 0x23456789, 0x34567890] + +def update_keys(b): + keys[0] = crc32_update(keys[0], b) + keys[1] = ((keys[1] + (keys[0] & 0xFF)) * 134775813 + 1) & 0xFFFFFFFF + keys[2] = crc32_update(keys[2], keys[1] >> 24) + +def encrypt(data): + out = bytearray() + for b in data: + t = (keys[2] | 2) & 0xFFFF + out.append(b ^ (((t * (t ^ 1)) >> 8) & 0xFF)) + update_keys(b) + return bytes(out) + +for b in b'password': + update_keys(b) +# The last byte of the header is the high byte of the CRC (0) to pass the password check. +header = encrypt(bytes(11) + b'\x00') + +name = b'.backup' +local = struct.pack('&1 | grep -o -m1 'CANNOT_UNPACK_ARCHIVE' + +rm -rf "${WORK_DIR}" diff --git a/tests/queries/0_stateless/05812_system_sync_database_replica_access.reference b/tests/queries/0_stateless/05812_system_sync_database_replica_access.reference new file mode 100644 index 000000000000..88e89ab2bb9b --- /dev/null +++ b/tests/queries/0_stateless/05812_system_sync_database_replica_access.reference @@ -0,0 +1,5 @@ +-- without the grant +ACCESS_DENIED +ACCESS_DENIED +-- with the grant +ACCESS_DENIED diff --git a/tests/queries/0_stateless/05812_system_sync_database_replica_access.sh b/tests/queries/0_stateless/05812_system_sync_database_replica_access.sh new file mode 100755 index 000000000000..ffa01b06fd49 --- /dev/null +++ b/tests/queries/0_stateless/05812_system_sync_database_replica_access.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Tags: zookeeper + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="user_05812_${CLICKHOUSE_DATABASE}" +db="${CLICKHOUSE_DATABASE}_repl" + +cleanup() +{ + ${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}" + ${CLICKHOUSE_CLIENT} --query "DROP DATABASE IF EXISTS ${db} SYNC" +} + +trap cleanup EXIT +cleanup + +${CLICKHOUSE_CLIENT} <&1 | grep -o -m1 "ACCESS_DENIED" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SYSTEM SYNC DATABASE REPLICA ${CLICKHOUSE_DATABASE}" 2>&1 | grep -o -m1 "ACCESS_DENIED" + +echo "-- with the grant" +${CLICKHOUSE_CLIENT} --query "GRANT SYSTEM SYNC DATABASE REPLICA ON ${db}.* TO ${user}" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SYSTEM SYNC DATABASE REPLICA ${db}" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SYSTEM SYNC DATABASE REPLICA ${CLICKHOUSE_DATABASE}" 2>&1 | grep -o -m1 "ACCESS_DENIED" diff --git a/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference new file mode 100644 index 000000000000..d669fdca1cc6 --- /dev/null +++ b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference @@ -0,0 +1,10 @@ +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +0 local_directory +1 memory +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +policy_05813_source local_directory +policy_05813_target memory +policy_05813_renamed local_directory +policy_05813_target memory diff --git a/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh new file mode 100755 index 000000000000..08195f41a32c --- /dev/null +++ b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# no-replicated-database: that configuration replaces the user directories, so there is no `memory` storage. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A rename of a quota or a row policy with `IN` must not take a name used in another user directory. + +source_quota="quota_05813_source_${CLICKHOUSE_DATABASE}" +target_quota="quota_05813_target_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP QUOTA IF EXISTS ${source_quota}, ${target_quota}" +${CLICKHOUSE_CLIENT} --query "CREATE QUOTA ${source_quota} IN local_directory" +${CLICKHOUSE_CLIENT} --query "CREATE QUOTA ${target_quota} IN memory" +${CLICKHOUSE_CLIENT} --query "ALTER QUOTA ${source_quota} IN local_directory RENAME TO ${target_quota}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "ALTER QUOTA IF EXISTS ${source_quota} IN local_directory RENAME TO ${target_quota}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT name = '${target_quota}', storage FROM system.quotas WHERE name IN ('${source_quota}', '${target_quota}') ORDER BY storage" +${CLICKHOUSE_CLIENT} --query "DROP QUOTA ${source_quota}, ${target_quota}" + +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_05813 (x UInt8) ENGINE = Memory" +${CLICKHOUSE_CLIENT} --query "DROP ROW POLICY IF EXISTS policy_05813_source, policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813" +${CLICKHOUSE_CLIENT} --query "CREATE ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory" +${CLICKHOUSE_CLIENT} --query "CREATE ROW POLICY policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813 IN memory" +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_target" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY IF EXISTS policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_target" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT short_name, storage FROM system.row_policies WHERE database = '${CLICKHOUSE_DATABASE}' AND table = 't_05813' ORDER BY storage" + +# A rename within the requested directory to a free name still works. +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_renamed" +${CLICKHOUSE_CLIENT} --query "SELECT short_name, storage FROM system.row_policies WHERE database = '${CLICKHOUSE_DATABASE}' AND table = 't_05813' ORDER BY storage" + +${CLICKHOUSE_CLIENT} --query "DROP ROW POLICY policy_05813_renamed, policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813" +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_05813" diff --git a/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.reference b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.reference new file mode 100644 index 000000000000..e722b1cbb8b7 --- /dev/null +++ b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.reference @@ -0,0 +1,6 @@ +CREATE DICTIONARY default.d_url\n(\n `id` UInt64,\n `v` String\n)\nPRIMARY KEY id\nSOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\'))\nLIFETIME(MIN 0 MAX 0)\nLAYOUT(FLAT()) +d_endpoint SOURCE(HTTP(ENDPOINT \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +d_plain SOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +d_token SOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +d_url SOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +4 0 diff --git a/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.sql b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.sql new file mode 100644 index 000000000000..ee9ca781bfa6 --- /dev/null +++ b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.sql @@ -0,0 +1,40 @@ +-- The `url` and `endpoint` of an `HTTP` dictionary source are hidden whole in `SHOW CREATE DICTIONARY`, +-- `system.tables` and `system.query_log`. + +SET format_display_secrets_in_show_and_select = 0; + +DROP DICTIONARY IF EXISTS d_url; +DROP DICTIONARY IF EXISTS d_endpoint; +DROP DICTIONARY IF EXISTS d_plain; +DROP DICTIONARY IF EXISTS d_token; + +CREATE DICTIONARY d_url (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(URL 'http://admin:SEKRIT_PW@localhost:11111/data.csv?access_token=SEKRIT_TOKEN&x=1' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +CREATE DICTIONARY d_endpoint (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(ENDPOINT 'http://admin:SEKRIT_PW@localhost:11111/data.csv?sig=SEKRIT_SIG' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +CREATE DICTIONARY d_plain (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(URL 'http://localhost:11111/data.csv?x=1' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +CREATE DICTIONARY d_token (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(URL 'https://SEKRIT_TOKEN@localhost:11111/data.csv' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +SHOW CREATE DICTIONARY d_url; + +SELECT name, extract(create_table_query, 'SOURCE.*\\)\\)') +FROM system.tables WHERE database = currentDatabase() AND name IN ('d_url', 'd_endpoint', 'd_plain', 'd_token') ORDER BY name; + +SYSTEM FLUSH LOGS query_log; +SELECT count(), countIf(query LIKE concat('%', 'SEKRIT', '%')) +FROM system.query_log +WHERE current_database = currentDatabase() AND query_kind = 'Create' AND type = 'QueryFinish' AND event_date >= yesterday(); + +DROP DICTIONARY d_url; +DROP DICTIONARY d_endpoint; +DROP DICTIONARY d_plain; +DROP DICTIONARY d_token; diff --git a/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.reference b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.reference new file mode 100644 index 000000000000..cd6458e7af8e --- /dev/null +++ b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.reference @@ -0,0 +1,2 @@ +SOURCE(MONGODB(URI \'mongodb://admin:[HIDDEN]@localhost:27017/db\' COLLECTION \'c\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +1 0 diff --git a/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.sql b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.sql new file mode 100644 index 000000000000..293df73d37ee --- /dev/null +++ b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest +-- no-fasttest: the MongoDB dictionary source needs USE_MONGODB + +-- The password in the `uri` of a `MongoDB` dictionary source is hidden in `system.tables` and `system.query_log`. + +SET format_display_secrets_in_show_and_select = 0; + +DROP DICTIONARY IF EXISTS d_mongo; + +CREATE DICTIONARY d_mongo (id UInt64, v String) PRIMARY KEY id +SOURCE(MONGODB(URI 'mongodb://admin:SEKRIT_PW@localhost:27017/db' COLLECTION 'c')) +LIFETIME(0) LAYOUT(FLAT()); + +SELECT extract(create_table_query, 'SOURCE.*\\)\\)') +FROM system.tables WHERE database = currentDatabase() AND name = 'd_mongo'; + +SYSTEM FLUSH LOGS query_log; +SELECT count(), countIf(query LIKE concat('%', 'SEKRIT', '%')) +FROM system.query_log +WHERE current_database = currentDatabase() AND query_kind = 'Create' AND type = 'QueryFinish' AND event_date >= yesterday(); + +DROP DICTIONARY d_mongo; diff --git a/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference new file mode 100644 index 000000000000..af49df254bf0 --- /dev/null +++ b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference @@ -0,0 +1,55 @@ +--- File properties are rejected in a collection created by SQL +kafka.ssl_key_location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_certificate_location: Kafka property `ssl.certificate.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.certificate.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_crl_location: Kafka property `ssl.crl.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_keystore_location: Kafka property `ssl.keystore.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_engine_location: Kafka property `ssl.engine.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_engine_id: Kafka property `ssl.engine.id` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_providers: Kafka property `ssl.providers` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.https_ca_location: Kafka property `https.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `https.ca.pem` instead. (BAD_ARGUMENTS) +kafka.sasl_kerberos_keytab: Kafka property `sasl.kerberos.keytab` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_kerberos_kinit_cmd: Kafka property `sasl.kerberos.kinit.cmd` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_file: Kafka property `sasl.oauthbearer.assertion.file` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_private_key_file: Kafka property `sasl.oauthbearer.assertion.private.key.file` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `sasl.oauthbearer.assertion.private.key.pem` instead. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_jwt_template_file: Kafka property `sasl.oauthbearer.assertion.jwt.template.file` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.plugin_library_paths: Kafka property `plugin.library.paths` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.offset_store_path: Kafka property `offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +--- Unlisted properties are server-local by default +kafka.future_option: Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.consumer.future.fetch_min_bytes: Kafka property `future.fetch.min.bytes` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +--- Other spellings and sections +kafka.ssl.key.location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.topic.offset.store.path: Kafka property `topic.offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.consumer.ssl_key_location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.producer.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +kafka.kafka_topic.offset_store_path: Kafka property `offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.kafka_topic.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +--- A null character in the name of a property +kafka.ssl_key_location\0suffix: Kafka property name `kafka.ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +kafka.consumer.ssl_key_location\0: Kafka property name `kafka.consumer.ssl_key_location\0` contains a null character. (BAD_ARGUMENTS) +kafka.client_rack\0suffix: Kafka property name `kafka.client_rack\0suffix` contains a null character. (BAD_ARGUMENTS) +--- The contents of the file are accepted, and also the value that is not a path +kafka.ssl_ca_location: OK +kafka.ssl_key_pem: OK +kafka.consumer.fetch.min.bytes: OK +--- A collection from the server configuration file is accepted +OK +--- Consumers are created for the accepted properties +Consumer set property fetch.min.bytes:456 +kafka_config_table: OK 0 +kafka_pem_table: OK 0 +kafka_probe_table: OK 0 +--- A property that is added after the table is created +kafka.ssl_key_pem: OK +kafka.future_option: +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +OK +kafka.ssl_key_pem: OK +kafka.ssl_key_location\0suffix: +Kafka property name `ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +Kafka property name `ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +Kafka property name `kafka.ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +OK diff --git a/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh new file mode 100755 index 000000000000..b1adaaa9e2d6 --- /dev/null +++ b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-replicated-database +# no-fasttest: the Kafka engine is not built in fasttest +# no-replicated-database: named collections created by SQL are not replicated + +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=fatal + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The `kafka.*` keys of a named collection are forwarded to librdkafka. Some librdkafka properties refer to +# the filesystem of the server: librdkafka reads, creates, loads or runs the file with the privileges of the server. +# `CREATE NAMED COLLECTION` does not require the privileges to access the files of the server, thus these +# properties are accepted only from a named collection that is defined in the server configuration file. +# No broker is needed: `CREATE TABLE` does not connect, and the configuration of a consumer or a producer +# is checked before the connection. + +collection="${CLICKHOUSE_TEST_UNIQUE_NAME}" +required_keys="kafka_broker_list = '127.0.0.1:1', kafka_topic_list = 'topic', kafka_group_name = 'group', kafka_format = 'JSONEachRow'" +table_settings="SETTINGS kafka_poll_timeout_ms = 100, kafka_flush_interval_ms = 100" +all_collections=() +all_tables=(kafka_table kafka_probe_table kafka_pem_table kafka_config_table kafka_scoped_table kafka_altered_table kafka_altered_null_table) + +function cleanup() +{ + local queries="" + for name in "${all_tables[@]}" + do + queries+=" DROP TABLE IF EXISTS ${name};" + done + for name in "${all_collections[@]}" + do + queries+=" DROP NAMED COLLECTION IF EXISTS ${name};" + done + $CLICKHOUSE_CLIENT -q "$queries" +} +trap cleanup EXIT + +# Prints `OK` and the result of the queries, or the message of the error about the Kafka property. +function run() +{ + local output + local message + if output=$($CLICKHOUSE_CLIENT -q "$1" 2>&1) + then + echo "OK${output:+ $output}" + else + message=$(grep -o 'Kafka property .*(BAD_ARGUMENTS)' <<< "$output" | sed 's/: While executing [A-Za-z]*\././' | head -1) + echo "${message:-$output}" + fi +} + +# Creates a named collection with one extended property and then a table that uses it. +function create_table() +{ + local key="$1" + local value="$2" + local table="${3:-kafka_table}" + local name="${collection}_${#all_collections[@]}" + all_collections+=("$name") + + echo "${key}: $(run " + CREATE NAMED COLLECTION ${name} AS ${required_keys}, \`${key}\` = '${value}'; + CREATE TABLE ${table} (x UInt64) ENGINE = Kafka(${name}) ${table_settings};")" +} + +# Creates a table with an accepted named collection, and then adds a property to the collection. +function alter_collection_of_existing_table() +{ + local key="$1" + local table="$2" + + create_table 'kafka.ssl_key_pem' 'contents of the file' "$table" + $CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${all_collections[-1]} SET \`${key}\` = '/etc/passwd'" + echo "${key}:" + run "SELECT count() FROM ${table} SETTINGS stream_like_engine_allow_direct_select = 1" + run "INSERT INTO ${table} VALUES (1)" + # A table that is read back from its metadata is checked in the same way as a new table. + $CLICKHOUSE_CLIENT -q "DETACH TABLE ${table}" + run "ATTACH TABLE ${table}" + # The table is attached again when the collection does not have the property. + # `ALTER NAMED COLLECTION ... DELETE` is not used: the formatted query cannot be parsed back if the key has a dot. + # The collection is created again instead: the detached table does not prevent `DROP NAMED COLLECTION`. + $CLICKHOUSE_CLIENT -q " + DROP NAMED COLLECTION ${all_collections[-1]}; + CREATE NAMED COLLECTION ${all_collections[-1]} AS ${required_keys};" + run "ATTACH TABLE ${table}" +} + +echo '--- File properties are rejected in a collection created by SQL' +for key in \ + ssl_key_location ssl_certificate_location ssl_ca_location ssl_crl_location ssl_keystore_location \ + ssl_engine_location ssl_engine_id ssl_providers https_ca_location \ + sasl_kerberos_keytab sasl_kerberos_kinit_cmd \ + sasl_oauthbearer_assertion_file sasl_oauthbearer_assertion_private_key_file sasl_oauthbearer_assertion_jwt_template_file \ + plugin_library_paths offset_store_path +do + create_table "kafka.${key}" '/etc/passwd' +done + +echo '--- Unlisted properties are server-local by default' +create_table 'kafka.future_option' '1' +create_table 'kafka.consumer.future.fetch_min_bytes' '1' + +echo '--- Other spellings and sections' +create_table 'kafka.ssl.key.location' '/etc/passwd' +create_table 'kafka.topic.offset.store.path' '/etc/passwd' +create_table 'kafka.consumer.ssl_key_location' '/etc/passwd' +create_table 'kafka.producer.ssl_ca_location' '/etc/passwd' +create_table 'kafka.kafka_topic.offset_store_path' '/etc/passwd' +create_table 'kafka.kafka_topic.ssl_ca_location' '' + +echo '--- A null character in the name of a property' +# librdkafka gets the name as a C string, thus it uses only the part before the null character: +# without the check, the first key sets `ssl.key.location`. +create_table 'kafka.ssl_key_location\0suffix' '/etc/passwd' +create_table 'kafka.consumer.ssl_key_location\0' '/etc/passwd' +create_table 'kafka.client_rack\0suffix' 'rack' + +echo '--- The contents of the file are accepted, and also the value that is not a path' +create_table 'kafka.ssl_ca_location' 'probe' kafka_probe_table +create_table 'kafka.ssl_key_pem' 'contents of the file' kafka_pem_table +create_table 'kafka.consumer.fetch.min.bytes' '123' kafka_scoped_table +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${all_collections[-1]} SET + \`kafka.consumer.kafka_topic.name\` = 'topic', \`kafka.consumer.kafka_topic.fetch_min_bytes\` = '456'" + +echo '--- A collection from the server configuration file is accepted' +run "CREATE TABLE kafka_config_table (x UInt64) ENGINE = Kafka(kafka_config_file_paths) ${table_settings}" + +echo '--- Consumers are created for the accepted properties' +# Each consumer waits for the assignment of partitions for 15 seconds, thus the tables are read at the same time. +{ + for table in kafka_probe_table kafka_pem_table kafka_config_table + do + echo "${table}: $(run "SELECT count() FROM ${table} SETTINGS stream_like_engine_allow_direct_select = 1")" & + done + $CLICKHOUSE_CLIENT --send_logs_level=trace -q 'SELECT count() FROM kafka_scoped_table SETTINGS stream_like_engine_allow_direct_select = 1' 2>&1 \ + | grep -o 'Consumer set property fetch.min.bytes:456' | sort -u & + wait +} | sort + +echo '--- A property that is added after the table is created' +alter_collection_of_existing_table 'kafka.future_option' kafka_altered_table +alter_collection_of_existing_table 'kafka.ssl_key_location\0suffix' kafka_altered_null_table diff --git a/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.reference b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.reference new file mode 100644 index 000000000000..394d6bf8f288 --- /dev/null +++ b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.reference @@ -0,0 +1,3 @@ +(1,'a') (5,'b') 3 +1 +0 diff --git a/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.sh b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.sh new file mode 100755 index 000000000000..be515083ee16 --- /dev/null +++ b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# `_minmax_count_projection` builds one `min`/`max` state per part. For a `Tuple` key that state owns +# heap memory, so a state that is never destroyed is a leak. A leak reports only at process exit, so +# the queries run in a short-lived `clickhouse-local` and the leak reports in its own sanitizer log +# are counted. The count is 0 on a build without a leak sanitizer, so one reference matches every +# build type. The last `log_path` wins over the runner's, and the pipeline keeps the shell from +# printing a job status line to stderr when the sanitizer aborts. +log="${CLICKHOUSE_TMP}/05828_${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -f "$log"* + +o="log_path=$log" +ASAN_OPTIONS="${ASAN_OPTIONS:+$ASAN_OPTIONS:}$o" MSAN_OPTIONS="${MSAN_OPTIONS:+$MSAN_OPTIONS:}$o" \ +TSAN_OPTIONS="${TSAN_OPTIONS:+$TSAN_OPTIONS:}$o" UBSAN_OPTIONS="${UBSAN_OPTIONS:+$UBSAN_OPTIONS:}$o" \ + $CLICKHOUSE_LOCAL --query " + CREATE TABLE tab (k Tuple(UInt64, String)) ENGINE = MergeTree ORDER BY k; + SYSTEM STOP MERGES tab; + INSERT INTO tab VALUES ((1, 'a')), ((5, 'b')); + INSERT INTO tab VALUES ((3, 'c')); + + SELECT min(k), max(k), count() FROM tab SETTINGS optimize_use_projections = 1, optimize_use_implicit_projections = 1; + + -- The query above must be answered by the projection, otherwise a zero leak count proves nothing. + SELECT count() > 0 FROM (EXPLAIN SELECT min(k), max(k), count() FROM tab SETTINGS optimize_use_projections = 1, optimize_use_implicit_projections = 1) + WHERE explain ILIKE '%_minmax_count_projection%'; + " | cat + +cat "$log"* 2>/dev/null | grep -c 'detected memory leaks' || true +rm -f "$log"* diff --git a/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.reference b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.reference new file mode 100644 index 000000000000..a7242c5404cf --- /dev/null +++ b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.reference @@ -0,0 +1,3 @@ +window: OK +argMax: OK +1 diff --git a/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.sh b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.sh new file mode 100755 index 000000000000..04044985266b --- /dev/null +++ b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +# An aggregate state was destroyed twice when its `create` threw right after the previous state was destroyed: +# in `recreate` of window aggregate states, and in `-ArgMin` / `-ArgMax` when the nested state is reset. +# `-Resample` makes most of the allocations happen in `create`, and only the last bucket keeps data that is freed +# twice. `-OrDefault` makes the results of the empty buckets cheap. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +SETTINGS="SETTINGS allow_introspection_functions = 1, memory_tracker_fault_probability = 0.0001, max_untracked_memory = 1" + +function check() +{ + local name=$1 query=$2 expected=$3 + local unexpected=0 + for _ in {1..10}; do + out=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "$query $SETTINGS" 2>&1) + if [ "$out" != "$expected" ] && ! grep -q "MEMORY_LIMIT_EXCEEDED" <<< "$out"; then + echo "$name: unexpected output: $out" + unexpected=1 + fi + done + [ $unexpected -eq 0 ] && echo "$name: OK" +} + +check window "SELECT count() FROM (SELECT flameGraphOrDefaultResample(0, 100, 1)([toUInt64(1)], 99) OVER (PARTITION BY number) AS r FROM numbers(5000))" 5000 +check argMax "SELECT length(flameGraphResampleArgMax(0, 100, 1)([toUInt64(1)], 99, number)) FROM numbers(3000)" 100 + +# The server is alive. +$CLICKHOUSE_CLIENT -q "SELECT 1" diff --git a/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference new file mode 100644 index 000000000000..996d06fdddaf --- /dev/null +++ b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference @@ -0,0 +1,4 @@ +THERE_IS_NO_COLUMN +ACCESS_DENIED +ACCESS_DENIED +x y diff --git a/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh new file mode 100755 index 000000000000..a9f02762ca78 --- /dev/null +++ b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A full-definition ATTACH MATERIALIZED VIEW validates the SELECT query like CREATE does. + +user="user05836_${CLICKHOUSE_DATABASE}_$RANDOM" +db=${CLICKHOUSE_DATABASE} + +${CLICKHOUSE_CLIENT} <&1 | grep -o -m1 -E "ACCESS_DENIED|THERE_IS_NO_COLUMN" +} + +# The SELECT outputs a column which is not in the target table. +${CLICKHOUSE_CLIENT} --send_logs_level=none --query " + ATTACH MATERIALIZED VIEW $db.mv UUID '$(${CLICKHOUSE_CLIENT} -q "SELECT generateUUIDv4()")' TO $db.dst (a String, b String) + AS SELECT a, b AS c FROM $db.src" 2>&1 | grep -o -m1 "THERE_IS_NO_COLUMN" + +# Privileges on the tables in the SELECT are required, the same as for CREATE. +${CLICKHOUSE_CLIENT} --user "$user" --query " + CREATE MATERIALIZED VIEW $db.mv TO $db.dst (a String, b String) AS SELECT a, b FROM $db.src" 2>&1 | grep -o -m1 "ACCESS_DENIED" +attach_mv --user "$user" + +${CLICKHOUSE_CLIENT} --query "GRANT SELECT ON $db.src TO $user" +attach_mv --user "$user" +${CLICKHOUSE_CLIENT} --query "INSERT INTO $db.src VALUES ('x', 'y')" +${CLICKHOUSE_CLIENT} --user "$user" --query "SELECT * FROM $db.dst" + +${CLICKHOUSE_CLIENT} --query "DROP TABLE $db.mv" +${CLICKHOUSE_CLIENT} --query "DROP USER $user" diff --git a/tests/queries/0_stateless/05843_capnproto_group_fields.reference b/tests/queries/0_stateless/05843_capnproto_group_fields.reference new file mode 100644 index 000000000000..920aaa9d364b --- /dev/null +++ b/tests/queries/0_stateless/05843_capnproto_group_fields.reference @@ -0,0 +1,44 @@ +two groups in a struct without pointers +6 1 2 3 +20971526 4 5 6 +117440518 7 8 9 +16045690984833335023 1229782938533634594 3689348815028241476 18446744073709551615 +the same as tuples +(6) 1 2 (3) +(20971526) 4 5 (6) +groups in a struct with pointers +a (6,'b',(7)) c +dd (20971526,'ee',(4294967295)) ff +named unions +6 1 a +\N 2 \N +20971526 3 \N +\N 4 b +groups in a nested struct and in a list +303132335758595A343536376162636438392D2D65666768 (1,(7)) [((6,'a')),((20971526,'b'))] +0600400100000000 (2,(20971526)) [] +null-first named unions after other fields +42 a 7 b +43 c \N \N +44 d 20971526 \N +45 e \N f +the same data read as plain fields +42 a 1 7 1 b +43 c 0 0 0 +44 d 1 20971526 0 +45 e 0 0 1 f +a tuple under a flattened name in a group +(6,7) 1 +(20971526,117440518) 2 +6 7 1 +20971526 117440518 2 +a tuple under a flattened name in a struct +(6,7) 1 +(20971526,117440518) 2 +6 7 1 +20971526 117440518 2 +schema inference +g Tuple(\n x UInt64) +m1 UInt64 +m2 UInt64 +h Tuple(\n y UInt64) diff --git a/tests/queries/0_stateless/05843_capnproto_group_fields.sql b/tests/queries/0_stateless/05843_capnproto_group_fields.sql new file mode 100644 index 000000000000..da33b61bbd3e --- /dev/null +++ b/tests/queries/0_stateless/05843_capnproto_group_fields.sql @@ -0,0 +1,63 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the Cap'n Proto format is not built in the Fast test build. + +-- A group (or a named union) is stored inline in its parent struct, not behind a pointer. + +SET output_format_parallel_formatting = 0; +SET input_format_parallel_parsing = 0; +-- The `file` table function is used so that both the writer and the reader use the schema below. +SET engine_file_truncate_on_insert = 1; + +SET format_schema_source = 'string'; +SET format_schema = '@0xd508eaf2a79b4a10; struct Inner { a @0 :UInt64; g :group { x @1 :UInt64; } } struct Elem { g :group { x @0 :UInt64; s @1 :Text; } } struct TwoGroups { g :group { x @0 :UInt64; } m1 @1 :UInt64; m2 @2 :UInt64; h :group { y @3 :UInt64; } } struct WithPointers { s1 @0 :Text; g :group { x @1 :UInt64; s @2 :Text; n :group { y @3 :UInt32; } } s2 @4 :Text; } struct NamedUnion { n :union { value @0 :UInt64; null @1 :Void; } m @2 :UInt64; t :union { null @3 :Void; value @4 :Text; } } struct Nested { blob @0 :Data; inner @1 :Inner; elems @2 :List(Elem); } struct NullFirst { prefix @0 :UInt64; s @1 :Text; n :union { null @2 :Void; value @3 :UInt64; } t :union { null @4 :Void; value @5 :Text; } } struct NullFirstPlain { prefix @0 :UInt64; s @1 :Text; nTag @2 :UInt16; nValue @3 :UInt64; tTag @4 :UInt16; tValue @5 :Text; } struct FlatGroups { g :group { h :group { x @0 :UInt64; y @1 :UInt64; } z @2 :UInt64; } } struct Pair { x @0 :UInt64; y @1 :UInt64; } struct Mid { h @0 :Pair; z @1 :UInt64; } struct FlatStructs { g @0 :Mid; }'; + +SELECT 'two groups in a struct without pointers'; +SET format_schema_message_name = 'TwoGroups'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_1.capnp', CapnProto, '`g.x` UInt64, m1 UInt64, m2 UInt64, `h.y` UInt64') VALUES (6, 1, 2, 3), (20971526, 4, 5, 6), (117440518, 7, 8, 9), (16045690984833335023, 1229782938533634594, 3689348815028241476, 18446744073709551615); +SELECT * FROM file(currentDatabase() || '_05843_1.capnp', CapnProto, '`g.x` UInt64, m1 UInt64, m2 UInt64, `h.y` UInt64') ORDER BY m1; + +SELECT 'the same as tuples'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_2.capnp', CapnProto, 'g Tuple(x UInt64), m1 UInt64, m2 UInt64, h Tuple(y UInt64)') VALUES ((6), 1, 2, (3)), ((20971526), 4, 5, (6)); +SELECT * FROM file(currentDatabase() || '_05843_2.capnp', CapnProto, 'g Tuple(x UInt64), m1 UInt64, m2 UInt64, h Tuple(y UInt64)') ORDER BY m1; + +SELECT 'groups in a struct with pointers'; +SET format_schema_message_name = 'WithPointers'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_3.capnp', CapnProto, 's1 String, g Tuple(x UInt64, s String, n Tuple(y UInt32)), s2 String') VALUES ('a', (6, 'b', (7)), 'c'), ('dd', (20971526, 'ee', (4294967295)), 'ff'); +SELECT * FROM file(currentDatabase() || '_05843_3.capnp', CapnProto, 's1 String, g Tuple(x UInt64, s String, n Tuple(y UInt32)), s2 String') ORDER BY s1; + +SELECT 'named unions'; +SET format_schema_message_name = 'NamedUnion'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_4.capnp', CapnProto, 'n Nullable(UInt64), m UInt64, t Nullable(String)') VALUES (6, 1, 'a'), (NULL, 2, NULL), (20971526, 3, NULL), (NULL, 4, 'b'); +SELECT * FROM file(currentDatabase() || '_05843_4.capnp', CapnProto, 'n Nullable(UInt64), m UInt64, t Nullable(String)') ORDER BY m; + +SELECT 'groups in a nested struct and in a list'; +SET format_schema_message_name = 'Nested'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_5.capnp', CapnProto, 'blob String, inner Tuple(a UInt64, g Tuple(x UInt64)), elems Array(Tuple(g Tuple(x UInt64, s String)))') VALUES ('0123WXYZ4567abcd89--efgh', (1, (7)), [((6, 'a')), ((20971526, 'b'))]), (unhex('0600400100000000'), (2, (20971526)), []); +SELECT hex(blob), inner, elems FROM file(currentDatabase() || '_05843_5.capnp', CapnProto, 'blob String, inner Tuple(a UInt64, g Tuple(x UInt64)), elems Array(Tuple(g Tuple(x UInt64, s String)))') ORDER BY inner.a; + +-- The value of a union is not in the slot 0 here, unlike its `Void` member. +SELECT 'null-first named unions after other fields'; +SET format_schema_message_name = 'NullFirst'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, n Nullable(UInt64), t Nullable(String)') VALUES (42, 'a', 7, 'b'), (43, 'c', NULL, NULL), (44, 'd', 20971526, NULL), (45, 'e', NULL, 'f'); +SELECT * FROM file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, n Nullable(UInt64), t Nullable(String)') ORDER BY prefix; + +-- `NullFirstPlain` has the same layout as `NullFirst`, with the discriminants of the unions as ordinary fields. +SELECT 'the same data read as plain fields'; +SET format_schema_message_name = 'NullFirstPlain'; +SELECT * FROM file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, nTag UInt16, nValue UInt64, tTag UInt16, tValue String') ORDER BY prefix; + +SELECT 'a tuple under a flattened name in a group'; +SET format_schema_message_name = 'FlatGroups'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') VALUES ((6, 7), 1), ((20971526, 117440518), 2); +SELECT * FROM file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') ORDER BY `g.z`; +SELECT * FROM file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h.x` UInt64, `g.h.y` UInt64, `g.z` UInt64') ORDER BY `g.z`; + +SELECT 'a tuple under a flattened name in a struct'; +SET format_schema_message_name = 'FlatStructs'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') VALUES ((6, 7), 1), ((20971526, 117440518), 2); +SELECT * FROM file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') ORDER BY `g.z`; +SELECT * FROM file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h.x` UInt64, `g.h.y` UInt64, `g.z` UInt64') ORDER BY `g.z`; + +SELECT 'schema inference'; +SET format_schema_message_name = 'TwoGroups'; +DESC format(CapnProto, ''); diff --git a/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference new file mode 100644 index 000000000000..b5535d7646e5 --- /dev/null +++ b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference @@ -0,0 +1,8 @@ +a list in a group +([],[]) +([1],[2]) +([3,4],[5,6]) +a list in a struct +([],[]) +([1],[2]) +([3,4],[5,6]) diff --git a/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql new file mode 100644 index 000000000000..36c42eb0304c --- /dev/null +++ b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql @@ -0,0 +1,27 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the Cap'n Proto format is not built in the Fast test build. + +-- Columns with flattened names (like `l.x` and `l.y`) are written to the same list, so the sizes of their arrays must match. +-- For top-level columns it is also checked on `INSERT` before the format, so the flattened names are put inside a `Tuple` +-- to reach the check in the format itself, like `SELECT ... FORMAT CapnProto` does. + +SET output_format_parallel_formatting = 0; +SET input_format_parallel_parsing = 0; +SET engine_file_truncate_on_insert = 1; + +SET format_schema_source = 'string'; +SET format_schema = '@0xeed9ecfa9f9df117; struct E { x @0 :UInt64; y @1 :UInt64; } struct T { l @0 :List(E); } struct InGroup { t :group { l @0 :List(E); } } struct InStruct { t @0 :T; }'; + +SELECT 'a list in a group'; +SET format_schema_message_name = 'InGroup'; +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([1, 2], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') VALUES (([], [])), (([1], [2])), (([3, 4], [5, 6])); +SELECT * FROM file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') ORDER BY length(t.1); + +SELECT 'a list in a struct'; +SET format_schema_message_name = 'InStruct'; +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([1, 2], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') VALUES (([], [])), (([1], [2])), (([3, 4], [5, 6])); +SELECT * FROM file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') ORDER BY length(t.1); diff --git a/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference new file mode 100644 index 000000000000..08552bc1f284 --- /dev/null +++ b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference @@ -0,0 +1,10 @@ +x Nullable(Int64) +y Nullable(UInt64) +x Nullable(Int64) +y Nullable(UInt64) +a Array(Nullable(Float64)) +b Array(Nullable(UInt64)) +x Nullable(String) +x Nullable(String) +x Nullable(String) +Array(Nullable(Int64)) Array(Dynamic) Array(Dynamic) diff --git a/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql new file mode 100644 index 000000000000..422740e3deaa --- /dev/null +++ b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql @@ -0,0 +1,15 @@ +-- A type freed during inference must not pass its negative or parsed-from-string mark to another value. + +DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":1}\n{"y":18446744073709551615}'); +DESC format(JSONEachRow, '{"x":-1}\n{"x":-2}\n{"y":1}\n{"y":18446744073709551615}'); +DESC format(JSONEachRow, '{"a":[-1, 1.5], "b":[1, 18446744073709551615]}'); +DESC format(JSONEachRow, '{"x":"1"}\n{"x":"2"}\n{"y":1}\n{"y":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- The marks still work. +DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":-1}\n{"y":18446744073709551615}'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":["-1"]}\n{"x":["18446744073709551615"]}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":"1"}\n{"x":1.5}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +DESC format(JSONEachRow, '{"x":"-1"}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +DESC format(JSONEachRow, '{"x":1}\n{"x":1.5}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":"1"}\n{"x":"18446744073709551615"}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +SELECT dynamicType(j.a), dynamicType(j.b), dynamicType(j.c) FROM format(JSONEachRow, 'j JSON', '{"j":{"a":[-1, 1], "b":["-1", "18446744073709551615"], "c":[-1, 18446744073709551615]}}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1; diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference new file mode 100644 index 000000000000..c7fe4b160b3b --- /dev/null +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference @@ -0,0 +1,25 @@ +-- The key (the first argument) of the keyed SipHash functions must not be visible in formatted or logged queries. + +-- { echoOn } +EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash64Keyed(\'[HIDDEN]\', number, \'visible_input\') +FROM numbers(1) +EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash128Keyed(\'[HIDDEN]\', number, \'visible_input\') +FROM numbers(1) +EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', number, \'visible_input\') +FROM numbers(1) +-- A key which is not a literal is hidden as well. +EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); +SELECT sipHash64Keyed(\'[HIDDEN]\', \'visible_input\') +FROM numbers(1) +-- The functions without a key are not affected. +EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); +SELECT sipHash64((CAST(\'1311768467463790320\', \'UInt64\'), CAST(\'18364758544493064720\', \'UInt64\')), \'visible_input\') +FROM system.one +1 +SELECT sipHash128Keyed(\'[HIDDEN]\', \'logged_input_2\') FORMAT `Null` +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', \'logged_input_3\') FORMAT `Null` +SELECT sipHash64Keyed(\'[HIDDEN]\', \'logged_input_1\') FORMAT `Null` +0 diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql new file mode 100644 index 000000000000..ae1de74058d0 --- /dev/null +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql @@ -0,0 +1,32 @@ +-- The key (the first argument) of the keyed SipHash functions must not be visible in formatted or logged queries. + +-- { echoOn } +EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); + +-- A key which is not a literal is hidden as well. +EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); + +-- The functions without a key are not affected. +EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); +-- { echoOff } + +-- Masking does not change the result. +SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input') = sipHash64Keyed((materialize(1311768467463790320::UInt64), 18364758544493064720::UInt64), 'visible_input'); + +SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_1') FORMAT Null; +SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_2') FORMAT Null; +SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_3') FORMAT Null; + +SYSTEM FLUSH LOGS query_log; + +SELECT query +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE '%logged\_input\__%' AND query NOT LIKE '%system.query_log%' +ORDER BY query; + +SELECT count() +FROM system.query_log +WHERE current_database = currentDatabase() AND query NOT LIKE '%system.query_log%' + AND (query LIKE '%1311768467463790320%' OR query LIKE '%18364758544493064720%') AND query NOT LIKE '%sipHash64(%'; diff --git a/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference new file mode 100644 index 000000000000..616bb8316151 --- /dev/null +++ b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference @@ -0,0 +1,3 @@ +1 [1,2,3] [1,2,3] +2 [4] [4] +1 5 diff --git a/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql new file mode 100644 index 000000000000..ee1916b245ab --- /dev/null +++ b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql @@ -0,0 +1,17 @@ +-- A column TTL on a column that is not stored (ALIAS, EPHEMERAL) must not break TTL merges. + +DROP TABLE IF EXISTS t_alias_ttl; +CREATE TABLE t_alias_ttl (id UInt64, dt Date, arr Array(UInt64), al Array(UInt64) ALIAS arr TTL dt + INTERVAL 1 MONTH) +ENGINE = MergeTree ORDER BY id; +INSERT INTO t_alias_ttl VALUES (1, '2000-01-01', [1, 2, 3]), (2, '2100-01-01', [4]); +OPTIMIZE TABLE t_alias_ttl FINAL; +SELECT id, arr, al FROM t_alias_ttl ORDER BY id; +DROP TABLE t_alias_ttl; + +DROP TABLE IF EXISTS t_ephemeral_ttl; +CREATE TABLE t_ephemeral_ttl (id UInt64, dt Date, e UInt64 EPHEMERAL 0 TTL dt + INTERVAL 1 MONTH, v UInt64 DEFAULT e) +ENGINE = MergeTree ORDER BY id; +INSERT INTO t_ephemeral_ttl (id, dt, e) VALUES (1, '2000-01-01', 5); +OPTIMIZE TABLE t_ephemeral_ttl FINAL; +SELECT id, v FROM t_ephemeral_ttl; +DROP TABLE t_ephemeral_ttl; diff --git a/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference new file mode 100644 index 000000000000..78981922613b --- /dev/null +++ b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference @@ -0,0 +1 @@ +a diff --git a/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql new file mode 100644 index 000000000000..7546f3b71464 --- /dev/null +++ b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql @@ -0,0 +1,25 @@ +-- Tags: no-fasttest +-- no-fasttest: the cluster secret requires SSL + +-- A remote (non-local) ClickHouse dictionary source sends its query without `initial_user`, +-- and the remote server has to forward it over a cluster with a secret. + +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dist; +DROP TABLE IF EXISTS data; + +CREATE TABLE data (key UInt64, value String) ENGINE = MergeTree ORDER BY key; +INSERT INTO data VALUES (1, 'a'); +CREATE TABLE dist AS data ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), data); + +CREATE DICTIONARY dict (key UInt64, value String) +PRIMARY KEY key +SOURCE(CLICKHOUSE(HOST '127.0.0.2' PORT tcpPort() DB currentDatabase() TABLE 'dist')) +LAYOUT(HASHED()) +LIFETIME(0); + +SELECT dictGet('dict', 'value', 1::UInt64); + +DROP DICTIONARY dict; +DROP TABLE dist; +DROP TABLE data; diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.reference b/tests/queries/0_stateless/05877_forged_interserver_interface.reference new file mode 100644 index 000000000000..3e43aed0dcab --- /dev/null +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.reference @@ -0,0 +1,2 @@ +forged interface: query accepted +1 diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.sh b/tests/queries/0_stateless/05877_forged_interserver_interface.sh new file mode 100755 index 000000000000..824717dc22bb --- /dev/null +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +python3 - < "$base/db/inner.csv" +echo 'secret' > "$base/other/secret.csv" + +fs_db="${CLICKHOUSE_DATABASE}_fs" +${CLICKHOUSE_CLIENT} -q "CREATE DATABASE $fs_db ENGINE = Filesystem('$base/db')" + +function query() +{ + ${CLICKHOUSE_CLIENT} -q "$1" 2>&1 | grep -o -m1 -e 'PATH_ACCESS_DENIED' -e '^[a-z01]*$' +} + +echo "-- inside" +query "SELECT * FROM $fs_db.\`inner.csv\`" +query "SELECT * FROM $fs_db.\`sub/../inner.csv\`" +query "SELECT * FROM $fs_db.\`{inner,missing}.csv\`" +query "EXISTS TABLE $fs_db.\`inner.csv\`" + +echo "-- outside" +query "SELECT * FROM $fs_db.\`../other/secret.csv\`" +query "SELECT * FROM $fs_db.\`$base/other/secret.csv\`" +query "SELECT * FROM $fs_db.\`../other/*.csv\`" +query "SELECT * FROM $fs_db.\`{..,sub}/other/secret.csv\`" +query "SELECT * FROM $fs_db.\`{../other/secret,inner}.csv\`" +query "EXISTS TABLE $fs_db.\`../other/secret.csv\`" +query "EXISTS TABLE $fs_db.\`../other/missing.csv\`" + +${CLICKHOUSE_CLIENT} -q "DROP DATABASE $fs_db" +rm -rf "$base" diff --git a/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference new file mode 100644 index 000000000000..2f72dd2c0684 --- /dev/null +++ b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference @@ -0,0 +1,18 @@ +-- _headers before another virtual column +hello / 1 +-- _headers between other virtual columns +/ hello 1 +-- _headers after the other virtual columns +/ hello 1 +-- _headers in SELECT, another virtual column in WHERE +hello 1 +-- the query of the AST fuzzer, with the condition negated to get a row +1 1 +-- _headers before all the other virtual columns +hello 1 1 / 1 +-- the number of rows is in the cache +1 +-- only virtual columns, _headers before another virtual column +hello / +-- only virtual columns, _headers after another virtual column +/ hello diff --git a/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql new file mode 100644 index 000000000000..2b656def13df --- /dev/null +++ b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql @@ -0,0 +1,50 @@ +-- The `url` table function added the `_headers` virtual column to its chunks after all the other +-- virtual columns, while the header of the source lists the virtual columns in the order they are +-- requested in. With `_headers` requested before another virtual column, the query read one column +-- in place of the other: an exception about the type of a column at best, a server crash otherwise. + +-- The HTTP interface adds the header of the `http_response_headers` setting, `{'X-Test':'hello'}`, to its response. + +SELECT '-- _headers before another virtual column'; +SELECT _headers['X-Test'], _path, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers between other virtual columns'; +SELECT _path, _headers['X-Test'], _file, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers after the other virtual columns'; +SELECT _path, _file, _headers['X-Test'], s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers in SELECT, another virtual column in WHERE'; +SELECT _headers['X-Test'], s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String') +WHERE _path = '/'; + +SELECT '-- the query of the AST fuzzer, with the condition negated to get a row'; +SELECT empty(_headers['X-Long']), s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String') +WHERE NOT isNotDistinctFrom(_size, true); + +-- The HTTP interface does not tell the size and the modification time of its response. +SELECT '-- _headers before all the other virtual columns'; +SELECT _headers['X-Test'], _size IS NULL OR _size > 0, _time IS NULL OR _time > '2000-01-01 00:00:00', _path, _file, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +-- A read of only virtual columns takes the number of rows from the cache without a request for the +-- data, and `_headers` was empty then, while it is the headers of the response to that request. +-- The cache is used for a URL without the `Last-Modified` header only with the setting below. +SET schema_inference_cache_require_modification_time_for_url = 0; + +SELECT '-- the number of rows is in the cache'; +SELECT count() +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers before another virtual column'; +SELECT _headers['X-Test'], _path +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers after another virtual column'; +SELECT _path, _headers['X-Test'] +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); diff --git a/tests/queries/0_stateless/helpers/fake_native_server.py b/tests/queries/0_stateless/helpers/fake_native_server.py new file mode 100644 index 000000000000..b28940a5f493 --- /dev/null +++ b/tests/queries/0_stateless/helpers/fake_native_server.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""A fake ClickHouse server that answers the query of clickhouse-client with a crafted reply. + +It is used by the tests of what a reader of the native protocol does with a malformed result block: +a real server never sends one. The server announces `REVISION`, so the reply must use its layout. +""" + +import os +import shlex +import socket +import struct +import subprocess +import threading + +# DBMS_MIN_REVISION_WITH_REPLICATED_SERIALIZATION +REVISION = 54482 +QUERY = "SELECT 'the reply of a fake server'" + + +def writeVarUInt(x, ba): + while True: + byte = x & 0x7F + x >>= 7 + ba.append(byte | (0x80 if x else 0)) + if not x: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") + writeVarUInt(len(b), ba) + ba.extend(b) + + +def serverHello(): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary("fake server", ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeVarUInt(1, ba) # parallel replicas protocol version (>= 54471) + writeStringBinary("UTC", ba) # timezone (>= 54058) + writeStringBinary("fake", ba) # display name (>= 54372) + writeVarUInt(0, ba) # version patch (>= 54401) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # password complexity rules (>= 54461) + ba.extend(struct.pack("= 54462) + writeStringBinary("", ba) # end of the server settings (>= 54474) + writeVarUInt(0, ba) # query plan serialization version (>= 54477) + writeVarUInt(0, ba) # cluster function protocol version (>= 54479) + return bytes(ba) + + +def readVarUInt(connection): + x = 0 + for shift in range(0, 63, 7): + byte = connection.recv(1) + if not byte: + raise EOFError + x |= (byte[0] & 0x7F) << shift + if not byte[0] & 0x80: + break + return x + + +def skipStringBinary(connection): + size = readVarUInt(connection) + while size: + chunk = connection.recv(size) + if not chunk: + raise EOFError + size -= len(chunk) + + +def serveOneQuery(listener, reply): + """Answers the query of one client with `reply`, without parsing the query that the client sends.""" + connection, _ = listener.accept() + with connection: + connection.settimeout(60) + received = connection.recv(65536) # the Hello of the client + connection.sendall(serverHello()) + try: + # The addendum: quota key (>= 54458), proto_send and proto_recv chunked (>= 54470), + # parallel replicas protocol version (>= 54471). + for _ in range(3): + skipStringBinary(connection) + readVarUInt(connection) + # A client may check the connection with a Ping before the query, and waits for the Pong. + packet_type = readVarUInt(connection) + while packet_type == 4: # Ping + connection.sendall(bytes([4])) # Pong + packet_type = readVarUInt(connection) + except EOFError: + return + # The Query packet follows. Once the text of the query is here, the + # client is about to wait for the result. + while QUERY.encode() not in received: + chunk = connection.recv(65536) + if not chunk: + return + received += chunk + connection.sendall(reply) + # The reply may be cut short: signal EOF so that the client gets a short read instead of + # waiting for the missing bytes, then wait until it closes the connection. + connection.shutdown(socket.SHUT_WR) + try: + while connection.recv(65536): + pass + except OSError: + pass + + +def runClientAgainstFakeServer(reply): + """The output of clickhouse-client whose server answers the query with `reply`.""" + client = shlex.split(os.environ["CLICKHOUSE_CLIENT_BINARY"]) + listener = socket.create_server(("127.0.0.1", 0)) + listener.settimeout(60) + thread = threading.Thread(target=serveOneQuery, args=(listener, reply), daemon=True) + thread.start() + try: + port = listener.getsockname()[1] + result = subprocess.run( + client + + ["--host", "127.0.0.1", "--port", str(port), "--compression", "0"] + + ["--query", QUERY], + capture_output=True, + timeout=120, + ) + return (result.stdout + result.stderr).decode("utf-8", "replace") + finally: + thread.join(timeout=60) + listener.close() diff --git a/utils/list-licenses/list-licenses.sh b/utils/list-licenses/list-licenses.sh index aafa75a247c1..b27c8cf1a948 100755 --- a/utils/list-licenses/list-licenses.sh +++ b/utils/list-licenses/list-licenses.sh @@ -137,6 +137,7 @@ process_rust_crate() { "LICENSE_A2" "LICENSE_CC0" "LICENSE_A2LLVM" + "LICENSE-0BSD.txt" ) for possible_path in "${arr[@]}" do @@ -155,6 +156,7 @@ process_rust_crate() { [ "$LICENSE_TYPE" == "MIT/Apache-2.0" ] || [ "$LICENSE_TYPE" == "MIT OR Apache-2.0 OR LGPL-2.1-or-later" ] || [ "$LICENSE_TYPE" == "Zlib OR Apache-2.0 OR MIT" ] || + [ "$LICENSE_TYPE" == "Zlib OR MIT OR Apache-2.0" ] || [ "$LICENSE_TYPE" == "Apache-2.0 OR BSL-1.0 OR MIT" ] || [ "$LICENSE_TYPE" == "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" ] || [ "$LICENSE_TYPE" == "Apache-2.0 WITH LLVM-exception" ] ||