Merge branch 'master' into fix-race-condition-between-inserts-and-dropping-mvs

This commit is contained in:
AlfVII 2022-11-24 12:32:40 +01:00 committed by GitHub
commit 6848d3df63
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
223 changed files with 4992 additions and 789 deletions

View File

@ -442,8 +442,9 @@ elseif (OS_DARWIN)
include(cmake/darwin/default_libs.cmake) include(cmake/darwin/default_libs.cmake)
elseif (OS_FREEBSD) elseif (OS_FREEBSD)
include(cmake/freebsd/default_libs.cmake) include(cmake/freebsd/default_libs.cmake)
endif () else()
link_libraries(global-group) link_libraries(global-group)
endif ()
if (NOT (OS_LINUX OR OS_DARWIN)) if (NOT (OS_LINUX OR OS_DARWIN))
# Using system libs can cause a lot of warnings in includes (on macro expansion). # Using system libs can cause a lot of warnings in includes (on macro expansion).
@ -592,7 +593,7 @@ add_subdirectory (programs)
add_subdirectory (tests) add_subdirectory (tests)
add_subdirectory (utils) add_subdirectory (utils)
include (cmake/sanitize_target_link_libraries.cmake) include (cmake/sanitize_targets.cmake)
# Build native targets if necessary # Build native targets if necessary
get_property(NATIVE_BUILD_TARGETS GLOBAL PROPERTY NATIVE_BUILD_TARGETS) get_property(NATIVE_BUILD_TARGETS GLOBAL PROPERTY NATIVE_BUILD_TARGETS)

View File

@ -220,13 +220,13 @@ struct statx {
uint32_t stx_dev_minor; uint32_t stx_dev_minor;
uint64_t spare[14]; uint64_t spare[14];
}; };
#endif
int statx(int fd, const char *restrict path, int flag, int statx(int fd, const char *restrict path, int flag,
unsigned int mask, struct statx *restrict statxbuf) unsigned int mask, struct statx *restrict statxbuf)
{ {
return syscall(SYS_statx, fd, path, flag, mask, statxbuf); return syscall(SYS_statx, fd, path, flag, mask, statxbuf);
} }
#endif
#include <syscall.h> #include <syscall.h>

View File

@ -23,6 +23,7 @@ set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
include (cmake/cxx.cmake) include (cmake/cxx.cmake)
link_libraries(global-group)
target_link_libraries(global-group INTERFACE target_link_libraries(global-group INTERFACE
$<TARGET_PROPERTY:global-libs,INTERFACE_LINK_LIBRARIES> $<TARGET_PROPERTY:global-libs,INTERFACE_LINK_LIBRARIES>

View File

@ -24,6 +24,7 @@ find_package(Threads REQUIRED)
include (cmake/unwind.cmake) include (cmake/unwind.cmake)
include (cmake/cxx.cmake) include (cmake/cxx.cmake)
link_libraries(global-group)
target_link_libraries(global-group INTERFACE target_link_libraries(global-group INTERFACE
$<TARGET_PROPERTY:global-libs,INTERFACE_LINK_LIBRARIES> $<TARGET_PROPERTY:global-libs,INTERFACE_LINK_LIBRARIES>

View File

@ -34,6 +34,13 @@ set(CMAKE_C_STANDARD_LIBRARIES ${DEFAULT_LIBS})
set(THREADS_PREFER_PTHREAD_FLAG ON) set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
include (cmake/unwind.cmake)
include (cmake/cxx.cmake)
# Delay the call to link the global interface after the libc++ libraries are included to avoid circular dependencies
# which are ok with static libraries but not with dynamic ones
link_libraries(global-group)
if (NOT OS_ANDROID) if (NOT OS_ANDROID)
if (NOT USE_MUSL) if (NOT USE_MUSL)
# Our compatibility layer doesn't build under Android, many errors in musl. # Our compatibility layer doesn't build under Android, many errors in musl.
@ -42,9 +49,6 @@ if (NOT OS_ANDROID)
add_subdirectory(base/harmful) add_subdirectory(base/harmful)
endif () endif ()
include (cmake/unwind.cmake)
include (cmake/cxx.cmake)
target_link_libraries(global-group INTERFACE target_link_libraries(global-group INTERFACE
-Wl,--start-group -Wl,--start-group
$<TARGET_PROPERTY:global-libs,INTERFACE_LINK_LIBRARIES> $<TARGET_PROPERTY:global-libs,INTERFACE_LINK_LIBRARIES>

View File

@ -1,3 +1,13 @@
# https://stackoverflow.com/a/62311397/328260
macro (get_all_targets_recursive targets dir)
get_property (subdirectories DIRECTORY ${dir} PROPERTY SUBDIRECTORIES)
foreach (subdir ${subdirectories})
get_all_targets_recursive (${targets} ${subdir})
endforeach ()
get_property (current_targets DIRECTORY ${dir} PROPERTY BUILDSYSTEM_TARGETS)
list (APPEND ${targets} ${current_targets})
endmacro ()
# When you will try to link target with the directory (that exists), cmake will # When you will try to link target with the directory (that exists), cmake will
# skip this without an error, only the following warning will be reported: # skip this without an error, only the following warning will be reported:
# #
@ -18,23 +28,12 @@
# -- but cannot be used with link_libraries() # -- but cannot be used with link_libraries()
# - use BUILDSYSTEM_TARGETS property to get list of all targets and sanitize # - use BUILDSYSTEM_TARGETS property to get list of all targets and sanitize
# -- this will work. # -- this will work.
# https://stackoverflow.com/a/62311397/328260
function (get_all_targets var) function (get_all_targets var)
set (targets) set (targets)
get_all_targets_recursive (targets ${CMAKE_CURRENT_SOURCE_DIR}) get_all_targets_recursive (targets ${CMAKE_CURRENT_SOURCE_DIR})
set (${var} ${targets} PARENT_SCOPE) set (${var} ${targets} PARENT_SCOPE)
endfunction() endfunction()
macro (get_all_targets_recursive targets dir) function (sanitize_link_libraries target)
get_property (subdirectories DIRECTORY ${dir} PROPERTY SUBDIRECTORIES)
foreach (subdir ${subdirectories})
get_all_targets_recursive (${targets} ${subdir})
endforeach ()
get_property (current_targets DIRECTORY ${dir} PROPERTY BUILDSYSTEM_TARGETS)
list (APPEND ${targets} ${current_targets})
endmacro ()
macro (sanitize_link_libraries target)
get_target_property(target_type ${target} TYPE) get_target_property(target_type ${target} TYPE)
if (${target_type} STREQUAL "INTERFACE_LIBRARY") if (${target_type} STREQUAL "INTERFACE_LIBRARY")
get_property(linked_libraries TARGET ${target} PROPERTY INTERFACE_LINK_LIBRARIES) get_property(linked_libraries TARGET ${target} PROPERTY INTERFACE_LINK_LIBRARIES)
@ -48,9 +47,35 @@ macro (sanitize_link_libraries target)
message(FATAL_ERROR "${target} requested to link with directory: ${linked_library}") message(FATAL_ERROR "${target} requested to link with directory: ${linked_library}")
endif() endif()
endforeach() endforeach()
endmacro() endfunction()
get_all_targets (all_targets) get_all_targets (all_targets)
foreach (target ${all_targets}) foreach (target ${all_targets})
sanitize_link_libraries(${target}) sanitize_link_libraries(${target})
endforeach() endforeach()
#
# Do not allow to define -W* from contrib publically (INTERFACE/PUBLIC).
#
function (get_contrib_targets var)
set (targets)
get_all_targets_recursive (targets ${CMAKE_CURRENT_SOURCE_DIR}/contrib)
set (${var} ${targets} PARENT_SCOPE)
endfunction()
function (sanitize_interface_flags target)
get_target_property(target_type ${target} TYPE)
get_property(compile_definitions TARGET ${target} PROPERTY INTERFACE_COMPILE_DEFINITIONS)
get_property(compile_options TARGET ${target} PROPERTY INTERFACE_COMPILE_OPTIONS)
if (NOT "${compile_options}" STREQUAL "")
message(FATAL_ERROR "${target} set INTERFACE_COMPILE_OPTIONS to ${compile_options}. This is forbidden.")
endif()
if ("${compile_definitions}" MATCHES "-Wl,")
# linker option - OK
elseif ("${compile_definitions}" MATCHES "-W")
message(FATAL_ERROR "${target} contains ${compile_definitions} flags in INTERFACE_COMPILE_DEFINITIONS. This is forbidden.")
endif()
endfunction()
get_contrib_targets (contrib_targets)
foreach (contrib_target ${contrib_targets})
sanitize_interface_flags(${contrib_target})
endforeach()

View File

@ -57,7 +57,7 @@ add_library(cxx ${SRCS})
set_target_properties(cxx PROPERTIES FOLDER "contrib/libcxx-cmake") set_target_properties(cxx PROPERTIES FOLDER "contrib/libcxx-cmake")
target_include_directories(cxx SYSTEM BEFORE PRIVATE $<BUILD_INTERFACE:${LIBCXX_SOURCE_DIR}/src>) target_include_directories(cxx SYSTEM BEFORE PRIVATE $<BUILD_INTERFACE:${LIBCXX_SOURCE_DIR}/src>)
target_include_directories(cxx SYSTEM BEFORE PUBLIC $<BUILD_INTERFACE:${LIBCXX_SOURCE_DIR}/include>) target_include_directories(cxx SYSTEM BEFORE PUBLIC $<$<COMPILE_LANGUAGE:CXX>:$<BUILD_INTERFACE:${LIBCXX_SOURCE_DIR}/include>>)
target_compile_definitions(cxx PRIVATE -D_LIBCPP_BUILDING_LIBRARY -DLIBCXX_BUILDING_LIBCXXABI) target_compile_definitions(cxx PRIVATE -D_LIBCPP_BUILDING_LIBRARY -DLIBCXX_BUILDING_LIBCXXABI)
# Enable capturing stack traces for all exceptions. # Enable capturing stack traces for all exceptions.

View File

@ -388,6 +388,8 @@ else
rm -f /etc/clickhouse-server/config.d/storage_conf.xml ||: rm -f /etc/clickhouse-server/config.d/storage_conf.xml ||:
rm -f /etc/clickhouse-server/config.d/azure_storage_conf.xml ||: rm -f /etc/clickhouse-server/config.d/azure_storage_conf.xml ||:
# Turn on after 22.12
rm -f /etc/clickhouse-server/config.d/compressed_marks_and_index.xml ||:
# it uses recently introduced settings which previous versions may not have # it uses recently introduced settings which previous versions may not have
rm -f /etc/clickhouse-server/users.d/insert_keeper_retries.xml ||: rm -f /etc/clickhouse-server/users.d/insert_keeper_retries.xml ||:
@ -451,6 +453,7 @@ else
# FIXME https://github.com/ClickHouse/ClickHouse/issues/39197 ("Missing columns: 'v3' while processing query: 'v3, k, v1, v2, p'") # FIXME https://github.com/ClickHouse/ClickHouse/issues/39197 ("Missing columns: 'v3' while processing query: 'v3, k, v1, v2, p'")
# NOTE Incompatibility was introduced in https://github.com/ClickHouse/ClickHouse/pull/39263, it's expected # NOTE Incompatibility was introduced in https://github.com/ClickHouse/ClickHouse/pull/39263, it's expected
# ("This engine is deprecated and is not supported in transactions", "[Queue = DB::MergeMutateRuntimeQueue]: Code: 235. DB::Exception: Part") # ("This engine is deprecated and is not supported in transactions", "[Queue = DB::MergeMutateRuntimeQueue]: Code: 235. DB::Exception: Part")
# FIXME https://github.com/ClickHouse/ClickHouse/issues/39174 - bad mutation does not indicate backward incompatibility
echo "Check for Error messages in server log:" echo "Check for Error messages in server log:"
zgrep -Fav -e "Code: 236. DB::Exception: Cancelled merging parts" \ zgrep -Fav -e "Code: 236. DB::Exception: Cancelled merging parts" \
-e "Code: 236. DB::Exception: Cancelled mutating parts" \ -e "Code: 236. DB::Exception: Cancelled mutating parts" \
@ -485,6 +488,7 @@ else
-e "(ReplicatedMergeTreeAttachThread): Initialization failed. Error" \ -e "(ReplicatedMergeTreeAttachThread): Initialization failed. Error" \
-e "Code: 269. DB::Exception: Destination table is myself" \ -e "Code: 269. DB::Exception: Destination table is myself" \
-e "Coordination::Exception: Connection loss" \ -e "Coordination::Exception: Connection loss" \
-e "MutateFromLogEntryTask" \
/var/log/clickhouse-server/clickhouse-server.backward.clean.log | zgrep -Fa "<Error>" > /test_output/bc_check_error_messages.txt \ /var/log/clickhouse-server/clickhouse-server.backward.clean.log | zgrep -Fa "<Error>" > /test_output/bc_check_error_messages.txt \
&& echo -e 'Backward compatibility check: Error message in clickhouse-server.log (see bc_check_error_messages.txt)\tFAIL' >> /test_output/test_results.tsv \ && echo -e 'Backward compatibility check: Error message in clickhouse-server.log (see bc_check_error_messages.txt)\tFAIL' >> /test_output/test_results.tsv \
|| echo -e 'Backward compatibility check: No Error messages in clickhouse-server.log\tOK' >> /test_output/test_results.tsv || echo -e 'Backward compatibility check: No Error messages in clickhouse-server.log\tOK' >> /test_output/test_results.tsv

View File

@ -48,6 +48,7 @@ The supported formats are:
| [JSONCompactStringsEachRowWithNames](#jsoncompactstringseachrowwithnames) | ✔ | ✔ | | [JSONCompactStringsEachRowWithNames](#jsoncompactstringseachrowwithnames) | ✔ | ✔ |
| [JSONCompactStringsEachRowWithNamesAndTypes](#jsoncompactstringseachrowwithnamesandtypes) | ✔ | ✔ | | [JSONCompactStringsEachRowWithNamesAndTypes](#jsoncompactstringseachrowwithnamesandtypes) | ✔ | ✔ |
| [JSONObjectEachRow](#jsonobjecteachrow) | ✔ | ✔ | | [JSONObjectEachRow](#jsonobjecteachrow) | ✔ | ✔ |
| [BSONEachRow](#bsoneachrow) | ✔ | ✔ |
| [TSKV](#tskv) | ✔ | ✔ | | [TSKV](#tskv) | ✔ | ✔ |
| [Pretty](#pretty) | ✗ | ✔ | | [Pretty](#pretty) | ✗ | ✔ |
| [PrettyNoEscapes](#prettynoescapes) | ✗ | ✔ | | [PrettyNoEscapes](#prettynoescapes) | ✗ | ✔ |
@ -1210,6 +1211,69 @@ SELECT * FROM json_each_row_nested
- [output_format_json_array_of_rows](../operations/settings/settings.md#output_format_json_array_of_rows) - output a JSON array of all rows in JSONEachRow(Compact) format. Default value - `false`. - [output_format_json_array_of_rows](../operations/settings/settings.md#output_format_json_array_of_rows) - output a JSON array of all rows in JSONEachRow(Compact) format. Default value - `false`.
- [output_format_json_validate_utf8](../operations/settings/settings.md#output_format_json_validate_utf8) - enables validation of UTF-8 sequences in JSON output formats (note that it doesn't impact formats JSON/JSONCompact/JSONColumnsWithMetadata, they always validate utf8). Default value - `false`. - [output_format_json_validate_utf8](../operations/settings/settings.md#output_format_json_validate_utf8) - enables validation of UTF-8 sequences in JSON output formats (note that it doesn't impact formats JSON/JSONCompact/JSONColumnsWithMetadata, they always validate utf8). Default value - `false`.
## BSONEachRow {#bsoneachrow}
In this format, ClickHouse formats/parses data as a sequence of BSON documents without any separator between them.
Each row is formatted as a single document and each column is formatted as a single BSON document field with column name as a key.
For output it uses the following correspondence between ClickHouse types and BSON types:
| ClickHouse type | BSON Type |
|-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
| [Bool](../sql-reference/data-types/boolean.md) | `\x08` boolean |
| [Int8/UInt8](../sql-reference/data-types/int-uint.md) | `\x10` int32 |
| [Int16UInt16](../sql-reference/data-types/int-uint.md) | `\x10` int32 |
| [Int32](../sql-reference/data-types/int-uint.md) | `\x10` int32 |
| [UInt32](../sql-reference/data-types/int-uint.md) | `\x12` int64 |
| [Int64/UInt64](../sql-reference/data-types/int-uint.md) | `\x12` int64 |
| [Float32/Float64](../sql-reference/data-types/float.md) | `\x01` double |
| [Date](../sql-reference/data-types/date.md)/[Date32](../sql-reference/data-types/date32.md) | `\x10` int32 |
| [DateTime](../sql-reference/data-types/datetime.md) | `\x12` int64 |
| [DateTime64](../sql-reference/data-types/datetime64.md) | `\x09` datetime |
| [Decimal32](../sql-reference/data-types/decimal.md) | `\x10` int32 |
| [Decimal64](../sql-reference/data-types/decimal.md) | `\x12` int64 |
| [Decimal128](../sql-reference/data-types/decimal.md) | `\x05` binary, `\x00` binary subtype, size = 16 |
| [Decimal256](../sql-reference/data-types/decimal.md) | `\x05` binary, `\x00` binary subtype, size = 32 |
| [Int128/UInt128](../sql-reference/data-types/int-uint.md) | `\x05` binary, `\x00` binary subtype, size = 16 |
| [Int256/UInt256](../sql-reference/data-types/int-uint.md) | `\x05` binary, `\x00` binary subtype, size = 32 |
| [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) | `\x05` binary, `\x00` binary subtype or \x02 string if setting output_format_bson_string_as_string is enabled |
| [UUID](../sql-reference/data-types/uuid.md) | `\x05` binary, `\x04` uuid subtype, size = 16 |
| [Array](../sql-reference/data-types/array.md) | `\x04` array |
| [Tuple](../sql-reference/data-types/tuple.md) | `\x04` array |
| [Named Tuple](../sql-reference/data-types/tuple.md) | `\x03` document |
| [Map](../sql-reference/data-types/map.md) (with String keys) | `\x03` document |
For input it uses the following correspondence between BSON types and ClickHouse types:
| BSON Type | ClickHouse Type |
|------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `\x01` double | [Float32/Float64](../sql-reference/data-types/float.md) |
| `\x02` string | [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) |
| `\x03` document | [Map](../sql-reference/data-types/map.md)/[Named Tuple](../sql-reference/data-types/tuple.md) |
| `\x04` array | [Array](../sql-reference/data-types/array.md)/[Tuple](../sql-reference/data-types/tuple.md) |
| `\x05` binary, `\x00` binary subtype | [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) |
| `\x05` binary, `\x02` old binary subtype | [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) |
| `\x05` binary, `\x03` old uuid subtype | [UUID](../sql-reference/data-types/uuid.md) |
| `\x05` binary, `\x04` uuid subtype | [UUID](../sql-reference/data-types/uuid.md) |
| `\x07` ObjectId | [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) |
| `\x08` boolean | [Bool](../sql-reference/data-types/boolean.md) |
| `\x09` datetime | [DateTime64](../sql-reference/data-types/datetime64.md) |
| `\x0A` null value | [NULL](../sql-reference/data-types/nullable.md) |
| `\x0D` JavaScript code | [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) |
| `\x0E` symbol | [String](../sql-reference/data-types/string.md)/[FixedString](../sql-reference/data-types/fixedstring.md) |
| `\x10` int32 | [Int32/UInt32](../sql-reference/data-types/int-uint.md)/[Decimal32](../sql-reference/data-types/decimal.md) |
| `\x12` int64 | [Int64/UInt64](../sql-reference/data-types/int-uint.md)/[Decimal64](../sql-reference/data-types/decimal.md)/[DateTime64](../sql-reference/data-types/datetime64.md) |
Other BSON types are not supported. Also, it performs conversion between different integer types (for example, you can insert BSON int32 value into ClickHouse UInt8).
Big integers and decimals (Int128/UInt128/Int256/UInt256/Decimal128/Decimal256) can be parsed from BSON Binary value with `\x00` binary subtype. In this case this format will validate that the size of binary data equals the size of expected value.
Note: this format don't work properly on Big-Endian platforms.
### BSON format settings {#bson-format-settings}
- [output_format_bson_string_as_string](../operations/settings/settings.md#output_format_bson_string_as_string) - use BSON String type instead of Binary for String columns. Default value - `false`.
- [input_format_bson_skip_fields_with_unsupported_types_in_schema_inference](../operations/settings/settings.md#input_format_bson_skip_fields_with_unsupported_types_in_schema_inference) - allow skipping columns with unsupported types while schema inference for format BSONEachRow. Default value - `false`.
## Native {#native} ## Native {#native}
The most efficient format. Data is written and read by blocks in binary format. For each block, the number of rows, number of columns, column names and types, and parts of columns in this block are recorded one after another. In other words, this format is “columnar” it does not convert columns to rows. This is the format used in the native interface for interaction between servers, for using the command-line client, and for C++ clients. The most efficient format. Data is written and read by blocks in binary format. For each block, the number of rows, number of columns, column names and types, and parts of columns in this block are recorded one after another. In other words, this format is “columnar” it does not convert columns to rows. This is the format used in the native interface for interaction between servers, for using the command-line client, and for C++ clients.

View File

@ -4784,7 +4784,7 @@ Possible values:
Default value: 1. Default value: 1.
## SQLInsert format settings {$sqlinsert-format-settings} ## SQLInsert format settings {#sqlinsert-format-settings}
### output_format_sql_insert_max_batch_size {#output_format_sql_insert_max_batch_size} ### output_format_sql_insert_max_batch_size {#output_format_sql_insert_max_batch_size}
@ -4815,3 +4815,17 @@ Default value: `false`.
Quote column names with "`" characters Quote column names with "`" characters
Default value: `true`. Default value: `true`.
## BSONEachRow format settings {#bson-each-row-format-settings}
### output_format_bson_string_as_string {#output_format_bson_string_as_string}
Use BSON String type instead of Binary for String columns.
Disabled by default.
### input_format_bson_skip_fields_with_unsupported_types_in_schema_inference {#input_format_bson_skip_fields_with_unsupported_types_in_schema_inference}
Allow skipping columns with unsupported types while schema inference for format BSONEachRow.
Disabled by default.

View File

@ -11,6 +11,14 @@ Projections store data in a format that optimizes query execution, this feature
You can define one or more projections for a table, and during the query analysis the projection with the least data to scan will be selected by ClickHouse without modifying the query provided by the user. You can define one or more projections for a table, and during the query analysis the projection with the least data to scan will be selected by ClickHouse without modifying the query provided by the user.
:::note Disk usage
Projections will create internally a new hidden table, this means that more IO and space on disk will be required.
Example, If the projection has defined a different primary key, all the data from the original table will be duplicated.
:::
You can see more technical details about how projections work internally on this [page](/docs/en/guides/improving-query-performance/sparse-primary-indexes/sparse-primary-indexes-multiple.md/#option-3-projections).
## Example filtering without using primary keys ## Example filtering without using primary keys
Creating the table: Creating the table:

View File

@ -60,7 +60,7 @@ If you specify `POPULATE`, the existing table data is inserted into the view whe
A `SELECT` query can contain `DISTINCT`, `GROUP BY`, `ORDER BY`, `LIMIT`. Note that the corresponding conversions are performed independently on each block of inserted data. For example, if `GROUP BY` is set, data is aggregated during insertion, but only within a single packet of inserted data. The data wont be further aggregated. The exception is when using an `ENGINE` that independently performs data aggregation, such as `SummingMergeTree`. A `SELECT` query can contain `DISTINCT`, `GROUP BY`, `ORDER BY`, `LIMIT`. Note that the corresponding conversions are performed independently on each block of inserted data. For example, if `GROUP BY` is set, data is aggregated during insertion, but only within a single packet of inserted data. The data wont be further aggregated. The exception is when using an `ENGINE` that independently performs data aggregation, such as `SummingMergeTree`.
The execution of [ALTER](../../../sql-reference/statements/alter/view.md) queries on materialized views has limitations, so they might be inconvenient. If the materialized view uses the construction `TO [db.]name`, you can `DETACH` the view, run `ALTER` for the target table, and then `ATTACH` the previously detached (`DETACH`) view. The execution of [ALTER](/docs/en/sql-reference/statements/alter/view.md) queries on materialized views has limitations, for example, you can not update the `SELECT` query, so this might be inconvenient. If the materialized view uses the construction `TO [db.]name`, you can `DETACH` the view, run `ALTER` for the target table, and then `ATTACH` the previously detached (`DETACH`) view.
Note that materialized view is influenced by [optimize_on_insert](../../../operations/settings/settings.md#optimize-on-insert) setting. The data is merged before the insertion into a view. Note that materialized view is influenced by [optimize_on_insert](../../../operations/settings/settings.md#optimize-on-insert) setting. The data is merged before the insertion into a view.

View File

@ -47,6 +47,7 @@ Union
- `AST` — Abstract syntax tree. - `AST` — Abstract syntax tree.
- `SYNTAX` — Query text after AST-level optimizations. - `SYNTAX` — Query text after AST-level optimizations.
- `QUERY TREE` — Query tree after Query Tree level optimizations.
- `PLAN` — Query execution plan. - `PLAN` — Query execution plan.
- `PIPELINE` — Query execution pipeline. - `PIPELINE` — Query execution pipeline.
@ -110,6 +111,32 @@ FROM
CROSS JOIN system.numbers AS c CROSS JOIN system.numbers AS c
``` ```
### EXPLAIN QUERY TREE
Settings:
- `run_passes` — Run all query tree passes before dumping the query tree. Defaul: `1`.
- `dump_passes` — Dump information about used passes before dumping the query tree. Default: `0`.
- `passes` — Specifies how many passes to run. If set to `-1`, runs all the passes. Default: `-1`.
Example:
```sql
EXPLAIN QUERY TREE SELECT id, value FROM test_table;
```
```
QUERY id: 0
PROJECTION COLUMNS
id UInt64
value String
PROJECTION
LIST id: 1, nodes: 2
COLUMN id: 2, column_name: id, result_type: UInt64, source_id: 3
COLUMN id: 4, column_name: value, result_type: String, source_id: 3
JOIN TREE
TABLE id: 3, table_name: default.test_table
```
### EXPLAIN PLAN ### EXPLAIN PLAN
Dump query plan steps. Dump query plan steps.

View File

@ -243,6 +243,54 @@ If `max_rows_to_group_by` and `group_by_overflow_mode = 'any'` are not used, all
You can use `WITH TOTALS` in subqueries, including subqueries in the [JOIN](../../../sql-reference/statements/select/join.md) clause (in this case, the respective total values are combined). You can use `WITH TOTALS` in subqueries, including subqueries in the [JOIN](../../../sql-reference/statements/select/join.md) clause (in this case, the respective total values are combined).
## GROUP BY ALL
`GROUP BY ALL` is equivalent to listing all the SELECT-ed expressions that are not aggregate functions.
For example:
``` sql
SELECT
a * 2,
b,
count(c),
FROM t
GROUP BY ALL
```
is the same as
``` sql
SELECT
a * 2,
b,
count(c),
FROM t
GROUP BY a * 2, b
```
For a special case that if there is a function having both aggregate functions and other fields as its arguments, the `GROUP BY` keys will contain the maximum non-aggregate fields we can extract from it.
For example:
``` sql
SELECT
substring(a, 4, 2),
substring(substring(a, 1, 2), 1, count(b))
FROM t
GROUP BY ALL
```
is the same as
``` sql
SELECT
substring(a, 4, 2),
substring(substring(a, 1, 2), 1, count(b))
FROM t
GROUP BY substring(a, 4, 2), substring(a, 1, 2)
```
## Examples ## Examples
Example: Example:

View File

@ -98,7 +98,7 @@ ClickHouse предоставляет возможность аутентифи
:::danger "Важно" :::danger "Важно"
Если пользователь настроен для Kerberos-аутентификации, другие виды уатентификации будут для него недоступны. Если наряду с `kerberos` в определении пользователя будет указан какой-либо другой способ аутентификации, ClickHouse завершит работу. Если пользователь настроен для Kerberos-аутентификации, другие виды аутентификации будут для него недоступны. Если наряду с `kerberos` в определении пользователя будет указан какой-либо другой способ аутентификации, ClickHouse завершит работу.
:::info "" :::info ""
Ещё раз отметим, что кроме `users.xml`, необходимо также включить Kerberos в `config.xml`. Ещё раз отметим, что кроме `users.xml`, необходимо также включить Kerberos в `config.xml`.

View File

@ -74,7 +74,7 @@ Kafka 特性:
消费的消息会被自动追踪,因此每个消息在不同的消费组里只会记录一次。如果希望获得两次数据,则使用另一个组名创建副本。 消费的消息会被自动追踪,因此每个消息在不同的消费组里只会记录一次。如果希望获得两次数据,则使用另一个组名创建副本。
消费组可以灵活配置并且在集群之间同步。例如如果群集中有10个主题和5个表副本则每个副本将获得2个主题。 如果副本数量发生变化,主题将自动在副本中重新分配。了解更多信息请访问 http://kafka.apache.org/intro。 消费组可以灵活配置并且在集群之间同步。例如如果群集中有10个主题和5个表副本则每个副本将获得2个主题。 如果副本数量发生变化,主题将自动在副本中重新分配。了解更多信息请访问 [http://kafka.apache.org/intro](http://kafka.apache.org/intro)
`SELECT` 查询对于读取消息并不是很有用(调试除外),因为每条消息只能被读取一次。使用物化视图创建实时线程更实用。您可以这样做: `SELECT` 查询对于读取消息并不是很有用(调试除外),因为每条消息只能被读取一次。使用物化视图创建实时线程更实用。您可以这样做:

View File

@ -164,7 +164,7 @@ SETTINGS index_granularity = 8192, index_granularity_bytes = 0;
<li><font face = "monospace">index_granularity</font>: 显式设置为其默认值8192。这意味着对于每一组8192行主索引将有一个索引条目例如如果表包含16384行那么索引将有两个索引条目。 <li><font face = "monospace">index_granularity</font>: 显式设置为其默认值8192。这意味着对于每一组8192行主索引将有一个索引条目例如如果表包含16384行那么索引将有两个索引条目。
</li> </li>
<br/> <br/>
<li><font face = "monospace">index_granularity_bytes</font>: 设置为0表示禁止<a href="https://clickhouse.com/docs/en/whats-new/changelog/2019/#experimental-features-1" target="_blank"><font color="blue">适应索引粒度</font></a>。自适应索引粒度意味着ClickHouse自动为一组n行创建一个索引条目 <li><font face = "monospace">index_granularity_bytes</font>: 设置为0表示禁止<a href="https://clickhouse.com/docs/en/whats-new/changelog/2019/#experimental-features-1" target="_blank"><font color="blue">适应索引粒度</font></a>。自适应索引粒度意味着ClickHouse自动为一组n行创建一个索引条目
<ul> <ul>
<li>如果n小于8192但n行的合并行数据大小大于或等于10MB (index_granularity_bytes的默认值)或</li> <li>如果n小于8192但n行的合并行数据大小大于或等于10MB (index_granularity_bytes的默认值)或</li>
<li>n达到8192</li> <li>n达到8192</li>

View File

@ -77,6 +77,54 @@ sidebar_label: GROUP BY
您可以使用 `WITH TOTALS` 在子查询中,包括在子查询 [JOIN](../../../sql-reference/statements/select/join.md) 子句(在这种情况下,将各自的总值合并)。 您可以使用 `WITH TOTALS` 在子查询中,包括在子查询 [JOIN](../../../sql-reference/statements/select/join.md) 子句(在这种情况下,将各自的总值合并)。
## GROUP BY ALL {#group-by-all}
`GROUP BY ALL` 相当于对所有被查询的并且不被聚合函数使用的字段进行`GROUP BY`。
例如
``` sql
SELECT
a * 2,
b,
count(c),
FROM t
GROUP BY ALL
```
效果等同于
``` sql
SELECT
a * 2,
b,
count(c),
FROM t
GROUP BY a * 2, b
```
对于一种特殊情况,如果一个 function 的参数中同时有聚合函数和其他字段,会对参数中能提取的最大非聚合字段进行`GROUP BY`。
例如:
``` sql
SELECT
substring(a, 4, 2),
substring(substring(a, 1, 2), 1, count(b))
FROM t
GROUP BY ALL
```
效果等同于
``` sql
SELECT
substring(a, 4, 2),
substring(substring(a, 1, 2), 1, count(b))
FROM t
GROUP BY substring(a, 4, 2), substring(a, 1, 2)
```
## 例子 {#examples} ## 例子 {#examples}
示例: 示例:

View File

@ -9,7 +9,10 @@ After=time-sync.target network-online.target
Wants=time-sync.target Wants=time-sync.target
[Service] [Service]
Type=simple Type=notify
# Switching off watchdog is very important for sd_notify to work correctly.
Environment=CLICKHOUSE_WATCHDOG_ENABLE=0
User=clickhouse User=clickhouse
Group=clickhouse Group=clickhouse
Restart=always Restart=always

View File

@ -80,8 +80,8 @@ require (
go.opentelemetry.io/otel v1.4.1 // indirect go.opentelemetry.io/otel v1.4.1 // indirect
go.opentelemetry.io/otel/trace v1.4.1 // indirect go.opentelemetry.io/otel/trace v1.4.1 // indirect
golang.org/x/net v0.0.0-20211108170745-6635138e15ea // indirect golang.org/x/net v0.0.0-20211108170745-6635138e15ea // indirect
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
golang.org/x/text v0.3.7 // indirect golang.org/x/text v0.3.8 // indirect
google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa // indirect google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa // indirect
google.golang.org/grpc v1.43.0 // indirect google.golang.org/grpc v1.43.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect google.golang.org/protobuf v1.27.1 // indirect

View File

@ -1078,8 +1078,8 @@ golang.org/x/sys v0.0.0-20211109184856-51b60fd695b3/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@ -1089,8 +1089,9 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=

View File

@ -262,6 +262,7 @@ void Keeper::defineOptions(Poco::Util::OptionSet & options)
} }
int Keeper::main(const std::vector<std::string> & /*args*/) int Keeper::main(const std::vector<std::string> & /*args*/)
try
{ {
Poco::Logger * log = &logger(); Poco::Logger * log = &logger();
@ -473,6 +474,12 @@ int Keeper::main(const std::vector<std::string> & /*args*/)
return Application::EXIT_OK; return Application::EXIT_OK;
} }
catch (...)
{
/// Poco does not provide stacktrace.
tryLogCurrentException("Application");
throw;
}
void Keeper::logRevision() const void Keeper::logRevision() const

View File

@ -99,6 +99,10 @@
#include "config_version.h" #include "config_version.h"
#if defined(OS_LINUX) #if defined(OS_LINUX)
# include <cstddef>
# include <cstdlib>
# include <sys/socket.h>
# include <sys/un.h>
# include <sys/mman.h> # include <sys/mman.h>
# include <sys/ptrace.h> # include <sys/ptrace.h>
# include <Common/hasLinuxCapability.h> # include <Common/hasLinuxCapability.h>
@ -273,6 +277,7 @@ namespace ErrorCodes
extern const int MISMATCHING_USERS_FOR_PROCESS_AND_DATA; extern const int MISMATCHING_USERS_FOR_PROCESS_AND_DATA;
extern const int NETWORK_ERROR; extern const int NETWORK_ERROR;
extern const int CORRUPTED_DATA; extern const int CORRUPTED_DATA;
extern const int SYSTEM_ERROR;
} }
@ -646,7 +651,53 @@ static void sanityChecks(Server & server)
} }
} }
#if defined(OS_LINUX)
/// Sends notification to systemd, analogous to sd_notify from libsystemd
static void systemdNotify(const std::string_view & command)
{
const char * path = getenv("NOTIFY_SOCKET"); // NOLINT(concurrency-mt-unsafe)
if (path == nullptr)
return; /// not using systemd
int s = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (s == -1)
throwFromErrno("Can't create UNIX socket for systemd notify.", ErrorCodes::SYSTEM_ERROR);
SCOPE_EXIT({ close(s); });
const size_t len = strlen(path);
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
if (len < 2 || len > sizeof(addr.sun_path) - 1)
throw Exception(ErrorCodes::SYSTEM_ERROR, "NOTIFY_SOCKET env var value \"{}\" is wrong.", path);
memcpy(addr.sun_path, path, len + 1); /// write last zero as well.
size_t addrlen = offsetof(struct sockaddr_un, sun_path) + len;
/// '@' meass this is Linux abstract socket, per documentation it must be sun_path[0] must be set to '\0' for it.
if (path[0] == '@')
addr.sun_path[0] = 0;
else if (path[0] == '/')
addrlen += 1; /// non-abstract-addresses should be zero terminated.
else
throw Exception(ErrorCodes::SYSTEM_ERROR, "Wrong UNIX path \"{}\" in NOTIFY_SOCKET env var", path);
const struct sockaddr *sock_addr = reinterpret_cast <const struct sockaddr *>(&addr);
if (sendto(s, command.data(), command.size(), 0, sock_addr, static_cast <socklen_t>(addrlen)) != static_cast <ssize_t>(command.size()))
throw Exception("Failed to notify systemd.", ErrorCodes::SYSTEM_ERROR);
}
#endif
int Server::main(const std::vector<std::string> & /*args*/) int Server::main(const std::vector<std::string> & /*args*/)
try
{ {
Poco::Logger * log = &logger(); Poco::Logger * log = &logger();
@ -1148,6 +1199,9 @@ int Server::main(const std::vector<std::string> & /*args*/)
total_memory_tracker.setDescription("(total)"); total_memory_tracker.setDescription("(total)");
total_memory_tracker.setMetric(CurrentMetrics::MemoryTracking); total_memory_tracker.setMetric(CurrentMetrics::MemoryTracking);
bool allow_use_jemalloc_memory = config->getBool("allow_use_jemalloc_memory", true);
total_memory_tracker.setAllowUseJemallocMemory(allow_use_jemalloc_memory);
auto * global_overcommit_tracker = global_context->getGlobalOvercommitTracker(); auto * global_overcommit_tracker = global_context->getGlobalOvercommitTracker();
total_memory_tracker.setOvercommitTracker(global_overcommit_tracker); total_memory_tracker.setOvercommitTracker(global_overcommit_tracker);
@ -1776,6 +1830,10 @@ int Server::main(const std::vector<std::string> & /*args*/)
tryLogCurrentException(log, "Caught exception while starting cluster discovery"); tryLogCurrentException(log, "Caught exception while starting cluster discovery");
} }
#if defined(OS_LINUX)
systemdNotify("READY=1\n");
#endif
SCOPE_EXIT_SAFE({ SCOPE_EXIT_SAFE({
LOG_DEBUG(log, "Received termination signal."); LOG_DEBUG(log, "Received termination signal.");
@ -1845,6 +1903,12 @@ int Server::main(const std::vector<std::string> & /*args*/)
return Application::EXIT_OK; return Application::EXIT_OK;
} }
catch (...)
{
/// Poco does not provide stacktrace.
tryLogCurrentException("Application");
throw;
}
std::unique_ptr<TCPProtocolStackFactory> Server::buildProtocolStackFromConfig( std::unique_ptr<TCPProtocolStackFactory> Server::buildProtocolStackFromConfig(
const Poco::Util::AbstractConfiguration & config, const Poco::Util::AbstractConfiguration & config,

View File

@ -130,8 +130,8 @@ enum class AccessType
M(SHOW_ROW_POLICIES, "SHOW POLICIES, SHOW CREATE ROW POLICY, SHOW CREATE POLICY", TABLE, SHOW_ACCESS) \ M(SHOW_ROW_POLICIES, "SHOW POLICIES, SHOW CREATE ROW POLICY, SHOW CREATE POLICY", TABLE, SHOW_ACCESS) \
M(SHOW_QUOTAS, "SHOW CREATE QUOTA", GLOBAL, SHOW_ACCESS) \ M(SHOW_QUOTAS, "SHOW CREATE QUOTA", GLOBAL, SHOW_ACCESS) \
M(SHOW_SETTINGS_PROFILES, "SHOW PROFILES, SHOW CREATE SETTINGS PROFILE, SHOW CREATE PROFILE", GLOBAL, SHOW_ACCESS) \ M(SHOW_SETTINGS_PROFILES, "SHOW PROFILES, SHOW CREATE SETTINGS PROFILE, SHOW CREATE PROFILE", GLOBAL, SHOW_ACCESS) \
M(SHOW_NAMED_COLLECTIONS, "SHOW NAMED COLLECTIONS", GLOBAL, SHOW_ACCESS) \
M(SHOW_ACCESS, "", GROUP, ACCESS_MANAGEMENT) \ M(SHOW_ACCESS, "", GROUP, ACCESS_MANAGEMENT) \
M(SHOW_NAMED_COLLECTIONS, "SHOW NAMED COLLECTIONS", GROUP, ACCESS_MANAGEMENT) \
M(ACCESS_MANAGEMENT, "", GROUP, ALL) \ M(ACCESS_MANAGEMENT, "", GROUP, ALL) \
\ \
M(SYSTEM_SHUTDOWN, "SYSTEM KILL, SHUTDOWN", GLOBAL, SYSTEM) \ M(SYSTEM_SHUTDOWN, "SYSTEM KILL, SHUTDOWN", GLOBAL, SYSTEM) \

View File

@ -2,6 +2,8 @@
#include <Access/LDAPClient.h> #include <Access/LDAPClient.h>
#include <Common/Exception.h> #include <Common/Exception.h>
#include <Common/quoteString.h> #include <Common/quoteString.h>
#include <Common/SipHash.h>
#include <Poco/Util/AbstractConfiguration.h> #include <Poco/Util/AbstractConfiguration.h>
#include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string/case_conv.hpp>
@ -73,6 +75,7 @@ void parseLDAPServer(LDAPClient::Params & params, const Poco::Util::AbstractConf
const bool has_tls_ca_cert_file = config.has(ldap_server_config + ".tls_ca_cert_file"); const bool has_tls_ca_cert_file = config.has(ldap_server_config + ".tls_ca_cert_file");
const bool has_tls_ca_cert_dir = config.has(ldap_server_config + ".tls_ca_cert_dir"); const bool has_tls_ca_cert_dir = config.has(ldap_server_config + ".tls_ca_cert_dir");
const bool has_tls_cipher_suite = config.has(ldap_server_config + ".tls_cipher_suite"); const bool has_tls_cipher_suite = config.has(ldap_server_config + ".tls_cipher_suite");
const bool has_search_limit = config.has(ldap_server_config + ".search_limit");
if (!has_host) if (!has_host)
throw Exception("Missing 'host' entry", ErrorCodes::BAD_ARGUMENTS); throw Exception("Missing 'host' entry", ErrorCodes::BAD_ARGUMENTS);
@ -91,8 +94,8 @@ void parseLDAPServer(LDAPClient::Params & params, const Poco::Util::AbstractConf
} }
else if (has_auth_dn_prefix || has_auth_dn_suffix) else if (has_auth_dn_prefix || has_auth_dn_suffix)
{ {
const auto auth_dn_prefix = config.getString(ldap_server_config + ".auth_dn_prefix"); std::string auth_dn_prefix = config.getString(ldap_server_config + ".auth_dn_prefix");
const auto auth_dn_suffix = config.getString(ldap_server_config + ".auth_dn_suffix"); std::string auth_dn_suffix = config.getString(ldap_server_config + ".auth_dn_suffix");
params.bind_dn = auth_dn_prefix + "{user_name}" + auth_dn_suffix; params.bind_dn = auth_dn_prefix + "{user_name}" + auth_dn_suffix;
} }
@ -176,14 +179,17 @@ void parseLDAPServer(LDAPClient::Params & params, const Poco::Util::AbstractConf
if (has_port) if (has_port)
{ {
const auto port = config.getInt64(ldap_server_config + ".port"); UInt32 port = config.getUInt(ldap_server_config + ".port");
if (port < 0 || port > 65535) if (port > 65535)
throw Exception("Bad value for 'port' entry", ErrorCodes::BAD_ARGUMENTS); throw Exception("Bad value for 'port' entry", ErrorCodes::BAD_ARGUMENTS);
params.port = port; params.port = port;
} }
else else
params.port = (params.enable_tls == LDAPClient::Params::TLSEnable::YES ? 636 : 389); params.port = (params.enable_tls == LDAPClient::Params::TLSEnable::YES ? 636 : 389);
if (has_search_limit)
params.search_limit = static_cast<UInt32>(config.getUInt64(ldap_server_config + ".search_limit"));
} }
void parseKerberosParams(GSSAcceptorContext::Params & params, const Poco::Util::AbstractConfiguration & config) void parseKerberosParams(GSSAcceptorContext::Params & params, const Poco::Util::AbstractConfiguration & config)
@ -313,11 +319,26 @@ void ExternalAuthenticators::setConfiguration(const Poco::Util::AbstractConfigur
} }
} }
UInt128 computeParamsHash(const LDAPClient::Params & params, const LDAPClient::RoleSearchParamsList * role_search_params)
{
SipHash hash;
params.updateHash(hash);
if (role_search_params)
{
for (const auto & params_instance : *role_search_params)
{
params_instance.updateHash(hash);
}
}
return hash.get128();
}
bool ExternalAuthenticators::checkLDAPCredentials(const String & server, const BasicCredentials & credentials, bool ExternalAuthenticators::checkLDAPCredentials(const String & server, const BasicCredentials & credentials,
const LDAPClient::RoleSearchParamsList * role_search_params, LDAPClient::SearchResultsList * role_search_results) const const LDAPClient::RoleSearchParamsList * role_search_params, LDAPClient::SearchResultsList * role_search_results) const
{ {
std::optional<LDAPClient::Params> params; std::optional<LDAPClient::Params> params;
std::size_t params_hash = 0; UInt128 params_hash = 0;
{ {
std::scoped_lock lock(mutex); std::scoped_lock lock(mutex);
@ -331,14 +352,7 @@ bool ExternalAuthenticators::checkLDAPCredentials(const String & server, const B
params->user = credentials.getUserName(); params->user = credentials.getUserName();
params->password = credentials.getPassword(); params->password = credentials.getPassword();
params->combineCoreHash(params_hash); params_hash = computeParamsHash(*params, role_search_params);
if (role_search_params)
{
for (const auto & params_instance : *role_search_params)
{
params_instance.combineHash(params_hash);
}
}
// Check the cache, but only if the caching is enabled at all. // Check the cache, but only if the caching is enabled at all.
if (params->verification_cooldown > std::chrono::seconds{0}) if (params->verification_cooldown > std::chrono::seconds{0})
@ -408,15 +422,7 @@ bool ExternalAuthenticators::checkLDAPCredentials(const String & server, const B
new_params.user = credentials.getUserName(); new_params.user = credentials.getUserName();
new_params.password = credentials.getPassword(); new_params.password = credentials.getPassword();
std::size_t new_params_hash = 0; const UInt128 new_params_hash = computeParamsHash(new_params, role_search_params);
new_params.combineCoreHash(new_params_hash);
if (role_search_params)
{
for (const auto & params_instance : *role_search_params)
{
params_instance.combineHash(new_params_hash);
}
}
// If the critical server params have changed while we were checking the password, we discard the current result. // If the critical server params have changed while we were checking the password, we discard the current result.
if (params_hash != new_params_hash) if (params_hash != new_params_hash)

View File

@ -2,10 +2,10 @@
#include <Common/Exception.h> #include <Common/Exception.h>
#include <base/scope_guard.h> #include <base/scope_guard.h>
#include <Common/logger_useful.h> #include <Common/logger_useful.h>
#include <Common/SipHash.h>
#include <Poco/Logger.h> #include <Poco/Logger.h>
#include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/predicate.hpp>
#include <boost/container_hash/hash.hpp>
#include <mutex> #include <mutex>
#include <utility> #include <utility>
@ -15,6 +15,22 @@
#include <sys/time.h> #include <sys/time.h>
namespace
{
template <typename T, typename = std::enable_if_t<std::is_fundamental_v<std::decay_t<T>>>>
void updateHash(SipHash & hash, const T & value)
{
hash.update(value);
}
void updateHash(SipHash & hash, const std::string & value)
{
hash.update(value.size());
hash.update(value);
}
}
namespace DB namespace DB
{ {
@ -26,30 +42,30 @@ namespace ErrorCodes
extern const int LDAP_ERROR; extern const int LDAP_ERROR;
} }
void LDAPClient::SearchParams::combineHash(std::size_t & seed) const void LDAPClient::SearchParams::updateHash(SipHash & hash) const
{ {
boost::hash_combine(seed, base_dn); ::updateHash(hash, base_dn);
boost::hash_combine(seed, static_cast<int>(scope)); ::updateHash(hash, static_cast<int>(scope));
boost::hash_combine(seed, search_filter); ::updateHash(hash, search_filter);
boost::hash_combine(seed, attribute); ::updateHash(hash, attribute);
} }
void LDAPClient::RoleSearchParams::combineHash(std::size_t & seed) const void LDAPClient::RoleSearchParams::updateHash(SipHash & hash) const
{ {
SearchParams::combineHash(seed); SearchParams::updateHash(hash);
boost::hash_combine(seed, prefix); ::updateHash(hash, prefix);
} }
void LDAPClient::Params::combineCoreHash(std::size_t & seed) const void LDAPClient::Params::updateHash(SipHash & hash) const
{ {
boost::hash_combine(seed, host); ::updateHash(hash, host);
boost::hash_combine(seed, port); ::updateHash(hash, port);
boost::hash_combine(seed, bind_dn); ::updateHash(hash, bind_dn);
boost::hash_combine(seed, user); ::updateHash(hash, user);
boost::hash_combine(seed, password); ::updateHash(hash, password);
if (user_dn_detection) if (user_dn_detection)
user_dn_detection->combineHash(seed); user_dn_detection->updateHash(hash);
} }
LDAPClient::LDAPClient(const Params & params_) LDAPClient::LDAPClient(const Params & params_)
@ -153,13 +169,13 @@ namespace
} }
void LDAPClient::diag(int rc, String text) void LDAPClient::handleError(int result_code, String text)
{ {
std::scoped_lock lock(ldap_global_mutex); std::scoped_lock lock(ldap_global_mutex);
if (rc != LDAP_SUCCESS) if (result_code != LDAP_SUCCESS)
{ {
const char * raw_err_str = ldap_err2string(rc); const char * raw_err_str = ldap_err2string(result_code);
if (raw_err_str && *raw_err_str != '\0') if (raw_err_str && *raw_err_str != '\0')
{ {
if (!text.empty()) if (!text.empty())
@ -214,7 +230,7 @@ bool LDAPClient::openConnection()
SCOPE_EXIT({ ldap_memfree(uri); }); SCOPE_EXIT({ ldap_memfree(uri); });
diag(ldap_initialize(&handle, uri)); handleError(ldap_initialize(&handle, uri));
if (!handle) if (!handle)
throw Exception("ldap_initialize() failed", ErrorCodes::LDAP_ERROR); throw Exception("ldap_initialize() failed", ErrorCodes::LDAP_ERROR);
} }
@ -226,13 +242,13 @@ bool LDAPClient::openConnection()
case LDAPClient::Params::ProtocolVersion::V2: value = LDAP_VERSION2; break; case LDAPClient::Params::ProtocolVersion::V2: value = LDAP_VERSION2; break;
case LDAPClient::Params::ProtocolVersion::V3: value = LDAP_VERSION3; break; case LDAPClient::Params::ProtocolVersion::V3: value = LDAP_VERSION3; break;
} }
diag(ldap_set_option(handle, LDAP_OPT_PROTOCOL_VERSION, &value)); handleError(ldap_set_option(handle, LDAP_OPT_PROTOCOL_VERSION, &value));
} }
diag(ldap_set_option(handle, LDAP_OPT_RESTART, LDAP_OPT_ON)); handleError(ldap_set_option(handle, LDAP_OPT_RESTART, LDAP_OPT_ON));
#ifdef LDAP_OPT_KEEPCONN #ifdef LDAP_OPT_KEEPCONN
diag(ldap_set_option(handle, LDAP_OPT_KEEPCONN, LDAP_OPT_ON)); handleError(ldap_set_option(handle, LDAP_OPT_KEEPCONN, LDAP_OPT_ON));
#endif #endif
#ifdef LDAP_OPT_TIMEOUT #ifdef LDAP_OPT_TIMEOUT
@ -240,7 +256,7 @@ bool LDAPClient::openConnection()
::timeval operation_timeout; ::timeval operation_timeout;
operation_timeout.tv_sec = params.operation_timeout.count(); operation_timeout.tv_sec = params.operation_timeout.count();
operation_timeout.tv_usec = 0; operation_timeout.tv_usec = 0;
diag(ldap_set_option(handle, LDAP_OPT_TIMEOUT, &operation_timeout)); handleError(ldap_set_option(handle, LDAP_OPT_TIMEOUT, &operation_timeout));
} }
#endif #endif
@ -249,18 +265,18 @@ bool LDAPClient::openConnection()
::timeval network_timeout; ::timeval network_timeout;
network_timeout.tv_sec = params.network_timeout.count(); network_timeout.tv_sec = params.network_timeout.count();
network_timeout.tv_usec = 0; network_timeout.tv_usec = 0;
diag(ldap_set_option(handle, LDAP_OPT_NETWORK_TIMEOUT, &network_timeout)); handleError(ldap_set_option(handle, LDAP_OPT_NETWORK_TIMEOUT, &network_timeout));
} }
#endif #endif
{ {
const int search_timeout = static_cast<int>(params.search_timeout.count()); const int search_timeout = static_cast<int>(params.search_timeout.count());
diag(ldap_set_option(handle, LDAP_OPT_TIMELIMIT, &search_timeout)); handleError(ldap_set_option(handle, LDAP_OPT_TIMELIMIT, &search_timeout));
} }
{ {
const int size_limit = params.search_limit; const int size_limit = static_cast<int>(params.search_limit);
diag(ldap_set_option(handle, LDAP_OPT_SIZELIMIT, &size_limit)); handleError(ldap_set_option(handle, LDAP_OPT_SIZELIMIT, &size_limit));
} }
#ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
@ -274,7 +290,7 @@ bool LDAPClient::openConnection()
case LDAPClient::Params::TLSProtocolVersion::TLS1_1: value = LDAP_OPT_X_TLS_PROTOCOL_TLS1_1; break; case LDAPClient::Params::TLSProtocolVersion::TLS1_1: value = LDAP_OPT_X_TLS_PROTOCOL_TLS1_1; break;
case LDAPClient::Params::TLSProtocolVersion::TLS1_2: value = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2; break; case LDAPClient::Params::TLSProtocolVersion::TLS1_2: value = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2; break;
} }
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_PROTOCOL_MIN, &value)); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_PROTOCOL_MIN, &value));
} }
#endif #endif
@ -288,44 +304,44 @@ bool LDAPClient::openConnection()
case LDAPClient::Params::TLSRequireCert::TRY: value = LDAP_OPT_X_TLS_TRY; break; case LDAPClient::Params::TLSRequireCert::TRY: value = LDAP_OPT_X_TLS_TRY; break;
case LDAPClient::Params::TLSRequireCert::DEMAND: value = LDAP_OPT_X_TLS_DEMAND; break; case LDAPClient::Params::TLSRequireCert::DEMAND: value = LDAP_OPT_X_TLS_DEMAND; break;
} }
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_REQUIRE_CERT, &value)); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_REQUIRE_CERT, &value));
} }
#endif #endif
#ifdef LDAP_OPT_X_TLS_CERTFILE #ifdef LDAP_OPT_X_TLS_CERTFILE
if (!params.tls_cert_file.empty()) if (!params.tls_cert_file.empty())
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_CERTFILE, params.tls_cert_file.c_str())); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_CERTFILE, params.tls_cert_file.c_str()));
#endif #endif
#ifdef LDAP_OPT_X_TLS_KEYFILE #ifdef LDAP_OPT_X_TLS_KEYFILE
if (!params.tls_key_file.empty()) if (!params.tls_key_file.empty())
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_KEYFILE, params.tls_key_file.c_str())); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_KEYFILE, params.tls_key_file.c_str()));
#endif #endif
#ifdef LDAP_OPT_X_TLS_CACERTFILE #ifdef LDAP_OPT_X_TLS_CACERTFILE
if (!params.tls_ca_cert_file.empty()) if (!params.tls_ca_cert_file.empty())
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_CACERTFILE, params.tls_ca_cert_file.c_str())); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_CACERTFILE, params.tls_ca_cert_file.c_str()));
#endif #endif
#ifdef LDAP_OPT_X_TLS_CACERTDIR #ifdef LDAP_OPT_X_TLS_CACERTDIR
if (!params.tls_ca_cert_dir.empty()) if (!params.tls_ca_cert_dir.empty())
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_CACERTDIR, params.tls_ca_cert_dir.c_str())); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_CACERTDIR, params.tls_ca_cert_dir.c_str()));
#endif #endif
#ifdef LDAP_OPT_X_TLS_CIPHER_SUITE #ifdef LDAP_OPT_X_TLS_CIPHER_SUITE
if (!params.tls_cipher_suite.empty()) if (!params.tls_cipher_suite.empty())
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_CIPHER_SUITE, params.tls_cipher_suite.c_str())); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_CIPHER_SUITE, params.tls_cipher_suite.c_str()));
#endif #endif
#ifdef LDAP_OPT_X_TLS_NEWCTX #ifdef LDAP_OPT_X_TLS_NEWCTX
{ {
const int i_am_a_server = 0; const int i_am_a_server = 0;
diag(ldap_set_option(handle, LDAP_OPT_X_TLS_NEWCTX, &i_am_a_server)); handleError(ldap_set_option(handle, LDAP_OPT_X_TLS_NEWCTX, &i_am_a_server));
} }
#endif #endif
if (params.enable_tls == LDAPClient::Params::TLSEnable::YES_STARTTLS) if (params.enable_tls == LDAPClient::Params::TLSEnable::YES_STARTTLS)
diag(ldap_start_tls_s(handle, nullptr, nullptr)); handleError(ldap_start_tls_s(handle, nullptr, nullptr));
final_user_name = escapeForDN(params.user); final_user_name = escapeForDN(params.user);
final_bind_dn = replacePlaceholders(params.bind_dn, { {"{user_name}", final_user_name} }); final_bind_dn = replacePlaceholders(params.bind_dn, { {"{user_name}", final_user_name} });
@ -346,7 +362,7 @@ bool LDAPClient::openConnection()
if (rc == LDAP_INVALID_CREDENTIALS) if (rc == LDAP_INVALID_CREDENTIALS)
return false; return false;
diag(rc); handleError(rc);
} }
// Once bound, run the user DN search query and update the default value, if asked. // Once bound, run the user DN search query and update the default value, if asked.
@ -425,7 +441,7 @@ LDAPClient::SearchResults LDAPClient::search(const SearchParams & search_params)
} }
}); });
diag(ldap_search_ext_s(handle, final_base_dn.c_str(), scope, final_search_filter.c_str(), attrs, 0, nullptr, nullptr, &timeout, params.search_limit, &msgs)); handleError(ldap_search_ext_s(handle, final_base_dn.c_str(), scope, final_search_filter.c_str(), attrs, 0, nullptr, nullptr, &timeout, params.search_limit, &msgs));
for ( for (
auto * msg = ldap_first_message(handle, msgs); auto * msg = ldap_first_message(handle, msgs);
@ -452,7 +468,7 @@ LDAPClient::SearchResults LDAPClient::search(const SearchParams & search_params)
::berval bv; ::berval bv;
diag(ldap_get_dn_ber(handle, msg, &ber, &bv)); handleError(ldap_get_dn_ber(handle, msg, &ber, &bv));
if (bv.bv_val && bv.bv_len > 0) if (bv.bv_val && bv.bv_len > 0)
result.emplace(bv.bv_val, bv.bv_len); result.emplace(bv.bv_val, bv.bv_len);
@ -504,7 +520,7 @@ LDAPClient::SearchResults LDAPClient::search(const SearchParams & search_params)
case LDAP_RES_SEARCH_REFERENCE: case LDAP_RES_SEARCH_REFERENCE:
{ {
char ** referrals = nullptr; char ** referrals = nullptr;
diag(ldap_parse_reference(handle, msg, &referrals, nullptr, 0)); handleError(ldap_parse_reference(handle, msg, &referrals, nullptr, 0));
if (referrals) if (referrals)
{ {
@ -528,7 +544,7 @@ LDAPClient::SearchResults LDAPClient::search(const SearchParams & search_params)
char * matched_msg = nullptr; char * matched_msg = nullptr;
char * error_msg = nullptr; char * error_msg = nullptr;
diag(ldap_parse_result(handle, msg, &rc, &matched_msg, &error_msg, nullptr, nullptr, 0)); handleError(ldap_parse_result(handle, msg, &rc, &matched_msg, &error_msg, nullptr, nullptr, 0));
if (rc != LDAP_SUCCESS) if (rc != LDAP_SUCCESS)
{ {
@ -610,7 +626,7 @@ bool LDAPSimpleAuthClient::authenticate(const RoleSearchParamsList * role_search
#else // USE_LDAP #else // USE_LDAP
void LDAPClient::diag(const int, String) void LDAPClient::handleError(const int, String)
{ {
throw Exception("ClickHouse was built without LDAP support", ErrorCodes::FEATURE_IS_NOT_ENABLED_AT_BUILD_TIME); throw Exception("ClickHouse was built without LDAP support", ErrorCodes::FEATURE_IS_NOT_ENABLED_AT_BUILD_TIME);
} }

View File

@ -16,6 +16,7 @@
#include <set> #include <set>
#include <vector> #include <vector>
class SipHash;
namespace DB namespace DB
{ {
@ -38,7 +39,7 @@ public:
String search_filter; String search_filter;
String attribute = "cn"; String attribute = "cn";
void combineHash(std::size_t & seed) const; void updateHash(SipHash & hash) const;
}; };
struct RoleSearchParams struct RoleSearchParams
@ -46,7 +47,7 @@ public:
{ {
String prefix; String prefix;
void combineHash(std::size_t & seed) const; void updateHash(SipHash & hash) const;
}; };
using RoleSearchParamsList = std::vector<RoleSearchParams>; using RoleSearchParamsList = std::vector<RoleSearchParams>;
@ -95,7 +96,7 @@ public:
ProtocolVersion protocol_version = ProtocolVersion::V3; ProtocolVersion protocol_version = ProtocolVersion::V3;
String host; String host;
std::uint16_t port = 636; UInt16 port = 636;
TLSEnable enable_tls = TLSEnable::YES; TLSEnable enable_tls = TLSEnable::YES;
TLSProtocolVersion tls_minimum_protocol_version = TLSProtocolVersion::TLS1_2; TLSProtocolVersion tls_minimum_protocol_version = TLSProtocolVersion::TLS1_2;
@ -119,9 +120,9 @@ public:
std::chrono::seconds operation_timeout{40}; std::chrono::seconds operation_timeout{40};
std::chrono::seconds network_timeout{30}; std::chrono::seconds network_timeout{30};
std::chrono::seconds search_timeout{20}; std::chrono::seconds search_timeout{20};
std::uint32_t search_limit = 100; UInt32 search_limit = 256; /// An arbitrary number, no particular motivation for this value.
void combineCoreHash(std::size_t & seed) const; void updateHash(SipHash & hash) const;
}; };
explicit LDAPClient(const Params & params_); explicit LDAPClient(const Params & params_);
@ -133,7 +134,7 @@ public:
LDAPClient & operator= (LDAPClient &&) = delete; LDAPClient & operator= (LDAPClient &&) = delete;
protected: protected:
MAYBE_NORETURN void diag(int rc, String text = ""); MAYBE_NORETURN void handleError(int result_code, String text = "");
MAYBE_NORETURN bool openConnection(); MAYBE_NORETURN bool openConnection();
void closeConnection() noexcept; void closeConnection() noexcept;
SearchResults search(const SearchParams & search_params); SearchResults search(const SearchParams & search_params);

View File

@ -228,6 +228,12 @@ namespace
user->access.revokeGrantOption(AccessType::ALL); user->access.revokeGrantOption(AccessType::ALL);
} }
bool show_named_collections = config.getBool(user_config + ".show_named_collections", false);
if (!show_named_collections)
{
user->access.revoke(AccessType::SHOW_NAMED_COLLECTIONS);
}
String default_database = config.getString(user_config + ".default_database", ""); String default_database = config.getString(user_config + ".default_database", "");
user->default_database = default_database; user->default_database = default_database;

View File

@ -13,6 +13,7 @@ struct Settings;
namespace ErrorCodes namespace ErrorCodes
{ {
extern const int ILLEGAL_TYPE_OF_ARGUMENT; extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int CORRUPTED_DATA;
} }
@ -89,6 +90,13 @@ public:
{ {
this->data(place).result.read(buf, *serialization_res, arena); this->data(place).result.read(buf, *serialization_res, arena);
this->data(place).value.read(buf, *serialization_val, arena); this->data(place).value.read(buf, *serialization_val, arena);
if (unlikely(this->data(place).value.has() != this->data(place).result.has()))
throw Exception(
ErrorCodes::CORRUPTED_DATA,
"Invalid state of the aggregate function {}: has_value ({}) != has_result ({})",
getName(),
this->data(place).value.has(),
this->data(place).result.has());
} }
bool allocatesMemoryInArena() const override bool allocatesMemoryInArena() const override

View File

@ -30,6 +30,7 @@ namespace ErrorCodes
extern const int ILLEGAL_TYPE_OF_ARGUMENT; extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int NOT_IMPLEMENTED; extern const int NOT_IMPLEMENTED;
extern const int TOO_LARGE_STRING_SIZE; extern const int TOO_LARGE_STRING_SIZE;
extern const int LOGICAL_ERROR;
} }
/** Aggregate functions that store one of passed values. /** Aggregate functions that store one of passed values.
@ -448,6 +449,34 @@ public:
}; };
struct Compatibility
{
/// Old versions used to store terminating null-character in SingleValueDataString.
/// Then -WithTerminatingZero methods were removed from IColumn interface,
/// because these methods are quite dangerous and easy to misuse. It introduced incompatibility.
/// See https://github.com/ClickHouse/ClickHouse/pull/41431 and https://github.com/ClickHouse/ClickHouse/issues/42916
/// Here we keep these functions for compatibility.
/// It's safe because there's no way unsanitized user input (without \0 at the end) can reach these functions.
static StringRef getDataAtWithTerminatingZero(const ColumnString & column, size_t n)
{
auto res = column.getDataAt(n);
/// ColumnString always reserves extra byte for null-character after string.
/// But getDataAt returns StringRef without the null-character. Let's add it.
chassert(res.data[res.size] == '\0');
++res.size;
return res;
}
static void insertDataWithTerminatingZero(ColumnString & column, const char * pos, size_t length)
{
/// String already has terminating null-character.
/// But insertData will add another one unconditionally. Trim existing null-character to avoid duplication.
chassert(0 < length);
chassert(pos[length - 1] == '\0');
column.insertData(pos, length - 1);
}
};
/** For strings. Short strings are stored in the object itself, and long strings are allocated separately. /** For strings. Short strings are stored in the object itself, and long strings are allocated separately.
* NOTE It could also be suitable for arrays of numbers. * NOTE It could also be suitable for arrays of numbers.
@ -457,13 +486,15 @@ struct SingleValueDataString //-V730
private: private:
using Self = SingleValueDataString; using Self = SingleValueDataString;
Int32 size = -1; /// -1 indicates that there is no value. /// 0 size indicates that there is no value. Empty string must has terminating '\0' and, therefore, size of empty string is 1
Int32 capacity = 0; /// power of two or zero UInt32 size = 0;
UInt32 capacity = 0; /// power of two or zero
char * large_data; char * large_data;
public: public:
static constexpr Int32 AUTOMATIC_STORAGE_SIZE = 64; static constexpr UInt32 AUTOMATIC_STORAGE_SIZE = 64;
static constexpr Int32 MAX_SMALL_STRING_SIZE = AUTOMATIC_STORAGE_SIZE - sizeof(size) - sizeof(capacity) - sizeof(large_data); static constexpr UInt32 MAX_SMALL_STRING_SIZE = AUTOMATIC_STORAGE_SIZE - sizeof(size) - sizeof(capacity) - sizeof(large_data);
static constexpr UInt32 MAX_STRING_SIZE = std::numeric_limits<Int32>::max();
private: private:
char small_data[MAX_SMALL_STRING_SIZE]; /// Including the terminating zero. char small_data[MAX_SMALL_STRING_SIZE]; /// Including the terminating zero.
@ -474,12 +505,22 @@ public:
bool has() const bool has() const
{ {
return size >= 0; return size;
}
private:
char * getDataMutable()
{
return size <= MAX_SMALL_STRING_SIZE ? small_data : large_data;
} }
const char * getData() const const char * getData() const
{ {
return size <= MAX_SMALL_STRING_SIZE ? small_data : large_data; const char * data_ptr = size <= MAX_SMALL_STRING_SIZE ? small_data : large_data;
/// It must always be terminated with null-character
chassert(0 < size);
chassert(data_ptr[size - 1] == '\0');
return data_ptr;
} }
StringRef getStringRef() const StringRef getStringRef() const
@ -487,65 +528,105 @@ public:
return StringRef(getData(), size); return StringRef(getData(), size);
} }
public:
void insertResultInto(IColumn & to) const void insertResultInto(IColumn & to) const
{ {
if (has()) if (has())
assert_cast<ColumnString &>(to).insertData(getData(), size); Compatibility::insertDataWithTerminatingZero(assert_cast<ColumnString &>(to), getData(), size);
else else
assert_cast<ColumnString &>(to).insertDefault(); assert_cast<ColumnString &>(to).insertDefault();
} }
void write(WriteBuffer & buf, const ISerialization & /*serialization*/) const void write(WriteBuffer & buf, const ISerialization & /*serialization*/) const
{ {
writeBinary(size, buf); if (unlikely(MAX_STRING_SIZE < size))
throw Exception(ErrorCodes::LOGICAL_ERROR, "String size is too big ({}), it's a bug", size);
/// For serialization we use signed Int32 (for historical reasons), -1 means "no value"
Int32 size_to_write = size ? size : -1;
writeBinary(size_to_write, buf);
if (has()) if (has())
buf.write(getData(), size); buf.write(getData(), size);
} }
void read(ReadBuffer & buf, const ISerialization & /*serialization*/, Arena * arena) void allocateLargeDataIfNeeded(UInt32 size_to_reserve, Arena * arena)
{ {
Int32 rhs_size; if (capacity < size_to_reserve)
readBinary(rhs_size, buf); {
if (unlikely(MAX_STRING_SIZE < size_to_reserve))
throw Exception(ErrorCodes::TOO_LARGE_STRING_SIZE, "String size is too big ({})", size_to_reserve);
if (rhs_size >= 0) size_t rounded_capacity = roundUpToPowerOfTwoOrZero(size_to_reserve);
{ chassert(rounded_capacity <= MAX_STRING_SIZE + 1); /// rounded_capacity <= 2^31
if (rhs_size <= MAX_SMALL_STRING_SIZE) capacity = static_cast<UInt32>(rounded_capacity);
{
/// Don't free large_data here.
size = rhs_size;
if (size > 0)
buf.readStrict(small_data, size);
}
else
{
if (capacity < rhs_size)
{
capacity = static_cast<Int32>(roundUpToPowerOfTwoOrZero(rhs_size));
/// It might happen if the size was too big and the rounded value does not fit a size_t
if (unlikely(capacity < rhs_size))
throw Exception(ErrorCodes::TOO_LARGE_STRING_SIZE, "String size is too big ({})", rhs_size);
/// Don't free large_data here. /// Don't free large_data here.
large_data = arena->alloc(capacity); large_data = arena->alloc(capacity);
} }
}
size = rhs_size; void read(ReadBuffer & buf, const ISerialization & /*serialization*/, Arena * arena)
buf.readStrict(large_data, size); {
/// For serialization we use signed Int32 (for historical reasons), -1 means "no value"
Int32 rhs_size_signed;
readBinary(rhs_size_signed, buf);
if (rhs_size_signed < 0)
{
/// Don't free large_data here.
size = 0;
return;
} }
}
else UInt32 rhs_size = rhs_size_signed;
if (rhs_size <= MAX_SMALL_STRING_SIZE)
{ {
/// Don't free large_data here. /// Don't free large_data here.
size = rhs_size; size = rhs_size;
buf.readStrict(small_data, size);
} }
else
{
/// Reserve one byte more for null-character
allocateLargeDataIfNeeded(rhs_size + 1, arena);
size = rhs_size;
buf.readStrict(large_data, size);
}
/// Check if the string we read is null-terminated (getDataMutable does not have the assertion)
if (0 < size && getDataMutable()[size - 1] == '\0')
return;
/// It's not null-terminated, but it must be (for historical reasons). There are two variants:
/// - The value was serialized by one of the incompatible versions of ClickHouse. We had some range of versions
/// that used to serialize SingleValueDataString without terminating '\0'. Let's just append it.
/// - An attacker sent crafted data. Sanitize it and append '\0'.
/// In all other cases the string must be already null-terminated.
/// NOTE We cannot add '\0' unconditionally, because it will be duplicated.
/// NOTE It's possible that a string that actually ends with '\0' was written by one of the incompatible versions.
/// Unfortunately, we cannot distinguish it from normal string written by normal version.
/// So such strings will be trimmed.
if (size == MAX_SMALL_STRING_SIZE)
{
/// Special case: We have to move value to large_data
allocateLargeDataIfNeeded(size + 1, arena);
memcpy(large_data, small_data, size);
}
/// We have enough space to append
++size;
getDataMutable()[size - 1] = '\0';
} }
/// Assuming to.has() /// Assuming to.has()
void changeImpl(StringRef value, Arena * arena) void changeImpl(StringRef value, Arena * arena)
{ {
Int32 value_size = static_cast<Int32>(value.size); if (unlikely(MAX_STRING_SIZE < value.size))
throw Exception(ErrorCodes::TOO_LARGE_STRING_SIZE, "String size is too big ({})", value.size);
UInt32 value_size = static_cast<UInt32>(value.size);
if (value_size <= MAX_SMALL_STRING_SIZE) if (value_size <= MAX_SMALL_STRING_SIZE)
{ {
@ -557,13 +638,7 @@ public:
} }
else else
{ {
if (capacity < value_size) allocateLargeDataIfNeeded(value_size, arena);
{
/// Don't free large_data here.
capacity = static_cast<Int32>(roundUpToPowerOfTwoOrZero(value_size));
large_data = arena->alloc(capacity);
}
size = value_size; size = value_size;
memcpy(large_data, value.data, size); memcpy(large_data, value.data, size);
} }
@ -571,7 +646,7 @@ public:
void change(const IColumn & column, size_t row_num, Arena * arena) void change(const IColumn & column, size_t row_num, Arena * arena)
{ {
changeImpl(assert_cast<const ColumnString &>(column).getDataAt(row_num), arena); changeImpl(Compatibility::getDataAtWithTerminatingZero(assert_cast<const ColumnString &>(column), row_num), arena);
} }
void change(const Self & to, Arena * arena) void change(const Self & to, Arena * arena)
@ -620,7 +695,7 @@ public:
bool changeIfLess(const IColumn & column, size_t row_num, Arena * arena) bool changeIfLess(const IColumn & column, size_t row_num, Arena * arena)
{ {
if (!has() || assert_cast<const ColumnString &>(column).getDataAt(row_num) < getStringRef()) if (!has() || Compatibility::getDataAtWithTerminatingZero(assert_cast<const ColumnString &>(column), row_num) < getStringRef())
{ {
change(column, row_num, arena); change(column, row_num, arena);
return true; return true;
@ -642,7 +717,7 @@ public:
bool changeIfGreater(const IColumn & column, size_t row_num, Arena * arena) bool changeIfGreater(const IColumn & column, size_t row_num, Arena * arena)
{ {
if (!has() || assert_cast<const ColumnString &>(column).getDataAt(row_num) > getStringRef()) if (!has() || Compatibility::getDataAtWithTerminatingZero(assert_cast<const ColumnString &>(column), row_num) > getStringRef())
{ {
change(column, row_num, arena); change(column, row_num, arena);
return true; return true;
@ -669,7 +744,7 @@ public:
bool isEqualTo(const IColumn & column, size_t row_num) const bool isEqualTo(const IColumn & column, size_t row_num) const
{ {
return has() && assert_cast<const ColumnString &>(column).getDataAt(row_num) == getStringRef(); return has() && Compatibility::getDataAtWithTerminatingZero(assert_cast<const ColumnString &>(column), row_num) == getStringRef();
} }
static bool allocatesMemoryInArena() static bool allocatesMemoryInArena()

View File

@ -155,7 +155,7 @@ public:
"Values for {} are expected to be Numeric, Float or Decimal, passed type {}", "Values for {} are expected to be Numeric, Float or Decimal, passed type {}",
getName(), value_type->getName()}; getName(), value_type->getName()};
WhichDataType value_type_to_check(value_type); WhichDataType value_type_to_check(value_type_without_nullable);
/// Do not promote decimal because of implementation issues of this function design /// Do not promote decimal because of implementation issues of this function design
/// Currently we cannot get result column type in case of decimal we cannot get decimal scale /// Currently we cannot get result column type in case of decimal we cannot get decimal scale

60
src/Analyzer/HashUtils.h Normal file
View File

@ -0,0 +1,60 @@
#pragma once
#include <Analyzer/IQueryTreeNode.h>
namespace DB
{
/** This structure holds query tree node ptr and its hash. It can be used as hash map key to avoid unnecessary hash
* recalculations.
*
* Example of usage:
* std::unordered_map<QueryTreeNodeConstRawPtrWithHash, std::string> map;
*/
template <typename QueryTreeNodePtrType>
struct QueryTreeNodeWithHash
{
QueryTreeNodeWithHash(QueryTreeNodePtrType node_) /// NOLINT
: node(std::move(node_))
, hash(node->getTreeHash().first)
{}
QueryTreeNodePtrType node = nullptr;
size_t hash = 0;
};
template <typename T>
inline bool operator==(const QueryTreeNodeWithHash<T> & lhs, const QueryTreeNodeWithHash<T> & rhs)
{
return lhs.hash == rhs.hash && lhs.node->isEqual(*rhs.node);
}
template <typename T>
inline bool operator!=(const QueryTreeNodeWithHash<T> & lhs, const QueryTreeNodeWithHash<T> & rhs)
{
return !(lhs == rhs);
}
using QueryTreeNodePtrWithHash = QueryTreeNodeWithHash<QueryTreeNodePtr>;
using QueryTreeNodeRawPtrWithHash = QueryTreeNodeWithHash<IQueryTreeNode *>;
using QueryTreeNodeConstRawPtrWithHash = QueryTreeNodeWithHash<const IQueryTreeNode *>;
using QueryTreeNodePtrWithHashSet = std::unordered_set<QueryTreeNodePtrWithHash>;
using QueryTreeNodeConstRawPtrWithHashSet = std::unordered_set<QueryTreeNodeConstRawPtrWithHash>;
template <typename Value>
using QueryTreeNodePtrWithHashMap = std::unordered_map<QueryTreeNodePtrWithHash, Value>;
template <typename Value>
using QueryTreeNodeConstRawPtrWithHashMap = std::unordered_map<QueryTreeNodeConstRawPtrWithHash, Value>;
}
template <typename T>
struct std::hash<DB::QueryTreeNodeWithHash<T>>
{
size_t operator()(const DB::QueryTreeNodeWithHash<T> & node_with_hash) const
{
return node_with_hash.hash;
}
};

View File

@ -8,6 +8,7 @@
#include <Analyzer/InDepthQueryTreeVisitor.h> #include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/FunctionNode.h> #include <Analyzer/FunctionNode.h>
#include <Analyzer/ConstantNode.h> #include <Analyzer/ConstantNode.h>
#include <Analyzer/HashUtils.h>
#include <DataTypes/DataTypesNumber.h> #include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeArray.h> #include <DataTypes/DataTypeArray.h>
@ -48,43 +49,24 @@ public:
/// Do not apply for `count()` with without arguments or `count(*)`, only `count(x)` is supported. /// Do not apply for `count()` with without arguments or `count(*)`, only `count(x)` is supported.
return; return;
mapping[QueryTreeNodeWithHash(argument_nodes[0])].push_back(&node); argument_to_functions_mapping[argument_nodes[0]].push_back(&node);
} }
struct QueryTreeNodeWithHash
{
const QueryTreeNodePtr & node;
IQueryTreeNode::Hash hash;
explicit QueryTreeNodeWithHash(const QueryTreeNodePtr & node_)
: node(node_)
, hash(node->getTreeHash())
{}
bool operator==(const QueryTreeNodeWithHash & rhs) const
{
return hash == rhs.hash && node->isEqual(*rhs.node);
}
struct Hash
{
size_t operator() (const QueryTreeNodeWithHash & key) const { return key.hash.first ^ key.hash.second; }
};
};
/// argument -> list of sum/count/avg functions with this argument /// argument -> list of sum/count/avg functions with this argument
std::unordered_map<QueryTreeNodeWithHash, std::vector<QueryTreeNodePtr *>, QueryTreeNodeWithHash::Hash> mapping; QueryTreeNodePtrWithHashMap<std::vector<QueryTreeNodePtr *>> argument_to_functions_mapping;
private: private:
std::unordered_set<String> names_to_collect; std::unordered_set<String> names_to_collect;
}; };
QueryTreeNodePtr createResolvedFunction(ContextPtr context, const String & name, DataTypePtr result_type, QueryTreeNodes arguments) QueryTreeNodePtr createResolvedFunction(const ContextPtr & context, const String & name, const DataTypePtr & result_type, QueryTreeNodes arguments)
{ {
auto function_node = std::make_shared<FunctionNode>(name); auto function_node = std::make_shared<FunctionNode>(name);
auto function = FunctionFactory::instance().get(name, context); auto function = FunctionFactory::instance().get(name, context);
function_node->resolveAsFunction(std::move(function), result_type); function_node->resolveAsFunction(std::move(function), result_type);
function_node->getArguments().getNodes() = std::move(arguments); function_node->getArguments().getNodes() = std::move(arguments);
return function_node; return function_node;
} }
@ -94,21 +76,20 @@ FunctionNodePtr createResolvedAggregateFunction(const String & name, const Query
AggregateFunctionProperties properties; AggregateFunctionProperties properties;
auto aggregate_function = AggregateFunctionFactory::instance().get(name, {argument->getResultType()}, parameters, properties); auto aggregate_function = AggregateFunctionFactory::instance().get(name, {argument->getResultType()}, parameters, properties);
function_node->resolveAsAggregateFunction(aggregate_function, aggregate_function->getReturnType()); function_node->resolveAsAggregateFunction(aggregate_function, aggregate_function->getReturnType());
function_node->getArguments().getNodes() = { argument };
function_node->getArgumentsNode() = std::make_shared<ListNode>(QueryTreeNodes{argument});
return function_node; return function_node;
} }
QueryTreeNodePtr createTupleElementFunction(ContextPtr context, DataTypePtr result_type, QueryTreeNodePtr argument, UInt64 index) QueryTreeNodePtr createTupleElementFunction(const ContextPtr & context, const DataTypePtr & result_type, QueryTreeNodePtr argument, UInt64 index)
{ {
return createResolvedFunction(context, "tupleElement", result_type, {argument, std::make_shared<ConstantNode>(index)}); return createResolvedFunction(context, "tupleElement", result_type, {std::move(argument), std::make_shared<ConstantNode>(index)});
} }
QueryTreeNodePtr createArrayElementFunction(ContextPtr context, DataTypePtr result_type, QueryTreeNodePtr argument, UInt64 index) QueryTreeNodePtr createArrayElementFunction(const ContextPtr & context, const DataTypePtr & result_type, QueryTreeNodePtr argument, UInt64 index)
{ {
return createResolvedFunction(context, "arrayElement", result_type, {argument, std::make_shared<ConstantNode>(index)}); return createResolvedFunction(context, "arrayElement", result_type, {std::move(argument), std::make_shared<ConstantNode>(index)});
} }
void replaceWithSumCount(QueryTreeNodePtr & node, const FunctionNodePtr & sum_count_node, ContextPtr context) void replaceWithSumCount(QueryTreeNodePtr & node, const FunctionNodePtr & sum_count_node, ContextPtr context)
@ -151,6 +132,7 @@ FunctionNodePtr createFusedQuantilesNode(const std::vector<QueryTreeNodePtr *> n
{ {
Array parameters; Array parameters;
parameters.reserve(nodes.size()); parameters.reserve(nodes.size());
for (const auto * node : nodes) for (const auto * node : nodes)
{ {
const FunctionNode & function_node = (*node)->as<const FunctionNode &>(); const FunctionNode & function_node = (*node)->as<const FunctionNode &>();
@ -172,6 +154,7 @@ FunctionNodePtr createFusedQuantilesNode(const std::vector<QueryTreeNodePtr *> n
parameters.push_back(constant_value->getValue()); parameters.push_back(constant_value->getValue());
} }
return createResolvedAggregateFunction("quantiles", argument, parameters); return createResolvedAggregateFunction("quantiles", argument, parameters);
} }
@ -181,7 +164,7 @@ void tryFuseSumCountAvg(QueryTreeNodePtr query_tree_node, ContextPtr context)
FuseFunctionsVisitor visitor({"sum", "count", "avg"}); FuseFunctionsVisitor visitor({"sum", "count", "avg"});
visitor.visit(query_tree_node); visitor.visit(query_tree_node);
for (auto & [argument, nodes] : visitor.mapping) for (auto & [argument, nodes] : visitor.argument_to_functions_mapping)
{ {
if (nodes.size() < 2) if (nodes.size() < 2)
continue; continue;
@ -199,26 +182,24 @@ void tryFuseQuantiles(QueryTreeNodePtr query_tree_node, ContextPtr context)
{ {
FuseFunctionsVisitor visitor_quantile({"quantile"}); FuseFunctionsVisitor visitor_quantile({"quantile"});
visitor_quantile.visit(query_tree_node); visitor_quantile.visit(query_tree_node);
for (auto & [argument, nodes] : visitor_quantile.mapping)
for (auto & [argument, nodes] : visitor_quantile.argument_to_functions_mapping)
{ {
if (nodes.size() < 2) size_t nodes_size = nodes.size();
if (nodes_size < 2)
continue; continue;
auto quantiles_node = createFusedQuantilesNode(nodes, argument.node); auto quantiles_node = createFusedQuantilesNode(nodes, argument.node);
auto result_array_type = std::dynamic_pointer_cast<const DataTypeArray>(quantiles_node->getResultType()); auto result_array_type = std::dynamic_pointer_cast<const DataTypeArray>(quantiles_node->getResultType());
if (!result_array_type) if (!result_array_type)
{
throw Exception(ErrorCodes::LOGICAL_ERROR, throw Exception(ErrorCodes::LOGICAL_ERROR,
"Unexpected return type '{}' of function '{}', should be array", "Unexpected return type '{}' of function '{}', should be array",
quantiles_node->getResultType(), quantiles_node->getFunctionName()); quantiles_node->getResultType(), quantiles_node->getFunctionName());
}
for (size_t i = 0; i < nodes.size(); ++i) for (size_t i = 0; i < nodes_size; ++i)
{
*nodes[i] = createArrayElementFunction(context, result_array_type->getNestedType(), quantiles_node, i + 1); *nodes[i] = createArrayElementFunction(context, result_array_type->getNestedType(), quantiles_node, i + 1);
} }
} }
}
} }

View File

@ -3,6 +3,7 @@
#include <Analyzer/InDepthQueryTreeVisitor.h> #include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/QueryNode.h> #include <Analyzer/QueryNode.h>
#include <Analyzer/SortNode.h> #include <Analyzer/SortNode.h>
#include <Analyzer/HashUtils.h>
namespace DB namespace DB
{ {
@ -10,35 +11,6 @@ namespace DB
namespace namespace
{ {
struct QueryTreeNodeWithHash
{
explicit QueryTreeNodeWithHash(const IQueryTreeNode * node_)
: node(node_)
, hash(node->getTreeHash().first)
{}
const IQueryTreeNode * node = nullptr;
size_t hash = 0;
};
struct QueryTreeNodeWithHashHash
{
size_t operator()(const QueryTreeNodeWithHash & node_with_hash) const
{
return node_with_hash.hash;
}
};
struct QueryTreeNodeWithHashEqualTo
{
bool operator()(const QueryTreeNodeWithHash & lhs_node, const QueryTreeNodeWithHash & rhs_node) const
{
return lhs_node.hash == rhs_node.hash && lhs_node.node->isEqual(*rhs_node.node);
}
};
using QueryTreeNodeWithHashSet = std::unordered_set<QueryTreeNodeWithHash, QueryTreeNodeWithHashHash, QueryTreeNodeWithHashEqualTo>;
class OrderByLimitByDuplicateEliminationVisitor : public InDepthQueryTreeVisitor<OrderByLimitByDuplicateEliminationVisitor> class OrderByLimitByDuplicateEliminationVisitor : public InDepthQueryTreeVisitor<OrderByLimitByDuplicateEliminationVisitor>
{ {
public: public:
@ -93,7 +65,7 @@ public:
} }
private: private:
QueryTreeNodeWithHashSet unique_expressions_nodes_set; QueryTreeNodeConstRawPtrWithHashSet unique_expressions_nodes_set;
}; };
} }

View File

@ -67,6 +67,8 @@
#include <Analyzer/InDepthQueryTreeVisitor.h> #include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/QueryTreeBuilder.h> #include <Analyzer/QueryTreeBuilder.h>
#include <Common/checkStackSize.h>
namespace DB namespace DB
{ {
@ -517,7 +519,7 @@ public:
private: private:
QueryTreeNodes expressions; QueryTreeNodes expressions;
std::unordered_map<std::string, std::vector<QueryTreeNodePtr>> alias_name_to_expressions; std::unordered_map<std::string, QueryTreeNodes> alias_name_to_expressions;
}; };
/** Projection names is name of query tree node that is used in projection part of query node. /** Projection names is name of query tree node that is used in projection part of query node.
@ -1100,6 +1102,10 @@ private:
static void validateJoinTableExpressionWithoutAlias(const QueryTreeNodePtr & join_node, const QueryTreeNodePtr & table_expression_node, IdentifierResolveScope & scope); static void validateJoinTableExpressionWithoutAlias(const QueryTreeNodePtr & join_node, const QueryTreeNodePtr & table_expression_node, IdentifierResolveScope & scope);
static void expandGroupByAll(QueryNode & query_tree_node_typed);
static std::pair<bool, UInt64> recursivelyCollectMaxOrdinaryExpressions(QueryTreeNodePtr & node, QueryTreeNodes & into);
/// Resolve identifier functions /// Resolve identifier functions
static QueryTreeNodePtr tryResolveTableIdentifierFromDatabaseCatalog(const Identifier & table_identifier, ContextPtr context); static QueryTreeNodePtr tryResolveTableIdentifierFromDatabaseCatalog(const Identifier & table_identifier, ContextPtr context);
@ -1929,6 +1935,68 @@ void QueryAnalyzer::validateJoinTableExpressionWithoutAlias(const QueryTreeNodeP
scope.scope_node->formatASTForErrorMessage()); scope.scope_node->formatASTForErrorMessage());
} }
std::pair<bool, UInt64> QueryAnalyzer::recursivelyCollectMaxOrdinaryExpressions(QueryTreeNodePtr & node, QueryTreeNodes & into)
{
checkStackSize();
if (node->as<ColumnNode>())
{
into.push_back(node);
return {false, 1};
}
auto * function = node->as<FunctionNode>();
if (!function)
return {false, 0};
if (function->isAggregateFunction())
return {true, 0};
UInt64 pushed_children = 0;
bool has_aggregate = false;
for (auto & child : function->getArguments().getNodes())
{
auto [child_has_aggregate, child_pushed_children] = recursivelyCollectMaxOrdinaryExpressions(child, into);
has_aggregate |= child_has_aggregate;
pushed_children += child_pushed_children;
}
/// The current function is not aggregate function and there is no aggregate function in its arguments,
/// so use the current function to replace its arguments
if (!has_aggregate)
{
for (UInt64 i = 0; i < pushed_children; i++)
into.pop_back();
into.push_back(node);
pushed_children = 1;
}
return {has_aggregate, pushed_children};
}
/** Expand GROUP BY ALL by extracting all the SELECT-ed expressions that are not aggregate functions.
*
* For a special case that if there is a function having both aggregate functions and other fields as its arguments,
* the `GROUP BY` keys will contain the maximum non-aggregate fields we can extract from it.
*
* Example:
* SELECT substring(a, 4, 2), substring(substring(a, 1, 2), 1, count(b)) FROM t GROUP BY ALL
* will expand as
* SELECT substring(a, 4, 2), substring(substring(a, 1, 2), 1, count(b)) FROM t GROUP BY substring(a, 4, 2), substring(a, 1, 2)
*/
void QueryAnalyzer::expandGroupByAll(QueryNode & query_tree_node_typed)
{
auto & group_by_nodes = query_tree_node_typed.getGroupBy().getNodes();
auto & projection_list = query_tree_node_typed.getProjection();
for (auto & node : projection_list.getNodes())
recursivelyCollectMaxOrdinaryExpressions(node, group_by_nodes);
}
/// Resolve identifier functions implementation /// Resolve identifier functions implementation
@ -2171,18 +2239,19 @@ QueryTreeNodePtr QueryAnalyzer::tryResolveIdentifierFromAliases(const Identifier
auto & alias_identifier_node = it->second->as<IdentifierNode &>(); auto & alias_identifier_node = it->second->as<IdentifierNode &>();
auto identifier = alias_identifier_node.getIdentifier(); auto identifier = alias_identifier_node.getIdentifier();
auto lookup_result = tryResolveIdentifier(IdentifierLookup{identifier, identifier_lookup.lookup_context}, scope, identifier_resolve_settings); auto lookup_result = tryResolveIdentifier(IdentifierLookup{identifier, identifier_lookup.lookup_context}, scope, identifier_resolve_settings);
if (!lookup_result.isResolved()) if (!lookup_result.resolved_identifier)
{ {
std::unordered_set<Identifier> valid_identifiers; std::unordered_set<Identifier> valid_identifiers;
collectScopeWithParentScopesValidIdentifiersForTypoCorrection(identifier, scope, true, false, false, valid_identifiers); collectScopeWithParentScopesValidIdentifiersForTypoCorrection(identifier, scope, true, false, false, valid_identifiers);
auto hints = collectIdentifierTypoHints(identifier, valid_identifiers); auto hints = collectIdentifierTypoHints(identifier, valid_identifiers);
throw Exception(ErrorCodes::UNKNOWN_IDENTIFIER, "Unknown {} identifier '{}' in scope {}{}",
toStringLowercase(IdentifierLookupContext::EXPRESSION), throw Exception(ErrorCodes::UNKNOWN_IDENTIFIER, "Unknown {} identifier '{}'. In scope {}{}",
toStringLowercase(identifier_lookup.lookup_context),
identifier.getFullName(), identifier.getFullName(),
scope.scope_node->formatASTForErrorMessage(), scope.scope_node->formatASTForErrorMessage(),
getHintsErrorMessageSuffix(hints)); getHintsErrorMessageSuffix(hints));
} }
it->second = lookup_result.resolved_identifier; it->second = lookup_result.resolved_identifier;
/** During collection of aliases if node is identifier and has alias, we cannot say if it is /** During collection of aliases if node is identifier and has alias, we cannot say if it is
@ -2193,9 +2262,9 @@ QueryTreeNodePtr QueryAnalyzer::tryResolveIdentifierFromAliases(const Identifier
* If we resolved identifier node as function, we must remove identifier node alias from * If we resolved identifier node as function, we must remove identifier node alias from
* expression alias map. * expression alias map.
*/ */
if (identifier_lookup.isExpressionLookup() && it->second) if (identifier_lookup.isExpressionLookup())
scope.alias_name_to_lambda_node.erase(identifier_bind_part); scope.alias_name_to_lambda_node.erase(identifier_bind_part);
else if (identifier_lookup.isFunctionLookup() && it->second) else if (identifier_lookup.isFunctionLookup())
scope.alias_name_to_expression_node.erase(identifier_bind_part); scope.alias_name_to_expression_node.erase(identifier_bind_part);
scope.expressions_in_resolve_process_stack.popNode(); scope.expressions_in_resolve_process_stack.popNode();
@ -3203,11 +3272,9 @@ QueryAnalyzer::QueryTreeNodesWithNames QueryAnalyzer::resolveUnqualifiedMatcher(
if (auto * array_join_node = table_expression->as<ArrayJoinNode>()) if (auto * array_join_node = table_expression->as<ArrayJoinNode>())
{ {
size_t table_expressions_column_nodes_with_names_stack_size = table_expressions_column_nodes_with_names_stack.size(); if (table_expressions_column_nodes_with_names_stack.empty())
if (table_expressions_column_nodes_with_names_stack_size < 1)
throw Exception(ErrorCodes::LOGICAL_ERROR, throw Exception(ErrorCodes::LOGICAL_ERROR,
"Expected at least 1 table expressions on stack before ARRAY JOIN processing. Actual {}", "Expected at least 1 table expressions on stack before ARRAY JOIN processing");
table_expressions_column_nodes_with_names_stack_size);
auto & table_expression_column_nodes_with_names = table_expressions_column_nodes_with_names_stack.back(); auto & table_expression_column_nodes_with_names = table_expressions_column_nodes_with_names_stack.back();
@ -5388,25 +5455,7 @@ void QueryAnalyzer::resolveQueryJoinTreeNode(QueryTreeNodePtr & join_tree_node,
} }
} }
/// TODO: Special functions that can take query resolveExpressionNodeList(table_function_node.getArgumentsNode(), scope, false /*allow_lambda_expression*/, true /*allow_table_expression*/);
/// TODO: Support qualified matchers for table function
for (auto & argument_node : table_function_node.getArguments().getNodes())
{
if (argument_node->getNodeType() == QueryTreeNodeType::MATCHER)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Matcher as table function argument is not supported {}. In scope {}",
join_tree_node->formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
}
auto * function_node = argument_node->as<FunctionNode>();
if (function_node && table_function_factory.hasNameOrAlias(function_node->getFunctionName()))
continue;
resolveExpressionNode(argument_node, scope, false /*allow_lambda_expression*/, true /*allow_table_expression*/);
}
auto table_function_ast = table_function_node.toAST(); auto table_function_ast = table_function_node.toAST();
table_function_ptr->parseArguments(table_function_ast, scope_context); table_function_ptr->parseArguments(table_function_ast, scope_context);
@ -6006,6 +6055,9 @@ void QueryAnalyzer::resolveQuery(const QueryTreeNodePtr & query_node, Identifier
node->removeAlias(); node->removeAlias();
} }
if (query_node_typed.isGroupByAll())
expandGroupByAll(query_node_typed);
/** Validate aggregates /** Validate aggregates
* *
* 1. Check that there are no aggregate functions and GROUPING function in JOIN TREE, WHERE, PREWHERE, in another aggregate functions. * 1. Check that there are no aggregate functions and GROUPING function in JOIN TREE, WHERE, PREWHERE, in another aggregate functions.

View File

@ -54,6 +54,9 @@ void QueryNode::dumpTreeImpl(WriteBuffer & buffer, FormatState & format_state, s
if (is_group_by_with_totals) if (is_group_by_with_totals)
buffer << ", is_group_by_with_totals: " << is_group_by_with_totals; buffer << ", is_group_by_with_totals: " << is_group_by_with_totals;
if (is_group_by_all)
buffer << ", is_group_by_all: " << is_group_by_all;
std::string group_by_type; std::string group_by_type;
if (is_group_by_with_rollup) if (is_group_by_with_rollup)
group_by_type = "rollup"; group_by_type = "rollup";
@ -117,7 +120,7 @@ void QueryNode::dumpTreeImpl(WriteBuffer & buffer, FormatState & format_state, s
getWhere()->dumpTreeImpl(buffer, format_state, indent + 4); getWhere()->dumpTreeImpl(buffer, format_state, indent + 4);
} }
if (hasGroupBy()) if (!is_group_by_all && hasGroupBy())
{ {
buffer << '\n' << std::string(indent + 2, ' ') << "GROUP BY\n"; buffer << '\n' << std::string(indent + 2, ' ') << "GROUP BY\n";
getGroupBy().dumpTreeImpl(buffer, format_state, indent + 4); getGroupBy().dumpTreeImpl(buffer, format_state, indent + 4);
@ -198,7 +201,8 @@ bool QueryNode::isEqualImpl(const IQueryTreeNode & rhs) const
is_group_by_with_totals == rhs_typed.is_group_by_with_totals && is_group_by_with_totals == rhs_typed.is_group_by_with_totals &&
is_group_by_with_rollup == rhs_typed.is_group_by_with_rollup && is_group_by_with_rollup == rhs_typed.is_group_by_with_rollup &&
is_group_by_with_cube == rhs_typed.is_group_by_with_cube && is_group_by_with_cube == rhs_typed.is_group_by_with_cube &&
is_group_by_with_grouping_sets == rhs_typed.is_group_by_with_grouping_sets; is_group_by_with_grouping_sets == rhs_typed.is_group_by_with_grouping_sets &&
is_group_by_all == rhs_typed.is_group_by_all;
} }
void QueryNode::updateTreeHashImpl(HashState & state) const void QueryNode::updateTreeHashImpl(HashState & state) const
@ -226,6 +230,7 @@ void QueryNode::updateTreeHashImpl(HashState & state) const
state.update(is_group_by_with_rollup); state.update(is_group_by_with_rollup);
state.update(is_group_by_with_cube); state.update(is_group_by_with_cube);
state.update(is_group_by_with_grouping_sets); state.update(is_group_by_with_grouping_sets);
state.update(is_group_by_all);
if (constant_value) if (constant_value)
{ {
@ -251,6 +256,7 @@ QueryTreeNodePtr QueryNode::cloneImpl() const
result_query_node->is_group_by_with_rollup = is_group_by_with_rollup; result_query_node->is_group_by_with_rollup = is_group_by_with_rollup;
result_query_node->is_group_by_with_cube = is_group_by_with_cube; result_query_node->is_group_by_with_cube = is_group_by_with_cube;
result_query_node->is_group_by_with_grouping_sets = is_group_by_with_grouping_sets; result_query_node->is_group_by_with_grouping_sets = is_group_by_with_grouping_sets;
result_query_node->is_group_by_all = is_group_by_all;
result_query_node->cte_name = cte_name; result_query_node->cte_name = cte_name;
result_query_node->projection_columns = projection_columns; result_query_node->projection_columns = projection_columns;
result_query_node->constant_value = constant_value; result_query_node->constant_value = constant_value;
@ -267,6 +273,7 @@ ASTPtr QueryNode::toASTImpl() const
select_query->group_by_with_rollup = is_group_by_with_rollup; select_query->group_by_with_rollup = is_group_by_with_rollup;
select_query->group_by_with_cube = is_group_by_with_cube; select_query->group_by_with_cube = is_group_by_with_cube;
select_query->group_by_with_grouping_sets = is_group_by_with_grouping_sets; select_query->group_by_with_grouping_sets = is_group_by_with_grouping_sets;
select_query->group_by_all = is_group_by_all;
if (hasWith()) if (hasWith())
select_query->setExpression(ASTSelectQuery::Expression::WITH, getWith().toAST()); select_query->setExpression(ASTSelectQuery::Expression::WITH, getWith().toAST());
@ -283,7 +290,7 @@ ASTPtr QueryNode::toASTImpl() const
if (getWhere()) if (getWhere())
select_query->setExpression(ASTSelectQuery::Expression::WHERE, getWhere()->toAST()); select_query->setExpression(ASTSelectQuery::Expression::WHERE, getWhere()->toAST());
if (hasGroupBy()) if (!is_group_by_all && hasGroupBy())
select_query->setExpression(ASTSelectQuery::Expression::GROUP_BY, getGroupBy().toAST()); select_query->setExpression(ASTSelectQuery::Expression::GROUP_BY, getGroupBy().toAST());
if (hasHaving()) if (hasHaving())

View File

@ -176,6 +176,18 @@ public:
is_group_by_with_grouping_sets = is_group_by_with_grouping_sets_value; is_group_by_with_grouping_sets = is_group_by_with_grouping_sets_value;
} }
/// Returns true, if query node has GROUP BY ALL modifier, false otherwise
bool isGroupByAll() const
{
return is_group_by_all;
}
/// Set query node GROUP BY ALL modifier value
void setIsGroupByAll(bool is_group_by_all_value)
{
is_group_by_all = is_group_by_all_value;
}
/// Returns true if query node WITH section is not empty, false otherwise /// Returns true if query node WITH section is not empty, false otherwise
bool hasWith() const bool hasWith() const
{ {
@ -580,6 +592,7 @@ private:
bool is_group_by_with_rollup = false; bool is_group_by_with_rollup = false;
bool is_group_by_with_cube = false; bool is_group_by_with_cube = false;
bool is_group_by_with_grouping_sets = false; bool is_group_by_with_grouping_sets = false;
bool is_group_by_all = false;
std::string cte_name; std::string cte_name;
NamesAndTypes projection_columns; NamesAndTypes projection_columns;

View File

@ -215,6 +215,7 @@ QueryTreeNodePtr QueryTreeBuilder::buildSelectExpression(const ASTPtr & select_q
current_query_tree->setIsGroupByWithCube(select_query_typed.group_by_with_cube); current_query_tree->setIsGroupByWithCube(select_query_typed.group_by_with_cube);
current_query_tree->setIsGroupByWithRollup(select_query_typed.group_by_with_rollup); current_query_tree->setIsGroupByWithRollup(select_query_typed.group_by_with_rollup);
current_query_tree->setIsGroupByWithGroupingSets(select_query_typed.group_by_with_grouping_sets); current_query_tree->setIsGroupByWithGroupingSets(select_query_typed.group_by_with_grouping_sets);
current_query_tree->setIsGroupByAll(select_query_typed.group_by_all);
current_query_tree->setOriginalAST(select_query); current_query_tree->setOriginalAST(select_query);
auto select_settings = select_query_typed.settings(); auto select_settings = select_query_typed.settings();

View File

@ -110,12 +110,12 @@ void registerBackupEngineS3(BackupFactory & factory)
if (params.open_mode == IBackup::OpenMode::READ) if (params.open_mode == IBackup::OpenMode::READ)
{ {
auto reader = std::make_shared<BackupReaderS3>(S3::URI{Poco::URI{s3_uri}}, access_key_id, secret_access_key, params.context); auto reader = std::make_shared<BackupReaderS3>(S3::URI{s3_uri}, access_key_id, secret_access_key, params.context);
return std::make_unique<BackupImpl>(backup_name_for_logging, archive_params, params.base_backup_info, reader, params.context); return std::make_unique<BackupImpl>(backup_name_for_logging, archive_params, params.base_backup_info, reader, params.context);
} }
else else
{ {
auto writer = std::make_shared<BackupWriterS3>(S3::URI{Poco::URI{s3_uri}}, access_key_id, secret_access_key, params.context); auto writer = std::make_shared<BackupWriterS3>(S3::URI{s3_uri}, access_key_id, secret_access_key, params.context);
return std::make_unique<BackupImpl>(backup_name_for_logging, archive_params, params.base_backup_info, writer, params.context, params.is_internal_backup, params.backup_coordination, params.backup_uuid); return std::make_unique<BackupImpl>(backup_name_for_logging, archive_params, params.base_backup_info, writer, params.context, params.is_internal_backup, params.backup_coordination, params.backup_uuid);
} }
#else #else

View File

@ -1401,6 +1401,11 @@ try
QueryPipeline pipeline(std::move(pipe)); QueryPipeline pipeline(std::move(pipe));
PullingAsyncPipelineExecutor executor(pipeline); PullingAsyncPipelineExecutor executor(pipeline);
if (need_render_progress)
{
pipeline.setProgressCallback([this](const Progress & progress){ onProgress(progress); });
}
Block block; Block block;
while (executor.pull(block)) while (executor.pull(block))
{ {
@ -1445,12 +1450,6 @@ catch (...)
void ClientBase::sendDataFromStdin(Block & sample, const ColumnsDescription & columns_description, ASTPtr parsed_query) void ClientBase::sendDataFromStdin(Block & sample, const ColumnsDescription & columns_description, ASTPtr parsed_query)
{ {
if (need_render_progress)
{
/// Add callback to track reading from fd.
std_in.setProgressCallback(global_context);
}
/// Send data read from stdin. /// Send data read from stdin.
try try
{ {

View File

@ -171,6 +171,11 @@ protected:
void initTtyBuffer(ProgressOption progress); void initTtyBuffer(ProgressOption progress);
/// Should be one of the first, to be destroyed the last,
/// since other members can use them.
SharedContextHolder shared_context;
ContextMutablePtr global_context;
bool is_interactive = false; /// Use either interactive line editing interface or batch mode. bool is_interactive = false; /// Use either interactive line editing interface or batch mode.
bool is_multiquery = false; bool is_multiquery = false;
bool delayed_interactive = false; bool delayed_interactive = false;
@ -208,9 +213,6 @@ protected:
/// Settings specified via command line args /// Settings specified via command line args
Settings cmd_settings; Settings cmd_settings;
SharedContextHolder shared_context;
ContextMutablePtr global_context;
/// thread status should be destructed before shared context because it relies on process list. /// thread status should be destructed before shared context because it relies on process list.
std::optional<ThreadStatus> thread_status; std::optional<ThreadStatus> thread_status;

View File

@ -524,11 +524,13 @@ void ColumnArray::insertRangeFrom(const IColumn & src, size_t start, size_t leng
size_t nested_offset = src_concrete.offsetAt(start); size_t nested_offset = src_concrete.offsetAt(start);
size_t nested_length = src_concrete.getOffsets()[start + length - 1] - nested_offset; size_t nested_length = src_concrete.getOffsets()[start + length - 1] - nested_offset;
Offsets & cur_offsets = getOffsets();
/// Reserve offsets before to make it more exception safe (in case of MEMORY_LIMIT_EXCEEDED)
cur_offsets.reserve(cur_offsets.size() + length);
getData().insertRangeFrom(src_concrete.getData(), nested_offset, nested_length); getData().insertRangeFrom(src_concrete.getData(), nested_offset, nested_length);
Offsets & cur_offsets = getOffsets();
const Offsets & src_offsets = src_concrete.getOffsets(); const Offsets & src_offsets = src_concrete.getOffsets();
if (start == 0 && cur_offsets.empty()) if (start == 0 && cur_offsets.empty())
{ {
cur_offsets.assign(src_offsets.begin(), src_offsets.begin() + length); cur_offsets.assign(src_offsets.begin(), src_offsets.begin() + length);

View File

@ -124,6 +124,9 @@ void ColumnString::insertRangeFrom(const IColumn & src, size_t start, size_t len
size_t nested_offset = src_concrete.offsetAt(start); size_t nested_offset = src_concrete.offsetAt(start);
size_t nested_length = src_concrete.offsets[start + length - 1] - nested_offset; size_t nested_length = src_concrete.offsets[start + length - 1] - nested_offset;
/// Reserve offsets before to make it more exception safe (in case of MEMORY_LIMIT_EXCEEDED)
offsets.reserve(offsets.size() + length);
size_t old_chars_size = chars.size(); size_t old_chars_size = chars.size();
chars.resize(old_chars_size + nested_length); chars.resize(old_chars_size + nested_length);
memcpy(&chars[old_chars_size], &src_concrete.chars[nested_offset], nested_length); memcpy(&chars[old_chars_size], &src_concrete.chars[nested_offset], nested_length);

View File

@ -5,6 +5,7 @@
#define APPLY_FOR_METRICS(M) \ #define APPLY_FOR_METRICS(M) \
M(Query, "Number of executing queries") \ M(Query, "Number of executing queries") \
M(Merge, "Number of executing background merges") \ M(Merge, "Number of executing background merges") \
M(Move, "Number of currently executing moves") \
M(PartMutation, "Number of mutations (ALTER DELETE/UPDATE)") \ M(PartMutation, "Number of mutations (ALTER DELETE/UPDATE)") \
M(ReplicatedFetch, "Number of data parts being fetched from replica") \ M(ReplicatedFetch, "Number of data parts being fetched from replica") \
M(ReplicatedSend, "Number of data parts being sent to replicas") \ M(ReplicatedSend, "Number of data parts being sent to replicas") \

View File

@ -27,6 +27,14 @@ public:
/// NOTE: Adding events into distant past (further than `period`) must be avoided. /// NOTE: Adding events into distant past (further than `period`) must be avoided.
void add(double now, double count) void add(double now, double count)
{ {
// Remove data for initial heating stage that can present at the beginning of a query.
// Otherwise it leads to wrong gradual increase of average value, turning algorithm into not very reactive.
if (count != 0.0 && ++data_points < 5)
{
start = events.time;
events = ExponentiallySmoothedAverage();
}
if (now - period <= start) // precise counting mode if (now - period <= start) // precise counting mode
events = ExponentiallySmoothedAverage(events.value + count, now); events = ExponentiallySmoothedAverage(events.value + count, now);
else // exponential smoothing mode else // exponential smoothing mode
@ -51,6 +59,7 @@ public:
{ {
start = now; start = now;
events = ExponentiallySmoothedAverage(); events = ExponentiallySmoothedAverage();
data_points = 0;
} }
private: private:
@ -58,6 +67,7 @@ private:
const double half_decay_time; const double half_decay_time;
double start; // Instant in past without events before it; when measurement started or reset double start; // Instant in past without events before it; when measurement started or reset
ExponentiallySmoothedAverage events; // Estimated number of events in the last `period` ExponentiallySmoothedAverage events; // Estimated number of events in the last `period`
size_t data_points = 0;
}; };
} }

View File

@ -15,6 +15,7 @@
#include <Common/formatReadable.h> #include <Common/formatReadable.h>
#include <Common/filesystemHelpers.h> #include <Common/filesystemHelpers.h>
#include <Common/ErrorCodes.h> #include <Common/ErrorCodes.h>
#include <Common/SensitiveDataMasker.h>
#include <Common/LockMemoryExceptionInThread.h> #include <Common/LockMemoryExceptionInThread.h>
#include <filesystem> #include <filesystem>
@ -63,11 +64,18 @@ void handle_error_code([[maybe_unused]] const std::string & msg, int code, bool
ErrorCodes::increment(code, remote, msg, trace); ErrorCodes::increment(code, remote, msg, trace);
} }
Exception::Exception(const std::string & msg, int code, bool remote_) Exception::MessageMasked::MessageMasked(const std::string & msg_)
: Poco::Exception(msg, code) : msg(msg_)
{
if (auto * masker = SensitiveDataMasker::getInstance())
masker->wipeSensitiveData(msg);
}
Exception::Exception(const MessageMasked & msg_masked, int code, bool remote_)
: Poco::Exception(msg_masked.msg, code)
, remote(remote_) , remote(remote_)
{ {
handle_error_code(msg, code, remote, getStackFramePointers()); handle_error_code(msg_masked.msg, code, remote, getStackFramePointers());
} }
Exception::Exception(CreateFromPocoTag, const Poco::Exception & exc) Exception::Exception(CreateFromPocoTag, const Poco::Exception & exc)

View File

@ -27,7 +27,19 @@ public:
using FramePointers = std::vector<void *>; using FramePointers = std::vector<void *>;
Exception() = default; Exception() = default;
Exception(const std::string & msg, int code, bool remote_ = false);
// used to remove the sensitive information from exceptions if query_masking_rules is configured
struct MessageMasked
{
std::string msg;
MessageMasked(const std::string & msg_);
};
Exception(const MessageMasked & msg_masked, int code, bool remote_);
// delegating constructor to mask sensitive information from the message
Exception(const std::string & msg, int code, bool remote_ = false): Exception(MessageMasked(msg), code, remote_)
{}
Exception(int code, const std::string & message) Exception(int code, const std::string & message)
: Exception(message, code) : Exception(message, code)
@ -54,12 +66,17 @@ public:
template <typename... Args> template <typename... Args>
void addMessage(fmt::format_string<Args...> format, Args &&... args) void addMessage(fmt::format_string<Args...> format, Args &&... args)
{ {
extendedMessage(fmt::format(format, std::forward<Args>(args)...)); addMessage(fmt::format(format, std::forward<Args>(args)...));
} }
void addMessage(const std::string& message) void addMessage(const std::string& message)
{ {
extendedMessage(message); addMessage(MessageMasked(message));
}
void addMessage(const MessageMasked & msg_masked)
{
extendedMessage(msg_masked.msg);
} }
/// Used to distinguish local exceptions from the one that was received from remote node. /// Used to distinguish local exceptions from the one that was received from remote node.

View File

@ -220,7 +220,7 @@ void MemoryTracker::allocImpl(Int64 size, bool throw_if_memory_exceeded, MemoryT
Int64 limit_to_check = current_hard_limit; Int64 limit_to_check = current_hard_limit;
#if USE_JEMALLOC #if USE_JEMALLOC
if (level == VariableContext::Global) if (level == VariableContext::Global && allow_use_jemalloc_memory.load(std::memory_order_relaxed))
{ {
/// Jemalloc arenas may keep some extra memory. /// Jemalloc arenas may keep some extra memory.
/// This memory was substucted from RSS to decrease memory drift. /// This memory was substucted from RSS to decrease memory drift.

View File

@ -55,6 +55,7 @@ private:
std::atomic<Int64> soft_limit {0}; std::atomic<Int64> soft_limit {0};
std::atomic<Int64> hard_limit {0}; std::atomic<Int64> hard_limit {0};
std::atomic<Int64> profiler_limit {0}; std::atomic<Int64> profiler_limit {0};
std::atomic_bool allow_use_jemalloc_memory {true};
static std::atomic<Int64> free_memory_in_allocator_arenas; static std::atomic<Int64> free_memory_in_allocator_arenas;
@ -125,6 +126,10 @@ public:
{ {
return soft_limit.load(std::memory_order_relaxed); return soft_limit.load(std::memory_order_relaxed);
} }
void setAllowUseJemallocMemory(bool value)
{
allow_use_jemalloc_memory.store(value, std::memory_order_relaxed);
}
/** Set limit if it was not set. /** Set limit if it was not set.
* Otherwise, set limit to new value, if new value is greater than previous limit. * Otherwise, set limit to new value, if new value is greater than previous limit.

View File

@ -90,7 +90,7 @@ private:
bool write_progress_on_update = false; bool write_progress_on_update = false;
EventRateMeter cpu_usage_meter{static_cast<double>(clock_gettime_ns()), 3'000'000'000 /*ns*/}; // average cpu utilization last 3 second EventRateMeter cpu_usage_meter{static_cast<double>(clock_gettime_ns()), 2'000'000'000 /*ns*/}; // average cpu utilization last 2 second
HostToThreadTimesMap thread_data; HostToThreadTimesMap thread_data;
/// In case of all of the above: /// In case of all of the above:
/// - clickhouse-local /// - clickhouse-local

View File

@ -189,6 +189,13 @@ public:
finalize(); finalize();
return v0 ^ v1 ^ v2 ^ v3; return v0 ^ v1 ^ v2 ^ v3;
} }
UInt128 get128()
{
UInt128 res;
get128(res);
return res;
}
}; };
@ -208,9 +215,7 @@ inline UInt128 sipHash128(const char * data, const size_t size)
{ {
SipHash hash; SipHash hash;
hash.update(data, size); hash.update(data, size);
UInt128 res; return hash.get128();
hash.get128(res);
return res;
} }
inline UInt64 sipHash64(const char * data, const size_t size) inline UInt64 sipHash64(const char * data, const size_t size)

View File

@ -8,6 +8,7 @@
#include "hasLinuxCapability.h" #include "hasLinuxCapability.h"
#include <base/unaligned.h> #include <base/unaligned.h>
#include <Common/logger_useful.h>
#include <cerrno> #include <cerrno>
#include <cstdio> #include <cstdio>
@ -205,6 +206,20 @@ bool checkPermissionsImpl()
{ {
TaskStatsInfoGetter(); TaskStatsInfoGetter();
} }
catch (const Exception & e)
{
if (e.code() == ErrorCodes::NETLINK_ERROR)
{
/// This error happens all the time when running inside Docker - consider it ok,
/// don't create noise with this error.
LOG_DEBUG(&Poco::Logger::get(__PRETTY_FUNCTION__), "{}", getCurrentExceptionMessage(false));
}
else
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
return false;
}
catch (...) catch (...)
{ {
tryLogCurrentException(__PRETTY_FUNCTION__); tryLogCurrentException(__PRETTY_FUNCTION__);

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <base/types.h> #include <base/types.h>
#include <base/getThreadId.h>
#include <Common/ProfileEvents.h> #include <Common/ProfileEvents.h>
#include <sys/time.h> #include <sys/time.h>
#include <sys/resource.h> #include <sys/resource.h>
@ -47,6 +48,8 @@ struct RUsageCounters
UInt64 soft_page_faults = 0; UInt64 soft_page_faults = 0;
UInt64 hard_page_faults = 0; UInt64 hard_page_faults = 0;
UInt64 thread_id = 0;
RUsageCounters() = default; RUsageCounters() = default;
RUsageCounters(const ::rusage & rusage_, UInt64 real_time_) RUsageCounters(const ::rusage & rusage_, UInt64 real_time_)
{ {
@ -61,6 +64,8 @@ struct RUsageCounters
soft_page_faults = static_cast<UInt64>(rusage.ru_minflt); soft_page_faults = static_cast<UInt64>(rusage.ru_minflt);
hard_page_faults = static_cast<UInt64>(rusage.ru_majflt); hard_page_faults = static_cast<UInt64>(rusage.ru_majflt);
thread_id = getThreadId();
} }
static RUsageCounters current() static RUsageCounters current()
@ -78,6 +83,12 @@ struct RUsageCounters
static void incrementProfileEvents(const RUsageCounters & prev, const RUsageCounters & curr, ProfileEvents::Counters & profile_events) static void incrementProfileEvents(const RUsageCounters & prev, const RUsageCounters & curr, ProfileEvents::Counters & profile_events)
{ {
chassert(prev.thread_id == curr.thread_id);
/// LONG_MAX is ~106751 days
chassert(curr.real_time - prev.real_time < LONG_MAX);
chassert(curr.user_time - prev.user_time < LONG_MAX);
chassert(curr.sys_time - prev.sys_time < LONG_MAX);
profile_events.increment(ProfileEvents::RealTimeMicroseconds, (curr.real_time - prev.real_time) / 1000U); profile_events.increment(ProfileEvents::RealTimeMicroseconds, (curr.real_time - prev.real_time) / 1000U);
profile_events.increment(ProfileEvents::UserTimeMicroseconds, (curr.user_time - prev.user_time) / 1000U); profile_events.increment(ProfileEvents::UserTimeMicroseconds, (curr.user_time - prev.user_time) / 1000U);
profile_events.increment(ProfileEvents::SystemTimeMicroseconds, (curr.sys_time - prev.sys_time) / 1000U); profile_events.increment(ProfileEvents::SystemTimeMicroseconds, (curr.sys_time - prev.sys_time) / 1000U);

View File

@ -179,8 +179,8 @@ protected:
/// Is used to send logs from logs_queue to client in case of fatal errors. /// Is used to send logs from logs_queue to client in case of fatal errors.
std::function<void()> fatal_error_callback; std::function<void()> fatal_error_callback;
/// It is used to avoid enabling the query profiler when you have multiple ThreadStatus in the same thread /// See setInternalThread()
bool query_profiler_enabled = true; bool internal_thread = false;
/// Requires access to query_id. /// Requires access to query_id.
friend class MemoryTrackerThreadSwitcher; friend class MemoryTrackerThreadSwitcher;
@ -225,11 +225,21 @@ public:
return global_context.lock(); return global_context.lock();
} }
void disableProfiling() /// "Internal" ThreadStatus is used for materialized views for separate
{ /// tracking into system.query_views_log
assert(!query_profiler_real && !query_profiler_cpu); ///
query_profiler_enabled = false; /// You can have multiple internal threads, but only one non-internal with
} /// the same thread_id.
///
/// "Internal" thread:
/// - cannot have query profiler
/// since the running (main query) thread should already have one
/// - should not try to obtain latest counter on detach
/// because detaching of such threads will be done from a different
/// thread_id, and some counters are not available (i.e. getrusage()),
/// but anyway they are accounted correctly in the main ThreadStatus of a
/// query.
void setInternalThread();
/// Starts new query and create new thread group for it, current thread becomes master thread of the query /// Starts new query and create new thread group for it, current thread becomes master thread of the query
void initializeQuery(); void initializeQuery();

View File

@ -65,7 +65,7 @@ void KeeperSnapshotManagerS3::updateS3Configuration(const Poco::Util::AbstractCo
auto auth_settings = S3::AuthSettings::loadFromConfig(config_prefix, config); auto auth_settings = S3::AuthSettings::loadFromConfig(config_prefix, config);
auto endpoint = config.getString(config_prefix + ".endpoint"); auto endpoint = config.getString(config_prefix + ".endpoint");
auto new_uri = S3::URI{Poco::URI(endpoint)}; auto new_uri = S3::URI{endpoint};
{ {
std::lock_guard client_lock{snapshot_s3_client_mutex}; std::lock_guard client_lock{snapshot_s3_client_mutex};

View File

@ -667,9 +667,15 @@ Names Block::getDataTypeNames() const
} }
std::unordered_map<String, size_t> Block::getNamesToIndexesMap() const Block::NameMap Block::getNamesToIndexesMap() const
{ {
return index_by_name; NameMap res;
res.reserve(index_by_name.size());
for (const auto & [name, index] : index_by_name)
res[name] = index;
return res;
} }

View File

@ -5,6 +5,8 @@
#include <Core/ColumnsWithTypeAndName.h> #include <Core/ColumnsWithTypeAndName.h>
#include <Core/NamesAndTypes.h> #include <Core/NamesAndTypes.h>
#include <Common/HashTable/HashMap.h>
#include <initializer_list> #include <initializer_list>
#include <list> #include <list>
#include <map> #include <map>
@ -93,7 +95,10 @@ public:
Names getNames() const; Names getNames() const;
DataTypes getDataTypes() const; DataTypes getDataTypes() const;
Names getDataTypeNames() const; Names getDataTypeNames() const;
std::unordered_map<String, size_t> getNamesToIndexesMap() const;
/// Hash table match `column name -> position in the block`.
using NameMap = HashMap<StringRef, size_t, StringRefHash>;
NameMap getNamesToIndexesMap() const;
Serializations getSerializations() const; Serializations getSerializations() const;

View File

@ -851,6 +851,9 @@ static constexpr UInt64 operator""_GiB(unsigned long long value)
M(Bool, output_format_sql_insert_include_column_names, true, "Include column names in INSERT query", 0) \ M(Bool, output_format_sql_insert_include_column_names, true, "Include column names in INSERT query", 0) \
M(Bool, output_format_sql_insert_use_replace, false, "Use REPLACE statement instead of INSERT", 0) \ M(Bool, output_format_sql_insert_use_replace, false, "Use REPLACE statement instead of INSERT", 0) \
M(Bool, output_format_sql_insert_quote_names, true, "Quote column names with '`' characters", 0) \ M(Bool, output_format_sql_insert_quote_names, true, "Quote column names with '`' characters", 0) \
\
M(Bool, output_format_bson_string_as_string, false, "Use BSON String type instead of Binary for String columns.", 0) \
M(Bool, input_format_bson_skip_fields_with_unsupported_types_in_schema_inference, false, "Skip fields with unsupported types while schema inference for format BSON.", 0) \
// End of FORMAT_FACTORY_SETTINGS // End of FORMAT_FACTORY_SETTINGS
// Please add settings non-related to formats into the COMMON_SETTINGS above. // Please add settings non-related to formats into the COMMON_SETTINGS above.

View File

@ -284,7 +284,7 @@ std::vector<DictionaryAttribute> DictionaryStructure::getAttributes(
std::unordered_set<String> attribute_names; std::unordered_set<String> attribute_names;
std::vector<DictionaryAttribute> res_attributes; std::vector<DictionaryAttribute> res_attributes;
const FormatSettings format_settings; const FormatSettings format_settings = {};
for (const auto & config_elem : config_elems) for (const auto & config_elem : config_elems)
{ {

View File

@ -62,7 +62,7 @@ struct ExternalQueryBuilder
private: private:
const FormatSettings format_settings; const FormatSettings format_settings = {};
void composeLoadAllQuery(WriteBuffer & out) const; void composeLoadAllQuery(WriteBuffer & out) const;

View File

@ -74,7 +74,6 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory)
// Poco/MongoDB/BSONWriter.h:54: void writeCString(const std::string & value); // Poco/MongoDB/BSONWriter.h:54: void writeCString(const std::string & value);
// src/IO/WriteHelpers.h:146 #define writeCString(s, buf) // src/IO/WriteHelpers.h:146 #define writeCString(s, buf)
#include <IO/WriteHelpers.h> #include <IO/WriteHelpers.h>
#include <Processors/Transforms/MongoDBSource.h>
namespace DB namespace DB

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <Processors/Transforms/MongoDBSource.h>
#include <Core/Block.h> #include <Core/Block.h>
#include "DictionaryStructure.h" #include "DictionaryStructure.h"

View File

@ -42,7 +42,7 @@ std::unique_ptr<ReadBufferFromFileBase> createReadBufferFromFileBase(
if (read_hint.has_value()) if (read_hint.has_value())
estimated_size = *read_hint; estimated_size = *read_hint;
else if (file_size.has_value()) else if (file_size.has_value())
estimated_size = file_size.has_value() ? *file_size : 0; estimated_size = *file_size;
if (!existing_memory if (!existing_memory
&& settings.local_fs_method == LocalFSReadMethod::mmap && settings.local_fs_method == LocalFSReadMethod::mmap
@ -158,7 +158,15 @@ std::unique_ptr<ReadBufferFromFileBase> createReadBufferFromFileBase(
#endif #endif
ProfileEvents::increment(ProfileEvents::CreatedReadBufferOrdinary); ProfileEvents::increment(ProfileEvents::CreatedReadBufferOrdinary);
return create(settings.local_fs_buffer_size, flags);
size_t buffer_size = settings.local_fs_buffer_size;
/// Check if the buffer can be smaller than default
if (read_hint.has_value() && *read_hint > 0 && *read_hint < buffer_size)
buffer_size = *read_hint;
if (file_size.has_value() && *file_size < buffer_size)
buffer_size = *file_size;
return create(buffer_size, flags);
} }
} }

View File

@ -4,6 +4,7 @@
#include <Common/getRandomASCIIString.h> #include <Common/getRandomASCIIString.h>
#include <IO/WriteHelpers.h> #include <IO/WriteHelpers.h>
#include <IO/ReadHelpers.h> #include <IO/ReadHelpers.h>
#include <optional>
#include <ranges> #include <ranges>
#include <filesystem> #include <filesystem>
@ -62,7 +63,7 @@ UnlinkFileOperation::UnlinkFileOperation(const std::string & path_, IDisk & disk
void UnlinkFileOperation::execute(std::unique_lock<std::shared_mutex> &) void UnlinkFileOperation::execute(std::unique_lock<std::shared_mutex> &)
{ {
auto buf = disk.readFile(path); auto buf = disk.readFile(path, ReadSettings{}, std::nullopt, disk.getFileSize(path));
readStringUntilEOF(prev_data, *buf); readStringUntilEOF(prev_data, *buf);
disk.removeFile(path); disk.removeFile(path);
} }

View File

@ -658,7 +658,7 @@ std::unique_ptr<IObjectStorage> S3ObjectStorage::cloneObjectStorage(
return std::make_unique<S3ObjectStorage>( return std::make_unique<S3ObjectStorage>(
std::move(new_client), std::move(new_s3_settings), std::move(new_client), std::move(new_s3_settings),
version_id, s3_capabilities, new_namespace, version_id, s3_capabilities, new_namespace,
S3::URI(Poco::URI(config.getString(config_prefix + ".endpoint"))).endpoint); config.getString(config_prefix + ".endpoint"));
} }
} }

View File

@ -137,7 +137,7 @@ std::unique_ptr<Aws::S3::S3Client> getClient(
settings.request_settings.get_request_throttler, settings.request_settings.get_request_throttler,
settings.request_settings.put_request_throttler); settings.request_settings.put_request_throttler);
S3::URI uri(Poco::URI(config.getString(config_prefix + ".endpoint"))); S3::URI uri(config.getString(config_prefix + ".endpoint"));
if (uri.key.back() != '/') if (uri.key.back() != '/')
throw Exception("S3 path must ends with '/', but '" + uri.key + "' doesn't.", ErrorCodes::BAD_ARGUMENTS); throw Exception("S3 path must ends with '/', but '" + uri.key + "' doesn't.", ErrorCodes::BAD_ARGUMENTS);

View File

@ -104,7 +104,7 @@ void registerDiskS3(DiskFactory & factory, bool global_skip_access_check)
ContextPtr context, ContextPtr context,
const DisksMap & /*map*/) -> DiskPtr const DisksMap & /*map*/) -> DiskPtr
{ {
S3::URI uri(Poco::URI(config.getString(config_prefix + ".endpoint"))); S3::URI uri(config.getString(config_prefix + ".endpoint"));
if (uri.key.empty()) if (uri.key.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "No key in S3 uri: {}", uri.uri.toString()); throw Exception(ErrorCodes::BAD_ARGUMENTS, "No key in S3 uri: {}", uri.uri.toString());

106
src/Formats/BSONTypes.cpp Normal file
View File

@ -0,0 +1,106 @@
#include <Formats/BSONTypes.h>
#include <Common/Exception.h>
#include <Common/hex.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNKNOWN_TYPE;
}
static std::string byteToHexString(uint8_t byte)
{
return "0x" + getHexUIntUppercase(byte);
}
BSONType getBSONType(uint8_t value)
{
if ((value >= 0x01 && value <= 0x13) || value == 0xFF || value == 0x7f)
return BSONType(value);
throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown BSON type: {}", byteToHexString(value));
}
BSONBinarySubtype getBSONBinarySubtype(uint8_t value)
{
if (value <= 0x07)
return BSONBinarySubtype(value);
throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown BSON binary subtype: {}", byteToHexString(value));
}
std::string getBSONTypeName(BSONType type)
{
switch (type)
{
case BSONType::BINARY:
return "Binary";
case BSONType::SYMBOL:
return "Symbol";
case BSONType::ARRAY:
return "Array";
case BSONType::DOCUMENT:
return "Document";
case BSONType::TIMESTAMP:
return "Timestamp";
case BSONType::INT64:
return "Int64";
case BSONType::INT32:
return "Int32";
case BSONType::BOOL:
return "Bool";
case BSONType::DOUBLE:
return "Double";
case BSONType::STRING:
return "String";
case BSONType::DECIMAL128:
return "Decimal128";
case BSONType::JAVA_SCRIPT_CODE_W_SCOPE:
return "JavaScript code w/ scope";
case BSONType::JAVA_SCRIPT_CODE:
return "JavaScript code";
case BSONType::DB_POINTER:
return "DBPointer";
case BSONType::REGEXP:
return "Regexp";
case BSONType::DATETIME:
return "Datetime";
case BSONType::OBJECT_ID:
return "ObjectId";
case BSONType::UNDEFINED:
return "Undefined";
case BSONType::NULL_VALUE:
return "Null";
case BSONType::MAX_KEY:
return "Max key";
case BSONType::MIN_KEY:
return "Min key";
}
}
std::string getBSONBinarySubtypeName(BSONBinarySubtype subtype)
{
switch (subtype)
{
case BSONBinarySubtype::BINARY:
return "Binary";
case BSONBinarySubtype::FUNCTION:
return "Function";
case BSONBinarySubtype::BINARY_OLD:
return "Binary (Old)";
case BSONBinarySubtype::UUID_OLD:
return "UUID (Old)";
case BSONBinarySubtype::UUID:
return "UUID";
case BSONBinarySubtype::MD5:
return "MD5";
case BSONBinarySubtype::ENCRYPTED_BSON_VALUE:
return "Encrypted BSON value";
case BSONBinarySubtype::COMPRESSED_BSON_COLUMN:
return "Compressed BSON column";
}
}
}

57
src/Formats/BSONTypes.h Normal file
View File

@ -0,0 +1,57 @@
#pragma once
#include <cstdint>
#include <string>
namespace DB
{
static const uint8_t BSON_DOCUMENT_END = 0x00;
using BSONSizeT = uint32_t;
static const BSONSizeT MAX_BSON_SIZE = std::numeric_limits<BSONSizeT>::max();
/// See details on https://bsonspec.org/spec.html
enum class BSONType
{
DOUBLE = 0x01,
STRING = 0x02,
DOCUMENT = 0x03,
ARRAY = 0x04,
BINARY = 0x05,
UNDEFINED = 0x06,
OBJECT_ID = 0x07,
BOOL = 0x08,
DATETIME = 0x09,
NULL_VALUE = 0x0A,
REGEXP = 0x0B,
DB_POINTER = 0x0C,
JAVA_SCRIPT_CODE = 0x0D,
SYMBOL = 0x0E,
JAVA_SCRIPT_CODE_W_SCOPE = 0x0F,
INT32 = 0x10,
TIMESTAMP = 0x11,
INT64 = 0x12,
DECIMAL128 = 0x13,
MIN_KEY = 0xFF,
MAX_KEY = 0x7F,
};
enum class BSONBinarySubtype
{
BINARY = 0x00,
FUNCTION = 0x01,
BINARY_OLD = 0x02,
UUID_OLD = 0x03,
UUID = 0x04,
MD5 = 0x05,
ENCRYPTED_BSON_VALUE = 0x06,
COMPRESSED_BSON_COLUMN = 0x07,
};
BSONType getBSONType(uint8_t value);
std::string getBSONTypeName(BSONType type);
BSONBinarySubtype getBSONBinarySubtype(uint8_t value);
std::string getBSONBinarySubtypeName(BSONBinarySubtype subtype);
}

View File

@ -18,7 +18,7 @@ void ColumnMapping::setupByHeader(const Block & header)
} }
void ColumnMapping::addColumns( void ColumnMapping::addColumns(
const Names & column_names, const std::unordered_map<String, size_t> & column_indexes_by_names, const FormatSettings & settings) const Names & column_names, const Block::NameMap & column_indexes_by_names, const FormatSettings & settings)
{ {
std::vector<bool> read_columns(column_indexes_by_names.size(), false); std::vector<bool> read_columns(column_indexes_by_names.size(), false);
@ -26,8 +26,8 @@ void ColumnMapping::addColumns(
{ {
names_of_columns.push_back(name); names_of_columns.push_back(name);
const auto column_it = column_indexes_by_names.find(name); const auto * column_it = column_indexes_by_names.find(name);
if (column_it == column_indexes_by_names.end()) if (!column_it)
{ {
if (settings.skip_unknown_fields) if (settings.skip_unknown_fields)
{ {
@ -41,7 +41,7 @@ void ColumnMapping::addColumns(
name, column_indexes_for_input_fields.size()); name, column_indexes_for_input_fields.size());
} }
const auto column_index = column_it->second; const auto column_index = column_it->getMapped();
if (read_columns[column_index]) if (read_columns[column_index])
throw Exception("Duplicate field found while parsing format header: " + name, ErrorCodes::INCORRECT_DATA); throw Exception("Duplicate field found while parsing format header: " + name, ErrorCodes::INCORRECT_DATA);

View File

@ -28,7 +28,7 @@ struct ColumnMapping
void setupByHeader(const Block & header); void setupByHeader(const Block & header);
void addColumns( void addColumns(
const Names & column_names, const std::unordered_map<String, size_t> & column_indexes_by_names, const FormatSettings & settings); const Names & column_names, const Block::NameMap & column_indexes_by_names, const FormatSettings & settings);
void insertDefaultsForNotSeenColumns(MutableColumns & columns, std::vector<UInt8> & read_columns); void insertDefaultsForNotSeenColumns(MutableColumns & columns, std::vector<UInt8> & read_columns);
}; };

View File

@ -834,17 +834,23 @@ DataTypes getDefaultDataTypeForEscapingRules(const std::vector<FormatSettings::E
return data_types; return data_types;
} }
String getAdditionalFormatInfoForAllRowBasedFormats(const FormatSettings & settings)
{
return fmt::format(
"schema_inference_hints={}, max_rows_to_read_for_schema_inference={}",
settings.schema_inference_hints,
settings.max_rows_to_read_for_schema_inference);
}
String getAdditionalFormatInfoByEscapingRule(const FormatSettings & settings, FormatSettings::EscapingRule escaping_rule) String getAdditionalFormatInfoByEscapingRule(const FormatSettings & settings, FormatSettings::EscapingRule escaping_rule)
{ {
String result; String result = getAdditionalFormatInfoForAllRowBasedFormats(settings);
/// First, settings that are common for all text formats: /// First, settings that are common for all text formats:
result = fmt::format( result += fmt::format(
"schema_inference_hints={}, try_infer_integers={}, try_infer_dates={}, try_infer_datetimes={}, max_rows_to_read_for_schema_inference={}", ", try_infer_integers={}, try_infer_dates={}, try_infer_datetimes={}",
settings.schema_inference_hints,
settings.try_infer_integers, settings.try_infer_integers,
settings.try_infer_dates, settings.try_infer_dates,
settings.try_infer_datetimes, settings.try_infer_datetimes);
settings.max_rows_to_read_for_schema_inference);
/// Second, format-specific settings: /// Second, format-specific settings:
switch (escaping_rule) switch (escaping_rule)

View File

@ -77,6 +77,7 @@ void transformInferredTypesIfNeeded(DataTypePtr & first, DataTypePtr & second, c
void transformInferredJSONTypesIfNeeded(DataTypes & types, const FormatSettings & settings, const std::unordered_set<const IDataType *> * numbers_parsed_from_json_strings = nullptr); void transformInferredJSONTypesIfNeeded(DataTypes & types, const FormatSettings & settings, const std::unordered_set<const IDataType *> * numbers_parsed_from_json_strings = nullptr);
void transformInferredJSONTypesIfNeeded(DataTypePtr & first, DataTypePtr & second, const FormatSettings & settings); void transformInferredJSONTypesIfNeeded(DataTypePtr & first, DataTypePtr & second, const FormatSettings & settings);
String getAdditionalFormatInfoForAllRowBasedFormats(const FormatSettings & settings);
String getAdditionalFormatInfoByEscapingRule(const FormatSettings & settings, FormatSettings::EscapingRule escaping_rule); String getAdditionalFormatInfoByEscapingRule(const FormatSettings & settings, FormatSettings::EscapingRule escaping_rule);
void checkSupportedDelimiterAfterField(FormatSettings::EscapingRule escaping_rule, const String & delimiter, const DataTypePtr & type); void checkSupportedDelimiterAfterField(FormatSettings::EscapingRule escaping_rule, const String & delimiter, const DataTypePtr & type);

View File

@ -178,6 +178,8 @@ FormatSettings getFormatSettings(ContextPtr context, const Settings & settings)
format_settings.try_infer_integers = settings.input_format_try_infer_integers; format_settings.try_infer_integers = settings.input_format_try_infer_integers;
format_settings.try_infer_dates = settings.input_format_try_infer_dates; format_settings.try_infer_dates = settings.input_format_try_infer_dates;
format_settings.try_infer_datetimes = settings.input_format_try_infer_datetimes; format_settings.try_infer_datetimes = settings.input_format_try_infer_datetimes;
format_settings.bson.output_string_as_string = settings.output_format_bson_string_as_string;
format_settings.bson.skip_fields_with_unsupported_types_in_schema_inference = settings.input_format_bson_skip_fields_with_unsupported_types_in_schema_inference;
/// Validate avro_schema_registry_url with RemoteHostFilter when non-empty and in Server context /// Validate avro_schema_registry_url with RemoteHostFilter when non-empty and in Server context
if (format_settings.schema.is_server) if (format_settings.schema.is_server)

View File

@ -303,6 +303,12 @@ struct FormatSettings
bool use_replace = false; bool use_replace = false;
bool quote_names = true; bool quote_names = true;
} sql_insert; } sql_insert;
struct
{
bool output_string_as_string;
bool skip_fields_with_unsupported_types_in_schema_inference;
} bson;
}; };
} }

View File

@ -231,7 +231,14 @@ namespace JSONUtils
{ {
auto type = getDataTypeFromFieldImpl(key_value_pair.second, settings, numbers_parsed_from_json_strings); auto type = getDataTypeFromFieldImpl(key_value_pair.second, settings, numbers_parsed_from_json_strings);
if (!type) if (!type)
{
/// If we couldn't infer nested type and Object type is not enabled,
/// we can't determine the type of this JSON field.
if (!settings.json.try_infer_objects)
return nullptr;
continue; continue;
}
if (settings.json.try_infer_objects && isObject(type)) if (settings.json.try_infer_objects && isObject(type))
return std::make_shared<DataTypeObject>("json", true); return std::make_shared<DataTypeObject>("json", true);

View File

@ -19,6 +19,7 @@ void registerFileSegmentationEngineJSONCompactEachRow(FormatFactory & factory);
void registerFileSegmentationEngineHiveText(FormatFactory & factory); void registerFileSegmentationEngineHiveText(FormatFactory & factory);
#endif #endif
void registerFileSegmentationEngineLineAsString(FormatFactory & factory); void registerFileSegmentationEngineLineAsString(FormatFactory & factory);
void registerFileSegmentationEngineBSONEachRow(FormatFactory & factory);
/// Formats for both input/output. /// Formats for both input/output.
@ -49,6 +50,8 @@ void registerInputFormatJSONColumns(FormatFactory & factory);
void registerOutputFormatJSONColumns(FormatFactory & factory); void registerOutputFormatJSONColumns(FormatFactory & factory);
void registerInputFormatJSONCompactColumns(FormatFactory & factory); void registerInputFormatJSONCompactColumns(FormatFactory & factory);
void registerOutputFormatJSONCompactColumns(FormatFactory & factory); void registerOutputFormatJSONCompactColumns(FormatFactory & factory);
void registerInputFormatBSONEachRow(FormatFactory & factory);
void registerOutputFormatBSONEachRow(FormatFactory & factory);
void registerInputFormatJSONColumnsWithMetadata(FormatFactory & factory); void registerInputFormatJSONColumnsWithMetadata(FormatFactory & factory);
void registerOutputFormatJSONColumnsWithMetadata(FormatFactory & factory); void registerOutputFormatJSONColumnsWithMetadata(FormatFactory & factory);
void registerInputFormatProtobuf(FormatFactory & factory); void registerInputFormatProtobuf(FormatFactory & factory);
@ -136,7 +139,7 @@ void registerTSKVSchemaReader(FormatFactory & factory);
void registerValuesSchemaReader(FormatFactory & factory); void registerValuesSchemaReader(FormatFactory & factory);
void registerTemplateSchemaReader(FormatFactory & factory); void registerTemplateSchemaReader(FormatFactory & factory);
void registerMySQLSchemaReader(FormatFactory & factory); void registerMySQLSchemaReader(FormatFactory & factory);
void registerBSONEachRowSchemaReader(FormatFactory & factory);
void registerFileExtensions(FormatFactory & factory); void registerFileExtensions(FormatFactory & factory);
@ -155,6 +158,7 @@ void registerFormats()
registerFileSegmentationEngineHiveText(factory); registerFileSegmentationEngineHiveText(factory);
#endif #endif
registerFileSegmentationEngineLineAsString(factory); registerFileSegmentationEngineLineAsString(factory);
registerFileSegmentationEngineBSONEachRow(factory);
registerInputFormatNative(factory); registerInputFormatNative(factory);
@ -184,6 +188,8 @@ void registerFormats()
registerOutputFormatJSONColumns(factory); registerOutputFormatJSONColumns(factory);
registerInputFormatJSONCompactColumns(factory); registerInputFormatJSONCompactColumns(factory);
registerOutputFormatJSONCompactColumns(factory); registerOutputFormatJSONCompactColumns(factory);
registerInputFormatBSONEachRow(factory);
registerOutputFormatBSONEachRow(factory);
registerInputFormatJSONColumnsWithMetadata(factory); registerInputFormatJSONColumnsWithMetadata(factory);
registerOutputFormatJSONColumnsWithMetadata(factory); registerOutputFormatJSONColumnsWithMetadata(factory);
registerInputFormatProtobuf(factory); registerInputFormatProtobuf(factory);
@ -267,6 +273,7 @@ void registerFormats()
registerValuesSchemaReader(factory); registerValuesSchemaReader(factory);
registerTemplateSchemaReader(factory); registerTemplateSchemaReader(factory);
registerMySQLSchemaReader(factory); registerMySQLSchemaReader(factory);
registerBSONEachRowSchemaReader(factory);
} }
} }

View File

@ -1,31 +1,40 @@
#include <Functions/IFunction.h> #include <Columns/ColumnString.h>
#include <Functions/FunctionFactory.h> #include <Columns/ColumnVector.h>
#include <DataTypes/DataTypesNumber.h> #include <DataTypes/DataTypesNumber.h>
#include <Disks/IDisk.h>
#include <Functions/FunctionFactory.h>
#include <Functions/IFunction.h>
#include <Interpreters/Context.h> #include <Interpreters/Context.h>
#include <filesystem>
#include <Poco/Util/AbstractConfiguration.h> #include <Poco/Util/AbstractConfiguration.h>
namespace DB namespace DB
{ {
namespace ErrorCodes
{
extern const int ILLEGAL_COLUMN;
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
extern const int UNKNOWN_DISK;
}
namespace namespace
{ {
struct FilesystemAvailable struct FilesystemAvailable
{ {
static constexpr auto name = "filesystemAvailable"; static constexpr auto name = "filesystemAvailable";
static std::uintmax_t get(const std::filesystem::space_info & spaceinfo) { return spaceinfo.available; } static std::uintmax_t get(const DiskPtr & disk) { return disk->getAvailableSpace(); }
}; };
struct FilesystemFree struct FilesystemUnreserved
{ {
static constexpr auto name = "filesystemFree"; static constexpr auto name = "filesystemUnreserved";
static std::uintmax_t get(const std::filesystem::space_info & spaceinfo) { return spaceinfo.free; } static std::uintmax_t get(const DiskPtr & disk) { return disk->getUnreservedSpace(); }
}; };
struct FilesystemCapacity struct FilesystemCapacity
{ {
static constexpr auto name = "filesystemCapacity"; static constexpr auto name = "filesystemCapacity";
static std::uintmax_t get(const std::filesystem::space_info & spaceinfo) { return spaceinfo.capacity; } static std::uintmax_t get(const DiskPtr & disk) { return disk->getTotalSpace(); }
}; };
template <typename Impl> template <typename Impl>
@ -34,34 +43,72 @@ class FilesystemImpl : public IFunction
public: public:
static constexpr auto name = Impl::name; static constexpr auto name = Impl::name;
static FunctionPtr create(ContextPtr context) static FunctionPtr create(ContextPtr context_) { return std::make_shared<FilesystemImpl<Impl>>(context_); }
{
return std::make_shared<FilesystemImpl<Impl>>(std::filesystem::space(context->getPath())); explicit FilesystemImpl(ContextPtr context_) : context(context_) { }
}
bool useDefaultImplementationForConstants() const override { return true; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override
{ {
return false; return false;
} }
explicit FilesystemImpl(std::filesystem::space_info spaceinfo_) : spaceinfo(spaceinfo_) { }
String getName() const override { return name; } String getName() const override { return name; }
bool isVariadic() const override { return true; }
size_t getNumberOfArguments() const override { return 0; } size_t getNumberOfArguments() const override { return 0; }
bool isDeterministic() const override { return false; } bool isDeterministic() const override { return false; }
DataTypePtr getReturnTypeImpl(const DataTypes & /*arguments*/) const override DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{ {
if (arguments.size() > 1)
{
throw Exception("Arguments size of function " + getName() + " should be 0 or 1", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
}
if (arguments.size() == 1 && !isStringOrFixedString(arguments[0]))
{
throw Exception(
"Arguments of function " + getName() + " should be String or FixedString", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
}
return std::make_shared<DataTypeUInt64>(); return std::make_shared<DataTypeUInt64>();
} }
ColumnPtr executeImpl(const ColumnsWithTypeAndName &, const DataTypePtr &, size_t input_rows_count) const override ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{ {
return DataTypeUInt64().createColumnConst(input_rows_count, static_cast<UInt64>(Impl::get(spaceinfo))); if (arguments.empty())
{
auto disk = context->getDisk("default");
return DataTypeUInt64().createColumnConst(input_rows_count, Impl::get(disk));
}
else
{
auto col = arguments[0].column;
if (const ColumnString * col_str = checkAndGetColumn<ColumnString>(col.get()))
{
auto disk_map = context->getDisksMap();
auto col_res = ColumnVector<UInt64>::create(col_str->size());
auto & data = col_res->getData();
for (size_t i = 0; i < col_str->size(); ++i)
{
auto disk_name = col_str->getDataAt(i).toString();
if (auto it = disk_map.find(disk_name); it != disk_map.end())
data[i] = Impl::get(it->second);
else
throw Exception(
"Unknown disk name " + disk_name + " while execute function " + getName(), ErrorCodes::UNKNOWN_DISK);
}
return col_res;
}
throw Exception(
"Illegal column " + arguments[0].column->getName() + " of argument of function " + getName(), ErrorCodes::ILLEGAL_COLUMN);
}
} }
private: private:
std::filesystem::space_info spaceinfo; ContextPtr context;
}; };
} }
@ -70,7 +117,7 @@ REGISTER_FUNCTION(Filesystem)
{ {
factory.registerFunction<FilesystemImpl<FilesystemAvailable>>(); factory.registerFunction<FilesystemImpl<FilesystemAvailable>>();
factory.registerFunction<FilesystemImpl<FilesystemCapacity>>(); factory.registerFunction<FilesystemImpl<FilesystemCapacity>>();
factory.registerFunction<FilesystemImpl<FilesystemFree>>(); factory.registerFunction<FilesystemImpl<FilesystemUnreserved>>();
} }
} }

View File

@ -1016,6 +1016,7 @@ public:
size_t getNumberOfArguments() const override { return 3; } size_t getNumberOfArguments() const override { return 3; }
bool useDefaultImplementationForNulls() const override { return false; } bool useDefaultImplementationForNulls() const override { return false; }
bool useDefaultImplementationForNothing() const override { return false; }
bool isShortCircuit(ShortCircuitSettings & settings, size_t /*number_of_arguments*/) const override bool isShortCircuit(ShortCircuitSettings & settings, size_t /*number_of_arguments*/) const override
{ {
settings.enable_lazy_execution_for_first_argument = false; settings.enable_lazy_execution_for_first_argument = false;

View File

@ -50,6 +50,7 @@ public:
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; } bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }
size_t getNumberOfArguments() const override { return 0; } size_t getNumberOfArguments() const override { return 0; }
bool useDefaultImplementationForNulls() const override { return false; } bool useDefaultImplementationForNulls() const override { return false; }
bool useDefaultImplementationForNothing() const override { return false; }
ColumnNumbers getArgumentsThatDontImplyNullableReturnType(size_t number_of_arguments) const override ColumnNumbers getArgumentsThatDontImplyNullableReturnType(size_t number_of_arguments) const override
{ {

View File

@ -57,7 +57,7 @@ namespace DB
if (unlikely(begin > end)) if (unlikely(begin > end))
{ {
const FormatSettings default_format; const FormatSettings default_format{};
WriteBufferFromOwnString buf_begin, buf_end; WriteBufferFromOwnString buf_begin, buf_end;
begin_serializaion->serializeTextQuoted(*(arguments[0].column), i, buf_begin, default_format); begin_serializaion->serializeTextQuoted(*(arguments[0].column), i, buf_begin, default_format);
end_serialization->serializeTextQuoted(*(arguments[1].column), i, buf_end, default_format); end_serialization->serializeTextQuoted(*(arguments[1].column), i, buf_end, default_format);

View File

@ -1278,6 +1278,25 @@ void skipToUnescapedNextLineOrEOF(ReadBuffer & buf)
} }
} }
void skipNullTerminated(ReadBuffer & buf)
{
while (!buf.eof())
{
char * next_pos = find_first_symbols<'\0'>(buf.position(), buf.buffer().end());
buf.position() = next_pos;
if (!buf.hasPendingData())
continue;
if (*buf.position() == '\0')
{
++buf.position();
return;
}
}
}
void saveUpToPosition(ReadBuffer & in, Memory<> & memory, char * current) void saveUpToPosition(ReadBuffer & in, Memory<> & memory, char * current)
{ {
assert(current >= in.position()); assert(current >= in.position());

View File

@ -1448,6 +1448,8 @@ void skipToCarriageReturnOrEOF(ReadBuffer & buf);
/// Skip to next character after next unescaped \n. If no \n in stream, skip to end. Does not throw on invalid escape sequences. /// Skip to next character after next unescaped \n. If no \n in stream, skip to end. Does not throw on invalid escape sequences.
void skipToUnescapedNextLineOrEOF(ReadBuffer & buf); void skipToUnescapedNextLineOrEOF(ReadBuffer & buf);
/// Skip to next character after next \0. If no \0 in stream, skip to end.
void skipNullTerminated(ReadBuffer & buf);
/** This function just copies the data from buffer's internal position (in.position()) /** This function just copies the data from buffer's internal position (in.position())
* to current position (from arguments) into memory. * to current position (from arguments) into memory.

View File

@ -76,7 +76,7 @@ TEST(IOTestAwsS3Client, AppendExtraSSECHeaders)
DB::RemoteHostFilter remote_host_filter; DB::RemoteHostFilter remote_host_filter;
unsigned int s3_max_redirects = 100; unsigned int s3_max_redirects = 100;
DB::S3::URI uri(Poco::URI(http.getUrl() + "/IOTestAwsS3ClientAppendExtraHeaders/test.txt")); DB::S3::URI uri(http.getUrl() + "/IOTestAwsS3ClientAppendExtraHeaders/test.txt");
String access_key_id = "ACCESS_KEY_ID"; String access_key_id = "ACCESS_KEY_ID";
String secret_access_key = "SECRET_ACCESS_KEY"; String secret_access_key = "SECRET_ACCESS_KEY";
String region = "us-east-1"; String region = "us-east-1";

View File

@ -759,7 +759,7 @@ namespace S3
put_request_throttler); put_request_throttler);
} }
URI::URI(const Poco::URI & uri_) URI::URI(const std::string & uri_)
{ {
/// Case when bucket name represented in domain name of S3 URL. /// Case when bucket name represented in domain name of S3 URL.
/// E.g. (https://bucket-name.s3.Region.amazonaws.com/key) /// E.g. (https://bucket-name.s3.Region.amazonaws.com/key)
@ -777,16 +777,32 @@ namespace S3
static constexpr auto OBS = "OBS"; static constexpr auto OBS = "OBS";
static constexpr auto OSS = "OSS"; static constexpr auto OSS = "OSS";
uri = uri_; uri = Poco::URI(uri_);
storage_name = S3; storage_name = S3;
if (uri.getHost().empty()) if (uri.getHost().empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Host is empty in S3 URI."); throw Exception(ErrorCodes::BAD_ARGUMENTS, "Host is empty in S3 URI.");
/// Extract object version ID from query string. /// Extract object version ID from query string.
bool has_version_id = false;
for (const auto & [query_key, query_value] : uri.getQueryParameters()) for (const auto & [query_key, query_value] : uri.getQueryParameters())
if (query_key == "versionId") if (query_key == "versionId")
{
version_id = query_value; version_id = query_value;
has_version_id = true;
}
/// Poco::URI will ignore '?' when parsing the path, but if there is a vestionId in the http parameter,
/// '?' can not be used as a wildcard, otherwise it will be ambiguous.
/// If no "vertionId" in the http parameter, '?' can be used as a wildcard.
/// It is necessary to encode '?' to avoid deletion during parsing path.
if (!has_version_id && uri_.find('?') != String::npos)
{
String uri_with_question_mark_encode;
Poco::URI::encode(uri_, "?", uri_with_question_mark_encode);
uri = Poco::URI(uri_with_question_mark_encode);
}
String name; String name;
String endpoint_authority_from_uri; String endpoint_authority_from_uri;

View File

@ -119,8 +119,7 @@ struct URI
bool is_virtual_hosted_style; bool is_virtual_hosted_style;
explicit URI(const Poco::URI & uri_); explicit URI(const std::string & uri_);
explicit URI(const std::string & uri_) : URI(Poco::URI(uri_)) {}
static void validateBucket(const String & bucket, const Poco::URI & uri); static void validateBucket(const String & bucket, const Poco::URI & uri);
}; };

View File

@ -20,55 +20,55 @@ struct TestCase
}; };
const TestCase TestCases[] = { const TestCase TestCases[] = {
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data")), {S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data"),
"https://s3.us-east-2.amazonaws.com", "https://s3.us-east-2.amazonaws.com",
"bucketname", "bucketname",
"data", "data",
"", "",
true}, true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?firstKey=someKey&secondKey=anotherKey")), {S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?firstKey=someKey&secondKey=anotherKey"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data?firstKey=someKey&secondKey=anotherKey",
"",
true},
{S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId=testVersionId&anotherKey=someOtherKey"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?firstKey=someKey&versionId=testVersionId&anotherKey=someOtherKey"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?anotherKey=someOtherKey&versionId=testVersionId"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId=testVersionId"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId="),
"https://s3.us-east-2.amazonaws.com", "https://s3.us-east-2.amazonaws.com",
"bucketname", "bucketname",
"data", "data",
"", "",
true}, true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId=testVersionId&anotherKey=someOtherKey")), {S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId&"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?firstKey=someKey&versionId=testVersionId&anotherKey=someOtherKey")),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?anotherKey=someOtherKey&versionId=testVersionId")),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId=testVersionId")),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"testVersionId",
true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId=")),
"https://s3.us-east-2.amazonaws.com", "https://s3.us-east-2.amazonaws.com",
"bucketname", "bucketname",
"data", "data",
"", "",
true}, true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId&")), {S3::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId"),
"https://s3.us-east-2.amazonaws.com",
"bucketname",
"data",
"",
true},
{S3::URI(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data?versionId")),
"https://s3.us-east-2.amazonaws.com", "https://s3.us-east-2.amazonaws.com",
"bucketname", "bucketname",
"data", "data",
@ -83,7 +83,7 @@ class S3UriTest : public testing::TestWithParam<std::string>
TEST(S3UriTest, validPatterns) TEST(S3UriTest, validPatterns)
{ {
{ {
S3::URI uri(Poco::URI("https://jokserfn.s3.amazonaws.com/")); S3::URI uri("https://jokserfn.s3.amazonaws.com/");
ASSERT_EQ("https://s3.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3.amazonaws.com", uri.endpoint);
ASSERT_EQ("jokserfn", uri.bucket); ASSERT_EQ("jokserfn", uri.bucket);
ASSERT_EQ("", uri.key); ASSERT_EQ("", uri.key);
@ -91,7 +91,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(true, uri.is_virtual_hosted_style); ASSERT_EQ(true, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://s3.amazonaws.com/jokserfn/")); S3::URI uri("https://s3.amazonaws.com/jokserfn/");
ASSERT_EQ("https://s3.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3.amazonaws.com", uri.endpoint);
ASSERT_EQ("jokserfn", uri.bucket); ASSERT_EQ("jokserfn", uri.bucket);
ASSERT_EQ("", uri.key); ASSERT_EQ("", uri.key);
@ -99,7 +99,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(false, uri.is_virtual_hosted_style); ASSERT_EQ(false, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://amazonaws.com/bucket/")); S3::URI uri("https://amazonaws.com/bucket/");
ASSERT_EQ("https://amazonaws.com", uri.endpoint); ASSERT_EQ("https://amazonaws.com", uri.endpoint);
ASSERT_EQ("bucket", uri.bucket); ASSERT_EQ("bucket", uri.bucket);
ASSERT_EQ("", uri.key); ASSERT_EQ("", uri.key);
@ -107,7 +107,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(false, uri.is_virtual_hosted_style); ASSERT_EQ(false, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://jokserfn.s3.amazonaws.com/data")); S3::URI uri("https://jokserfn.s3.amazonaws.com/data");
ASSERT_EQ("https://s3.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3.amazonaws.com", uri.endpoint);
ASSERT_EQ("jokserfn", uri.bucket); ASSERT_EQ("jokserfn", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -115,7 +115,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(true, uri.is_virtual_hosted_style); ASSERT_EQ(true, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://storage.amazonaws.com/jokserfn/data")); S3::URI uri("https://storage.amazonaws.com/jokserfn/data");
ASSERT_EQ("https://storage.amazonaws.com", uri.endpoint); ASSERT_EQ("https://storage.amazonaws.com", uri.endpoint);
ASSERT_EQ("jokserfn", uri.bucket); ASSERT_EQ("jokserfn", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -123,7 +123,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(false, uri.is_virtual_hosted_style); ASSERT_EQ(false, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://bucketname.cos.ap-beijing.myqcloud.com/data")); S3::URI uri("https://bucketname.cos.ap-beijing.myqcloud.com/data");
ASSERT_EQ("https://cos.ap-beijing.myqcloud.com", uri.endpoint); ASSERT_EQ("https://cos.ap-beijing.myqcloud.com", uri.endpoint);
ASSERT_EQ("bucketname", uri.bucket); ASSERT_EQ("bucketname", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -131,7 +131,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(true, uri.is_virtual_hosted_style); ASSERT_EQ(true, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://bucketname.s3.us-east-2.amazonaws.com/data")); S3::URI uri("https://bucketname.s3.us-east-2.amazonaws.com/data");
ASSERT_EQ("https://s3.us-east-2.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3.us-east-2.amazonaws.com", uri.endpoint);
ASSERT_EQ("bucketname", uri.bucket); ASSERT_EQ("bucketname", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -139,7 +139,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(true, uri.is_virtual_hosted_style); ASSERT_EQ(true, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://s3.us-east-2.amazonaws.com/bucketname/data")); S3::URI uri("https://s3.us-east-2.amazonaws.com/bucketname/data");
ASSERT_EQ("https://s3.us-east-2.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3.us-east-2.amazonaws.com", uri.endpoint);
ASSERT_EQ("bucketname", uri.bucket); ASSERT_EQ("bucketname", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -147,7 +147,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(false, uri.is_virtual_hosted_style); ASSERT_EQ(false, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://bucketname.s3-us-east-2.amazonaws.com/data")); S3::URI uri("https://bucketname.s3-us-east-2.amazonaws.com/data");
ASSERT_EQ("https://s3-us-east-2.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3-us-east-2.amazonaws.com", uri.endpoint);
ASSERT_EQ("bucketname", uri.bucket); ASSERT_EQ("bucketname", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -155,7 +155,7 @@ TEST(S3UriTest, validPatterns)
ASSERT_EQ(true, uri.is_virtual_hosted_style); ASSERT_EQ(true, uri.is_virtual_hosted_style);
} }
{ {
S3::URI uri(Poco::URI("https://s3-us-east-2.amazonaws.com/bucketname/data")); S3::URI uri("https://s3-us-east-2.amazonaws.com/bucketname/data");
ASSERT_EQ("https://s3-us-east-2.amazonaws.com", uri.endpoint); ASSERT_EQ("https://s3-us-east-2.amazonaws.com", uri.endpoint);
ASSERT_EQ("bucketname", uri.bucket); ASSERT_EQ("bucketname", uri.bucket);
ASSERT_EQ("data", uri.key); ASSERT_EQ("data", uri.key);
@ -166,7 +166,7 @@ TEST(S3UriTest, validPatterns)
TEST_P(S3UriTest, invalidPatterns) TEST_P(S3UriTest, invalidPatterns)
{ {
ASSERT_ANY_THROW(S3::URI(Poco::URI(GetParam()))); ASSERT_ANY_THROW(S3::URI new_uri(GetParam()));
} }
TEST(S3UriTest, versionIdChecks) TEST(S3UriTest, versionIdChecks)

View File

@ -24,6 +24,7 @@
#include <Storages/IStorage.h> #include <Storages/IStorage.h>
#include <Storages/MarkCache.h> #include <Storages/MarkCache.h>
#include <Storages/MergeTree/MergeList.h> #include <Storages/MergeTree/MergeList.h>
#include <Storages/MergeTree/MovesList.h>
#include <Storages/MergeTree/ReplicatedFetchList.h> #include <Storages/MergeTree/ReplicatedFetchList.h>
#include <Storages/MergeTree/MergeTreeData.h> #include <Storages/MergeTree/MergeTreeData.h>
#include <Storages/MergeTree/MergeTreeSettings.h> #include <Storages/MergeTree/MergeTreeSettings.h>
@ -229,6 +230,7 @@ struct ContextSharedPart : boost::noncopyable
ProcessList process_list; /// Executing queries at the moment. ProcessList process_list; /// Executing queries at the moment.
GlobalOvercommitTracker global_overcommit_tracker; GlobalOvercommitTracker global_overcommit_tracker;
MergeList merge_list; /// The list of executable merge (for (Replicated)?MergeTree) MergeList merge_list; /// The list of executable merge (for (Replicated)?MergeTree)
MovesList moves_list; /// The list of executing moves (for (Replicated)?MergeTree)
ReplicatedFetchList replicated_fetch_list; ReplicatedFetchList replicated_fetch_list;
ConfigurationPtr users_config; /// Config with the users, profiles and quotas sections. ConfigurationPtr users_config; /// Config with the users, profiles and quotas sections.
InterserverIOHandler interserver_io_handler; /// Handler for interserver communication. InterserverIOHandler interserver_io_handler; /// Handler for interserver communication.
@ -637,6 +639,8 @@ const ProcessList & Context::getProcessList() const { return shared->process_lis
OvercommitTracker * Context::getGlobalOvercommitTracker() const { return &shared->global_overcommit_tracker; } OvercommitTracker * Context::getGlobalOvercommitTracker() const { return &shared->global_overcommit_tracker; }
MergeList & Context::getMergeList() { return shared->merge_list; } MergeList & Context::getMergeList() { return shared->merge_list; }
const MergeList & Context::getMergeList() const { return shared->merge_list; } const MergeList & Context::getMergeList() const { return shared->merge_list; }
MovesList & Context::getMovesList() { return shared->moves_list; }
const MovesList & Context::getMovesList() const { return shared->moves_list; }
ReplicatedFetchList & Context::getReplicatedFetchList() { return shared->replicated_fetch_list; } ReplicatedFetchList & Context::getReplicatedFetchList() { return shared->replicated_fetch_list; }
const ReplicatedFetchList & Context::getReplicatedFetchList() const { return shared->replicated_fetch_list; } const ReplicatedFetchList & Context::getReplicatedFetchList() const { return shared->replicated_fetch_list; }

View File

@ -63,6 +63,7 @@ using InterserverCredentialsPtr = std::shared_ptr<const InterserverCredentials>;
class InterserverIOHandler; class InterserverIOHandler;
class BackgroundSchedulePool; class BackgroundSchedulePool;
class MergeList; class MergeList;
class MovesList;
class ReplicatedFetchList; class ReplicatedFetchList;
class Cluster; class Cluster;
class Compiler; class Compiler;
@ -775,6 +776,9 @@ public:
MergeList & getMergeList(); MergeList & getMergeList();
const MergeList & getMergeList() const; const MergeList & getMergeList() const;
MovesList & getMovesList();
const MovesList & getMovesList() const;
ReplicatedFetchList & getReplicatedFetchList(); ReplicatedFetchList & getReplicatedFetchList();
const ReplicatedFetchList & getReplicatedFetchList() const; const ReplicatedFetchList & getReplicatedFetchList() const;

View File

@ -1015,7 +1015,7 @@ void DatabaseCatalog::dropTableFinally(const TableMarkedAsDropped & table)
for (const auto & [disk_name, disk] : getContext()->getDisksMap()) for (const auto & [disk_name, disk] : getContext()->getDisksMap())
{ {
String data_path = "store/" + getPathForUUID(table.table_id.uuid); String data_path = "store/" + getPathForUUID(table.table_id.uuid);
if (!disk->exists(data_path) || disk->isReadOnly()) if (disk->isReadOnly() || !disk->exists(data_path))
continue; continue;
LOG_INFO(log, "Removing data directory {} of dropped table {} from disk {}", data_path, table.table_id.getNameForLogs(), disk_name); LOG_INFO(log, "Removing data directory {} of dropped table {} from disk {}", data_path, table.table_id.getNameForLogs(), disk_name);

View File

@ -165,7 +165,7 @@ struct QueryASTSettings
struct QueryTreeSettings struct QueryTreeSettings
{ {
bool run_passes = false; bool run_passes = true;
bool dump_passes = false; bool dump_passes = false;
bool dump_ast = false; bool dump_ast = false;
Int64 passes = -1; Int64 passes = -1;

View File

@ -2728,13 +2728,18 @@ void InterpreterSelectQuery::executeDistinct(QueryPlan & query_plan, bool before
{ {
const Settings & settings = context->getSettingsRef(); const Settings & settings = context->getSettingsRef();
auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context);
UInt64 limit_for_distinct = 0; UInt64 limit_for_distinct = 0;
/// If after this stage of DISTINCT ORDER BY is not executed, /// If after this stage of DISTINCT,
/// (1) ORDER BY is not executed
/// (2) there is no LIMIT BY (todo: we can check if DISTINCT and LIMIT BY expressions are match)
/// then you can get no more than limit_length + limit_offset of different rows. /// then you can get no more than limit_length + limit_offset of different rows.
if ((!query.orderBy() || !before_order) && limit_length <= std::numeric_limits<UInt64>::max() - limit_offset) if ((!query.orderBy() || !before_order) && !query.limitBy())
{
auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context);
if (limit_length <= std::numeric_limits<UInt64>::max() - limit_offset)
limit_for_distinct = limit_length + limit_offset; limit_for_distinct = limit_length + limit_offset;
}
SizeLimits limits(settings.max_rows_in_distinct, settings.max_bytes_in_distinct, settings.distinct_overflow_mode); SizeLimits limits(settings.max_rows_in_distinct, settings.max_bytes_in_distinct, settings.distinct_overflow_mode);

View File

@ -131,6 +131,12 @@ void ThreadStatus::setupState(const ThreadGroupStatusPtr & thread_group_)
thread_state = ThreadState::AttachedToQuery; thread_state = ThreadState::AttachedToQuery;
} }
void ThreadStatus::setInternalThread()
{
chassert(!query_profiler_real && !query_profiler_cpu);
internal_thread = true;
}
void ThreadStatus::initializeQuery() void ThreadStatus::initializeQuery()
{ {
setupState(std::make_shared<ThreadGroupStatus>()); setupState(std::make_shared<ThreadGroupStatus>());
@ -177,6 +183,8 @@ void ThreadStatus::initPerformanceCounters()
// query_start_time_nanoseconds cannot be used here since RUsageCounters expect CLOCK_MONOTONIC // query_start_time_nanoseconds cannot be used here since RUsageCounters expect CLOCK_MONOTONIC
*last_rusage = RUsageCounters::current(); *last_rusage = RUsageCounters::current();
if (!internal_thread)
{
if (auto query_context_ptr = query_context.lock()) if (auto query_context_ptr = query_context.lock())
{ {
const Settings & settings = query_context_ptr->getSettingsRef(); const Settings & settings = query_context_ptr->getSettingsRef();
@ -208,10 +216,11 @@ void ThreadStatus::initPerformanceCounters()
if (taskstats) if (taskstats)
taskstats->reset(); taskstats->reset();
} }
}
void ThreadStatus::finalizePerformanceCounters() void ThreadStatus::finalizePerformanceCounters()
{ {
if (performance_counters_finalized) if (performance_counters_finalized || internal_thread)
return; return;
performance_counters_finalized = true; performance_counters_finalized = true;
@ -270,7 +279,7 @@ void ThreadStatus::resetPerformanceCountersLastUsage()
void ThreadStatus::initQueryProfiler() void ThreadStatus::initQueryProfiler()
{ {
if (!query_profiler_enabled) if (internal_thread)
return; return;
/// query profilers are useless without trace collector /// query profilers are useless without trace collector

View File

@ -1,8 +1,8 @@
#include <algorithm> #include <algorithm>
#include <memory> #include <memory>
#include <Core/Settings.h> #include <Core/Settings.h>
#include <Core/NamesAndTypes.h> #include <Core/NamesAndTypes.h>
#include <Core/SettingsEnums.h> #include <Core/SettingsEnums.h>
#include <Interpreters/ArrayJoinedColumnsVisitor.h> #include <Interpreters/ArrayJoinedColumnsVisitor.h>
@ -45,10 +45,10 @@
#include <DataTypes/NestedUtils.h> #include <DataTypes/NestedUtils.h>
#include <DataTypes/DataTypeNullable.h> #include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeLowCardinality.h> #include <DataTypes/DataTypeLowCardinality.h>
#include <DataTypes/DataTypesNumber.h>
#include <IO/WriteHelpers.h> #include <IO/WriteHelpers.h>
#include <Storages/IStorage.h> #include <Storages/IStorage.h>
#include <Common/checkStackSize.h>
#include <AggregateFunctions/AggregateFunctionFactory.h> #include <AggregateFunctions/AggregateFunctionFactory.h>
@ -784,6 +784,67 @@ void collectJoinedColumns(TableJoin & analyzed_join, ASTTableJoin & table_join,
} }
} }
std::pair<bool, UInt64> recursivelyCollectMaxOrdinaryExpressions(const ASTPtr & expr, ASTExpressionList & into)
{
checkStackSize();
if (expr->as<ASTIdentifier>())
{
into.children.push_back(expr);
return {false, 1};
}
auto * function = expr->as<ASTFunction>();
if (!function)
return {false, 0};
if (AggregateUtils::isAggregateFunction(*function))
return {true, 0};
UInt64 pushed_children = 0;
bool has_aggregate = false;
for (const auto & child : function->arguments->children)
{
auto [child_has_aggregate, child_pushed_children] = recursivelyCollectMaxOrdinaryExpressions(child, into);
has_aggregate |= child_has_aggregate;
pushed_children += child_pushed_children;
}
/// The current function is not aggregate function and there is no aggregate function in its arguments,
/// so use the current function to replace its arguments
if (!has_aggregate)
{
for (UInt64 i = 0; i < pushed_children; i++)
into.children.pop_back();
into.children.push_back(expr);
pushed_children = 1;
}
return {has_aggregate, pushed_children};
}
/** Expand GROUP BY ALL by extracting all the SELECT-ed expressions that are not aggregate functions.
*
* For a special case that if there is a function having both aggregate functions and other fields as its arguments,
* the `GROUP BY` keys will contain the maximum non-aggregate fields we can extract from it.
*
* Example:
* SELECT substring(a, 4, 2), substring(substring(a, 1, 2), 1, count(b)) FROM t GROUP BY ALL
* will expand as
* SELECT substring(a, 4, 2), substring(substring(a, 1, 2), 1, count(b)) FROM t GROUP BY substring(a, 4, 2), substring(a, 1, 2)
*/
void expandGroupByAll(ASTSelectQuery * select_query)
{
auto group_expression_list = std::make_shared<ASTExpressionList>();
for (const auto & expr : select_query->select()->children)
recursivelyCollectMaxOrdinaryExpressions(expr, *group_expression_list);
select_query->setExpression(ASTSelectQuery::Expression::GROUP_BY, group_expression_list);
}
std::vector<const ASTFunction *> getAggregates(ASTPtr & query, const ASTSelectQuery & select_query) std::vector<const ASTFunction *> getAggregates(ASTPtr & query, const ASTSelectQuery & select_query)
{ {
@ -1276,6 +1337,10 @@ TreeRewriterResultPtr TreeRewriter::analyzeSelect(
normalize(query, result.aliases, all_source_columns_set, select_options.ignore_alias, settings, /* allow_self_aliases = */ true, getContext()); normalize(query, result.aliases, all_source_columns_set, select_options.ignore_alias, settings, /* allow_self_aliases = */ true, getContext());
// expand GROUP BY ALL
if (select_query->group_by_all)
expandGroupByAll(select_query);
/// Remove unneeded columns according to 'required_result_columns'. /// Remove unneeded columns according to 'required_result_columns'.
/// Leave all selected columns in case of DISTINCT; columns that contain arrayJoin function inside. /// Leave all selected columns in case of DISTINCT; columns that contain arrayJoin function inside.
/// Must be after 'normalizeTree' (after expanding aliases, for aliases not get lost) /// Must be after 'normalizeTree' (after expanding aliases, for aliases not get lost)

View File

@ -93,7 +93,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F
where()->formatImpl(s, state, frame); where()->formatImpl(s, state, frame);
} }
if (groupBy()) if (!group_by_all && groupBy())
{ {
s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "GROUP BY" << (s.hilite ? hilite_none : ""); s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "GROUP BY" << (s.hilite ? hilite_none : "");
if (!group_by_with_grouping_sets) if (!group_by_with_grouping_sets)
@ -104,6 +104,9 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F
} }
} }
if (group_by_all)
s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "GROUP BY ALL" << (s.hilite ? hilite_none : "");
if (group_by_with_rollup) if (group_by_with_rollup)
s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << (s.one_line ? "" : " ") << "WITH ROLLUP" << (s.hilite ? hilite_none : ""); s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << (s.one_line ? "" : " ") << "WITH ROLLUP" << (s.hilite ? hilite_none : "");

View File

@ -82,6 +82,7 @@ public:
ASTPtr clone() const override; ASTPtr clone() const override;
bool distinct = false; bool distinct = false;
bool group_by_all = false;
bool group_by_with_totals = false; bool group_by_with_totals = false;
bool group_by_with_rollup = false; bool group_by_with_rollup = false;
bool group_by_with_cube = false; bool group_by_with_cube = false;

View File

@ -195,6 +195,8 @@ bool ParserSelectQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
select_query->group_by_with_cube = true; select_query->group_by_with_cube = true;
else if (s_grouping_sets.ignore(pos, expected)) else if (s_grouping_sets.ignore(pos, expected))
select_query->group_by_with_grouping_sets = true; select_query->group_by_with_grouping_sets = true;
else if (s_all.ignore(pos, expected))
select_query->group_by_all = true;
if ((select_query->group_by_with_rollup || select_query->group_by_with_cube || select_query->group_by_with_grouping_sets) && if ((select_query->group_by_with_rollup || select_query->group_by_with_cube || select_query->group_by_with_grouping_sets) &&
!open_bracket.ignore(pos, expected)) !open_bracket.ignore(pos, expected))
@ -205,7 +207,7 @@ bool ParserSelectQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
if (!grouping_sets_list.parse(pos, group_expression_list, expected)) if (!grouping_sets_list.parse(pos, group_expression_list, expected))
return false; return false;
} }
else else if (!select_query->group_by_all)
{ {
if (!exp_list.parse(pos, group_expression_list, expected)) if (!exp_list.parse(pos, group_expression_list, expected))
return false; return false;

View File

@ -15,6 +15,12 @@ try
DB::ParserCreateQuery parser; DB::ParserCreateQuery parser;
DB::ASTPtr ast = parseQuery(parser, input.data(), input.data() + input.size(), "", 0, 1000); DB::ASTPtr ast = parseQuery(parser, input.data(), input.data() + input.size(), "", 0, 1000);
const UInt64 max_ast_depth = 1000;
ast->checkDepth(max_ast_depth);
const UInt64 max_ast_elements = 50000;
ast->checkSize(max_ast_elements);
DB::WriteBufferFromOwnString wb; DB::WriteBufferFromOwnString wb;
DB::formatAST(*ast, wb); DB::formatAST(*ast, wb);

View File

@ -183,19 +183,19 @@ public:
} }
private: private:
/// Valid for table, table function, query, union, array join table expression nodes /// Valid for table, table function, array join, query, union nodes
NamesAndTypesList columns; NamesAndTypesList columns;
/// Valid for table, table function, query, union, array join table expression nodes /// Valid for table, table function, array join, query, union nodes
NameSet columns_names; NameSet columns_names;
/// Valid only for table table expression node /// Valid only for table node
NameSet alias_columns_names; NameSet alias_columns_names;
/// Valid for table, table function, query, union table, array join expression nodes /// Valid for table, table function, array join, query, union nodes
ColumnNameToColumnIdentifier column_name_to_column_identifier; ColumnNameToColumnIdentifier column_name_to_column_identifier;
/// Valid for table, table function, query, union table, array join expression nodes /// Valid for table, table function, array join, query, union nodes
ColumnIdentifierToColumnName column_identifier_to_column_name; ColumnIdentifierToColumnName column_identifier_to_column_name;
/// Is storage remote /// Is storage remote

View File

@ -0,0 +1,978 @@
#include <IO/ReadBufferFromString.h>
#include <Formats/FormatFactory.h>
#include <Formats/FormatSettings.h>
#include <Formats/BSONTypes.h>
#include <Formats/EscapingRuleUtils.h>
#include <Processors/Formats/Impl/BSONEachRowRowInputFormat.h>
#include <IO/ReadHelpers.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnLowCardinality.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnDecimal.h>
#include <Columns/ColumnArray.h>
#include <Columns/ColumnTuple.h>
#include <Columns/ColumnMap.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeUUID.h>
#include <DataTypes/DataTypeDateTime64.h>
#include <DataTypes/DataTypeLowCardinality.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypeMap.h>
#include <DataTypes/DataTypeFactory.h>
#include <DataTypes/getLeastSupertype.h>
namespace DB
{
namespace ErrorCodes
{
extern const int INCORRECT_DATA;
extern const int ILLEGAL_COLUMN;
extern const int TOO_LARGE_STRING_SIZE;
extern const int UNKNOWN_TYPE;
}
namespace
{
enum
{
UNKNOWN_FIELD = size_t(-1),
};
}
BSONEachRowRowInputFormat::BSONEachRowRowInputFormat(
ReadBuffer & in_, const Block & header_, Params params_, const FormatSettings & format_settings_)
: IRowInputFormat(header_, in_, std::move(params_))
, format_settings(format_settings_)
, name_map(header_.getNamesToIndexesMap())
, prev_positions(header_.columns())
, types(header_.getDataTypes())
{
}
inline size_t BSONEachRowRowInputFormat::columnIndex(const StringRef & name, size_t key_index)
{
/// Optimization by caching the order of fields (which is almost always the same)
/// and a quick check to match the next expected field, instead of searching the hash table.
if (prev_positions.size() > key_index && prev_positions[key_index] && name == prev_positions[key_index]->getKey())
{
return prev_positions[key_index]->getMapped();
}
else
{
auto * it = name_map.find(name);
if (it)
{
if (key_index < prev_positions.size())
prev_positions[key_index] = it;
return it->getMapped();
}
else
return UNKNOWN_FIELD;
}
}
/// Read the field name. Resulting StringRef is valid only before next read from buf.
static StringRef readBSONKeyName(ReadBuffer & in, String & key_holder)
{
// This is just an optimization: try to avoid copying the name into key_holder
if (!in.eof())
{
char * next_pos = find_first_symbols<0>(in.position(), in.buffer().end());
if (next_pos != in.buffer().end())
{
StringRef res(in.position(), next_pos - in.position());
in.position() = next_pos + 1;
return res;
}
}
key_holder.clear();
readNullTerminated(key_holder, in);
return key_holder;
}
static UInt8 readBSONType(ReadBuffer & in)
{
UInt8 type;
readBinary(type, in);
return type;
}
static size_t readBSONSize(ReadBuffer & in)
{
BSONSizeT size;
readBinary(size, in);
return size;
}
template <typename T>
static void readAndInsertInteger(ReadBuffer & in, IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
/// We allow to read any integer into any integer column.
/// For example we can read BSON Int32 into ClickHouse UInt8.
if (bson_type == BSONType::INT32)
{
UInt32 value;
readBinary(value, in);
assert_cast<ColumnVector<T> &>(column).insertValue(static_cast<T>(value));
}
else if (bson_type == BSONType::INT64)
{
UInt64 value;
readBinary(value, in);
assert_cast<ColumnVector<T> &>(column).insertValue(static_cast<T>(value));
}
else if (bson_type == BSONType::BOOL)
{
UInt8 value;
readBinary(value, in);
assert_cast<ColumnVector<T> &>(column).insertValue(static_cast<T>(value));
}
else
{
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into column with type {}", getBSONTypeName(bson_type), data_type->getName());
}
}
template <typename T>
static void readAndInsertDouble(ReadBuffer & in, IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type != BSONType::DOUBLE)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into column with type {}", getBSONTypeName(bson_type), data_type->getName());
Float64 value;
readBinary(value, in);
assert_cast<ColumnVector<T> &>(column).insertValue(static_cast<T>(value));
}
template <typename DecimalType, BSONType expected_bson_type>
static void readAndInsertSmallDecimal(ReadBuffer & in, IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type != expected_bson_type)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into column with type {}", getBSONTypeName(bson_type), data_type->getName());
DecimalType value;
readBinary(value, in);
assert_cast<ColumnDecimal<DecimalType> &>(column).insertValue(value);
}
static void readAndInsertDateTime64(ReadBuffer & in, IColumn & column, BSONType bson_type)
{
if (bson_type != BSONType::INT64 && bson_type != BSONType::DATETIME)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into DateTime64 column", getBSONTypeName(bson_type));
DateTime64 value;
readBinary(value, in);
assert_cast<DataTypeDateTime64::ColumnType &>(column).insertValue(value);
}
template <typename ColumnType>
static void readAndInsertBigInteger(ReadBuffer & in, IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type != BSONType::BINARY)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into column with type {}", getBSONTypeName(bson_type), data_type->getName());
auto size = readBSONSize(in);
auto subtype = getBSONBinarySubtype(readBSONType(in));
if (subtype != BSONBinarySubtype::BINARY)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON Binary subtype {} into column with type {}", getBSONBinarySubtypeName(subtype), data_type->getName());
using ValueType = typename ColumnType::ValueType;
if (size != sizeof(ValueType))
throw Exception(
ErrorCodes::INCORRECT_DATA,
"Cannot parse value of type {}, size of binary data is not equal to the binary size of expected value: {} != {}",
data_type->getName(),
size,
sizeof(ValueType));
ValueType value;
readBinary(value, in);
assert_cast<ColumnType &>(column).insertValue(value);
}
template <bool is_fixed_string>
static void readAndInsertStringImpl(ReadBuffer & in, IColumn & column, size_t size)
{
if constexpr (is_fixed_string)
{
auto & fixed_string_column = assert_cast<ColumnFixedString &>(column);
size_t n = fixed_string_column.getN();
if (size > n)
throw Exception("Too large string for FixedString column", ErrorCodes::TOO_LARGE_STRING_SIZE);
auto & data = fixed_string_column.getChars();
size_t old_size = data.size();
data.resize_fill(old_size + n);
try
{
in.readStrict(reinterpret_cast<char *>(data.data() + old_size), size);
}
catch (...)
{
/// Restore column state in case of any exception.
data.resize_assume_reserved(old_size);
throw;
}
}
else
{
auto & column_string = assert_cast<ColumnString &>(column);
auto & data = column_string.getChars();
auto & offsets = column_string.getOffsets();
size_t old_chars_size = data.size();
size_t offset = old_chars_size + size + 1;
offsets.push_back(offset);
try
{
data.resize(offset);
in.readStrict(reinterpret_cast<char *>(&data[offset - size - 1]), size);
data.back() = 0;
}
catch (...)
{
/// Restore column state in case of any exception.
offsets.pop_back();
data.resize_assume_reserved(old_chars_size);
throw;
}
}
}
template <bool is_fixed_string>
static void readAndInsertString(ReadBuffer & in, IColumn & column, BSONType bson_type)
{
if (bson_type == BSONType::STRING || bson_type == BSONType::SYMBOL || bson_type == BSONType::JAVA_SCRIPT_CODE)
{
auto size = readBSONSize(in);
readAndInsertStringImpl<is_fixed_string>(in, column, size - 1);
assertChar(0, in);
}
else if (bson_type == BSONType::BINARY)
{
auto size = readBSONSize(in);
auto subtype = getBSONBinarySubtype(readBSONType(in));
if (subtype == BSONBinarySubtype::BINARY || subtype == BSONBinarySubtype::BINARY_OLD)
readAndInsertStringImpl<is_fixed_string>(in, column, size);
else
throw Exception(
ErrorCodes::ILLEGAL_COLUMN,
"Cannot insert BSON Binary subtype {} into String column",
getBSONBinarySubtypeName(subtype));
}
else if (bson_type == BSONType::OBJECT_ID)
{
readAndInsertStringImpl<is_fixed_string>(in, column, 12);
}
else
{
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into String column", getBSONTypeName(bson_type));
}
}
static void readAndInsertUUID(ReadBuffer & in, IColumn & column, BSONType bson_type)
{
if (bson_type == BSONType::BINARY)
{
auto size = readBSONSize(in);
auto subtype = getBSONBinarySubtype(readBSONType(in));
if (subtype == BSONBinarySubtype::UUID || subtype == BSONBinarySubtype::UUID_OLD)
{
if (size != sizeof(UUID))
throw Exception(
ErrorCodes::INCORRECT_DATA,
"Cannot parse value of type UUID, size of binary data is not equal to the binary size of UUID value: {} != {}",
size,
sizeof(UUID));
UUID value;
readBinary(value, in);
assert_cast<ColumnUUID &>(column).insertValue(value);
}
else
{
throw Exception(
ErrorCodes::ILLEGAL_COLUMN,
"Cannot insert BSON Binary subtype {} into UUID column",
getBSONBinarySubtypeName(subtype));
}
}
else
{
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into UUID column", getBSONTypeName(bson_type));
}
}
void BSONEachRowRowInputFormat::readArray(IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type != BSONType::ARRAY)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into Array column", getBSONTypeName(bson_type));
const auto * data_type_array = assert_cast<const DataTypeArray *>(data_type.get());
const auto & nested_type = data_type_array->getNestedType();
auto & array_column = assert_cast<ColumnArray &>(column);
auto & nested_column = array_column.getData();
size_t document_start = in->count();
BSONSizeT document_size;
readBinary(document_size, *in);
while (in->count() - document_start + sizeof(BSON_DOCUMENT_END) != document_size)
{
auto nested_bson_type = getBSONType(readBSONType(*in));
readBSONKeyName(*in, current_key_name);
readField(nested_column, nested_type, nested_bson_type);
}
assertChar(BSON_DOCUMENT_END, *in);
array_column.getOffsets().push_back(array_column.getData().size());
}
void BSONEachRowRowInputFormat::readTuple(IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type != BSONType::ARRAY && bson_type != BSONType::DOCUMENT)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into Tuple column", getBSONTypeName(bson_type));
/// When BSON type is ARRAY, names in nested document are not useful
/// (most likely they are just sequential numbers).
bool use_key_names = bson_type == BSONType::DOCUMENT;
const auto * data_type_tuple = assert_cast<const DataTypeTuple *>(data_type.get());
auto & tuple_column = assert_cast<ColumnTuple &>(column);
size_t read_nested_columns = 0;
size_t document_start = in->count();
BSONSizeT document_size;
readBinary(document_size, *in);
while (in->count() - document_start + sizeof(BSON_DOCUMENT_END) != document_size)
{
auto nested_bson_type = getBSONType(readBSONType(*in));
auto name = readBSONKeyName(*in, current_key_name);
size_t index = read_nested_columns;
if (use_key_names)
{
auto try_get_index = data_type_tuple->tryGetPositionByName(name.toString());
if (!try_get_index)
throw Exception(
ErrorCodes::INCORRECT_DATA,
"Cannot parse tuple column with type {} from BSON array/embedded document field: tuple doesn't have element with name \"{}\"",
data_type->getName(),
name);
index = *try_get_index;
}
if (index >= data_type_tuple->getElements().size())
throw Exception(
ErrorCodes::INCORRECT_DATA,
"Cannot parse tuple column with type {} from BSON array/embedded document field: the number of fields BSON document exceeds the number of fields in tuple",
data_type->getName());
readField(tuple_column.getColumn(index), data_type_tuple->getElement(index), nested_bson_type);
++read_nested_columns;
}
assertChar(BSON_DOCUMENT_END, *in);
if (read_nested_columns != data_type_tuple->getElements().size())
throw Exception(
ErrorCodes::INCORRECT_DATA,
"Cannot parse tuple column with type {} from BSON array/embedded document field, the number of fields in tuple and BSON document doesn't match: {} != {}",
data_type->getName(),
data_type_tuple->getElements().size(),
read_nested_columns);
}
void BSONEachRowRowInputFormat::readMap(IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type != BSONType::DOCUMENT)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON {} into Map column", getBSONTypeName(bson_type));
const auto * data_type_map = assert_cast<const DataTypeMap *>(data_type.get());
const auto & key_data_type = data_type_map->getKeyType();
if (!isStringOrFixedString(key_data_type))
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Only maps with String key type are supported in BSON, got key type: {}", key_data_type->getName());
const auto & value_data_type = data_type_map->getValueType();
auto & column_map = assert_cast<ColumnMap &>(column);
auto & key_column = column_map.getNestedData().getColumn(0);
auto & value_column = column_map.getNestedData().getColumn(1);
auto & offsets = column_map.getNestedColumn().getOffsets();
size_t document_start = in->count();
BSONSizeT document_size;
readBinary(document_size, *in);
while (in->count() - document_start + sizeof(BSON_DOCUMENT_END) != document_size)
{
auto nested_bson_type = getBSONType(readBSONType(*in));
auto name = readBSONKeyName(*in, current_key_name);
key_column.insertData(name.data, name.size);
readField(value_column, value_data_type, nested_bson_type);
}
assertChar(BSON_DOCUMENT_END, *in);
offsets.push_back(key_column.size());
}
bool BSONEachRowRowInputFormat::readField(IColumn & column, const DataTypePtr & data_type, BSONType bson_type)
{
if (bson_type == BSONType::NULL_VALUE)
{
if (data_type->isNullable())
{
column.insertDefault();
return true;
}
if (!format_settings.null_as_default)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert BSON Null value into non-nullable column with type {}", getBSONTypeName(bson_type), data_type->getName());
column.insertDefault();
return false;
}
switch (data_type->getTypeId())
{
case TypeIndex::Nullable:
{
auto & nullable_column = assert_cast<ColumnNullable &>(column);
auto & nested_column = nullable_column.getNestedColumn();
const auto & nested_type = assert_cast<const DataTypeNullable *>(data_type.get())->getNestedType();
nullable_column.getNullMapColumn().insertValue(0);
return readField(nested_column, nested_type, bson_type);
}
case TypeIndex::LowCardinality:
{
auto & lc_column = assert_cast<ColumnLowCardinality &>(column);
auto tmp_column = lc_column.getDictionary().getNestedColumn()->cloneEmpty();
const auto & dict_type = assert_cast<const DataTypeLowCardinality *>(data_type.get())->getDictionaryType();
auto res = readField(*tmp_column, dict_type, bson_type);
lc_column.insertFromFullColumn(*tmp_column, 0);
return res;
}
case TypeIndex::Int8:
{
readAndInsertInteger<Int8>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::UInt8:
{
readAndInsertInteger<UInt8>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Int16:
{
readAndInsertInteger<Int16>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Date: [[fallthrough]];
case TypeIndex::UInt16:
{
readAndInsertInteger<UInt16>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Date32: [[fallthrough]];
case TypeIndex::Int32:
{
readAndInsertInteger<Int32>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::DateTime: [[fallthrough]];
case TypeIndex::UInt32:
{
readAndInsertInteger<UInt32>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Int64:
{
readAndInsertInteger<Int64>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::UInt64:
{
readAndInsertInteger<UInt64>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Int128:
{
readAndInsertBigInteger<ColumnInt128>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::UInt128:
{
readAndInsertBigInteger<ColumnUInt128>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Int256:
{
readAndInsertBigInteger<ColumnInt256>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::UInt256:
{
readAndInsertBigInteger<ColumnUInt256>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Float32:
{
readAndInsertDouble<Float32>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Float64:
{
readAndInsertDouble<Float64>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Decimal32:
{
readAndInsertSmallDecimal<Decimal32, BSONType::INT32>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Decimal64:
{
readAndInsertSmallDecimal<Decimal64, BSONType::INT64>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Decimal128:
{
readAndInsertBigInteger<ColumnDecimal<Decimal128>>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::Decimal256:
{
readAndInsertBigInteger<ColumnDecimal<Decimal256>>(*in, column, data_type, bson_type);
return true;
}
case TypeIndex::DateTime64:
{
readAndInsertDateTime64(*in, column, bson_type);
return true;
}
case TypeIndex::FixedString:
{
readAndInsertString<true>(*in, column, bson_type);
return true;
}
case TypeIndex::String:
{
readAndInsertString<false>(*in, column, bson_type);
return true;
}
case TypeIndex::UUID:
{
readAndInsertUUID(*in, column, bson_type);
return true;
}
case TypeIndex::Array:
{
readArray(column, data_type, bson_type);
return true;
}
case TypeIndex::Tuple:
{
readTuple(column, data_type, bson_type);
return true;
}
case TypeIndex::Map:
{
readMap(column, data_type, bson_type);
return true;
}
default:
{
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for output in BSON format", data_type->getName());
}
}
}
static void skipBSONField(ReadBuffer & in, BSONType type)
{
switch (type)
{
case BSONType::DOUBLE:
{
in.ignore(sizeof(Float64));
break;
}
case BSONType::BOOL:
{
in.ignore(sizeof(UInt8));
break;
}
case BSONType::INT64: [[fallthrough]];
case BSONType::DATETIME: [[fallthrough]];
case BSONType::TIMESTAMP:
{
in.ignore(sizeof(UInt64));
break;
}
case BSONType::INT32:
{
in.ignore(sizeof(Int32));
break;
}
case BSONType::JAVA_SCRIPT_CODE: [[fallthrough]];
case BSONType::SYMBOL: [[fallthrough]];
case BSONType::STRING:
{
BSONSizeT size;
readBinary(size, in);
in.ignore(size);
break;
}
case BSONType::DOCUMENT: [[fallthrough]];
case BSONType::ARRAY:
{
BSONSizeT size;
readBinary(size, in);
in.ignore(size - sizeof(size));
break;
}
case BSONType::BINARY:
{
BSONSizeT size;
readBinary(size, in);
in.ignore(size + 1);
break;
}
case BSONType::MIN_KEY: [[fallthrough]];
case BSONType::MAX_KEY: [[fallthrough]];
case BSONType::UNDEFINED: [[fallthrough]];
case BSONType::NULL_VALUE:
{
break;
}
case BSONType::OBJECT_ID:
{
in.ignore(12);
break;
}
case BSONType::REGEXP:
{
skipNullTerminated(in);
skipNullTerminated(in);
break;
}
case BSONType::DB_POINTER:
{
BSONSizeT size;
readBinary(size, in);
in.ignore(size + 12);
break;
}
case BSONType::JAVA_SCRIPT_CODE_W_SCOPE:
{
BSONSizeT size;
readBinary(size, in);
in.ignore(size - sizeof(size));
break;
}
case BSONType::DECIMAL128:
{
in.ignore(16);
break;
}
}
}
void BSONEachRowRowInputFormat::skipUnknownField(BSONType type, const String & key_name)
{
if (!format_settings.skip_unknown_fields)
throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown field found while parsing BSONEachRow format: {}", key_name);
skipBSONField(*in, type);
}
void BSONEachRowRowInputFormat::syncAfterError()
{
/// Skip all remaining bytes in current document
size_t already_read_bytes = in->count() - current_document_start;
in->ignore(current_document_size - already_read_bytes);
}
bool BSONEachRowRowInputFormat::readRow(MutableColumns & columns, RowReadExtension & ext)
{
size_t num_columns = columns.size();
read_columns.assign(num_columns, false);
seen_columns.assign(num_columns, false);
if (in->eof())
return false;
size_t key_index = 0;
current_document_start = in->count();
readBinary(current_document_size, *in);
while (in->count() - current_document_start + sizeof(BSON_DOCUMENT_END) != current_document_size)
{
auto type = getBSONType(readBSONType(*in));
auto name = readBSONKeyName(*in, current_key_name);
auto index = columnIndex(name, key_index);
if (index == UNKNOWN_FIELD)
{
current_key_name.assign(name.data, name.size);
skipUnknownField(BSONType(type), current_key_name);
}
else
{
seen_columns[index] = true;
read_columns[index] = readField(*columns[index], types[index], BSONType(type));
}
++key_index;
}
assertChar(BSON_DOCUMENT_END, *in);
const auto & header = getPort().getHeader();
/// Fill non-visited columns with the default values.
for (size_t i = 0; i < num_columns; ++i)
if (!seen_columns[i])
header.getByPosition(i).type->insertDefaultInto(*columns[i]);
if (format_settings.defaults_for_omitted_fields)
ext.read_columns = read_columns;
else
ext.read_columns.assign(read_columns.size(), true);
return true;
}
BSONEachRowSchemaReader::BSONEachRowSchemaReader(ReadBuffer & in_, const FormatSettings & settings_)
: IRowWithNamesSchemaReader(in_, settings_)
{
}
DataTypePtr BSONEachRowSchemaReader::getDataTypeFromBSONField(BSONType type, bool allow_to_skip_unsupported_types, bool & skip)
{
switch (type)
{
case BSONType::DOUBLE:
{
in.ignore(sizeof(Float64));
return makeNullable(std::make_shared<DataTypeFloat64>());
}
case BSONType::BOOL:
{
in.ignore(sizeof(UInt8));
return makeNullable(DataTypeFactory::instance().get("Bool"));
}
case BSONType::INT64:
{
in.ignore(sizeof(Int64));
return makeNullable(std::make_shared<DataTypeInt64>());
}
case BSONType::DATETIME:
{
in.ignore(sizeof(Int64));
return makeNullable(std::make_shared<DataTypeDateTime64>(6, "UTC"));
}
case BSONType::INT32:
{
in.ignore(sizeof(Int32));
return makeNullable(std::make_shared<DataTypeInt32>());
}
case BSONType::SYMBOL: [[fallthrough]];
case BSONType::JAVA_SCRIPT_CODE: [[fallthrough]];
case BSONType::OBJECT_ID: [[fallthrough]];
case BSONType::STRING:
{
BSONSizeT size;
readBinary(size, in);
in.ignore(size);
return makeNullable(std::make_shared<DataTypeString>());
}
case BSONType::DOCUMENT:
{
auto nested_names_and_types = getDataTypesFromBSONDocument(false);
auto nested_types = nested_names_and_types.getTypes();
bool types_are_equal = true;
if (nested_types.empty() || !nested_types[0])
return nullptr;
for (size_t i = 1; i != nested_types.size(); ++i)
{
if (!nested_types[i])
return nullptr;
types_are_equal &= nested_types[i]->equals(*nested_types[0]);
}
if (types_are_equal)
return std::make_shared<DataTypeMap>(std::make_shared<DataTypeString>(), nested_types[0]);
return std::make_shared<DataTypeTuple>(std::move(nested_types), nested_names_and_types.getNames());
}
case BSONType::ARRAY:
{
auto nested_types = getDataTypesFromBSONDocument(false).getTypes();
bool types_are_equal = true;
if (nested_types.empty() || !nested_types[0])
return nullptr;
for (size_t i = 1; i != nested_types.size(); ++i)
{
if (!nested_types[i])
return nullptr;
types_are_equal &= nested_types[i]->equals(*nested_types[0]);
}
if (types_are_equal)
return std::make_shared<DataTypeArray>(nested_types[0]);
return std::make_shared<DataTypeTuple>(std::move(nested_types));
}
case BSONType::BINARY:
{
BSONSizeT size;
readBinary(size, in);
auto subtype = getBSONBinarySubtype(readBSONType(in));
in.ignore(size);
switch (subtype)
{
case BSONBinarySubtype::BINARY_OLD: [[fallthrough]];
case BSONBinarySubtype::BINARY:
return makeNullable(std::make_shared<DataTypeString>());
case BSONBinarySubtype::UUID_OLD: [[fallthrough]];
case BSONBinarySubtype::UUID:
return makeNullable(std::make_shared<DataTypeUUID>());
default:
throw Exception(ErrorCodes::UNKNOWN_TYPE, "BSON binary subtype {} is not supported", getBSONBinarySubtypeName(subtype));
}
}
case BSONType::NULL_VALUE:
{
return nullptr;
}
default:
{
if (!allow_to_skip_unsupported_types)
throw Exception(ErrorCodes::UNKNOWN_TYPE, "BSON type {} is not supported", getBSONTypeName(type));
skip = true;
skipBSONField(in, type);
return nullptr;
}
}
}
NamesAndTypesList BSONEachRowSchemaReader::getDataTypesFromBSONDocument(bool allow_to_skip_unsupported_types)
{
size_t document_start = in.count();
BSONSizeT document_size;
readBinary(document_size, in);
NamesAndTypesList names_and_types;
while (in.count() - document_start + sizeof(BSON_DOCUMENT_END) != document_size)
{
auto bson_type = getBSONType(readBSONType(in));
String name;
readNullTerminated(name, in);
bool skip = false;
auto type = getDataTypeFromBSONField(bson_type, allow_to_skip_unsupported_types, skip);
if (!skip)
names_and_types.emplace_back(name, type);
}
assertChar(BSON_DOCUMENT_END, in);
return names_and_types;
}
NamesAndTypesList BSONEachRowSchemaReader::readRowAndGetNamesAndDataTypes(bool & eof)
{
if (in.eof())
{
eof = true;
return {};
}
return getDataTypesFromBSONDocument(format_settings.bson.skip_fields_with_unsupported_types_in_schema_inference);
}
void BSONEachRowSchemaReader::transformTypesIfNeeded(DataTypePtr & type, DataTypePtr & new_type)
{
DataTypes types = {type, new_type};
/// For example for integer conversion Int32,
auto least_supertype = tryGetLeastSupertype(types);
if (least_supertype)
type = new_type = least_supertype;
}
static std::pair<bool, size_t>
fileSegmentationEngineBSONEachRow(ReadBuffer & in, DB::Memory<> & memory, size_t min_bytes, size_t max_rows)
{
size_t number_of_rows = 0;
while (!in.eof() && memory.size() < min_bytes && number_of_rows < max_rows)
{
BSONSizeT document_size;
readBinary(document_size, in);
if (min_bytes != 0 && document_size > 10 * min_bytes)
throw ParsingException(
ErrorCodes::INCORRECT_DATA,
"Size of BSON document is extremely large. Expected not greater than {} bytes, but current is {} bytes per row. Increase "
"the value setting 'min_chunk_bytes_for_parallel_parsing' or check your data manually, most likely BSON is malformed",
min_bytes, document_size);
size_t old_size = memory.size();
memory.resize(old_size + document_size);
memcpy(memory.data() + old_size, reinterpret_cast<char *>(&document_size), sizeof(document_size));
in.readStrict(memory.data() + old_size + sizeof(document_size), document_size - sizeof(document_size));
++number_of_rows;
}
return {!in.eof(), number_of_rows};
}
void registerInputFormatBSONEachRow(FormatFactory & factory)
{
factory.registerInputFormat(
"BSONEachRow",
[](ReadBuffer & buf, const Block & sample, IRowInputFormat::Params params, const FormatSettings & settings)
{ return std::make_shared<BSONEachRowRowInputFormat>(buf, sample, std::move(params), settings); });
}
void registerFileSegmentationEngineBSONEachRow(FormatFactory & factory)
{
factory.registerFileSegmentationEngine("BSONEachRow", &fileSegmentationEngineBSONEachRow);
}
void registerBSONEachRowSchemaReader(FormatFactory & factory)
{
factory.registerSchemaReader("BSONEachRow", [](ReadBuffer & buf, const FormatSettings & settings)
{
return std::make_unique<BSONEachRowSchemaReader>(buf, settings);
});
factory.registerAdditionalInfoForSchemaCacheGetter("BSONEachRow", [](const FormatSettings & settings)
{
String result = getAdditionalFormatInfoForAllRowBasedFormats(settings);
return result + fmt::format(", skip_fields_with_unsupported_types_in_schema_inference={}",
settings.bson.skip_fields_with_unsupported_types_in_schema_inference);
});
}
}

Some files were not shown because too many files have changed in this diff Show More