Support MergeTree Engine

This commit is contained in:
hexiaoting 2020-10-23 16:36:17 +08:00
commit 483be134b2
622 changed files with 33179 additions and 4367 deletions

View File

@ -57,8 +57,8 @@ if (SANITIZE)
endif () endif ()
elseif (SANITIZE STREQUAL "undefined") elseif (SANITIZE STREQUAL "undefined")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SAN_FLAGS} -fsanitize=undefined -fno-sanitize-recover=all -fno-sanitize=float-divide-by-zero") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SAN_FLAGS} -fsanitize=undefined -fno-sanitize-recover=all -fno-sanitize=float-divide-by-zero -fsanitize-blacklist=${CMAKE_SOURCE_DIR}/tests/ubsan_suppressions.txt")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SAN_FLAGS} -fsanitize=undefined -fno-sanitize-recover=all -fno-sanitize=float-divide-by-zero") set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SAN_FLAGS} -fsanitize=undefined -fno-sanitize-recover=all -fno-sanitize=float-divide-by-zero -fsanitize-blacklist=${CMAKE_SOURCE_DIR}/tests/ubsan_suppressions.txt")
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=undefined") set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=undefined")
endif() endif()

View File

@ -15,6 +15,10 @@ if (COMPILER_GCC)
elseif (COMPILER_CLANG) elseif (COMPILER_CLANG)
# Require minimum version of clang/apple-clang # Require minimum version of clang/apple-clang
if (CMAKE_CXX_COMPILER_ID MATCHES "AppleClang") if (CMAKE_CXX_COMPILER_ID MATCHES "AppleClang")
# If you are developer you can figure out what exact versions of AppleClang are Ok,
# remove the following line and commit changes below.
message (FATAL_ERROR "AppleClang is not supported, you should install clang from brew.")
# AppleClang 10.0.1 (Xcode 10.2) corresponds to LLVM/Clang upstream version 7.0.0 # AppleClang 10.0.1 (Xcode 10.2) corresponds to LLVM/Clang upstream version 7.0.0
# AppleClang 11.0.0 (Xcode 11.0) corresponds to LLVM/Clang upstream version 8.0.0 # AppleClang 11.0.0 (Xcode 11.0) corresponds to LLVM/Clang upstream version 8.0.0
set (XCODE_MINIMUM_VERSION 10.2) set (XCODE_MINIMUM_VERSION 10.2)

View File

@ -153,82 +153,19 @@ initdb()
start() start()
{ {
[ -x $CLICKHOUSE_BINDIR/$PROGRAM ] || exit 0 ${CLICKHOUSE_GENERIC_PROGRAM} start --user "${CLICKHOUSE_USER}" --pid-path "${CLICKHOUSE_PIDDIR}" --config-path "${CLICKHOUSE_CONFDIR}" --binary-path "${CLICKHOUSE_BINDIR}"
local EXIT_STATUS
EXIT_STATUS=0
echo -n "Start $PROGRAM service: "
if is_running; then
echo -n "already running "
EXIT_STATUS=1
else
ulimit -n 262144
mkdir -p $CLICKHOUSE_PIDDIR
chown -R $CLICKHOUSE_USER:$CLICKHOUSE_GROUP $CLICKHOUSE_PIDDIR
initdb
if ! is_running; then
# Lock should not be held while running child process, so we release the lock. Note: obviously, there is race condition.
# But clickhouse-server has protection from simultaneous runs with same data directory.
su -s $SHELL ${CLICKHOUSE_USER} -c "$FLOCK -u 9; $CLICKHOUSE_PROGRAM_ENV exec -a \"$PROGRAM\" \"$CLICKHOUSE_BINDIR/$PROGRAM\" --daemon --pid-file=\"$CLICKHOUSE_PIDFILE\" --config-file=\"$CLICKHOUSE_CONFIG\""
EXIT_STATUS=$?
if [ $EXIT_STATUS -ne 0 ]; then
return $EXIT_STATUS
fi
fi
fi
if [ $EXIT_STATUS -eq 0 ]; then
attempts=0
while ! is_running && [ $attempts -le ${CLICKHOUSE_START_TIMEOUT:=10} ]; do
attempts=$(($attempts + 1))
sleep 1
done
if is_running; then
echo "DONE"
else
echo "UNKNOWN"
fi
else
echo "FAILED"
fi
return $EXIT_STATUS
} }
stop() stop()
{ {
#local EXIT_STATUS ${CLICKHOUSE_GENERIC_PROGRAM} stop --pid-path "${CLICKHOUSE_PIDDIR}"
EXIT_STATUS=0
if [ -f $CLICKHOUSE_PIDFILE ]; then
echo -n "Stop $PROGRAM service: "
kill -TERM $(cat "$CLICKHOUSE_PIDFILE")
if ! wait_for_done ${CLICKHOUSE_STOP_TIMEOUT}; then
EXIT_STATUS=2
echo "TIMEOUT"
else
echo "DONE"
fi
fi
return $EXIT_STATUS
} }
restart() restart()
{ {
check_config ${CLICKHOUSE_GENERIC_PROGRAM} restart --user "${CLICKHOUSE_USER}" --pid-path "${CLICKHOUSE_PIDDIR}" --config-path "${CLICKHOUSE_CONFDIR}" --binary-path "${CLICKHOUSE_BINDIR}"
if stop; then
if start; then
return 0
fi
fi
return 1
} }

View File

@ -2,6 +2,7 @@
set -e set -e
# set -x # set -x
PROGRAM=clickhouse-server
CLICKHOUSE_USER=${CLICKHOUSE_USER:=clickhouse} CLICKHOUSE_USER=${CLICKHOUSE_USER:=clickhouse}
CLICKHOUSE_GROUP=${CLICKHOUSE_GROUP:=${CLICKHOUSE_USER}} CLICKHOUSE_GROUP=${CLICKHOUSE_GROUP:=${CLICKHOUSE_USER}}
# Please note that we don't support paths with whitespaces. This is rather ignorant. # Please note that we don't support paths with whitespaces. This is rather ignorant.
@ -12,6 +13,7 @@ CLICKHOUSE_BINDIR=${CLICKHOUSE_BINDIR:=/usr/bin}
CLICKHOUSE_GENERIC_PROGRAM=${CLICKHOUSE_GENERIC_PROGRAM:=clickhouse} CLICKHOUSE_GENERIC_PROGRAM=${CLICKHOUSE_GENERIC_PROGRAM:=clickhouse}
EXTRACT_FROM_CONFIG=${CLICKHOUSE_GENERIC_PROGRAM}-extract-from-config EXTRACT_FROM_CONFIG=${CLICKHOUSE_GENERIC_PROGRAM}-extract-from-config
CLICKHOUSE_CONFIG=$CLICKHOUSE_CONFDIR/config.xml CLICKHOUSE_CONFIG=$CLICKHOUSE_CONFDIR/config.xml
CLICKHOUSE_PIDDIR=/var/run/$PROGRAM
[ -f /usr/share/debconf/confmodule ] && . /usr/share/debconf/confmodule [ -f /usr/share/debconf/confmodule ] && . /usr/share/debconf/confmodule
[ -f /etc/default/clickhouse ] && . /etc/default/clickhouse [ -f /etc/default/clickhouse ] && . /etc/default/clickhouse
@ -41,105 +43,5 @@ if [ "$1" = configure ] || [ -n "$not_deb_os" ]; then
fi fi
fi fi
# Make sure the administrative user exists ${CLICKHOUSE_GENERIC_PROGRAM} install --user "${CLICKHOUSE_USER}" --group "${CLICKHOUSE_GROUP}" --pid-path "${CLICKHOUSE_PIDDIR}" --config-path "${CLICKHOUSE_CONFDIR}" --binary-path "${CLICKHOUSE_BINDIR}" --log-path "${CLICKHOUSE_LOGDIR}" --data-path "${CLICKHOUSE_DATADIR}"
if ! getent passwd ${CLICKHOUSE_USER} > /dev/null; then
if [ -n "$not_deb_os" ]; then
useradd -r -s /bin/false --home-dir /nonexistent ${CLICKHOUSE_USER} > /dev/null
else
adduser --system --disabled-login --no-create-home --home /nonexistent \
--shell /bin/false --group --gecos "ClickHouse server" ${CLICKHOUSE_USER} > /dev/null
fi
fi
# if the user was created manually, make sure the group is there as well
if ! getent group ${CLICKHOUSE_GROUP} > /dev/null; then
groupadd -r ${CLICKHOUSE_GROUP} > /dev/null
fi
# make sure user is in the correct group
if ! id -Gn ${CLICKHOUSE_USER} | grep -qw ${CLICKHOUSE_USER}; then
usermod -a -G ${CLICKHOUSE_GROUP} ${CLICKHOUSE_USER} > /dev/null
fi
# check validity of user and group
if [ "$(id -u ${CLICKHOUSE_USER})" -eq 0 ]; then
echo "The ${CLICKHOUSE_USER} system user must not have uid 0 (root).
Please fix this and reinstall this package." >&2
exit 1
fi
if [ "$(id -g ${CLICKHOUSE_GROUP})" -eq 0 ]; then
echo "The ${CLICKHOUSE_USER} system user must not have root as primary group.
Please fix this and reinstall this package." >&2
exit 1
fi
if [ -x "$CLICKHOUSE_BINDIR/$EXTRACT_FROM_CONFIG" ] && [ -f "$CLICKHOUSE_CONFIG" ]; then
if [ -z "$SHELL" ]; then
SHELL="/bin/sh"
fi
CLICKHOUSE_DATADIR_FROM_CONFIG=$(su -s $SHELL ${CLICKHOUSE_USER} -c "$CLICKHOUSE_BINDIR/$EXTRACT_FROM_CONFIG --config-file=\"$CLICKHOUSE_CONFIG\" --key=path") ||:
echo "Path to data directory in ${CLICKHOUSE_CONFIG}: ${CLICKHOUSE_DATADIR_FROM_CONFIG}"
fi
CLICKHOUSE_DATADIR_FROM_CONFIG=${CLICKHOUSE_DATADIR_FROM_CONFIG:=$CLICKHOUSE_DATADIR}
if [ ! -d ${CLICKHOUSE_DATADIR_FROM_CONFIG} ]; then
mkdir -p ${CLICKHOUSE_DATADIR_FROM_CONFIG}
chown ${CLICKHOUSE_USER}:${CLICKHOUSE_GROUP} ${CLICKHOUSE_DATADIR_FROM_CONFIG}
chmod 700 ${CLICKHOUSE_DATADIR_FROM_CONFIG}
fi
if [ -d ${CLICKHOUSE_CONFDIR} ]; then
mkdir -p ${CLICKHOUSE_CONFDIR}/users.d
mkdir -p ${CLICKHOUSE_CONFDIR}/config.d
rm -fv ${CLICKHOUSE_CONFDIR}/*-preprocessed.xml ||:
fi
[ -e ${CLICKHOUSE_CONFDIR}/preprocessed ] || ln -s ${CLICKHOUSE_DATADIR_FROM_CONFIG}/preprocessed_configs ${CLICKHOUSE_CONFDIR}/preprocessed ||:
if [ ! -d ${CLICKHOUSE_LOGDIR} ]; then
mkdir -p ${CLICKHOUSE_LOGDIR}
chown root:${CLICKHOUSE_GROUP} ${CLICKHOUSE_LOGDIR}
# Allow everyone to read logs, root and clickhouse to read-write
chmod 775 ${CLICKHOUSE_LOGDIR}
fi
# Set net_admin capabilities to support introspection of "taskstats" performance metrics from the kernel
# and ipc_lock capabilities to allow mlock of clickhouse binary.
# 1. Check that "setcap" tool exists.
# 2. Check that an arbitrary program with installed capabilities can run.
# 3. Set the capabilities.
# The second is important for Docker and systemd-nspawn.
# When the container has no capabilities,
# but the executable file inside the container has capabilities,
# then attempt to run this file will end up with a cryptic "Operation not permitted" message.
TMPFILE=/tmp/test_setcap.sh
command -v setcap >/dev/null \
&& echo > $TMPFILE && chmod a+x $TMPFILE && $TMPFILE && setcap "cap_net_admin,cap_ipc_lock,cap_sys_nice+ep" $TMPFILE && $TMPFILE && rm $TMPFILE \
&& setcap "cap_net_admin,cap_ipc_lock,cap_sys_nice+ep" "${CLICKHOUSE_BINDIR}/${CLICKHOUSE_GENERIC_PROGRAM}" \
|| echo "Cannot set 'net_admin' or 'ipc_lock' or 'sys_nice' capability for clickhouse binary. This is optional. Taskstats accounting will be disabled. To enable taskstats accounting you may add the required capability later manually."
# Clean old dynamic compilation results
if [ -d "${CLICKHOUSE_DATADIR_FROM_CONFIG}/build" ]; then
rm -f ${CLICKHOUSE_DATADIR_FROM_CONFIG}/build/*.cpp ${CLICKHOUSE_DATADIR_FROM_CONFIG}/build/*.so ||:
fi
if [ -f /usr/share/debconf/confmodule ]; then
db_get clickhouse-server/default-password
defaultpassword="$RET"
if [ -n "$defaultpassword" ]; then
echo "<yandex><users><default><password>$defaultpassword</password></default></users></yandex>" > ${CLICKHOUSE_CONFDIR}/users.d/default-password.xml
chown ${CLICKHOUSE_USER}:${CLICKHOUSE_GROUP} ${CLICKHOUSE_CONFDIR}/users.d/default-password.xml
chmod 600 ${CLICKHOUSE_CONFDIR}/users.d/default-password.xml
fi
# everything went well, so now let's reset the password
db_set clickhouse-server/default-password ""
# ... done with debconf here
db_stop
fi
fi fi

View File

@ -31,14 +31,10 @@ RUN curl -O https://clickhouse-builds.s3.yandex.net/utils/1/dpkg-deb \
&& chmod +x dpkg-deb \ && chmod +x dpkg-deb \
&& cp dpkg-deb /usr/bin && cp dpkg-deb /usr/bin
ENV APACHE_PUBKEY_HASH="bba6987b63c63f710fd4ed476121c588bc3812e99659d27a855f8c4d312783ee66ad6adfce238765691b04d62fa3688f"
RUN export CODENAME="$(lsb_release --codename --short | tr 'A-Z' 'a-z')" \ RUN export CODENAME="$(lsb_release --codename --short | tr 'A-Z' 'a-z')" \
&& wget -nv -O /tmp/arrow-keyring.deb "https://apache.bintray.com/arrow/ubuntu/apache-arrow-archive-keyring-latest-${CODENAME}.deb" \ && wget -nv -O /tmp/arrow-keyring.deb "https://apache.bintray.com/arrow/ubuntu/apache-arrow-archive-keyring-latest-${CODENAME}.deb" \
&& echo "${APACHE_PUBKEY_HASH} /tmp/arrow-keyring.deb" | sha384sum -c \
&& dpkg -i /tmp/arrow-keyring.deb && dpkg -i /tmp/arrow-keyring.deb
# Libraries from OS are only needed to test the "unbundled" build (this is not used in production). # Libraries from OS are only needed to test the "unbundled" build (this is not used in production).
RUN apt-get update \ RUN apt-get update \
&& apt-get install \ && apt-get install \

View File

@ -53,7 +53,6 @@ RUN apt-get update \
ninja-build \ ninja-build \
psmisc \ psmisc \
python3 \ python3 \
python3-pip \
python3-lxml \ python3-lxml \
python3-requests \ python3-requests \
python3-termcolor \ python3-termcolor \
@ -63,8 +62,6 @@ RUN apt-get update \
unixodbc \ unixodbc \
--yes --no-install-recommends --yes --no-install-recommends
RUN pip3 install numpy scipy pandas
# This symlink required by gcc to find lld compiler # This symlink required by gcc to find lld compiler
RUN ln -s /usr/bin/lld-${LLVM_VERSION} /usr/bin/ld.lld RUN ln -s /usr/bin/lld-${LLVM_VERSION} /usr/bin/ld.lld

View File

@ -219,6 +219,8 @@ TESTS_TO_SKIP=(
01268_dictionary_direct_layout 01268_dictionary_direct_layout
01280_ssd_complex_key_dictionary 01280_ssd_complex_key_dictionary
01281_group_by_limit_memory_tracking # max_memory_usage_for_user can interfere another queries running concurrently 01281_group_by_limit_memory_tracking # max_memory_usage_for_user can interfere another queries running concurrently
01318_encrypt # Depends on OpenSSL
01318_decrypt # Depends on OpenSSL
01281_unsucceeded_insert_select_queries_counter 01281_unsucceeded_insert_select_queries_counter
01292_create_user 01292_create_user
01294_lazy_database_concurrent 01294_lazy_database_concurrent

View File

@ -37,7 +37,28 @@ RUN apt-get update \
ENV TZ=Europe/Moscow ENV TZ=Europe/Moscow
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN python3 -m pip install urllib3==1.23 pytest docker-compose==1.22.0 docker dicttoxml kazoo PyMySQL psycopg2==2.7.5 pymongo tzlocal kafka-python protobuf redis aerospike pytest-timeout minio grpcio grpcio-tools cassandra-driver confluent-kafka avro RUN python3 -m pip install \
PyMySQL \
aerospike \
avro \
cassandra-driver \
confluent-kafka \
dicttoxml \
docker \
docker-compose==1.22.0 \
grpcio \
grpcio-tools \
kafka-python \
kazoo \
minio \
protobuf \
psycopg2-binary==2.7.5 \
pymongo \
pytest \
pytest-timeout \
redis \
tzlocal \
urllib3
ENV DOCKER_CHANNEL stable ENV DOCKER_CHANNEL stable
ENV DOCKER_VERSION 17.09.1-ce ENV DOCKER_VERSION 17.09.1-ce

View File

@ -48,12 +48,13 @@ This table shows queries that take significantly longer to process on the client
#### Unexpected Query Duration #### Unexpected Query Duration
Action required for every item -- these are errors that must be fixed. Action required for every item -- these are errors that must be fixed.
Queries that have "short" duration (on the order of 0.1 s) can't be reliably tested in a normal way, where we perform a small (about ten) measurements for each server, because the signal-to-noise ratio is much smaller. There is a special mode for such queries that instead runs them for a fixed amount of time, normally with much higher number of measurements (up to thousands). This mode must be explicitly enabled by the test author to avoid accidental errors. It must be used only for queries that are meant to complete "immediately", such as `select count(*)`. If your query is not supposed to be "immediate", try to make it run longer, by e.g. processing more data. A query is supposed to run longer than 0.1 second. If your query runs faster, increase the amount of processed data to bring the run time above this threshold. You can use a bigger table (e.g. `hits_100m` instead of `hits_10m`), increase a `LIMIT`, make a query single-threaded, and so on. Queries that are too fast suffer from poor stability and precision.
This table shows queries for which the "short" marking is not consistent with the actual query run time -- i.e., a query runs for a long time but is marked as short, or it runs very fast but is not marked as short. Sometimes you want to test a query that is supposed to complete "instantaneously", i.e. in sublinear time. This might be `count(*)`, or parsing a complicated tuple. It might not be practical or even possible to increase the run time of such queries by adding more data. For such queries there is a specal comparison mode which runs them for a fixed amount of time, instead of a fixed number of iterations like we do normally. This mode is inferior to the normal mode, because the influence of noise and overhead is higher, which leads to less precise and stable results.
If your query is really supposed to complete "immediately" and can't be made to run longer, you have to mark it as "short". To do so, write `<query short="1">...` in the test file. The value of "short" attribute is evaluated as a python expression, and substitutions are performed, so you can write something like `<query short="{column1} = {column2}">select count(*) from table where {column1} > {column2}</query>`, to mark only a particular combination of variables as short. If it is impossible to increase the run time of a query and it is supposed to complete "immediately", you have to explicitly mark this in the test. To do so, add a `short` attribute to the query tag in the test file: `<query short="1">...`. The value of the `short` attribute is evaluated as a python expression, and substitutions are performed, so you can write something like `<query short="{column1} = {column2}">select count(*) from table where {column1} > {column2}</query>`, to mark only a particular combination of variables as short.
This table shows queries for which the `short` marking is not consistent with the actual query run time -- i.e., a query runs for a normal time but is marked as `short`, or it runs faster than normal but is not marked as `short`.
#### Partial Queries #### Partial Queries
Action required for the cells marked in red. Action required for the cells marked in red.

View File

@ -468,14 +468,14 @@ if args.report == 'main':
return return
columns = [ columns = [
'Test', #0 'Test', #0
'Wall clock time,&nbsp;s', #1 'Wall clock time, entire test,&nbsp;s', #1
'Total client time,&nbsp;s', #2 'Total client time for measured query runs,&nbsp;s', #2
'Total queries', #3 'Queries', #3
'Longest query<br>(sum for all runs),&nbsp;s', #4 'Longest query, total for measured runs,&nbsp;s', #4
'Avg wall clock time<br>(sum for all runs),&nbsp;s', #5 'Wall clock time per query,&nbsp;s', #5
'Shortest query<br>(sum for all runs),&nbsp;s', #6 'Shortest query, total for measured runs,&nbsp;s', #6
'', # Runs #7 '', # Runs #7
] ]
attrs = ['' for c in columns] attrs = ['' for c in columns]
attrs[7] = None attrs[7] = None

View File

@ -33,5 +33,8 @@ RUN mkdir -p /tmp/clickhouse-odbc-tmp \
ENV TZ=Europe/Moscow ENV TZ=Europe/Moscow
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
ENV NUM_TRIES=1
ENV MAX_RUN_TIME=0
COPY run.sh / COPY run.sh /
CMD ["/bin/bash", "/run.sh"] CMD ["/bin/bash", "/run.sh"]

View File

@ -1,6 +1,7 @@
#!/bin/bash #!/bin/bash
set -e -x # fail on errors, verbose and export all env variables
set -e -x -a
dpkg -i package_folder/clickhouse-common-static_*.deb dpkg -i package_folder/clickhouse-common-static_*.deb
dpkg -i package_folder/clickhouse-common-static-dbg_*.deb dpkg -i package_folder/clickhouse-common-static-dbg_*.deb
@ -16,9 +17,17 @@ service clickhouse-server start && sleep 5
if grep -q -- "--use-skip-list" /usr/bin/clickhouse-test; then if grep -q -- "--use-skip-list" /usr/bin/clickhouse-test; then
SKIP_LIST_OPT="--use-skip-list" SKIP_LIST_OPT="--use-skip-list"
fi fi
# We can have several additional options so we path them as array because it's # We can have several additional options so we path them as array because it's
# more idiologically correct. # more idiologically correct.
read -ra ADDITIONAL_OPTIONS <<< "${ADDITIONAL_OPTIONS:-}" read -ra ADDITIONAL_OPTIONS <<< "${ADDITIONAL_OPTIONS:-}"
clickhouse-test --testname --shard --zookeeper --hung-check --print-time "$SKIP_LIST_OPT" "${ADDITIONAL_OPTIONS[@]}" "$SKIP_TESTS_OPTION" 2>&1 | ts '%Y-%m-%d %H:%M:%S' | tee test_output/test_result.txt function run_tests()
{
for i in $(seq 1 $NUM_TRIES); do
clickhouse-test --testname --shard --zookeeper --hung-check --print-time "$SKIP_LIST_OPT" "${ADDITIONAL_OPTIONS[@]}" "$SKIP_TESTS_OPTION" 2>&1 | ts '%Y-%m-%d %H:%M:%S' | tee -a test_output/test_result.txt
done
}
export -f run_tests
timeout $MAX_RUN_TIME bash -c run_tests ||:

View File

@ -45,7 +45,7 @@ function start()
# for clickhouse-server (via service) # for clickhouse-server (via service)
echo "ASAN_OPTIONS='malloc_context_size=10 verbosity=1 allocator_release_to_os_interval_ms=10000'" >> /etc/environment echo "ASAN_OPTIONS='malloc_context_size=10 verbosity=1 allocator_release_to_os_interval_ms=10000'" >> /etc/environment
# for clickhouse-client # for clickhouse-client
export ASAN_OPTIONS='malloc_context_size=10 verbosity=1 allocator_release_to_os_interval_ms=10000' export ASAN_OPTIONS='malloc_context_size=10 allocator_release_to_os_interval_ms=10000'
start start

View File

@ -28,8 +28,18 @@ def get_options(i):
options = "" options = ""
if 0 < i: if 0 < i:
options += " --order=random" options += " --order=random"
if i % 2 == 1: if i % 2 == 1:
options += " --db-engine=Ordinary" options += " --db-engine=Ordinary"
# If database name is not specified, new database is created for each functional test.
# Run some threads with one database for all tests.
if i % 3 == 1:
options += " --database=test_{}".format(i)
if i == 13:
options += " --client-option='memory_tracker_fault_probability=0.00001'"
return options return options

View File

@ -117,7 +117,9 @@ CREATE TABLE table_name
</details> </details>
As the example shows, these parameters can contain substitutions in curly brackets. The substituted values are taken from the macros section of the configuration file. Example: As the example shows, these parameters can contain substitutions in curly brackets. The substituted values are taken from the «[macros](../../../operations/server-configuration-parameters/settings/#macros) section of the configuration file.
Example:
``` xml ``` xml
<macros> <macros>
@ -137,6 +139,9 @@ In this case, the path consists of the following parts:
`table_name` is the name of the node for the table in ZooKeeper. It is a good idea to make it the same as the table name. It is defined explicitly, because in contrast to the table name, it doesnt change after a RENAME query. `table_name` is the name of the node for the table in ZooKeeper. It is a good idea to make it the same as the table name. It is defined explicitly, because in contrast to the table name, it doesnt change after a RENAME query.
*HINT*: you could add a database name in front of `table_name` as well. E.g. `db_name.table_name` *HINT*: you could add a database name in front of `table_name` as well. E.g. `db_name.table_name`
The two built-in substitutions `{database}` and `{table}` can be used, they expand into the table name and the database name respectively (unless these macros are defined in the `macros` section). So the zookeeper path can be specified as `'/clickhouse/tables/{layer}-{shard}/{database}/{table}'`.
Be careful with table renames when using these built-in substitutions. The path in Zookeeper cannot be changed, and when the table is renamed, the macros will expand into a different path, the table will refer to a path that does not exist in Zookeeper, and will go into read-only mode.
The replica name identifies different replicas of the same table. You can use the server name for this, as in the example. The name only needs to be unique within each shard. The replica name identifies different replicas of the same table. You can use the server name for this, as in the example. The name only needs to be unique within each shard.
You can define the parameters explicitly instead of using substitutions. This might be convenient for testing and for configuring small clusters. However, you cant use distributed DDL queries (`ON CLUSTER`) in this case. You can define the parameters explicitly instead of using substitutions. This might be convenient for testing and for configuring small clusters. However, you cant use distributed DDL queries (`ON CLUSTER`) in this case.

View File

@ -88,6 +88,7 @@ toc_title: Adopters
| <a href="https://smi2.ru/" class="favicon">SMI2</a> | News | Analytics | — | — | [Blog Post in Russian, November 2017](https://habr.com/ru/company/smi2/blog/314558/) | | <a href="https://smi2.ru/" class="favicon">SMI2</a> | News | Analytics | — | — | [Blog Post in Russian, November 2017](https://habr.com/ru/company/smi2/blog/314558/) |
| <a href="https://www.splunk.com/" class="favicon">Splunk</a> | Business Analytics | Main product | — | — | [Slides in English, January 2018](https://github.com/ClickHouse/clickhouse-presentations/blob/master/meetup12/splunk.pdf) | | <a href="https://www.splunk.com/" class="favicon">Splunk</a> | Business Analytics | Main product | — | — | [Slides in English, January 2018](https://github.com/ClickHouse/clickhouse-presentations/blob/master/meetup12/splunk.pdf) |
| <a href="https://www.spotify.com" class="favicon">Spotify</a> | Music | Experimentation | — | — | [Slides, July 2018](https://www.slideshare.net/glebus/using-clickhouse-for-experimentation-104247173) | | <a href="https://www.spotify.com" class="favicon">Spotify</a> | Music | Experimentation | — | — | [Slides, July 2018](https://www.slideshare.net/glebus/using-clickhouse-for-experimentation-104247173) |
| <a href="https://www.staffcop.ru/" class="favicon">Staffcop</a> | Information Security | Main Product | — | — | [Official website, Documentation](https://www.staffcop.ru/sce43) |
| <a href="https://www.tencent.com" class="favicon">Tencent</a> | Big Data | Data processing | — | — | [Slides in Chinese, October 2018](https://github.com/ClickHouse/clickhouse-presentations/blob/master/meetup19/5.%20ClickHouse大数据集群应用_李俊飞腾讯网媒事业部.pdf) | | <a href="https://www.tencent.com" class="favicon">Tencent</a> | Big Data | Data processing | — | — | [Slides in Chinese, October 2018](https://github.com/ClickHouse/clickhouse-presentations/blob/master/meetup19/5.%20ClickHouse大数据集群应用_李俊飞腾讯网媒事业部.pdf) |
| <a href="https://www.tencent.com" class="favicon">Tencent</a> | Messaging | Logging | — | — | [Talk in Chinese, November 2019](https://youtu.be/T-iVQRuw-QY?t=5050) | | <a href="https://www.tencent.com" class="favicon">Tencent</a> | Messaging | Logging | — | — | [Talk in Chinese, November 2019](https://youtu.be/T-iVQRuw-QY?t=5050) |
| <a href="https://trafficstars.com/" class="favicon">Traffic Stars</a> | AD network | — | — | — | [Slides in Russian, May 2018](https://github.com/ClickHouse/clickhouse-presentations/blob/master/meetup15/lightning/ninja.pdf) | | <a href="https://trafficstars.com/" class="favicon">Traffic Stars</a> | AD network | — | — | — | [Slides in Russian, May 2018](https://github.com/ClickHouse/clickhouse-presentations/blob/master/meetup15/lightning/ninja.pdf) |

View File

@ -305,6 +305,10 @@ When enabled, replace empty input fields in TSV with default values. For complex
Disabled by default. Disabled by default.
## input_format_tsv_enum_as_number {#settings-input_format_tsv_enum_as_number}
For TSV input format switches to parsing enum values as enum ids.
## input_format_null_as_default {#settings-input-format-null-as-default} ## input_format_null_as_default {#settings-input-format-null-as-default}
Enables or disables using default values if input data contain `NULL`, but the data type of the corresponding column in not `Nullable(T)` (for text input formats). Enables or disables using default values if input data contain `NULL`, but the data type of the corresponding column in not `Nullable(T)` (for text input formats).
@ -1161,6 +1165,10 @@ The character is interpreted as a delimiter in the CSV data. By default, the del
For CSV input format enables or disables parsing of unquoted `NULL` as literal (synonym for `\N`). For CSV input format enables or disables parsing of unquoted `NULL` as literal (synonym for `\N`).
## input_format_csv_enum_as_number {#settings-input_format_csv_enum_as_number}
For CSV input format switches to parsing enum values as enum ids.
## output_format_csv_crlf_end_of_line {#settings-output-format-csv-crlf-end-of-line} ## output_format_csv_crlf_end_of_line {#settings-output-format-csv-crlf-end-of-line}
Use DOS/Windows-style line separator (CRLF) in CSV instead of Unix style (LF). Use DOS/Windows-style line separator (CRLF) in CSV instead of Unix style (LF).
@ -1398,6 +1406,17 @@ Possible values:
Default value: 0 Default value: 0
## allow_nondeterministic_optimize_skip_unused_shards {#allow-nondeterministic-optimize-skip-unused-shards}
Allow nondeterministic (like `rand` or `dictGet`, since later has some caveats with updates) functions in sharding key.
Possible values:
- 0 — Disallowed.
- 1 — Allowed.
Default value: 0
## optimize_skip_unused_shards_nesting {#optimize-skip-unused-shards-nesting} ## optimize_skip_unused_shards_nesting {#optimize-skip-unused-shards-nesting}
Controls [`optimize_skip_unused_shards`](#optimize-skip-unused-shards) (hence still requires [`optimize_skip_unused_shards`](#optimize-skip-unused-shards)) depends on the nesting level of the distributed query (case when you have `Distributed` table that look into another `Distributed` table). Controls [`optimize_skip_unused_shards`](#optimize-skip-unused-shards) (hence still requires [`optimize_skip_unused_shards`](#optimize-skip-unused-shards)) depends on the nesting level of the distributed query (case when you have `Distributed` table that look into another `Distributed` table).

View File

@ -461,6 +461,66 @@ For other regular expressions, the code is the same as for the match funct
The same thing as like, but negative. The same thing as like, but negative.
## ilike {#ilike}
Case insensitive variant of [like](https://clickhouse.tech/docs/en/sql-reference/functions/string-search-functions/#function-like) function. You can use `ILIKE` operator instead of the `ilike` function.
**Syntax**
``` sql
ilike(haystack, pattern)
```
**Parameters**
- `haystack` — Input string. [String](../../sql-reference/syntax.md#syntax-string-literal).
- `pattern` — If `pattern` doesn't contain percent signs or underscores, then the `pattern` only represents the string itself. An underscore (`_`) in `pattern` stands for (matches) any single character. A percent sign (`%`) matches any sequence of zero or more characters.
Some `pattern` examples:
``` text
'abc' ILIKE 'abc' true
'abc' ILIKE 'a%' true
'abc' ILIKE '_b_' true
'abc' ILIKE 'c' false
```
**Returned values**
- True, if the string matches `pattern`.
- False, if the string doesn't match `pattern`.
**Example**
Input table:
``` text
┌─id─┬─name─────┬─days─┐
│ 1 │ January │ 31 │
│ 2 │ February │ 29 │
│ 3 │ March │ 31 │
│ 4 │ April │ 30 │
└────┴──────────┴──────┘
```
Query:
``` sql
SELECT * FROM Months WHERE ilike(name, '%j%')
```
Result:
``` text
┌─id─┬─name────┬─days─┐
│ 1 │ January │ 31 │
└────┴─────────┴──────┘
```
**See Also**
- [like](https://clickhouse.tech/docs/en/sql-reference/functions/string-search-functions/#function-like) <!--hide-->
## ngramDistance(haystack, needle) {#ngramdistancehaystack-needle} ## ngramDistance(haystack, needle) {#ngramdistancehaystack-needle}
Calculates the 4-gram distance between `haystack` and `needle`: counts the symmetric difference between two multisets of 4-grams and normalizes it by the sum of their cardinalities. Returns float number from 0 to 1 the closer to zero, the more strings are similar to each other. If the constant `needle` or `haystack` is more than 32Kb, throws an exception. If some of the non-constant `haystack` or `needle` strings are more than 32Kb, the distance is always one. Calculates the 4-gram distance between `haystack` and `needle`: counts the symmetric difference between two multisets of 4-grams and normalizes it by the sum of their cardinalities. Returns float number from 0 to 1 the closer to zero, the more strings are similar to each other. If the constant `needle` or `haystack` is more than 32Kb, throws an exception. If some of the non-constant `haystack` or `needle` strings are more than 32Kb, the distance is always one.

View File

@ -53,6 +53,8 @@ ClickHouse transforms operators to their corresponding functions at the query pa
`a NOT LIKE s` The `notLike(a, b)` function. `a NOT LIKE s` The `notLike(a, b)` function.
`a ILIKE s` The `ilike(a, b)` function.
`a BETWEEN b AND c` The same as `a >= b AND a <= c`. `a BETWEEN b AND c` The same as `a >= b AND a <= c`.
`a NOT BETWEEN b AND c` The same as `a < b OR a > c`. `a NOT BETWEEN b AND c` The same as `a < b OR a > c`.

View File

@ -139,7 +139,7 @@ ENGINE = <Engine>
``` ```
The `Default` codec can be specified to reference default compression which may dependend on different settings (and properties of data) in runtime. The `Default` codec can be specified to reference default compression which may dependend on different settings (and properties of data) in runtime.
Example: `value UInt64 CODEC(Default)` - the same as lack of codec specification. Example: `value UInt64 CODEC(Default)` the same as lack of codec specification.
Also you can remove current CODEC from the column and use default compression from config.xml: Also you can remove current CODEC from the column and use default compression from config.xml:

View File

@ -0,0 +1,67 @@
---
toc_priority: 51
toc_title: view
---
## view {#view}
Turns a subquery into a table. The function implements views (see [CREATE VIEW](https://clickhouse.tech/docs/en/sql-reference/statements/create/view/#create-view)). The resulting table doesn't store data, but only stores the specified `SELECT` query. When reading from the table, ClickHouse executes the query and deletes all unnecessary columns from the result.
**Syntax**
``` sql
view(subquery)
```
**Parameters**
- `subquery``SELECT` query.
**Returned value**
- A table.
**Example**
Input table:
``` text
┌─id─┬─name─────┬─days─┐
│ 1 │ January │ 31 │
│ 2 │ February │ 29 │
│ 3 │ March │ 31 │
│ 4 │ April │ 30 │
└────┴──────────┴──────┘
```
Query:
``` sql
SELECT * FROM view(SELECT name FROM months)
```
Result:
``` text
┌─name─────┐
│ January │
│ February │
│ March │
│ April │
└──────────┘
```
You can use the `view` function as a parameter of the [remote](https://clickhouse.tech/docs/en/sql-reference/table-functions/remote/#remote-remotesecure) and [cluster](https://clickhouse.tech/docs/en/sql-reference/table-functions/cluster/#cluster-clusterallreplicas) table functions:
``` sql
SELECT * FROM remote(`127.0.0.1`, view(SELECT a, b, c FROM table_name))
```
``` sql
SELECT * FROM cluster(`cluster_name`, view(SELECT a, b, c FROM table_name))
```
**See Also**
- [View Table Engine](https://clickhouse.tech/docs/en/engines/table-engines/special/view/)
[Original article](https://clickhouse.tech/docs/en/query_language/table_functions/view/) <!--hide-->

View File

@ -113,7 +113,9 @@ CREATE TABLE table_name
</details> </details>
Как видно в примере, эти параметры могут содержать подстановки в фигурных скобках. Подставляемые значения достаются из конфигурационного файла, из секции `macros`. Пример: Как видно в примере, эти параметры могут содержать подстановки в фигурных скобках. Подставляемые значения достаются из конфигурационного файла, из секции «[macros](../../../operations/server-configuration-parameters/settings/#macros)».
Пример:
``` xml ``` xml
<macros> <macros>
@ -133,6 +135,9 @@ CREATE TABLE table_name
`table_name` - имя узла для таблицы в ZooKeeper. Разумно делать его таким же, как имя таблицы. Оно указывается явно, так как, в отличие от имени таблицы, оно не меняется после запроса RENAME. `table_name` - имя узла для таблицы в ZooKeeper. Разумно делать его таким же, как имя таблицы. Оно указывается явно, так как, в отличие от имени таблицы, оно не меняется после запроса RENAME.
*Подсказка*: можно также указать имя базы данных перед `table_name`, например `db_name.table_name` *Подсказка*: можно также указать имя базы данных перед `table_name`, например `db_name.table_name`
Можно использовать две встроенных подстановки `{database}` и `{table}`, они раскрываются в имя таблицы и в имя базы данных соответственно (если эти подстановки не переопределены в секции `macros`). Т.о. Zookeeper путь можно задать как `'/clickhouse/tables/{layer}-{shard}/{database}/{table}'`.
Будьте осторожны с переименованиями таблицы при использовании этих автоматических подстановок. Путь в Zookeeper-е нельзя изменить, а подстановка при переименовании таблицы раскроется в другой путь, таблица будет обращаться к несуществующему в Zookeeper-е пути и перейдет в режим только для чтения.
Имя реплики — то, что идентифицирует разные реплики одной и той же таблицы. Можно использовать для него имя сервера, как показано в примере. Впрочем, достаточно, чтобы имя было уникально лишь в пределах каждого шарда. Имя реплики — то, что идентифицирует разные реплики одной и той же таблицы. Можно использовать для него имя сервера, как показано в примере. Впрочем, достаточно, чтобы имя было уникально лишь в пределах каждого шарда.
Можно не использовать подстановки, а указать соответствующие параметры явно. Это может быть удобным для тестирования и при настройке маленьких кластеров. Однако в этом случае нельзя пользоваться распределенными DDL-запросами (`ON CLUSTER`). Можно не использовать подстановки, а указать соответствующие параметры явно. Это может быть удобным для тестирования и при настройке маленьких кластеров. Однако в этом случае нельзя пользоваться распределенными DDL-запросами (`ON CLUSTER`).

View File

@ -387,7 +387,7 @@ ClickHouse проверяет условия для `min_part_size` и `min_part
Можно не указывать, если реплицируемых таблицы не используются. Можно не указывать, если реплицируемых таблицы не используются.
Подробнее смотрите в разделе «[Создание реплицируемых таблиц](../../operations/server-configuration-parameters/settings.md)». Подробнее смотрите в разделе «[Создание реплицируемых таблиц](../../engines/table-engines/mergetree-family/replication.md)».
**Пример** **Пример**

View File

@ -1164,9 +1164,9 @@ ClickHouse генерирует исключение
## insert_quorum_timeout {#settings-insert_quorum_timeout} ## insert_quorum_timeout {#settings-insert_quorum_timeout}
Время ожидания кворумной записи в секундах. Если время прошло, а запись так не состоялась, то ClickHouse сгенерирует исключение и клиент должен повторить запрос на запись того же блока на эту же или любую другую реплику. Время ожидания кворумной записи в миллисекундах. Если время прошло, а запись так не состоялась, то ClickHouse сгенерирует исключение и клиент должен повторить запрос на запись того же блока на эту же или любую другую реплику.
Значение по умолчанию: 60 секунд. Значение по умолчанию: 600000 миллисекунд (10 минут).
См. также: См. также:

View File

@ -34,6 +34,7 @@ ClickHouse не удаляет данные из таблица автомати
- `event_date` ([Date](../../sql-reference/data-types/date.md)) — дата начала запроса. - `event_date` ([Date](../../sql-reference/data-types/date.md)) — дата начала запроса.
- `event_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — время начала запроса. - `event_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — время начала запроса.
- `query_start_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — время начала обработки запроса. - `query_start_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — время начала обработки запроса.
- `query_start_time_microseconds` ([DateTime64](../../sql-reference/data-types/datetime64.md)) — время начала обработки запроса с точностью до микросекунд.
- `query_duration_ms` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — длительность выполнения запроса в миллисекундах. - `query_duration_ms` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — длительность выполнения запроса в миллисекундах.
- `read_rows` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — Общее количество строк, считанных из всех таблиц и табличных функций, участвующих в запросе. Включает в себя обычные подзапросы, подзапросы для `IN` и `JOIN`. Для распределенных запросов `read_rows` включает в себя общее количество строк, прочитанных на всех репликах. Каждая реплика передает собственное значение `read_rows`, а сервер-инициатор запроса суммирует все полученные и локальные значения. Объемы кэша не учитываюся. - `read_rows` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — Общее количество строк, считанных из всех таблиц и табличных функций, участвующих в запросе. Включает в себя обычные подзапросы, подзапросы для `IN` и `JOIN`. Для распределенных запросов `read_rows` включает в себя общее количество строк, прочитанных на всех репликах. Каждая реплика передает собственное значение `read_rows`, а сервер-инициатор запроса суммирует все полученные и локальные значения. Объемы кэша не учитываюся.
- `read_bytes` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — Общее количество байтов, считанных из всех таблиц и табличных функций, участвующих в запросе. Включает в себя обычные подзапросы, подзапросы для `IN` и `JOIN`. Для распределенных запросов `read_bytes` включает в себя общее количество байтов, прочитанных на всех репликах. Каждая реплика передает собственное значение `read_bytes`, а сервер-инициатор запроса суммирует все полученные и локальные значения. Объемы кэша не учитываюся. - `read_bytes` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — Общее количество байтов, считанных из всех таблиц и табличных функций, участвующих в запросе. Включает в себя обычные подзапросы, подзапросы для `IN` и `JOIN`. Для распределенных запросов `read_bytes` включает в себя общее количество байтов, прочитанных на всех репликах. Каждая реплика передает собственное значение `read_bytes`, а сервер-инициатор запроса суммирует все полученные и локальные значения. Объемы кэша не учитываюся.

View File

@ -16,6 +16,7 @@ ClickHouse не удаляет данные из таблицы автомати
- `event_date` ([Date](../../sql-reference/data-types/date.md)) — дата завершения выполнения запроса потоком. - `event_date` ([Date](../../sql-reference/data-types/date.md)) — дата завершения выполнения запроса потоком.
- `event_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — дата и время завершения выполнения запроса потоком. - `event_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — дата и время завершения выполнения запроса потоком.
- `query_start_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — время начала обработки запроса. - `query_start_time` ([DateTime](../../sql-reference/data-types/datetime.md)) — время начала обработки запроса.
- `query_start_time_microseconds` ([DateTime64](../../sql-reference/data-types/datetime64.md)) — время начала обработки запроса с точностью до микросекунд.
- `query_duration_ms` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — длительность обработки запроса в миллисекундах. - `query_duration_ms` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — длительность обработки запроса в миллисекундах.
- `read_rows` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — количество прочитанных строк. - `read_rows` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — количество прочитанных строк.
- `read_bytes` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — количество прочитанных байтов. - `read_bytes` ([UInt64](../../sql-reference/data-types/int-uint.md#uint-ranges)) — количество прочитанных байтов.

View File

@ -442,6 +442,66 @@ SELECT extractAllGroupsVertical('abc=111, def=222, ghi=333', '("[^"]+"|\\w+)=("[
То же, что like, но с отрицанием. То же, что like, но с отрицанием.
## ilike {#ilike}
Нечувствительный к регистру вариант функции [like](https://clickhouse.tech/docs/ru/sql-reference/functions/string-search-functions/#function-like). Вы можете использовать оператор `ILIKE` вместо функции `ilike`.
**Синтаксис**
``` sql
ilike(haystack, pattern)
```
**Параметры**
- `haystack` — Входная строка. [String](../../sql-reference/syntax.md#syntax-string-literal).
- `pattern` — Если `pattern` не содержит процента или нижнего подчеркивания, тогда `pattern` представляет саму строку. Нижнее подчеркивание (`_`) в `pattern` обозначает любой отдельный символ. Знак процента (`%`) соответствует последовательности из любого количества символов: от нуля и более.
Некоторые примеры `pattern`:
``` text
'abc' ILIKE 'abc' true
'abc' ILIKE 'a%' true
'abc' ILIKE '_b_' true
'abc' ILIKE 'c' false
```
**Возвращаемые значения**
- Правда, если строка соответствует `pattern`.
- Ложь, если строка не соответствует `pattern`.
**Пример**
Входная таблица:
``` text
┌─id─┬─name─────┬─days─┐
│ 1 │ January │ 31 │
│ 2 │ February │ 29 │
│ 3 │ March │ 31 │
│ 4 │ April │ 30 │
└────┴──────────┴──────┘
```
Запрос:
``` sql
SELECT * FROM Months WHERE ilike(name, '%j%')
```
Результат:
``` text
┌─id─┬─name────┬─days─┐
│ 1 │ January │ 31 │
└────┴─────────┴──────┘
```
**Смотрите также**
- [like](https://clickhouse.tech/docs/ru/sql-reference/functions/string-search-functions/#function-like) <!--hide-->
## ngramDistance(haystack, needle) {#ngramdistancehaystack-needle} ## ngramDistance(haystack, needle) {#ngramdistancehaystack-needle}
Вычисление 4-граммного расстояния между `haystack` и `needle`: считается симметрическая разность между двумя мультимножествами 4-грамм и нормализуется на сумму их мощностей. Возвращает число float от 0 до 1 чем ближе к нулю, тем больше строки похожи друг на друга. Если константный `needle` или `haystack` больше чем 32КБ, кидается исключение. Если некоторые строки из неконстантного `haystack` или `needle` больше 32КБ, расстояние всегда равно единице. Вычисление 4-граммного расстояния между `haystack` и `needle`: считается симметрическая разность между двумя мультимножествами 4-грамм и нормализуется на сумму их мощностей. Возвращает число float от 0 до 1 чем ближе к нулю, тем больше строки похожи друг на друга. Если константный `needle` или `haystack` больше чем 32КБ, кидается исключение. Если некоторые строки из неконстантного `haystack` или `needle` больше 32КБ, расстояние всегда равно единице.

View File

@ -49,6 +49,8 @@
`a NOT LIKE s` - функция `notLike(a, b)` `a NOT LIKE s` - функция `notLike(a, b)`
`a ILIKE s` функция `ilike(a, b)`
`a BETWEEN b AND c` - равнозначно `a >= b AND a <= c` `a BETWEEN b AND c` - равнозначно `a >= b AND a <= c`
`a NOT BETWEEN b AND c` - равнозначно `a < b OR a > c` `a NOT BETWEEN b AND c` - равнозначно `a < b OR a > c`

View File

@ -119,7 +119,18 @@ ENGINE = <Engine>
... ...
``` ```
Если задать кодек для столбца, то кодек по умолчанию не применяется. Кодеки можно последовательно комбинировать, например, `CODEC(Delta, ZSTD)`. Чтобы выбрать наиболее подходящую для вашего проекта комбинацию кодеков, необходимо провести сравнительные тесты, подобные тем, что описаны в статье Altinity [New Encodings to Improve ClickHouse Efficiency](https://www.altinity.com/blog/2019/7/new-encodings-to-improve-clickhouse). Если кодек `Default` задан для столбца, используется сжатие по умолчанию, которое может зависеть от различных настроек (и свойств данных) во время выполнения.
Пример: `value UInt64 CODEC(Default)` — то же самое, что не указать кодек.
Также можно подменить кодек столбца сжатием по умолчанию, определенным в config.xml:
``` sql
ALTER TABLE codec_example MODIFY COLUMN float_value CODEC(Default);
```
Кодеки можно последовательно комбинировать, например, `CODEC(Delta, Default)`.
Чтобы выбрать наиболее подходящую для вашего проекта комбинацию кодеков, необходимо провести сравнительные тесты, подобные тем, что описаны в статье Altinity [New Encodings to Improve ClickHouse Efficiency](https://www.altinity.com/blog/2019/7/new-encodings-to-improve-clickhouse). Для столбцов типа `ALIAS` кодеки не применяются.
!!! warning "Предупреждение" !!! warning "Предупреждение"
Нельзя распаковать базу данных ClickHouse с помощью сторонних утилит наподобие `lz4`. Необходимо использовать специальную утилиту [clickhouse-compressor](https://github.com/ClickHouse/ClickHouse/tree/master/programs/compressor). Нельзя распаковать базу данных ClickHouse с помощью сторонних утилит наподобие `lz4`. Необходимо использовать специальную утилиту [clickhouse-compressor](https://github.com/ClickHouse/ClickHouse/tree/master/programs/compressor).
@ -195,4 +206,4 @@ CREATE TEMPORARY TABLE [IF NOT EXISTS] table_name
[Оригинальная статья](https://clickhouse.tech/docs/ru/sql-reference/statements/create/table) [Оригинальная статья](https://clickhouse.tech/docs/ru/sql-reference/statements/create/table)
<!--hide--> <!--hide-->

View File

@ -0,0 +1,62 @@
## view {#view}
Преобразовывает подзапрос в таблицу. Функция реализовывает представления (смотрите [CREATE VIEW](https://clickhouse.tech/docs/ru/sql-reference/statements/create/view/#create-view)). Результирующая таблица не хранит данные, а только сохраняет указанный запрос `SELECT`. При чтении из таблицы, ClickHouse выполняет запрос и удаляет все ненужные столбцы из результата.
**Синтаксис**
``` sql
view(subquery)
```
**Входные параметры**
- `subquery` — запрос `SELECT`.
**Возвращаемое значение**
- Таблица.
**Пример**
Входная таблица:
``` text
┌─id─┬─name─────┬─days─┐
│ 1 │ January │ 31 │
│ 2 │ February │ 29 │
│ 3 │ March │ 31 │
│ 4 │ April │ 30 │
└────┴──────────┴──────┘
```
Запрос:
``` sql
SELECT * FROM view(SELECT name FROM months)
```
Результат:
``` text
┌─name─────┐
│ January │
│ February │
│ March │
│ April │
└──────────┘
```
Вы можете использовать функцию `view` как параметр табличных функций [remote](https://clickhouse.tech/docs/ru/sql-reference/table-functions/remote/#remote-remotesecure) и [cluster](https://clickhouse.tech/docs/ru/sql-reference/table-functions/cluster/#cluster-clusterallreplicas):
``` sql
SELECT * FROM remote(`127.0.0.1`, view(SELECT a, b, c FROM table_name))
```
``` sql
SELECT * FROM cluster(`cluster_name`, view(SELECT a, b, c FROM table_name))
```
**Смотрите также**
- [view](https://clickhouse.tech/docs/ru/engines/table-engines/special/view/#table_engines-view)
[Оригинальная статья](https://clickhouse.tech/docs/ru/query_language/table_functions/view/) <!--hide-->

View File

@ -14,7 +14,7 @@ Jinja2==2.11.2
jinja2-highlight==0.6.1 jinja2-highlight==0.6.1
jsmin==2.2.2 jsmin==2.2.2
livereload==2.6.2 livereload==2.6.2
Markdown==3.2.1 Markdown==3.3.2
MarkupSafe==1.1.1 MarkupSafe==1.1.1
mkdocs==1.1.2 mkdocs==1.1.2
mkdocs-htmlproofer-plugin==0.0.3 mkdocs-htmlproofer-plugin==0.0.3

View File

@ -548,11 +548,27 @@ int mainEntryClickHouseInstall(int argc, char ** argv)
users_config_file.string(), users_d.string()); users_config_file.string(), users_d.string());
} }
/// Set capabilities for the binary. /** Set capabilities for the binary.
*
* 1. Check that "setcap" tool exists.
* 2. Check that an arbitrary program with installed capabilities can run.
* 3. Set the capabilities.
*
* The second is important for Docker and systemd-nspawn.
* When the container has no capabilities,
* but the executable file inside the container has capabilities,
* then attempt to run this file will end up with a cryptic "Operation not permitted" message.
*/
#if defined(__linux__) #if defined(__linux__)
fmt::print("Setting capabilities for clickhouse binary. This is optional.\n"); fmt::print("Setting capabilities for clickhouse binary. This is optional.\n");
std::string command = fmt::format("command -v setcap && setcap 'cap_net_admin,cap_ipc_lock,cap_sys_nice+ep' {}", main_bin_path.string()); std::string command = fmt::format("command -v setcap >/dev/null"
" && echo > {0} && chmod a+x {0} && {0} && setcap 'cap_net_admin,cap_ipc_lock,cap_sys_nice+ep' {0} && {0} && rm {0}"
" && setcap 'cap_net_admin,cap_ipc_lock,cap_sys_nice+ep' {1}"
" || echo \"Cannot set 'net_admin' or 'ipc_lock' or 'sys_nice' capability for clickhouse binary."
" This is optional. Taskstats accounting will be disabled."
" To enable taskstats accounting you may add the required capability later manually.\"",
"/tmp/test_setcap.sh", main_bin_path.string());
fmt::print(" {}\n", command); fmt::print(" {}\n", command);
executeScript(command); executeScript(command);
#endif #endif

View File

@ -4,7 +4,7 @@ set(CLICKHOUSE_SERVER_SOURCES
) )
if (OS_LINUX) if (OS_LINUX)
set (LINK_CONFIG_LIB INTERFACE "-Wl,${WHOLE_ARCHIVE} $<TARGET_FILE:clickhouse_server_configs> -Wl,${NO_WHOLE_ARCHIVE}") set (LINK_RESOURCE_LIB INTERFACE "-Wl,${WHOLE_ARCHIVE} $<TARGET_FILE:clickhouse_server_configs> -Wl,${NO_WHOLE_ARCHIVE}")
endif () endif ()
set (CLICKHOUSE_SERVER_LINK set (CLICKHOUSE_SERVER_LINK
@ -20,7 +20,7 @@ set (CLICKHOUSE_SERVER_LINK
clickhouse_table_functions clickhouse_table_functions
string_utils string_utils
${LINK_CONFIG_LIB} ${LINK_RESOURCE_LIB}
PUBLIC PUBLIC
daemon daemon
@ -37,20 +37,20 @@ if (OS_LINUX)
# 1. Allow to run the binary without download of any other files. # 1. Allow to run the binary without download of any other files.
# 2. Allow to implement "sudo clickhouse install" tool. # 2. Allow to implement "sudo clickhouse install" tool.
foreach(CONFIG_FILE config users embedded) foreach(RESOURCE_FILE config.xml users.xml embedded.xml play.html)
set(CONFIG_OBJ ${CONFIG_FILE}.o) set(RESOURCE_OBJ ${RESOURCE_FILE}.o)
set(CONFIG_OBJS ${CONFIG_OBJS} ${CONFIG_OBJ}) set(RESOURCE_OBJS ${RESOURCE_OBJS} ${RESOURCE_OBJ})
# https://stackoverflow.com/questions/14776463/compile-and-add-an-object-file-from-a-binary-with-cmake # https://stackoverflow.com/questions/14776463/compile-and-add-an-object-file-from-a-binary-with-cmake
add_custom_command(OUTPUT ${CONFIG_OBJ} add_custom_command(OUTPUT ${RESOURCE_OBJ}
COMMAND cd ${CMAKE_CURRENT_SOURCE_DIR} && ${OBJCOPY_PATH} -I binary ${OBJCOPY_ARCH_OPTIONS} ${CONFIG_FILE}.xml ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_OBJ} COMMAND cd ${CMAKE_CURRENT_SOURCE_DIR} && ${OBJCOPY_PATH} -I binary ${OBJCOPY_ARCH_OPTIONS} ${RESOURCE_FILE} ${CMAKE_CURRENT_BINARY_DIR}/${RESOURCE_OBJ}
COMMAND ${OBJCOPY_PATH} --rename-section .data=.rodata,alloc,load,readonly,data,contents COMMAND ${OBJCOPY_PATH} --rename-section .data=.rodata,alloc,load,readonly,data,contents
${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_OBJ} ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_OBJ}) ${CMAKE_CURRENT_BINARY_DIR}/${RESOURCE_OBJ} ${CMAKE_CURRENT_BINARY_DIR}/${RESOURCE_OBJ})
set_source_files_properties(${CONFIG_OBJ} PROPERTIES EXTERNAL_OBJECT true GENERATED true) set_source_files_properties(${RESOURCE_OBJ} PROPERTIES EXTERNAL_OBJECT true GENERATED true)
endforeach(CONFIG_FILE) endforeach(RESOURCE_FILE)
add_library(clickhouse_server_configs STATIC ${CONFIG_OBJS}) add_library(clickhouse_server_configs STATIC ${RESOURCE_OBJS})
set_target_properties(clickhouse_server_configs PROPERTIES LINKER_LANGUAGE C) set_target_properties(clickhouse_server_configs PROPERTIES LINKER_LANGUAGE C)
# whole-archive prevents symbols from being discarded for unknown reason # whole-archive prevents symbols from being discarded for unknown reason

View File

@ -212,22 +212,10 @@
<!-- Directory with user provided files that are accessible by 'file' table function. --> <!-- Directory with user provided files that are accessible by 'file' table function. -->
<user_files_path>/var/lib/clickhouse/user_files/</user_files_path> <user_files_path>/var/lib/clickhouse/user_files/</user_files_path>
<!-- Sources to read users, roles, access rights, profiles of settings, quotas. --> <!-- LDAP server definitions. -->
<user_directories>
<users_xml>
<!-- Path to configuration file with predefined users. -->
<path>users.xml</path>
</users_xml>
<local_directory>
<!-- Path to folder where users created by SQL commands are stored. -->
<path>/var/lib/clickhouse/access/</path>
</local_directory>
</user_directories>
<!-- External user directories (LDAP). -->
<ldap_servers> <ldap_servers>
<!-- List LDAP servers with their connection parameters here to later use them as authenticators for dedicated users, <!-- List LDAP servers with their connection parameters here to later 1) use them as authenticators for dedicated local users,
who have 'ldap' authentication mechanism specified instead of 'password'. who have 'ldap' authentication mechanism specified instead of 'password', or to 2) use them as remote user directories.
Parameters: Parameters:
host - LDAP server hostname or IP, this parameter is mandatory and cannot be empty. host - LDAP server hostname or IP, this parameter is mandatory and cannot be empty.
port - LDAP server port, default is 636 if enable_tls is set to true, 389 otherwise. port - LDAP server port, default is 636 if enable_tls is set to true, 389 otherwise.
@ -246,7 +234,7 @@
tls_key_file - path to certificate key file. tls_key_file - path to certificate key file.
tls_ca_cert_file - path to CA certificate file. tls_ca_cert_file - path to CA certificate file.
tls_ca_cert_dir - path to the directory containing CA certificates. tls_ca_cert_dir - path to the directory containing CA certificates.
tls_cipher_suite - allowed cipher suite. tls_cipher_suite - allowed cipher suite (in OpenSSL notation).
Example: Example:
<my_ldap_server> <my_ldap_server>
<host>localhost</host> <host>localhost</host>
@ -265,6 +253,36 @@
--> -->
</ldap_servers> </ldap_servers>
<!-- Sources to read users, roles, access rights, profiles of settings, quotas. -->
<user_directories>
<users_xml>
<!-- Path to configuration file with predefined users. -->
<path>users.xml</path>
</users_xml>
<local_directory>
<!-- Path to folder where users created by SQL commands are stored. -->
<path>/var/lib/clickhouse/access/</path>
</local_directory>
<!-- To add an LDAP server as a remote user directory of users that are not defined locally, define a single 'ldap' section
with the following parameters:
server - one of LDAP server names defined in 'ldap_servers' config section above.
This parameter is mandatory and cannot be empty.
roles - section with a list of locally defined roles that will be assigned to each user retrieved from the LDAP server.
If no roles are specified, user will not be able to perform any actions after authentication.
If any of the listed roles is not defined locally at the time of authentication, the authenthication attept
will fail as if the provided password was incorrect.
Example:
<ldap>
<server>my_ldap_server</server>
<roles>
<my_local_role1 />
<my_local_role2 />
</roles>
</ldap>
-->
</user_directories>
<!-- Default profile of settings. --> <!-- Default profile of settings. -->
<default_profile>default</default_profile> <default_profile>default</default_profile>
@ -704,18 +722,22 @@
--> -->
<format_schema_path>/var/lib/clickhouse/format_schemas/</format_schema_path> <format_schema_path>/var/lib/clickhouse/format_schemas/</format_schema_path>
<!-- Uncomment to use query masking rules. <!-- Default query masking rules, matching lines would be replaced with something else in the logs
(both text logs and system.query_log).
name - name for the rule (optional) name - name for the rule (optional)
regexp - RE2 compatible regular expression (mandatory) regexp - RE2 compatible regular expression (mandatory)
replace - substitution string for sensitive data (optional, by default - six asterisks) replace - substitution string for sensitive data (optional, by default - six asterisks)
-->
<query_masking_rules> <query_masking_rules>
<rule> <rule>
<name>hide SSN</name> <name>hide encrypt/decrypt arguments</name>
<regexp>\b\d{3}-\d{2}-\d{4}\b</regexp> <regexp>((?:aes_)?(?:encrypt|decrypt)(?:_mysql)?)\s*\(\s*(?:'(?:\\'|.)+'|.*?)\s*\)</regexp>
<replace>000-00-0000</replace> <!-- or more secure, but also more invasive:
(aes_\w+)\s*\(.*\)
-->
<replace>\1(???)</replace>
</rule> </rule>
</query_masking_rules> </query_masking_rules>
-->
<!-- Uncomment to use custom http handlers. <!-- Uncomment to use custom http handlers.
rules are checked from top to bottom, first match runs the handler rules are checked from top to bottom, first match runs the handler

448
programs/server/play.html Normal file
View File

@ -0,0 +1,448 @@
<html> <!-- TODO If I write DOCTYPE HTML something changes but I don't know what. -->
<head>
<meta charset="UTF-8">
<title>ClickHouse Query</title>
<!-- Code style:
Do not use any JavaScript or CSS frameworks or preprocessors.
This HTML page should not require any build systems (node.js, npm, gulp, etc.)
This HTML page should not be minified, instead it should be reasonably minimalistic by itself.
This HTML page should not load any external resources
(CSS and JavaScript must be embedded directly to the page. No external fonts or images should be loaded).
This UI should look as lightweight, clean and fast as possible.
All UI elements must be aligned in pixel-perfect way.
There should not be any animations.
No unexpected changes in positions of elements while the page is loading.
Navigation by keyboard should work.
64-bit numbers must display correctly.
-->
<style type="text/css">
:root {
--background-color: #DDF8FF; /* Or #FFFBEF; actually many pastel colors look great for light theme. */
--element-background-color: #FFF;
--border-color: #EEE;
--shadow-color: rgba(0, 0, 0, 0.1);
--button-color: #FFAA00; /* Orange on light-cyan is especially good. */
--text-color: #000;
--button-active-color: #F00;
--button-active-text-color: #FFF;
--misc-text-color: #888;
--error-color: #FEE; /* Light-pink on light-cyan is so neat, I even want to trigger errors to see this cool combination of colors. */
--table-header-color: #F8F8F8;
--table-hover-color: #FFF8EF;
--null-color: #A88;
}
[data-theme="dark"] {
--background-color: #000;
--element-background-color: #102030;
--border-color: #111;
--shadow-color: rgba(255, 255, 255, 0.1);
--text-color: #CCC;
--button-color: #FFAA00;
--button-text-color: #000;
--button-active-color: #F00;
--button-active-text-color: #FFF;
--misc-text-color: #888;
--error-color: #400;
--table-header-color: #102020;
--table-hover-color: #003333;
--null-color: #A88;
}
html, body
{
/* Personal choice. */
font-family: Sans-Serif;
background: var(--background-color);
color: var(--text-color);
}
/* Otherwise Webkit based browsers will display ugly border on focus. */
textarea, input, button
{
outline: none;
border: none;
color: var(--text-color);
}
/* Otherwise scrollbar may appear dynamically and it will alter viewport height,
then relative heights of elements will change suddenly, and it will break overall impression. */
/* html
{
overflow-x: scroll;
}*/
div
{
width: 100%;
}
.monospace
{
/* Prefer fonts that have full hinting info. This is important for non-retina displays.
Also I personally dislike "Ubuntu" font due to the similarity of 'r' and 'г' (it looks very ignorant).
*/
font-family: Liberation Mono, DejaVu Sans Mono, MonoLisa, Consolas, Monospace;
}
.shadow
{
box-shadow: 0 0 1rem var(--shadow-color);
}
input, textarea
{
border: 1px solid var(--border-color);
/* The font must be not too small (to be inclusive) and not too large (it's less practical and make general feel of insecurity) */
font-size: 11pt;
padding: 0.25rem;
background-color: var(--element-background-color);
}
#query
{
/* Make enough space for even huge queries. */
height: 20%;
width: 100%;
}
#inputs
{
white-space: nowrap;
width: 100%;
}
#url
{
width: 70%;
}
#user
{
width: 15%;
}
#password
{
width: 15%;
}
#run_div
{
margin-top: 1rem;
}
#run
{
color: var(--button-text-color);
background-color: var(--button-color);
padding: 0.25rem 1rem;
cursor: pointer;
font-weight: bold;
font-size: 100%; /* Otherwise button element will have lower font size. */
}
#run:hover, #run:focus
{
color: var(--button-active-text-color);
background-color: var(--button-active-color);
}
#stats
{
float: right;
color: var(--misc-text-color);
}
#toggle-light, #toggle-dark
{
float: right;
padding-right: 0.5rem;
cursor: pointer;
}
.hint
{
color: var(--misc-text-color);
}
#data_div
{
margin-top: 1rem;
}
#data-table
{
border-collapse: collapse;
border-spacing: 0;
/* I need pixel-perfect alignment but not sure the following is correct, please help */
min-width: calc(100vw - 2rem);
}
/* Will be displayed when user specified custom format. */
#data-unparsed
{
background-color: var(--element-background-color);
margin-top: 0rem;
padding: 0.25rem 0.5rem;
display: none;
}
td
{
background-color: var(--element-background-color);
white-space: nowrap;
/* For wide tables any individual column will be no more than 50% of page width. */
max-width: 50vw;
/* The content is cut unless you hover. */
overflow: hidden;
padding: 0.25rem 0.5rem;
border: 1px solid var(--border-color);
white-space: pre;
}
td.right
{
text-align: right;
}
th
{
padding: 0.25rem 0.5rem;
text-align: middle;
background-color: var(--table-header-color);
border: 1px solid var(--border-color);
}
/* The row under mouse pointer is highlight for better legibility. */
tr:hover, tr:hover td
{
background-color: var(--table-hover-color);
}
tr:hover
{
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1);
}
#error
{
background: var(--error-color);
white-space: pre-wrap;
padding: 0.5rem 1rem;
display: none;
}
/* When mouse pointer is over table cell, will display full text (with wrap) instead of cut.
TODO Find a way to make it work on touch devices. */
td.left:hover
{
white-space: pre-wrap;
}
/* The style for SQL NULL */
.null
{
color: var(--null-color);
}
</style>
</head>
<body>
<div id="inputs">
<input class="monospace shadow" id="url" type="text" value="http://localhost:8123/" /><input class="monospace shadow" id="user" type="text" value="default" /><input class="monospace shadow" id="password" type="password" />
</div>
<div>
<textarea autofocus spellcheck="false" class="monospace shadow" id="query"></textarea>
</div>
<div id="run_div">
<button class="shadow" id="run">Run</button>
<span class="hint">&nbsp;(Ctrl+Enter)</span>
<span id="stats"></span>
<span id="toggle-dark">🌑</span><span id="toggle-light">🌞</span>
</div>
<div id="data_div">
<table class="monospace shadow" id="data-table"></table>
<pre class="monospace shadow" id="data-unparsed"></pre>
</div>
<p id="error" class="monospace shadow">
</p>
</body>
<script type="text/javascript">
/// Substitute the address of the server where the page is served.
if (location.protocol != 'file:') {
document.getElementById('url').value = location.origin;
}
function post()
{
/// TODO: Avoid race condition on subsequent requests when responses may come out of order.
/// TODO: Check if URL already contains query string (append parameters).
var url = document.getElementById('url').value +
/// Ask server to allow cross-domain requests.
'?add_http_cors_header=1' +
'&user=' + encodeURIComponent(document.getElementById('user').value) +
'&password=' + encodeURIComponent(document.getElementById('password').value) +
'&default_format=JSONCompact' +
/// Safety settings to prevent results that browser cannot display.
'&max_result_rows=1000&max_result_bytes=10000000&result_overflow_mode=break';
var query = document.getElementById('query').value;
var xhr = new XMLHttpRequest;
xhr.open('POST', url, true);
xhr.send(query);
xhr.onreadystatechange = function()
{
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
var json;
try { json = JSON.parse(this.response); } catch (e) {}
if (json !== undefined && json.statistics !== undefined) {
renderResult(json);
} else {
renderUnparsedResult(this.response);
}
} else {
/// TODO: Proper rendering of network errors.
renderError(this.response);
}
} else {
//console.log(this);
}
}
}
document.getElementById('run').onclick = function()
{
post();
}
document.getElementById('query').onkeypress = function(event)
{
/// Firefox has code 13 for Enter and Chromium has code 10.
if (event.ctrlKey && (event.charCode == 13 || event.charCode == 10)) {
post();
}
}
function clear()
{
var table = document.getElementById('data-table');
while (table.firstChild) {
table.removeChild(table.lastChild);
}
document.getElementById('data-unparsed').innerText = '';
document.getElementById('data-unparsed').style.display = 'none';
document.getElementById('error').innerText = '';
document.getElementById('error').style.display = 'none';
document.getElementById('stats').innerText = '';
}
function renderResult(response)
{
//console.log(response);
clear();
var stats = document.getElementById('stats');
stats.innerText = 'Elapsed: ' + response.statistics.elapsed.toFixed(3) + " sec, read " + response.statistics.rows_read + " rows.";
var thead = document.createElement('thead');
for (var idx in response.meta) {
var th = document.createElement('th');
var name = document.createTextNode(response.meta[idx].name);
th.appendChild(name);
thead.appendChild(th);
}
/// To prevent hanging the browser, limit the number of cells in a table.
/// It's important to have the limit on number of cells, not just rows, because tables may be wide or narrow.
var max_rows = 10000 / response.meta.length;
var row_num = 0;
var tbody = document.createElement('tbody');
for (var row_idx in response.data) {
var tr = document.createElement('tr');
for (var col_idx in response.data[row_idx]) {
var td = document.createElement('td');
var cell = response.data[row_idx][col_idx];
var is_null = (cell === null);
var content = document.createTextNode(is_null ? 'ᴺᵁᴸᴸ' : cell);
td.appendChild(content);
/// TODO: Execute regexp only once for each column.
td.className = response.meta[col_idx].type.match(/^(U?Int|Decimal|Float)/) ? 'right' : 'left';
if (is_null) {
td.className += ' null';
}
tr.appendChild(td);
}
tbody.appendChild(tr);
++row_num;
if (row_num >= max_rows) {
break;
}
}
var table = document.getElementById('data-table');
table.appendChild(thead);
table.appendChild(tbody);
}
/// A function to render raw data when non-default format is specified.
function renderUnparsedResult(response)
{
clear();
var data = document.getElementById('data-unparsed')
if (response === '') {
/// TODO: Fade or remove previous result when new request will be performed.
response = 'Ok.';
}
data.innerText = response;
/// inline-block make width adjust to the size of content.
data.style.display = 'inline-block';
}
function renderError(response)
{
clear();
document.getElementById('error').innerText = response;
document.getElementById('error').style.display = 'block';
}
function setColorTheme(theme)
{
window.localStorage.setItem('theme', theme);
document.documentElement.setAttribute('data-theme', theme);
}
/// The choice of color theme is saved in browser.
var theme = window.localStorage.getItem('theme');
if (theme) {
setColorTheme(theme);
}
document.getElementById('toggle-light').onclick = function()
{
setColorTheme('light');
}
document.getElementById('toggle-dark').onclick = function()
{
setColorTheme('dark');
}
</script>
</html>

View File

@ -3,6 +3,7 @@
#include <Access/MemoryAccessStorage.h> #include <Access/MemoryAccessStorage.h>
#include <Access/UsersConfigAccessStorage.h> #include <Access/UsersConfigAccessStorage.h>
#include <Access/DiskAccessStorage.h> #include <Access/DiskAccessStorage.h>
#include <Access/LDAPAccessStorage.h>
#include <Access/ContextAccess.h> #include <Access/ContextAccess.h>
#include <Access/RoleCache.h> #include <Access/RoleCache.h>
#include <Access/RowPolicyCache.h> #include <Access/RowPolicyCache.h>
@ -253,6 +254,12 @@ void AccessControlManager::addMemoryStorage(const String & storage_name_)
} }
void AccessControlManager::addLDAPStorage(const String & storage_name_, const Poco::Util::AbstractConfiguration & config_, const String & prefix_)
{
addStorage(std::make_shared<LDAPAccessStorage>(storage_name_, this, config_, prefix_));
}
void AccessControlManager::addStoragesFromUserDirectoriesConfig( void AccessControlManager::addStoragesFromUserDirectoriesConfig(
const Poco::Util::AbstractConfiguration & config, const Poco::Util::AbstractConfiguration & config,
const String & key, const String & key,
@ -275,6 +282,8 @@ void AccessControlManager::addStoragesFromUserDirectoriesConfig(
type = UsersConfigAccessStorage::STORAGE_TYPE; type = UsersConfigAccessStorage::STORAGE_TYPE;
else if ((type == "local") || (type == "local_directory")) else if ((type == "local") || (type == "local_directory"))
type = DiskAccessStorage::STORAGE_TYPE; type = DiskAccessStorage::STORAGE_TYPE;
else if (type == "ldap")
type = LDAPAccessStorage::STORAGE_TYPE;
String name = config.getString(prefix + ".name", type); String name = config.getString(prefix + ".name", type);
@ -295,6 +304,10 @@ void AccessControlManager::addStoragesFromUserDirectoriesConfig(
bool readonly = config.getBool(prefix + ".readonly", false); bool readonly = config.getBool(prefix + ".readonly", false);
addDiskStorage(name, path, readonly); addDiskStorage(name, path, readonly);
} }
else if (type == LDAPAccessStorage::STORAGE_TYPE)
{
addLDAPStorage(name, config, prefix);
}
else else
throw Exception("Unknown storage type '" + type + "' at " + prefix + " in config", ErrorCodes::UNKNOWN_ELEMENT_IN_CONFIG); throw Exception("Unknown storage type '" + type + "' at " + prefix + " in config", ErrorCodes::UNKNOWN_ELEMENT_IN_CONFIG);
} }
@ -346,7 +359,7 @@ UUID AccessControlManager::login(const String & user_name, const String & passwo
void AccessControlManager::setExternalAuthenticatorsConfig(const Poco::Util::AbstractConfiguration & config) void AccessControlManager::setExternalAuthenticatorsConfig(const Poco::Util::AbstractConfiguration & config)
{ {
external_authenticators->setConfig(config, getLogger()); external_authenticators->setConfiguration(config, getLogger());
} }

View File

@ -82,6 +82,9 @@ public:
void addMemoryStorage(); void addMemoryStorage();
void addMemoryStorage(const String & storage_name_); void addMemoryStorage(const String & storage_name_);
/// Adds LDAPAccessStorage which allows querying remote LDAP server for user info.
void addLDAPStorage(const String & storage_name_, const Poco::Util::AbstractConfiguration & config_, const String & prefix_);
/// Adds storages from <users_directories> config. /// Adds storages from <users_directories> config.
void addStoragesFromUserDirectoriesConfig(const Poco::Util::AbstractConfiguration & config, void addStoragesFromUserDirectoriesConfig(const Poco::Util::AbstractConfiguration & config,
const String & key, const String & key,

View File

@ -156,7 +156,7 @@ void ExternalAuthenticators::reset()
ldap_server_params.clear(); ldap_server_params.clear();
} }
void ExternalAuthenticators::setConfig(const Poco::Util::AbstractConfiguration & config, Poco::Logger * log) void ExternalAuthenticators::setConfiguration(const Poco::Util::AbstractConfiguration & config, Poco::Logger * log)
{ {
std::scoped_lock lock(mutex); std::scoped_lock lock(mutex);
reset(); reset();

View File

@ -26,7 +26,7 @@ class ExternalAuthenticators
{ {
public: public:
void reset(); void reset();
void setConfig(const Poco::Util::AbstractConfiguration & config, Poco::Logger * log); void setConfiguration(const Poco::Util::AbstractConfiguration & config, Poco::Logger * log);
void setLDAPServerParams(const String & server, const LDAPServerParams & params); void setLDAPServerParams(const String & server, const LDAPServerParams & params);
LDAPServerParams getLDAPServerParams(const String & server) const; LDAPServerParams getLDAPServerParams(const String & server) const;

View File

@ -14,6 +14,8 @@ namespace ErrorCodes
extern const int ACCESS_ENTITY_ALREADY_EXISTS; extern const int ACCESS_ENTITY_ALREADY_EXISTS;
extern const int ACCESS_ENTITY_NOT_FOUND; extern const int ACCESS_ENTITY_NOT_FOUND;
extern const int ACCESS_STORAGE_READONLY; extern const int ACCESS_STORAGE_READONLY;
extern const int WRONG_PASSWORD;
extern const int IP_ADDRESS_NOT_ALLOWED;
extern const int AUTHENTICATION_FAILED; extern const int AUTHENTICATION_FAILED;
extern const int LOGICAL_ERROR; extern const int LOGICAL_ERROR;
} }
@ -418,9 +420,21 @@ UUID IAccessStorage::login(
const String & user_name, const String & user_name,
const String & password, const String & password,
const Poco::Net::IPAddress & address, const Poco::Net::IPAddress & address,
const ExternalAuthenticators & external_authenticators) const const ExternalAuthenticators & external_authenticators,
bool replace_exception_with_cannot_authenticate) const
{ {
return loginImpl(user_name, password, address, external_authenticators); try
{
return loginImpl(user_name, password, address, external_authenticators);
}
catch (...)
{
if (!replace_exception_with_cannot_authenticate)
throw;
tryLogCurrentException(getLogger(), user_name + ": Authentication failed");
throwCannotAuthenticate(user_name);
}
} }
@ -434,11 +448,16 @@ UUID IAccessStorage::loginImpl(
{ {
if (auto user = tryRead<User>(*id)) if (auto user = tryRead<User>(*id))
{ {
if (isPasswordCorrectImpl(*user, password, external_authenticators) && isAddressAllowedImpl(*user, address)) if (!isPasswordCorrectImpl(*user, password, external_authenticators))
return *id; throwInvalidPassword();
if (!isAddressAllowedImpl(*user, address))
throwAddressNotAllowed(address);
return *id;
} }
} }
throwCannotAuthenticate(user_name); throwNotFound(EntityType::USER, user_name);
} }
@ -554,6 +573,15 @@ void IAccessStorage::throwReadonlyCannotRemove(EntityType type, const String & n
ErrorCodes::ACCESS_STORAGE_READONLY); ErrorCodes::ACCESS_STORAGE_READONLY);
} }
void IAccessStorage::throwAddressNotAllowed(const Poco::Net::IPAddress & address)
{
throw Exception("Connections from " + address.toString() + " are not allowed", ErrorCodes::IP_ADDRESS_NOT_ALLOWED);
}
void IAccessStorage::throwInvalidPassword()
{
throw Exception("Invalid password", ErrorCodes::WRONG_PASSWORD);
}
void IAccessStorage::throwCannotAuthenticate(const String & user_name) void IAccessStorage::throwCannotAuthenticate(const String & user_name)
{ {

View File

@ -144,7 +144,7 @@ public:
/// Finds an user, check its password and returns the ID of the user. /// Finds an user, check its password and returns the ID of the user.
/// Throws an exception if no such user or password is incorrect. /// Throws an exception if no such user or password is incorrect.
UUID login(const String & user_name, const String & password, const Poco::Net::IPAddress & address, const ExternalAuthenticators & external_authenticators) const; UUID login(const String & user_name, const String & password, const Poco::Net::IPAddress & address, const ExternalAuthenticators & external_authenticators, bool replace_exception_with_cannot_authenticate = true) const;
/// Returns the ID of an user who has logged in (maybe on another node). /// Returns the ID of an user who has logged in (maybe on another node).
/// The function assumes that the password has been already checked somehow, so we can skip checking it now. /// The function assumes that the password has been already checked somehow, so we can skip checking it now.
@ -182,6 +182,8 @@ protected:
[[noreturn]] void throwReadonlyCannotInsert(EntityType type, const String & name) const; [[noreturn]] void throwReadonlyCannotInsert(EntityType type, const String & name) const;
[[noreturn]] void throwReadonlyCannotUpdate(EntityType type, const String & name) const; [[noreturn]] void throwReadonlyCannotUpdate(EntityType type, const String & name) const;
[[noreturn]] void throwReadonlyCannotRemove(EntityType type, const String & name) const; [[noreturn]] void throwReadonlyCannotRemove(EntityType type, const String & name) const;
[[noreturn]] static void throwAddressNotAllowed(const Poco::Net::IPAddress & address);
[[noreturn]] static void throwInvalidPassword();
[[noreturn]] static void throwCannotAuthenticate(const String & user_name); [[noreturn]] static void throwCannotAuthenticate(const String & user_name);
using Notification = std::tuple<OnChangedHandler, UUID, AccessEntityPtr>; using Notification = std::tuple<OnChangedHandler, UUID, AccessEntityPtr>;

View File

@ -0,0 +1,313 @@
#include <Access/LDAPAccessStorage.h>
#include <Access/AccessControlManager.h>
#include <Access/User.h>
#include <Access/Role.h>
#include <Common/Exception.h>
#include <common/logger_useful.h>
#include <ext/scope_guard.h>
#include <Poco/Util/AbstractConfiguration.h>
#include <Poco/JSON/JSON.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Stringifier.h>
#include <boost/range/algorithm/copy.hpp>
#include <iterator>
#include <sstream>
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
}
LDAPAccessStorage::LDAPAccessStorage(const String & storage_name_, AccessControlManager * access_control_manager_, const Poco::Util::AbstractConfiguration & config, const String & prefix)
: IAccessStorage(storage_name_)
{
setConfiguration(access_control_manager_, config, prefix);
}
void LDAPAccessStorage::setConfiguration(AccessControlManager * access_control_manager_, const Poco::Util::AbstractConfiguration & config, const String & prefix)
{
std::scoped_lock lock(mutex);
// TODO: switch to passing config as a ConfigurationView and remove this extra prefix once a version of Poco with proper implementation is available.
const String prefix_str = (prefix.empty() ? "" : prefix + ".");
const bool has_server = config.has(prefix_str + "server");
const bool has_roles = config.has(prefix_str + "roles");
if (!has_server)
throw Exception("Missing 'server' field for LDAP user directory.", ErrorCodes::BAD_ARGUMENTS);
const auto ldap_server_cfg = config.getString(prefix_str + "server");
if (ldap_server_cfg.empty())
throw Exception("Empty 'server' field for LDAP user directory.", ErrorCodes::BAD_ARGUMENTS);
std::set<String> roles_cfg;
if (has_roles)
{
Poco::Util::AbstractConfiguration::Keys role_names;
config.keys(prefix_str + "roles", role_names);
// Currently, we only extract names of roles from the section names and assign them directly and unconditionally.
roles_cfg.insert(role_names.begin(), role_names.end());
}
access_control_manager = access_control_manager_;
ldap_server = ldap_server_cfg;
default_role_names.swap(roles_cfg);
roles_of_interest.clear();
role_change_subscription = access_control_manager->subscribeForChanges<Role>(
[this] (const UUID & id, const AccessEntityPtr & entity)
{
return this->processRoleChange(id, entity);
}
);
/// Update `roles_of_interests` with initial values.
for (const auto & role_name : default_role_names)
{
if (auto role_id = access_control_manager->find<Role>(role_name))
roles_of_interest.emplace(*role_id, role_name);
}
}
void LDAPAccessStorage::processRoleChange(const UUID & id, const AccessEntityPtr & entity)
{
std::scoped_lock lock(mutex);
/// Update `roles_of_interests`.
auto role = typeid_cast<std::shared_ptr<const Role>>(entity);
bool need_to_update_users = false;
if (role && default_role_names.count(role->getName()))
{
/// If a role was created with one of the `default_role_names` or renamed to one of the `default_role_names`,
/// then set `need_to_update_users`.
need_to_update_users = roles_of_interest.insert_or_assign(id, role->getName()).second;
}
else
{
/// If a role was removed or renamed to a name which isn't contained in the `default_role_names`,
/// then set `need_to_update_users`.
need_to_update_users = roles_of_interest.erase(id) > 0;
}
/// Update users which have been created.
if (need_to_update_users)
{
auto update_func = [this] (const AccessEntityPtr & entity_) -> AccessEntityPtr
{
if (auto user = typeid_cast<std::shared_ptr<const User>>(entity_))
{
auto changed_user = typeid_cast<std::shared_ptr<User>>(user->clone());
auto & granted_roles = changed_user->granted_roles.roles;
granted_roles.clear();
boost::range::copy(roles_of_interest | boost::adaptors::map_keys, std::inserter(granted_roles, granted_roles.end()));
return changed_user;
}
return entity_;
};
memory_storage.update(memory_storage.findAll<User>(), update_func);
}
}
void LDAPAccessStorage::checkAllDefaultRoleNamesFoundNoLock() const
{
boost::container::flat_set<std::string_view> role_names_of_interest;
boost::range::copy(roles_of_interest | boost::adaptors::map_values, std::inserter(role_names_of_interest, role_names_of_interest.end()));
for (const auto & role_name : default_role_names)
{
if (!role_names_of_interest.count(role_name))
throwDefaultRoleNotFound(role_name);
}
}
const char * LDAPAccessStorage::getStorageType() const
{
return STORAGE_TYPE;
}
String LDAPAccessStorage::getStorageParamsJSON() const
{
std::scoped_lock lock(mutex);
Poco::JSON::Object params_json;
params_json.set("server", ldap_server);
params_json.set("roles", default_role_names);
std::ostringstream oss;
Poco::JSON::Stringifier::stringify(params_json, oss);
return oss.str();
}
std::optional<UUID> LDAPAccessStorage::findImpl(EntityType type, const String & name) const
{
std::scoped_lock lock(mutex);
return memory_storage.find(type, name);
}
std::vector<UUID> LDAPAccessStorage::findAllImpl(EntityType type) const
{
std::scoped_lock lock(mutex);
return memory_storage.findAll(type);
}
bool LDAPAccessStorage::existsImpl(const UUID & id) const
{
std::scoped_lock lock(mutex);
return memory_storage.exists(id);
}
AccessEntityPtr LDAPAccessStorage::readImpl(const UUID & id) const
{
std::scoped_lock lock(mutex);
return memory_storage.read(id);
}
String LDAPAccessStorage::readNameImpl(const UUID & id) const
{
std::scoped_lock lock(mutex);
return memory_storage.readName(id);
}
bool LDAPAccessStorage::canInsertImpl(const AccessEntityPtr &) const
{
return false;
}
UUID LDAPAccessStorage::insertImpl(const AccessEntityPtr & entity, bool)
{
throwReadonlyCannotInsert(entity->getType(), entity->getName());
}
void LDAPAccessStorage::removeImpl(const UUID & id)
{
std::scoped_lock lock(mutex);
auto entity = read(id);
throwReadonlyCannotRemove(entity->getType(), entity->getName());
}
void LDAPAccessStorage::updateImpl(const UUID & id, const UpdateFunc &)
{
std::scoped_lock lock(mutex);
auto entity = read(id);
throwReadonlyCannotUpdate(entity->getType(), entity->getName());
}
ext::scope_guard LDAPAccessStorage::subscribeForChangesImpl(const UUID & id, const OnChangedHandler & handler) const
{
std::scoped_lock lock(mutex);
return memory_storage.subscribeForChanges(id, handler);
}
ext::scope_guard LDAPAccessStorage::subscribeForChangesImpl(EntityType type, const OnChangedHandler & handler) const
{
std::scoped_lock lock(mutex);
return memory_storage.subscribeForChanges(type, handler);
}
bool LDAPAccessStorage::hasSubscriptionImpl(const UUID & id) const
{
std::scoped_lock lock(mutex);
return memory_storage.hasSubscription(id);
}
bool LDAPAccessStorage::hasSubscriptionImpl(EntityType type) const
{
std::scoped_lock lock(mutex);
return memory_storage.hasSubscription(type);
}
UUID LDAPAccessStorage::loginImpl(const String & user_name, const String & password, const Poco::Net::IPAddress & address, const ExternalAuthenticators & external_authenticators) const
{
std::scoped_lock lock(mutex);
auto id = memory_storage.find<User>(user_name);
if (id)
{
auto user = memory_storage.read<User>(*id);
if (!isPasswordCorrectImpl(*user, password, external_authenticators))
throwInvalidPassword();
if (!isAddressAllowedImpl(*user, address))
throwAddressNotAllowed(address);
return *id;
}
else
{
// User does not exist, so we create one, and will add it if authentication is successful.
auto user = std::make_shared<User>();
user->setName(user_name);
user->authentication = Authentication(Authentication::Type::LDAP_SERVER);
user->authentication.setServerName(ldap_server);
if (!isPasswordCorrectImpl(*user, password, external_authenticators))
throwInvalidPassword();
if (!isAddressAllowedImpl(*user, address))
throwAddressNotAllowed(address);
checkAllDefaultRoleNamesFoundNoLock();
auto & granted_roles = user->granted_roles.roles;
boost::range::copy(roles_of_interest | boost::adaptors::map_keys, std::inserter(granted_roles, granted_roles.end()));
return memory_storage.insert(user);
}
}
UUID LDAPAccessStorage::getIDOfLoggedUserImpl(const String & user_name) const
{
std::scoped_lock lock(mutex);
auto id = memory_storage.find<User>(user_name);
if (id)
{
return *id;
}
else
{
// User does not exist, so we create one, and add it pretending that the authentication is successful.
auto user = std::make_shared<User>();
user->setName(user_name);
user->authentication = Authentication(Authentication::Type::LDAP_SERVER);
user->authentication.setServerName(ldap_server);
checkAllDefaultRoleNamesFoundNoLock();
auto & granted_roles = user->granted_roles.roles;
boost::range::copy(roles_of_interest | boost::adaptors::map_keys, std::inserter(granted_roles, granted_roles.end()));
return memory_storage.insert(user);
}
}
void LDAPAccessStorage::throwDefaultRoleNotFound(const String & role_name)
{
throw Exception("One of the default roles, the role '" + role_name + "', is not found", IAccessEntity::TypeInfo::get(IAccessEntity::Type::ROLE).not_found_error_code);
}
}

View File

@ -0,0 +1,71 @@
#pragma once
#include <Access/MemoryAccessStorage.h>
#include <Core/Types.h>
#include <ext/scope_guard.h>
#include <map>
#include <mutex>
#include <set>
namespace Poco
{
namespace Util
{
class AbstractConfiguration;
}
}
namespace DB
{
class AccessControlManager;
/// Implementation of IAccessStorage which allows attaching users from a remote LDAP server.
/// Currently, any user name will be treated as a name of an existing remote user,
/// a user info entity will be created, with LDAP_SERVER authentication type.
class LDAPAccessStorage : public IAccessStorage
{
public:
static constexpr char STORAGE_TYPE[] = "ldap";
explicit LDAPAccessStorage(const String & storage_name_, AccessControlManager * access_control_manager_, const Poco::Util::AbstractConfiguration & config, const String & prefix);
virtual ~LDAPAccessStorage() override = default;
public: // IAccessStorage implementations.
virtual const char * getStorageType() const override;
virtual String getStorageParamsJSON() const override;
private: // IAccessStorage implementations.
virtual std::optional<UUID> findImpl(EntityType type, const String & name) const override;
virtual std::vector<UUID> findAllImpl(EntityType type) const override;
virtual bool existsImpl(const UUID & id) const override;
virtual AccessEntityPtr readImpl(const UUID & id) const override;
virtual String readNameImpl(const UUID & id) const override;
virtual bool canInsertImpl(const AccessEntityPtr &) const override;
virtual UUID insertImpl(const AccessEntityPtr & entity, bool replace_if_exists) override;
virtual void removeImpl(const UUID & id) override;
virtual void updateImpl(const UUID & id, const UpdateFunc & update_func) override;
virtual ext::scope_guard subscribeForChangesImpl(const UUID & id, const OnChangedHandler & handler) const override;
virtual ext::scope_guard subscribeForChangesImpl(EntityType type, const OnChangedHandler & handler) const override;
virtual bool hasSubscriptionImpl(const UUID & id) const override;
virtual bool hasSubscriptionImpl(EntityType type) const override;
virtual UUID loginImpl(const String & user_name, const String & password, const Poco::Net::IPAddress & address, const ExternalAuthenticators & external_authenticators) const override;
virtual UUID getIDOfLoggedUserImpl(const String & user_name) const override;
private:
void setConfiguration(AccessControlManager * access_control_manager_, const Poco::Util::AbstractConfiguration & config, const String & prefix);
void processRoleChange(const UUID & id, const AccessEntityPtr & entity);
void checkAllDefaultRoleNamesFoundNoLock() const;
[[noreturn]] static void throwDefaultRoleNotFound(const String & role_name);
mutable std::recursive_mutex mutex;
AccessControlManager * access_control_manager = nullptr;
String ldap_server;
std::set<String> default_role_names;
std::map<UUID, String> roles_of_interest;
ext::scope_guard role_change_subscription;
mutable MemoryAccessStorage memory_storage;
};
}

View File

@ -2,6 +2,8 @@
#include <Common/Exception.h> #include <Common/Exception.h>
#include <ext/scope_guard.h> #include <ext/scope_guard.h>
#include <mutex>
#include <cstring> #include <cstring>
#include <sys/time.h> #include <sys/time.h>
@ -27,16 +29,13 @@ LDAPClient::~LDAPClient()
closeConnection(); closeConnection();
} }
void LDAPClient::openConnection()
{
const bool graceful_bind_failure = false;
diag(openConnection(graceful_bind_failure));
}
#if USE_LDAP #if USE_LDAP
namespace namespace
{ {
std::recursive_mutex ldap_global_mutex;
auto escapeForLDAP(const String & src) auto escapeForLDAP(const String & src)
{ {
String dest; String dest;
@ -63,10 +62,13 @@ namespace
return dest; return dest;
} }
} }
void LDAPClient::diag(const int rc) void LDAPClient::diag(const int rc)
{ {
std::scoped_lock lock(ldap_global_mutex);
if (rc != LDAP_SUCCESS) if (rc != LDAP_SUCCESS)
{ {
String text; String text;
@ -100,8 +102,10 @@ void LDAPClient::diag(const int rc)
} }
} }
int LDAPClient::openConnection(const bool graceful_bind_failure) void LDAPClient::openConnection()
{ {
std::scoped_lock lock(ldap_global_mutex);
closeConnection(); closeConnection();
{ {
@ -232,8 +236,6 @@ int LDAPClient::openConnection(const bool graceful_bind_failure)
if (params.enable_tls == LDAPServerParams::TLSEnable::YES_STARTTLS) if (params.enable_tls == LDAPServerParams::TLSEnable::YES_STARTTLS)
diag(ldap_start_tls_s(handle, nullptr, nullptr)); diag(ldap_start_tls_s(handle, nullptr, nullptr));
int rc = LDAP_OTHER;
switch (params.sasl_mechanism) switch (params.sasl_mechanism)
{ {
case LDAPServerParams::SASLMechanism::SIMPLE: case LDAPServerParams::SASLMechanism::SIMPLE:
@ -244,20 +246,21 @@ int LDAPClient::openConnection(const bool graceful_bind_failure)
cred.bv_val = const_cast<char *>(params.password.c_str()); cred.bv_val = const_cast<char *>(params.password.c_str());
cred.bv_len = params.password.size(); cred.bv_len = params.password.size();
rc = ldap_sasl_bind_s(handle, dn.c_str(), LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr); diag(ldap_sasl_bind_s(handle, dn.c_str(), LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr));
if (!graceful_bind_failure)
diag(rc);
break; break;
} }
default:
{
throw Exception("Unknown SASL mechanism", ErrorCodes::LDAP_ERROR);
}
} }
return rc;
} }
void LDAPClient::closeConnection() noexcept void LDAPClient::closeConnection() noexcept
{ {
std::scoped_lock lock(ldap_global_mutex);
if (!handle) if (!handle)
return; return;
@ -267,42 +270,21 @@ void LDAPClient::closeConnection() noexcept
bool LDAPSimpleAuthClient::check() bool LDAPSimpleAuthClient::check()
{ {
if (params.user.empty()) std::scoped_lock lock(ldap_global_mutex);
throw Exception("LDAP authentication of a user with an empty name is not allowed", ErrorCodes::BAD_ARGUMENTS);
if (params.user.empty())
throw Exception("LDAP authentication of a user with empty name is not allowed", ErrorCodes::BAD_ARGUMENTS);
// Silently reject authentication attempt if the password is empty as if it didn't match.
if (params.password.empty()) if (params.password.empty())
return false; // Silently reject authentication attempt if the password is empty as if it didn't match. return false;
SCOPE_EXIT({ closeConnection(); }); SCOPE_EXIT({ closeConnection(); });
const bool graceful_bind_failure = true; // Will throw on any error, including invalid credentials.
const auto rc = openConnection(graceful_bind_failure); openConnection();
bool result = false; return true;
switch (rc)
{
case LDAP_SUCCESS:
{
result = true;
break;
}
case LDAP_INVALID_CREDENTIALS:
{
result = false;
break;
}
default:
{
result = false;
diag(rc);
break;
}
}
return result;
} }
#else // USE_LDAP #else // USE_LDAP
@ -312,7 +294,7 @@ void LDAPClient::diag(const int)
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);
} }
int LDAPClient::openConnection(const bool) void LDAPClient::openConnection()
{ {
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

@ -32,7 +32,6 @@ public:
protected: protected:
MAYBE_NORETURN void diag(const int rc); MAYBE_NORETURN void diag(const int rc);
MAYBE_NORETURN void openConnection(); MAYBE_NORETURN void openConnection();
int openConnection(const bool graceful_bind_failure = false);
void closeConnection() noexcept; void closeConnection() noexcept;
protected: protected:

View File

@ -42,6 +42,7 @@ struct LDAPServerParams
enum class SASLMechanism enum class SASLMechanism
{ {
UNKNOWN,
SIMPLE SIMPLE
}; };

View File

@ -69,7 +69,7 @@ UUID MemoryAccessStorage::insertImpl(const AccessEntityPtr & new_entity, bool re
UUID id = generateRandomID(); UUID id = generateRandomID();
std::lock_guard lock{mutex}; std::lock_guard lock{mutex};
insertNoLock(generateRandomID(), new_entity, replace_if_exists, notifications); insertNoLock(id, new_entity, replace_if_exists, notifications);
return id; return id;
} }

View File

@ -2,6 +2,7 @@
#include <Common/Exception.h> #include <Common/Exception.h>
#include <ext/range.h> #include <ext/range.h>
#include <boost/range/adaptor/map.hpp> #include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/find.hpp> #include <boost/range/algorithm/find.hpp>
@ -27,6 +28,15 @@ MultipleAccessStorage::MultipleAccessStorage(const String & storage_name_)
{ {
} }
MultipleAccessStorage::~MultipleAccessStorage()
{
/// It's better to remove the storages in the reverse order because they could depend on each other somehow.
const auto storages = getStoragesPtr();
for (const auto & storage : *storages | boost::adaptors::reversed)
{
removeStorage(storage);
}
}
void MultipleAccessStorage::setStorages(const std::vector<StoragePtr> & storages) void MultipleAccessStorage::setStorages(const std::vector<StoragePtr> & storages)
{ {
@ -400,7 +410,7 @@ UUID MultipleAccessStorage::loginImpl(const String & user_name, const String & p
{ {
try try
{ {
auto id = storage->login(user_name, password, address, external_authenticators); auto id = storage->login(user_name, password, address, external_authenticators, /* replace_exception_with_cannot_authenticate = */ false);
std::lock_guard lock{mutex}; std::lock_guard lock{mutex};
ids_cache.set(id, storage); ids_cache.set(id, storage);
return id; return id;
@ -416,7 +426,7 @@ UUID MultipleAccessStorage::loginImpl(const String & user_name, const String & p
throw; throw;
} }
} }
throwCannotAuthenticate(user_name); throwNotFound(EntityType::USER, user_name);
} }

View File

@ -18,6 +18,7 @@ public:
using ConstStoragePtr = std::shared_ptr<const Storage>; using ConstStoragePtr = std::shared_ptr<const Storage>;
MultipleAccessStorage(const String & storage_name_ = STORAGE_TYPE); MultipleAccessStorage(const String & storage_name_ = STORAGE_TYPE);
~MultipleAccessStorage() override;
const char * getStorageType() const override { return STORAGE_TYPE; } const char * getStorageType() const override { return STORAGE_TYPE; }

View File

@ -24,6 +24,7 @@ SRCS(
GrantedRoles.cpp GrantedRoles.cpp
IAccessEntity.cpp IAccessEntity.cpp
IAccessStorage.cpp IAccessStorage.cpp
LDAPAccessStorage.cpp
LDAPClient.cpp LDAPClient.cpp
MemoryAccessStorage.cpp MemoryAccessStorage.cpp
MultipleAccessStorage.cpp MultipleAccessStorage.cpp

View File

@ -143,13 +143,12 @@ void LinearModelData::updateState()
void LinearModelData::predict( void LinearModelData::predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const Context & context) const const Context & context) const
{ {
gradient_computer->predict(container, columns, offset, limit, arguments, weights, bias, context); gradient_computer->predict(container, arguments, offset, limit, weights, bias, context);
} }
void LinearModelData::returnWeights(IColumn & to) const void LinearModelData::returnWeights(IColumn & to) const
@ -449,15 +448,14 @@ void IWeightsUpdater::addToBatch(
void LogisticRegression::predict( void LogisticRegression::predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const std::vector<Float64> & weights, const std::vector<Float64> & weights,
Float64 bias, Float64 bias,
const Context & /*context*/) const const Context & /*context*/) const
{ {
size_t rows_num = columns[arguments.front()].column->size(); size_t rows_num = arguments.front().column->size();
if (offset > rows_num || offset + limit > rows_num) if (offset > rows_num || offset + limit > rows_num)
throw Exception("Invalid offset and limit for LogisticRegression::predict. " throw Exception("Invalid offset and limit for LogisticRegression::predict. "
@ -468,7 +466,7 @@ void LogisticRegression::predict(
for (size_t i = 1; i < arguments.size(); ++i) for (size_t i = 1; i < arguments.size(); ++i)
{ {
const ColumnWithTypeAndName & cur_col = columns[arguments[i]]; const ColumnWithTypeAndName & cur_col = arguments[i];
if (!isNativeNumber(cur_col.type)) if (!isNativeNumber(cur_col.type))
throw Exception("Prediction arguments must have numeric type", ErrorCodes::BAD_ARGUMENTS); throw Exception("Prediction arguments must have numeric type", ErrorCodes::BAD_ARGUMENTS);
@ -518,10 +516,9 @@ void LogisticRegression::compute(
void LinearRegression::predict( void LinearRegression::predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const std::vector<Float64> & weights, const std::vector<Float64> & weights,
Float64 bias, Float64 bias,
const Context & /*context*/) const const Context & /*context*/) const
@ -531,7 +528,7 @@ void LinearRegression::predict(
throw Exception("In predict function number of arguments differs from the size of weights vector", ErrorCodes::LOGICAL_ERROR); throw Exception("In predict function number of arguments differs from the size of weights vector", ErrorCodes::LOGICAL_ERROR);
} }
size_t rows_num = columns[arguments.front()].column->size(); size_t rows_num = arguments.front().column->size();
if (offset > rows_num || offset + limit > rows_num) if (offset > rows_num || offset + limit > rows_num)
throw Exception("Invalid offset and limit for LogisticRegression::predict. " throw Exception("Invalid offset and limit for LogisticRegression::predict. "
@ -542,7 +539,7 @@ void LinearRegression::predict(
for (size_t i = 1; i < arguments.size(); ++i) for (size_t i = 1; i < arguments.size(); ++i)
{ {
const ColumnWithTypeAndName & cur_col = columns[arguments[i]]; const ColumnWithTypeAndName & cur_col = arguments[i];
if (!isNativeNumber(cur_col.type)) if (!isNativeNumber(cur_col.type))
throw Exception("Prediction arguments must have numeric type", ErrorCodes::BAD_ARGUMENTS); throw Exception("Prediction arguments must have numeric type", ErrorCodes::BAD_ARGUMENTS);

View File

@ -39,10 +39,9 @@ public:
virtual void predict( virtual void predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const std::vector<Float64> & weights, const std::vector<Float64> & weights,
Float64 bias, Float64 bias,
const Context & context) const = 0; const Context & context) const = 0;
@ -65,10 +64,9 @@ public:
void predict( void predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const std::vector<Float64> & weights, const std::vector<Float64> & weights,
Float64 bias, Float64 bias,
const Context & context) const override; const Context & context) const override;
@ -91,10 +89,9 @@ public:
void predict( void predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const std::vector<Float64> & weights, const std::vector<Float64> & weights,
Float64 bias, Float64 bias,
const Context & context) const override; const Context & context) const override;
@ -264,10 +261,9 @@ public:
void predict( void predict(
ColumnVector<Float64>::Container & container, ColumnVector<Float64>::Container & container,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const Context & context) const; const Context & context) const;
void returnWeights(IColumn & to) const; void returnWeights(IColumn & to) const;
@ -364,10 +360,9 @@ public:
void predictValues( void predictValues(
ConstAggregateDataPtr place, ConstAggregateDataPtr place,
IColumn & to, IColumn & to,
ColumnsWithTypeAndName & columns, ColumnsWithTypeAndName & arguments,
size_t offset, size_t offset,
size_t limit, size_t limit,
const ColumnNumbers & arguments,
const Context & context) const override const Context & context) const override
{ {
if (arguments.size() != param_num + 1) if (arguments.size() != param_num + 1)
@ -382,7 +377,7 @@ public:
throw Exception("Cast of column of predictions is incorrect. getReturnTypeToPredict must return same value as it is casted to", throw Exception("Cast of column of predictions is incorrect. getReturnTypeToPredict must return same value as it is casted to",
ErrorCodes::LOGICAL_ERROR); ErrorCodes::LOGICAL_ERROR);
this->data(place).predict(column->getData(), columns, offset, limit, arguments, context); this->data(place).predict(column->getData(), arguments, offset, limit, context);
} }
/** This function is called if aggregate function without State modifier is selected in a query. /** This function is called if aggregate function without State modifier is selected in a query.

View File

@ -21,10 +21,6 @@
#include <type_traits> #include <type_traits>
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
}
namespace DB namespace DB
{ {
@ -138,23 +134,18 @@ public:
const auto & value = this->data(place).values; const auto & value = this->data(place).values;
size_t size = this->data(place).size_x; size_t size = this->data(place).size_x;
if (size < 2) // create a copy of values not to format data
{
throw Exception("Aggregate function " + getName() + " requires samples to be of size > 1", ErrorCodes::BAD_ARGUMENTS);
}
//create a copy of values not to format data
PODArrayWithStackMemory<std::pair<Float64, Float64>, 32> tmp_values; PODArrayWithStackMemory<std::pair<Float64, Float64>, 32> tmp_values;
tmp_values.resize(size); tmp_values.resize(size);
for (size_t j = 0; j < size; ++ j) for (size_t j = 0; j < size; ++ j)
tmp_values[j] = static_cast<std::pair<Float64, Float64>>(value[j]); tmp_values[j] = static_cast<std::pair<Float64, Float64>>(value[j]);
//sort x_values // sort x_values
std::sort(std::begin(tmp_values), std::end(tmp_values), ComparePairFirst<std::greater>{}); std::sort(std::begin(tmp_values), std::end(tmp_values), ComparePairFirst<std::greater>{});
for (size_t j = 0; j < size;) for (size_t j = 0; j < size;)
{ {
//replace x_values with their ranks // replace x_values with their ranks
size_t rank = j + 1; size_t rank = j + 1;
size_t same = 1; size_t same = 1;
size_t cur_sum = rank; size_t cur_sum = rank;
@ -166,9 +157,9 @@ public:
{ {
// rank of (j + 1)th number // rank of (j + 1)th number
rank += 1; rank += 1;
same++; ++same;
cur_sum += rank; cur_sum += rank;
j++; ++j;
} }
else else
break; break;
@ -178,16 +169,16 @@ public:
Float64 insert_rank = static_cast<Float64>(cur_sum) / same; Float64 insert_rank = static_cast<Float64>(cur_sum) / same;
for (size_t i = cur_start; i <= j; ++i) for (size_t i = cur_start; i <= j; ++i)
tmp_values[i].first = insert_rank; tmp_values[i].first = insert_rank;
j++; ++j;
} }
//sort y_values // sort y_values
std::sort(std::begin(tmp_values), std::end(tmp_values), ComparePairSecond<std::greater>{}); std::sort(std::begin(tmp_values), std::end(tmp_values), ComparePairSecond<std::greater>{});
//replace y_values with their ranks // replace y_values with their ranks
for (size_t j = 0; j < size;) for (size_t j = 0; j < size;)
{ {
//replace x_values with their ranks // replace x_values with their ranks
size_t rank = j + 1; size_t rank = j + 1;
size_t same = 1; size_t same = 1;
size_t cur_sum = rank; size_t cur_sum = rank;
@ -199,9 +190,9 @@ public:
{ {
// rank of (j + 1)th number // rank of (j + 1)th number
rank += 1; rank += 1;
same++; ++same;
cur_sum += rank; cur_sum += rank;
j++; ++j;
} }
else else
{ {
@ -213,10 +204,10 @@ public:
Float64 insert_rank = static_cast<Float64>(cur_sum) / same; Float64 insert_rank = static_cast<Float64>(cur_sum) / same;
for (size_t i = cur_start; i <= j; ++i) for (size_t i = cur_start; i <= j; ++i)
tmp_values[i].second = insert_rank; tmp_values[i].second = insert_rank;
j++; ++j;
} }
//count d^2 sum // count d^2 sum
Float64 answer = static_cast<Float64>(0); Float64 answer = static_cast<Float64>(0);
for (size_t j = 0; j < size; ++ j) for (size_t j = 0; j < size; ++ j)
answer += (tmp_values[j].first - tmp_values[j].second) * (tmp_values[j].first - tmp_values[j].second); answer += (tmp_values[j].first - tmp_values[j].second) * (tmp_values[j].first - tmp_values[j].second);

View File

@ -114,10 +114,9 @@ public:
virtual void predictValues( virtual void predictValues(
ConstAggregateDataPtr /* place */, ConstAggregateDataPtr /* place */,
IColumn & /*to*/, IColumn & /*to*/,
ColumnsWithTypeAndName & /*block*/, ColumnsWithTypeAndName & /*arguments*/,
size_t /*offset*/, size_t /*offset*/,
size_t /*limit*/, size_t /*limit*/,
const ColumnNumbers & /*arguments*/,
const Context & /*context*/) const const Context & /*context*/) const
{ {
throw Exception("Method predictValues is not supported for " + getName(), ErrorCodes::NOT_IMPLEMENTED); throw Exception("Method predictValues is not supported for " + getName(), ErrorCodes::NOT_IMPLEMENTED);

View File

@ -161,7 +161,7 @@ MutableColumnPtr ColumnAggregateFunction::convertToValues(MutableColumnPtr colum
return res; return res;
} }
MutableColumnPtr ColumnAggregateFunction::predictValues(ColumnsWithTypeAndName & block, const ColumnNumbers & arguments, const Context & context) const MutableColumnPtr ColumnAggregateFunction::predictValues(ColumnsWithTypeAndName & arguments, const Context & context) const
{ {
MutableColumnPtr res = func->getReturnTypeToPredict()->createColumn(); MutableColumnPtr res = func->getReturnTypeToPredict()->createColumn();
res->reserve(data.size()); res->reserve(data.size());
@ -172,7 +172,7 @@ MutableColumnPtr ColumnAggregateFunction::predictValues(ColumnsWithTypeAndName &
if (data.size() == 1) if (data.size() == 1)
{ {
/// Case for const column. Predict using single model. /// Case for const column. Predict using single model.
machine_learning_function->predictValues(data[0], *res, block, 0, block[arguments.front()].column->size(), arguments, context); machine_learning_function->predictValues(data[0], *res, arguments, 0, arguments.front().column->size(), context);
} }
else else
{ {
@ -180,7 +180,7 @@ MutableColumnPtr ColumnAggregateFunction::predictValues(ColumnsWithTypeAndName &
size_t row_num = 0; size_t row_num = 0;
for (auto * val : data) for (auto * val : data)
{ {
machine_learning_function->predictValues(val, *res, block, row_num, 1, arguments, context); machine_learning_function->predictValues(val, *res, arguments, row_num, 1, context);
++row_num; ++row_num;
} }
} }

View File

@ -119,7 +119,7 @@ public:
const char * getFamilyName() const override { return "AggregateFunction"; } const char * getFamilyName() const override { return "AggregateFunction"; }
TypeIndex getDataType() const override { return TypeIndex::AggregateFunction; } TypeIndex getDataType() const override { return TypeIndex::AggregateFunction; }
MutableColumnPtr predictValues(ColumnsWithTypeAndName & block, const ColumnNumbers & arguments, const Context & context) const; MutableColumnPtr predictValues(ColumnsWithTypeAndName & arguments, const Context & context) const;
size_t size() const override size_t size() const override
{ {

View File

@ -188,15 +188,10 @@ ColumnWithTypeAndName ColumnFunction::reduce() const
"arguments but " + toString(captured) + " columns were captured.", ErrorCodes::LOGICAL_ERROR); "arguments but " + toString(captured) + " columns were captured.", ErrorCodes::LOGICAL_ERROR);
auto columns = captured_columns; auto columns = captured_columns;
columns.emplace_back(ColumnWithTypeAndName {nullptr, function->getReturnType(), ""}); ColumnWithTypeAndName res{nullptr, function->getResultType(), ""};
ColumnNumbers arguments(captured_columns.size()); res.column = function->execute(columns, res.type, size_);
for (size_t i = 0; i < captured_columns.size(); ++i) return res;
arguments[i] = i;
function->execute(columns, arguments, captured_columns.size(), size_);
return columns[captured_columns.size()];
} }
} }

View File

@ -634,4 +634,10 @@ void ColumnString::protect()
getOffsets().protect(); getOffsets().protect();
} }
void ColumnString::validate() const
{
if (!offsets.empty() && offsets.back() != chars.size())
throw Exception(ErrorCodes::LOGICAL_ERROR, "ColumnString validation failed: size mismatch (internal logical error) {} != {}", offsets.back(), chars.size());
}
} }

View File

@ -267,6 +267,9 @@ public:
Offsets & getOffsets() { return offsets; } Offsets & getOffsets() { return offsets; }
const Offsets & getOffsets() const { return offsets; } const Offsets & getOffsets() const { return offsets; }
// Throws an exception if offsets/chars are messed up
void validate() const;
}; };

View File

@ -510,7 +510,9 @@ namespace ErrorCodes
extern const int ROW_AND_ROWS_TOGETHER = 544; extern const int ROW_AND_ROWS_TOGETHER = 544;
extern const int FIRST_AND_NEXT_TOGETHER = 545; extern const int FIRST_AND_NEXT_TOGETHER = 545;
extern const int NO_ROW_DELIMITER = 546; extern const int NO_ROW_DELIMITER = 546;
extern const int CANNOT_READ_MAP_FROM_TEXT = 547; extern const int INVALID_RAID_TYPE = 547;
extern const int UNKNOWN_VOLUME = 548;
extern const int CANNOT_READ_MAP_FROM_TEXT = 549;
extern const int KEEPER_EXCEPTION = 999; extern const int KEEPER_EXCEPTION = 999;
extern const int POCO_EXCEPTION = 1000; extern const int POCO_EXCEPTION = 1000;

View File

@ -2,6 +2,7 @@
#include <string.h> #include <string.h>
#include <cxxabi.h> #include <cxxabi.h>
#include <cstdlib>
#include <Poco/String.h> #include <Poco/String.h>
#include <common/logger_useful.h> #include <common/logger_useful.h>
#include <IO/WriteHelpers.h> #include <IO/WriteHelpers.h>
@ -36,13 +37,13 @@ namespace ErrorCodes
Exception::Exception(const std::string & msg, int code) Exception::Exception(const std::string & msg, int code)
: Poco::Exception(msg, code) : Poco::Exception(msg, code)
{ {
// In debug builds, treat LOGICAL_ERROR as an assertion failure. // In debug builds and builds with sanitizers, treat LOGICAL_ERROR as an assertion failure.
// Log the message before we fail. // Log the message before we fail.
#ifndef NDEBUG #ifdef ABORT_ON_LOGICAL_ERROR
if (code == ErrorCodes::LOGICAL_ERROR) if (code == ErrorCodes::LOGICAL_ERROR)
{ {
LOG_ERROR(&Poco::Logger::root(), "Logical error: '{}'.", msg); LOG_FATAL(&Poco::Logger::root(), "Logical error: '{}'.", msg);
assert(false); abort();
} }
#endif #endif
} }

View File

@ -10,6 +10,10 @@
#include <fmt/format.h> #include <fmt/format.h>
#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || defined(MEMORY_SANITIZER) || defined(UNDEFINED_BEHAVIOR_SANITIZER)
#define ABORT_ON_LOGICAL_ERROR
#endif
namespace Poco { class Logger; } namespace Poco { class Logger; }

View File

@ -30,6 +30,8 @@ namespace ProfileEvents
static constexpr size_t log_peak_memory_usage_every = 1ULL << 30; static constexpr size_t log_peak_memory_usage_every = 1ULL << 30;
thread_local bool MemoryTracker::BlockerInThread::is_blocked = false;
MemoryTracker total_memory_tracker(nullptr, VariableContext::Global); MemoryTracker total_memory_tracker(nullptr, VariableContext::Global);
@ -56,13 +58,15 @@ MemoryTracker::~MemoryTracker()
void MemoryTracker::logPeakMemoryUsage() const void MemoryTracker::logPeakMemoryUsage() const
{ {
const auto * description = description_ptr.load(std::memory_order_relaxed); const auto * description = description_ptr.load(std::memory_order_relaxed);
LOG_DEBUG(&Poco::Logger::get("MemoryTracker"), "Peak memory usage{}: {}.", (description ? " " + std::string(description) : ""), ReadableSize(peak)); LOG_DEBUG(&Poco::Logger::get("MemoryTracker"),
"Peak memory usage{}: {}.", (description ? " " + std::string(description) : ""), ReadableSize(peak));
} }
void MemoryTracker::logMemoryUsage(Int64 current) const void MemoryTracker::logMemoryUsage(Int64 current) const
{ {
const auto * description = description_ptr.load(std::memory_order_relaxed); const auto * description = description_ptr.load(std::memory_order_relaxed);
LOG_DEBUG(&Poco::Logger::get("MemoryTracker"), "Current memory usage{}: {}.", (description ? " " + std::string(description) : ""), ReadableSize(current)); LOG_DEBUG(&Poco::Logger::get("MemoryTracker"),
"Current memory usage{}: {}.", (description ? " " + std::string(description) : ""), ReadableSize(current));
} }
@ -71,7 +75,7 @@ void MemoryTracker::alloc(Int64 size)
if (size < 0) if (size < 0)
throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Negative size ({}) is passed to MemoryTracker. It is a bug.", size); throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Negative size ({}) is passed to MemoryTracker. It is a bug.", size);
if (blocker.isCancelled()) if (BlockerInThread::isBlocked())
return; return;
/** Using memory_order_relaxed means that if allocations are done simultaneously, /** Using memory_order_relaxed means that if allocations are done simultaneously,
@ -86,12 +90,15 @@ void MemoryTracker::alloc(Int64 size)
Int64 current_hard_limit = hard_limit.load(std::memory_order_relaxed); Int64 current_hard_limit = hard_limit.load(std::memory_order_relaxed);
Int64 current_profiler_limit = profiler_limit.load(std::memory_order_relaxed); Int64 current_profiler_limit = profiler_limit.load(std::memory_order_relaxed);
/// Cap the limit to the total_memory_tracker, since it may include some drift. /// Cap the limit to the total_memory_tracker, since it may include some drift
/// for user-level memory tracker.
/// ///
/// And since total_memory_tracker is reset to the process resident /// And since total_memory_tracker is reset to the process resident
/// memory peridically (in AsynchronousMetrics::update()), any limit can be /// memory peridically (in AsynchronousMetrics::update()), any limit can be
/// capped to it, to avoid possible drift. /// capped to it, to avoid possible drift.
if (unlikely(current_hard_limit && will_be > current_hard_limit)) if (unlikely(current_hard_limit
&& will_be > current_hard_limit
&& level == VariableContext::User))
{ {
Int64 total_amount = total_memory_tracker.get(); Int64 total_amount = total_memory_tracker.get();
if (amount > total_amount) if (amount > total_amount)
@ -104,10 +111,8 @@ void MemoryTracker::alloc(Int64 size)
std::bernoulli_distribution fault(fault_probability); std::bernoulli_distribution fault(fault_probability);
if (unlikely(fault_probability && fault(thread_local_rng))) if (unlikely(fault_probability && fault(thread_local_rng)))
{ {
free(size);
/// Prevent recursion. Exception::ctor -> std::string -> new[] -> MemoryTracker::alloc /// Prevent recursion. Exception::ctor -> std::string -> new[] -> MemoryTracker::alloc
auto untrack_lock = blocker.cancel(); // NOLINT BlockerInThread untrack_lock;
ProfileEvents::increment(ProfileEvents::QueryMemoryLimitExceeded); ProfileEvents::increment(ProfileEvents::QueryMemoryLimitExceeded);
std::stringstream message; std::stringstream message;
@ -118,12 +123,13 @@ void MemoryTracker::alloc(Int64 size)
<< " (attempt to allocate chunk of " << size << " bytes)" << " (attempt to allocate chunk of " << size << " bytes)"
<< ", maximum: " << formatReadableSizeWithBinarySuffix(current_hard_limit); << ", maximum: " << formatReadableSizeWithBinarySuffix(current_hard_limit);
amount.fetch_sub(size, std::memory_order_relaxed);
throw DB::Exception(message.str(), DB::ErrorCodes::MEMORY_LIMIT_EXCEEDED); throw DB::Exception(message.str(), DB::ErrorCodes::MEMORY_LIMIT_EXCEEDED);
} }
if (unlikely(current_profiler_limit && will_be > current_profiler_limit)) if (unlikely(current_profiler_limit && will_be > current_profiler_limit))
{ {
auto no_track = blocker.cancel(); BlockerInThread untrack_lock;
DB::TraceCollector::collect(DB::TraceType::Memory, StackTrace(), size); DB::TraceCollector::collect(DB::TraceType::Memory, StackTrace(), size);
setOrRaiseProfilerLimit((will_be + profiler_step - 1) / profiler_step * profiler_step); setOrRaiseProfilerLimit((will_be + profiler_step - 1) / profiler_step * profiler_step);
} }
@ -131,16 +137,14 @@ void MemoryTracker::alloc(Int64 size)
std::bernoulli_distribution sample(sample_probability); std::bernoulli_distribution sample(sample_probability);
if (unlikely(sample_probability && sample(thread_local_rng))) if (unlikely(sample_probability && sample(thread_local_rng)))
{ {
auto no_track = blocker.cancel(); BlockerInThread untrack_lock;
DB::TraceCollector::collect(DB::TraceType::MemorySample, StackTrace(), size); DB::TraceCollector::collect(DB::TraceType::MemorySample, StackTrace(), size);
} }
if (unlikely(current_hard_limit && will_be > current_hard_limit)) if (unlikely(current_hard_limit && will_be > current_hard_limit))
{ {
free(size);
/// Prevent recursion. Exception::ctor -> std::string -> new[] -> MemoryTracker::alloc /// Prevent recursion. Exception::ctor -> std::string -> new[] -> MemoryTracker::alloc
auto no_track = blocker.cancel(); // NOLINT BlockerInThread untrack_lock;
ProfileEvents::increment(ProfileEvents::QueryMemoryLimitExceeded); ProfileEvents::increment(ProfileEvents::QueryMemoryLimitExceeded);
std::stringstream message; std::stringstream message;
@ -151,6 +155,7 @@ void MemoryTracker::alloc(Int64 size)
<< " (attempt to allocate chunk of " << size << " bytes)" << " (attempt to allocate chunk of " << size << " bytes)"
<< ", maximum: " << formatReadableSizeWithBinarySuffix(current_hard_limit); << ", maximum: " << formatReadableSizeWithBinarySuffix(current_hard_limit);
amount.fetch_sub(size, std::memory_order_relaxed);
throw DB::Exception(message.str(), DB::ErrorCodes::MEMORY_LIMIT_EXCEEDED); throw DB::Exception(message.str(), DB::ErrorCodes::MEMORY_LIMIT_EXCEEDED);
} }
@ -177,13 +182,13 @@ void MemoryTracker::updatePeak(Int64 will_be)
void MemoryTracker::free(Int64 size) void MemoryTracker::free(Int64 size)
{ {
if (blocker.isCancelled()) if (BlockerInThread::isBlocked())
return; return;
std::bernoulli_distribution sample(sample_probability); std::bernoulli_distribution sample(sample_probability);
if (unlikely(sample_probability && sample(thread_local_rng))) if (unlikely(sample_probability && sample(thread_local_rng)))
{ {
auto no_track = blocker.cancel(); BlockerInThread untrack_lock;
DB::TraceCollector::collect(DB::TraceType::MemorySample, StackTrace(), -size); DB::TraceCollector::collect(DB::TraceType::MemorySample, StackTrace(), -size);
} }
@ -298,11 +303,3 @@ namespace CurrentMemoryTracker
} }
} }
} }
DB::SimpleActionLock getCurrentMemoryTrackerActionLock()
{
auto * memory_tracker = DB::CurrentThread::getMemoryTracker();
if (!memory_tracker)
return {};
return memory_tracker->blocker.cancel();
}

View File

@ -3,7 +3,6 @@
#include <atomic> #include <atomic>
#include <common/types.h> #include <common/types.h>
#include <Common/CurrentMetrics.h> #include <Common/CurrentMetrics.h>
#include <Common/SimpleActionBlocker.h>
#include <Common/VariableContext.h> #include <Common/VariableContext.h>
@ -131,8 +130,18 @@ public:
/// Prints info about peak memory consumption into log. /// Prints info about peak memory consumption into log.
void logPeakMemoryUsage() const; void logPeakMemoryUsage() const;
/// To be able to temporarily stop memory tracker /// To be able to temporarily stop memory tracking from current thread.
DB::SimpleActionBlocker blocker; struct BlockerInThread
{
private:
BlockerInThread(const BlockerInThread &) = delete;
BlockerInThread & operator=(const BlockerInThread &) = delete;
static thread_local bool is_blocked;
public:
BlockerInThread() { is_blocked = true; }
~BlockerInThread() { is_blocked = false; }
static bool isBlocked() { return is_blocked; }
};
}; };
extern MemoryTracker total_memory_tracker; extern MemoryTracker total_memory_tracker;
@ -145,7 +154,3 @@ namespace CurrentMemoryTracker
void realloc(Int64 old_size, Int64 new_size); void realloc(Int64 old_size, Int64 new_size);
void free(Int64 size); void free(Int64 size);
} }
/// Holding this object will temporarily disable memory tracking.
DB::SimpleActionLock getCurrentMemoryTrackerActionLock();

View File

@ -164,6 +164,8 @@ public:
void detachQuery(bool exit_if_already_detached = false, bool thread_exits = false); void detachQuery(bool exit_if_already_detached = false, bool thread_exits = false);
protected: protected:
void applyQuerySettings();
void initPerformanceCounters(); void initPerformanceCounters();
void initQueryProfiler(); void initQueryProfiler();

View File

@ -502,8 +502,8 @@ Float NO_INLINE really_unrolled(const PODArray<UInt8> & keys, const PODArray<Flo
struct State4 struct State4
{ {
Float sum[4] = {0, 0, 0, 0}; Float sum[4]{};
size_t count[4] = {0, 0, 0, 0}; size_t count[4]{};
template <UInt32 idx> template <UInt32 idx>
void add(Float value) void add(Float value)
@ -522,13 +522,13 @@ Float NO_INLINE another_unrolled_x4(const PODArray<UInt8> & keys, const PODArray
{ {
State4 map[256]{}; State4 map[256]{};
size_t size = keys.size() & ~size_t(3); size_t size = keys.size() / 4 * 4;
for (size_t i = 0; i < size; i+=4) for (size_t i = 0; i < size; i += 4)
{ {
map[keys[i]].add<0>(values[i]); map[keys[i]].add<0>(values[i]);
map[keys[i+1]].add<1>(values[i]); map[keys[i + 1]].add<1>(values[i]);
map[keys[i+2]].add<2>(values[i]); map[keys[i + 2]].add<2>(values[i]);
map[keys[i+3]].add<3>(values[i]); map[keys[i + 3]].add<3>(values[i]);
} }
/// tail /// tail

View File

@ -131,7 +131,10 @@ TEST(Common, RWLockRecursive)
auto lock2 = fifo_lock->getLock(RWLockImpl::Read, "q2"); auto lock2 = fifo_lock->getLock(RWLockImpl::Read, "q2");
#ifndef ABORT_ON_LOGICAL_ERROR
/// It throws LOGICAL_ERROR
EXPECT_ANY_THROW({fifo_lock->getLock(RWLockImpl::Write, "q2");}); EXPECT_ANY_THROW({fifo_lock->getLock(RWLockImpl::Write, "q2");});
#endif
} }
fifo_lock->getLock(RWLockImpl::Write, "q2"); fifo_lock->getLock(RWLockImpl::Write, "q2");

View File

@ -60,27 +60,17 @@ public:
using ArrayA = typename ColVecA::Container; using ArrayA = typename ColVecA::Container;
using ArrayB = typename ColVecB::Container; using ArrayB = typename ColVecB::Container;
DecimalComparison(ColumnsWithTypeAndName & data, size_t result, const ColumnWithTypeAndName & col_left, const ColumnWithTypeAndName & col_right) static ColumnPtr apply(const ColumnWithTypeAndName & col_left, const ColumnWithTypeAndName & col_right)
{
if (!apply(data, result, col_left, col_right))
throw Exception("Wrong decimal comparison with " + col_left.type->getName() + " and " + col_right.type->getName(),
ErrorCodes::LOGICAL_ERROR);
}
static bool apply(ColumnsWithTypeAndName & data, size_t result [[maybe_unused]],
const ColumnWithTypeAndName & col_left, const ColumnWithTypeAndName & col_right)
{ {
if constexpr (_actual) if constexpr (_actual)
{ {
ColumnPtr c_res; ColumnPtr c_res;
Shift shift = getScales<A, B>(col_left.type, col_right.type); Shift shift = getScales<A, B>(col_left.type, col_right.type);
c_res = applyWithScale(col_left.column, col_right.column, shift); return applyWithScale(col_left.column, col_right.column, shift);
if (c_res)
data[result].column = std::move(c_res);
return true;
} }
return false; else
return nullptr;
} }
static bool compare(A a, B b, UInt32 scale_a, UInt32 scale_b) static bool compare(A a, B b, UInt32 scale_a, UInt32 scale_b)

View File

@ -111,6 +111,7 @@ class IColumn;
M(UInt64, distributed_group_by_no_merge, 0, "If 1, Do not merge aggregation states from different servers for distributed query processing - in case it is for certain that there are different keys on different shards. If 2 - same as 1 but also apply ORDER BY and LIMIT stages", 0) \ M(UInt64, distributed_group_by_no_merge, 0, "If 1, Do not merge aggregation states from different servers for distributed query processing - in case it is for certain that there are different keys on different shards. If 2 - same as 1 but also apply ORDER BY and LIMIT stages", 0) \
M(Bool, optimize_distributed_group_by_sharding_key, false, "Optimize GROUP BY sharding_key queries (by avodiing costly aggregation on the initiator server).", 0) \ M(Bool, optimize_distributed_group_by_sharding_key, false, "Optimize GROUP BY sharding_key queries (by avodiing costly aggregation on the initiator server).", 0) \
M(Bool, optimize_skip_unused_shards, false, "Assumes that data is distributed by sharding_key. Optimization to skip unused shards if SELECT query filters by sharding_key.", 0) \ M(Bool, optimize_skip_unused_shards, false, "Assumes that data is distributed by sharding_key. Optimization to skip unused shards if SELECT query filters by sharding_key.", 0) \
M(Bool, allow_nondeterministic_optimize_skip_unused_shards, false, "Allow non-deterministic functions (includes dictGet) in sharding_key for optimize_skip_unused_shards", 0) \
M(UInt64, force_optimize_skip_unused_shards, 0, "Throw an exception if unused shards cannot be skipped (1 - throw only if the table has the sharding key, 2 - always throw.", 0) \ M(UInt64, force_optimize_skip_unused_shards, 0, "Throw an exception if unused shards cannot be skipped (1 - throw only if the table has the sharding key, 2 - always throw.", 0) \
M(UInt64, optimize_skip_unused_shards_nesting, 0, "Same as optimize_skip_unused_shards, but accept nesting level until which it will work.", 0) \ M(UInt64, optimize_skip_unused_shards_nesting, 0, "Same as optimize_skip_unused_shards, but accept nesting level until which it will work.", 0) \
M(UInt64, force_optimize_skip_unused_shards_nesting, 0, "Same as force_optimize_skip_unused_shards, but accept nesting level until which it will work.", 0) \ M(UInt64, force_optimize_skip_unused_shards_nesting, 0, "Same as force_optimize_skip_unused_shards, but accept nesting level until which it will work.", 0) \
@ -153,6 +154,7 @@ class IColumn;
\ \
M(DistributedProductMode, distributed_product_mode, DistributedProductMode::DENY, "How are distributed subqueries performed inside IN or JOIN sections?", IMPORTANT) \ M(DistributedProductMode, distributed_product_mode, DistributedProductMode::DENY, "How are distributed subqueries performed inside IN or JOIN sections?", IMPORTANT) \
\ \
M(UInt64, max_concurrent_queries_for_all_users, 0, "The maximum number of concurrent requests for all users.", 0) \
M(UInt64, max_concurrent_queries_for_user, 0, "The maximum number of concurrent requests per user.", 0) \ M(UInt64, max_concurrent_queries_for_user, 0, "The maximum number of concurrent requests per user.", 0) \
\ \
M(Bool, insert_deduplicate, true, "For INSERT queries in the replicated table, specifies that deduplication of insertings blocks should be performed", 0) \ M(Bool, insert_deduplicate, true, "For INSERT queries in the replicated table, specifies that deduplication of insertings blocks should be performed", 0) \
@ -411,12 +413,14 @@ class IColumn;
M(Bool, format_csv_allow_double_quotes, 1, "If it is set to true, allow strings in double quotes.", 0) \ M(Bool, format_csv_allow_double_quotes, 1, "If it is set to true, allow strings in double quotes.", 0) \
M(Bool, output_format_csv_crlf_end_of_line, false, "If it is set true, end of line in CSV format will be \\r\\n instead of \\n.", 0) \ M(Bool, output_format_csv_crlf_end_of_line, false, "If it is set true, end of line in CSV format will be \\r\\n instead of \\n.", 0) \
M(Bool, input_format_csv_unquoted_null_literal_as_null, false, "Consider unquoted NULL literal as \\N", 0) \ M(Bool, input_format_csv_unquoted_null_literal_as_null, false, "Consider unquoted NULL literal as \\N", 0) \
M(Bool, input_format_csv_enum_as_number, false, "Treat inserted enum values in CSV formats as enum indices \\N", 0) \
M(Bool, input_format_skip_unknown_fields, false, "Skip columns with unknown names from input data (it works for JSONEachRow, CSVWithNames, TSVWithNames and TSKV formats).", 0) \ M(Bool, input_format_skip_unknown_fields, false, "Skip columns with unknown names from input data (it works for JSONEachRow, CSVWithNames, TSVWithNames and TSKV formats).", 0) \
M(Bool, input_format_with_names_use_header, true, "For TSVWithNames and CSVWithNames input formats this controls whether format parser is to assume that column data appear in the input exactly as they are specified in the header.", 0) \ M(Bool, input_format_with_names_use_header, true, "For TSVWithNames and CSVWithNames input formats this controls whether format parser is to assume that column data appear in the input exactly as they are specified in the header.", 0) \
M(Bool, input_format_import_nested_json, false, "Map nested JSON data to nested tables (it works for JSONEachRow format).", 0) \ M(Bool, input_format_import_nested_json, false, "Map nested JSON data to nested tables (it works for JSONEachRow format).", 0) \
M(Bool, optimize_aggregators_of_group_by_keys, true, "Eliminates min/max/any/anyLast aggregators of GROUP BY keys in SELECT section", 0) \ M(Bool, optimize_aggregators_of_group_by_keys, true, "Eliminates min/max/any/anyLast aggregators of GROUP BY keys in SELECT section", 0) \
M(Bool, input_format_defaults_for_omitted_fields, true, "For input data calculate default expressions for omitted fields (it works for JSONEachRow, CSV and TSV formats).", IMPORTANT) \ M(Bool, input_format_defaults_for_omitted_fields, true, "For input data calculate default expressions for omitted fields (it works for JSONEachRow, CSV and TSV formats).", IMPORTANT) \
M(Bool, input_format_tsv_empty_as_default, false, "Treat empty fields in TSV input as default values.", 0) \ M(Bool, input_format_tsv_empty_as_default, false, "Treat empty fields in TSV input as default values.", 0) \
M(Bool, input_format_tsv_enum_as_number, false, "Treat inserted enum values in TSV formats as enum indices \\N", 0) \
M(Bool, input_format_null_as_default, false, "For text input formats initialize null fields with default values if data type of this field is not nullable", 0) \ M(Bool, input_format_null_as_default, false, "For text input formats initialize null fields with default values if data type of this field is not nullable", 0) \
\ \
M(DateTimeInputFormat, date_time_input_format, FormatSettings::DateTimeInputFormat::Basic, "Method to read DateTime from text input formats. Possible values: 'basic' and 'best_effort'.", 0) \ M(DateTimeInputFormat, date_time_input_format, FormatSettings::DateTimeInputFormat::Basic, "Method to read DateTime from text input formats. Possible values: 'basic' and 'best_effort'.", 0) \

View File

@ -146,12 +146,17 @@ void DataTypeEnum<Type>::serializeTextEscaped(const IColumn & column, size_t row
} }
template <typename Type> template <typename Type>
void DataTypeEnum<Type>::deserializeTextEscaped(IColumn & column, ReadBuffer & istr, const FormatSettings &) const void DataTypeEnum<Type>::deserializeTextEscaped(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const
{ {
/// NOTE It would be nice to do without creating a temporary object - at least extract std::string out. if (settings.tsv.input_format_enum_as_number)
std::string field_name; assert_cast<ColumnType &>(column).getData().push_back(readValue(istr));
readEscapedString(field_name, istr); else
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name))); {
/// NOTE It would be nice to do without creating a temporary object - at least extract std::string out.
std::string field_name;
readEscapedString(field_name, istr);
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name)));
}
} }
template <typename Type> template <typename Type>
@ -169,11 +174,16 @@ void DataTypeEnum<Type>::deserializeTextQuoted(IColumn & column, ReadBuffer & is
} }
template <typename Type> template <typename Type>
void DataTypeEnum<Type>::deserializeWholeText(IColumn & column, ReadBuffer & istr, const FormatSettings &) const void DataTypeEnum<Type>::deserializeWholeText(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const
{ {
std::string field_name; if (settings.tsv.input_format_enum_as_number)
readString(field_name, istr); assert_cast<ColumnType &>(column).getData().push_back(readValue(istr));
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name))); else
{
std::string field_name;
readString(field_name, istr);
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name)));
}
} }
template <typename Type> template <typename Type>
@ -191,9 +201,14 @@ void DataTypeEnum<Type>::serializeTextXML(const IColumn & column, size_t row_num
template <typename Type> template <typename Type>
void DataTypeEnum<Type>::deserializeTextJSON(IColumn & column, ReadBuffer & istr, const FormatSettings &) const void DataTypeEnum<Type>::deserializeTextJSON(IColumn & column, ReadBuffer & istr, const FormatSettings &) const
{ {
std::string field_name; if (!istr.eof() && *istr.position() != '"')
readJSONString(field_name, istr); assert_cast<ColumnType &>(column).getData().push_back(readValue(istr));
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name))); else
{
std::string field_name;
readJSONString(field_name, istr);
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name)));
}
} }
template <typename Type> template <typename Type>
@ -205,9 +220,14 @@ void DataTypeEnum<Type>::serializeTextCSV(const IColumn & column, size_t row_num
template <typename Type> template <typename Type>
void DataTypeEnum<Type>::deserializeTextCSV(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const void DataTypeEnum<Type>::deserializeTextCSV(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const
{ {
std::string field_name; if (settings.csv.input_format_enum_as_number)
readCSVString(field_name, istr, settings.csv); assert_cast<ColumnType &>(column).getData().push_back(readValue(istr));
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name))); else
{
std::string field_name;
readCSVString(field_name, istr, settings.csv);
assert_cast<ColumnType &>(column).getData().push_back(getValue(StringRef(field_name)));
}
} }
template <typename Type> template <typename Type>

View File

@ -66,13 +66,18 @@ public:
TypeIndex getTypeId() const override { return sizeof(FieldType) == 1 ? TypeIndex::Enum8 : TypeIndex::Enum16; } TypeIndex getTypeId() const override { return sizeof(FieldType) == 1 ? TypeIndex::Enum8 : TypeIndex::Enum16; }
const StringRef & getNameForValue(const FieldType & value) const auto findByValue(const FieldType & value) const
{ {
const auto it = value_to_name_map.find(value); const auto it = value_to_name_map.find(value);
if (it == std::end(value_to_name_map)) if (it == std::end(value_to_name_map))
throw Exception{"Unexpected value " + toString(value) + " for type " + getName(), ErrorCodes::BAD_ARGUMENTS}; throw Exception{"Unexpected value " + toString(value) + " for type " + getName(), ErrorCodes::BAD_ARGUMENTS};
return it->second; return it;
}
const StringRef & getNameForValue(const FieldType & value) const
{
return findByValue(value)->second;
} }
FieldType getValue(StringRef field_name) const FieldType getValue(StringRef field_name) const
@ -84,6 +89,13 @@ public:
return it->getMapped(); return it->getMapped();
} }
FieldType readValue(ReadBuffer & istr) const
{
FieldType x;
readText(x, istr);
return findByValue(x)->first;
}
Field castToName(const Field & value_or_name) const override; Field castToName(const Field & value_or_name) const override;
Field castToValue(const Field & value_or_name) const override; Field castToValue(const Field & value_or_name) const override;

View File

@ -303,6 +303,15 @@ static DeserializeBinaryBulkStateMap * checkAndGetMapDeserializeState(IDataType:
return map_state; return map_state;
} }
void DataTypeMap::enumerateStreams(const StreamCallback & callback, SubstreamPath & path) const
{
path.push_back(Substream::MapElement);
path.back().map_element_name = "keys";
keys->enumerateStreams(callback, path);
path.back().map_element_name = "values";
keys->enumerateStreams(callback, path);
path.pop_back();
}
void DataTypeMap::serializeBinaryBulkStatePrefix( void DataTypeMap::serializeBinaryBulkStatePrefix(
SerializeBinaryBulkSettings & settings, SerializeBinaryBulkSettings & settings,
@ -312,7 +321,9 @@ void DataTypeMap::serializeBinaryBulkStatePrefix(
map_state->states.resize(2); map_state->states.resize(2);
settings.path.push_back(Substream::MapElement); settings.path.push_back(Substream::MapElement);
settings.path.back().map_element_name = "keys";
keys->serializeBinaryBulkStatePrefix(settings, map_state->states[0]); keys->serializeBinaryBulkStatePrefix(settings, map_state->states[0]);
settings.path.back().map_element_name = "values";
values->serializeBinaryBulkStatePrefix(settings, map_state->states[1]); values->serializeBinaryBulkStatePrefix(settings, map_state->states[1]);
settings.path.pop_back(); settings.path.pop_back();
@ -326,7 +337,9 @@ void DataTypeMap::serializeBinaryBulkStateSuffix(
auto * map_state = checkAndGetMapSerializeState(state); auto * map_state = checkAndGetMapSerializeState(state);
settings.path.push_back(Substream::MapElement); settings.path.push_back(Substream::MapElement);
settings.path.back().map_element_name = "keys";
keys->serializeBinaryBulkStateSuffix(settings, map_state->states[0]); keys->serializeBinaryBulkStateSuffix(settings, map_state->states[0]);
settings.path.back().map_element_name = "values";
values->serializeBinaryBulkStateSuffix(settings, map_state->states[1]); values->serializeBinaryBulkStateSuffix(settings, map_state->states[1]);
settings.path.pop_back(); settings.path.pop_back();
} }
@ -339,7 +352,9 @@ void DataTypeMap::deserializeBinaryBulkStatePrefix(
map_state->states.resize(2); map_state->states.resize(2);
settings.path.push_back(Substream::MapElement); settings.path.push_back(Substream::MapElement);
settings.path.back().map_element_name = "keys";
keys->deserializeBinaryBulkStatePrefix(settings, map_state->states[0]); keys->deserializeBinaryBulkStatePrefix(settings, map_state->states[0]);
settings.path.back().map_element_name = "values";
values->deserializeBinaryBulkStatePrefix(settings, map_state->states[1]); values->deserializeBinaryBulkStatePrefix(settings, map_state->states[1]);
settings.path.pop_back(); settings.path.pop_back();
@ -356,10 +371,14 @@ void DataTypeMap::serializeBinaryBulkWithMultipleStreams(
{ {
auto * map_state = checkAndGetMapSerializeState(state); auto * map_state = checkAndGetMapSerializeState(state);
settings.path.push_back(Substream::MapElement); settings.path.push_back(Substream::MapElement);
const auto & keys_col = extractElementColumn(column, 0); const auto & keys_col = extractElementColumn(column, 0);
settings.path.back().map_element_name = "keys";
keys->serializeBinaryBulkWithMultipleStreams(keys_col, offset, limit, settings, map_state->states[0]); keys->serializeBinaryBulkWithMultipleStreams(keys_col, offset, limit, settings, map_state->states[0]);
const auto & values_col = extractElementColumn(column, 1); const auto & values_col = extractElementColumn(column, 1);
settings.path.back().map_element_name = "values";
values->serializeBinaryBulkWithMultipleStreams(values_col, offset, limit, settings, map_state->states[1]); values->serializeBinaryBulkWithMultipleStreams(values_col, offset, limit, settings, map_state->states[1]);
settings.path.pop_back(); settings.path.pop_back();
} }
@ -374,8 +393,10 @@ void DataTypeMap::deserializeBinaryBulkWithMultipleStreams(
settings.path.push_back(Substream::MapElement); settings.path.push_back(Substream::MapElement);
settings.avg_value_size_hint = 0; settings.avg_value_size_hint = 0;
auto & keys_col = extractElementColumn(column, 0); auto & keys_col = extractElementColumn(column, 0);
settings.path.back().map_element_name = "keys";
keys->deserializeBinaryBulkWithMultipleStreams(keys_col, limit, settings, map_state->states[0]); keys->deserializeBinaryBulkWithMultipleStreams(keys_col, limit, settings, map_state->states[0]);
auto & values_col = extractElementColumn(column, 1); auto & values_col = extractElementColumn(column, 1);
settings.path.back().map_element_name = "values";
values->deserializeBinaryBulkWithMultipleStreams(values_col, limit, settings, map_state->states[1]); values->deserializeBinaryBulkWithMultipleStreams(values_col, limit, settings, map_state->states[1]);
settings.path.pop_back(); settings.path.pop_back();

View File

@ -44,6 +44,11 @@ public:
void serializeTextCSV(const IColumn & column, size_t row_num, WriteBuffer & ostr, const FormatSettings &) const override; void serializeTextCSV(const IColumn & column, size_t row_num, WriteBuffer & ostr, const FormatSettings &) const override;
void deserializeTextCSV(IColumn & column, ReadBuffer & istr, const FormatSettings &) const override; void deserializeTextCSV(IColumn & column, ReadBuffer & istr, const FormatSettings &) const override;
/** Each sub-column in a map is serialized in separate stream.
*/
void enumerateStreams(const StreamCallback & callback, SubstreamPath & path) const override;
void serializeBinaryBulkStatePrefix( void serializeBinaryBulkStatePrefix(
SerializeBinaryBulkSettings & settings, SerializeBinaryBulkSettings & settings,
SerializeBinaryBulkStatePtr & state) const override; SerializeBinaryBulkStatePtr & state) const override;

View File

@ -123,6 +123,8 @@ String IDataType::getFileNameForStream(const String & column_name, const IDataTy
/// and name is encoded as a whole. /// and name is encoded as a whole.
stream_name += "%2E" + escapeForFileName(elem.tuple_element_name); stream_name += "%2E" + escapeForFileName(elem.tuple_element_name);
} }
else if (elem.type == Substream::MapElement)
stream_name += ".map." + escapeForFileName(elem.map_element_name);
else if (elem.type == Substream::DictionaryKeys) else if (elem.type == Substream::DictionaryKeys)
stream_name += ".dict"; stream_name += ".dict";
} }

View File

@ -101,6 +101,8 @@ public:
/// Index of tuple element, starting at 1. /// Index of tuple element, starting at 1.
String tuple_element_name; String tuple_element_name;
String map_element_name;
Substream(Type type_) : type(type_) {} Substream(Type type_) : type(type_) {}
}; };

View File

@ -32,7 +32,7 @@ FileDictionarySource::FileDictionarySource(
{ {
const String user_files_path = context.getUserFilesPath(); const String user_files_path = context.getUserFilesPath();
if (!startsWith(filepath, user_files_path)) if (!startsWith(filepath, user_files_path))
throw Exception("File path " + filepath + " is not inside " + user_files_path, ErrorCodes::PATH_ACCESS_DENIED); throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File path {} is not inside {}", filepath, user_files_path);
} }
} }
@ -60,7 +60,7 @@ BlockInputStreamPtr FileDictionarySource::loadAll()
std::string FileDictionarySource::toString() const std::string FileDictionarySource::toString() const
{ {
return "File: " + filepath + ' ' + format; return fmt::format("File: {}, {}", filepath, format);
} }

View File

@ -180,4 +180,9 @@ void DiskDecorator::sync(int fd) const
delegate->sync(fd); delegate->sync(fd);
} }
Executor & DiskDecorator::getExecutor()
{
return delegate->getExecutor();
}
} }

View File

@ -4,6 +4,10 @@
namespace DB namespace DB
{ {
/** Forwards all methods to another disk.
* Methods can be overridden by descendants.
*/
class DiskDecorator : public IDisk class DiskDecorator : public IDisk
{ {
public: public:
@ -46,6 +50,7 @@ public:
void close(int fd) const override; void close(int fd) const override;
void sync(int fd) const override; void sync(int fd) const override;
const String getType() const override { return delegate->getType(); } const String getType() const override { return delegate->getType(); }
Executor & getExecutor() override;
protected: protected:
DiskPtr delegate; DiskPtr delegate;

View File

@ -23,8 +23,11 @@ public:
DiskSelector(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, const Context & context); DiskSelector(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, const Context & context);
DiskSelector(const DiskSelector & from) : disks(from.disks) { } DiskSelector(const DiskSelector & from) : disks(from.disks) { }
DiskSelectorPtr DiskSelectorPtr updateFromConfig(
updateFromConfig(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, const Context & context) const; const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
const Context & context
) const;
/// Get disk by name /// Get disk by name
DiskPtr get(const String & name) const; DiskPtr get(const String & name) const;

View File

@ -195,10 +195,10 @@ public:
/// Invoked when Global Context is shutdown. /// Invoked when Global Context is shutdown.
virtual void shutdown() { } virtual void shutdown() { }
private:
/// Returns executor to perform asynchronous operations. /// Returns executor to perform asynchronous operations.
Executor & getExecutor() { return *executor; } virtual Executor & getExecutor() { return *executor; }
private:
std::unique_ptr<Executor> executor; std::unique_ptr<Executor> executor;
}; };

View File

@ -9,7 +9,7 @@ namespace DB
{ {
namespace ErrorCodes namespace ErrorCodes
{ {
extern const int EXCESSIVE_ELEMENT_IN_CONFIG; extern const int NO_ELEMENTS_IN_CONFIG;
extern const int INCONSISTENT_RESERVATIONS; extern const int INCONSISTENT_RESERVATIONS;
extern const int NO_RESERVATIONS_PROVIDED; extern const int NO_RESERVATIONS_PROVIDED;
extern const int UNKNOWN_VOLUME_TYPE; extern const int UNKNOWN_VOLUME_TYPE;
@ -51,7 +51,7 @@ IVolume::IVolume(
} }
if (disks.empty()) if (disks.empty())
throw Exception("Volume must contain at least one disk.", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG); throw Exception("Volume must contain at least one disk", ErrorCodes::NO_ELEMENTS_IN_CONFIG);
} }
UInt64 IVolume::getMaxUnreservedFreeSpace() const UInt64 IVolume::getMaxUnreservedFreeSpace() const

View File

@ -64,6 +64,12 @@ public:
virtual DiskPtr getDisk(size_t i) const { return disks[i]; } virtual DiskPtr getDisk(size_t i) const { return disks[i]; }
const Disks & getDisks() const { return disks; } const Disks & getDisks() const { return disks; }
/// Returns effective value of whether merges are allowed on this volume (true) or not (false).
virtual bool areMergesAvoided() const { return false; }
/// User setting for enabling and disabling merges on volume.
virtual void setAvoidMergesUserOverride(bool /*avoid*/) {}
protected: protected:
Disks disks; Disks disks;
const String name; const String name;

View File

@ -8,7 +8,7 @@ namespace DB
class SingleDiskVolume : public IVolume class SingleDiskVolume : public IVolume
{ {
public: public:
SingleDiskVolume(const String & name_, DiskPtr disk): IVolume(name_, {disk}) SingleDiskVolume(const String & name_, DiskPtr disk, size_t max_data_part_size_ = 0): IVolume(name_, {disk}, max_data_part_size_)
{ {
} }

View File

@ -11,6 +11,13 @@
#include <Poco/File.h> #include <Poco/File.h>
namespace
{
const auto DEFAULT_STORAGE_POLICY_NAME = "default";
const auto DEFAULT_VOLUME_NAME = "default";
const auto DEFAULT_DISK_NAME = "default";
}
namespace DB namespace DB
{ {
@ -18,11 +25,14 @@ namespace ErrorCodes
{ {
extern const int BAD_ARGUMENTS; extern const int BAD_ARGUMENTS;
extern const int EXCESSIVE_ELEMENT_IN_CONFIG; extern const int EXCESSIVE_ELEMENT_IN_CONFIG;
extern const int NO_ELEMENTS_IN_CONFIG;
extern const int UNKNOWN_DISK; extern const int UNKNOWN_DISK;
extern const int UNKNOWN_POLICY; extern const int UNKNOWN_POLICY;
extern const int UNKNOWN_VOLUME;
extern const int LOGICAL_ERROR; extern const int LOGICAL_ERROR;
} }
StoragePolicy::StoragePolicy( StoragePolicy::StoragePolicy(
String name_, String name_,
const Poco::Util::AbstractConfiguration & config, const Poco::Util::AbstractConfiguration & config,
@ -30,44 +40,42 @@ StoragePolicy::StoragePolicy(
DiskSelectorPtr disks) DiskSelectorPtr disks)
: name(std::move(name_)) : name(std::move(name_))
{ {
String volumes_prefix = config_prefix + ".volumes";
if (!config.has(volumes_prefix))
throw Exception("StoragePolicy must contain at least one volume (.volumes)", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);
Poco::Util::AbstractConfiguration::Keys keys; Poco::Util::AbstractConfiguration::Keys keys;
config.keys(volumes_prefix, keys); String volumes_prefix = config_prefix + ".volumes";
if (!config.has(volumes_prefix))
{
if (name != DEFAULT_STORAGE_POLICY_NAME)
throw Exception("Storage policy " + backQuote(name) + " must contain at least one volume (.volumes)", ErrorCodes::NO_ELEMENTS_IN_CONFIG);
}
else
{
config.keys(volumes_prefix, keys);
}
for (const auto & attr_name : keys) for (const auto & attr_name : keys)
{ {
if (!std::all_of(attr_name.begin(), attr_name.end(), isWordCharASCII)) if (!std::all_of(attr_name.begin(), attr_name.end(), isWordCharASCII))
throw Exception( throw Exception(
"Volume name can contain only alphanumeric and '_' (" + attr_name + ")", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG); "Volume name can contain only alphanumeric and '_' in storage policy " + backQuote(name) + " (" + attr_name + ")", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);
volumes.push_back(std::make_shared<VolumeJBOD>(attr_name, config, volumes_prefix + "." + attr_name, disks)); volumes.emplace_back(createVolumeFromConfig(attr_name, config, volumes_prefix + "." + attr_name, disks));
if (volumes_names.find(attr_name) != volumes_names.end()) }
throw Exception("Volumes names must be unique (" + attr_name + " duplicated)", ErrorCodes::UNKNOWN_POLICY);
volumes_names[attr_name] = volumes.size() - 1; if (volumes.empty() && name == DEFAULT_STORAGE_POLICY_NAME)
{
auto default_volume = std::make_shared<VolumeJBOD>(DEFAULT_VOLUME_NAME, std::vector<DiskPtr>{disks->get(DEFAULT_DISK_NAME)}, 0, false);
volumes.emplace_back(std::move(default_volume));
} }
if (volumes.empty()) if (volumes.empty())
throw Exception("StoragePolicy must contain at least one volume.", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG); throw Exception("Storage policy " + backQuote(name) + " must contain at least one volume.", ErrorCodes::NO_ELEMENTS_IN_CONFIG);
/// Check that disks are unique in Policy const double default_move_factor = volumes.size() > 1 ? 0.1 : 0.0;
std::set<String> disk_names; move_factor = config.getDouble(config_prefix + ".move_factor", default_move_factor);
for (const auto & volume : volumes)
{
for (const auto & disk : volume->getDisks())
{
if (disk_names.find(disk->getName()) != disk_names.end())
throw Exception(
"Duplicate disk '" + disk->getName() + "' in storage policy '" + name + "'", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);
disk_names.insert(disk->getName());
}
}
move_factor = config.getDouble(config_prefix + ".move_factor", 0.1);
if (move_factor > 1) if (move_factor > 1)
throw Exception("Disk move factor have to be in [0., 1.] interval, but set to " + toString(move_factor), ErrorCodes::LOGICAL_ERROR); throw Exception("Disk move factor have to be in [0., 1.] interval, but set to " + toString(move_factor) + " in storage policy " + backQuote(name), ErrorCodes::LOGICAL_ERROR);
buildVolumeIndices();
} }
@ -75,16 +83,43 @@ StoragePolicy::StoragePolicy(String name_, Volumes volumes_, double move_factor_
: volumes(std::move(volumes_)), name(std::move(name_)), move_factor(move_factor_) : volumes(std::move(volumes_)), name(std::move(name_)), move_factor(move_factor_)
{ {
if (volumes.empty()) if (volumes.empty())
throw Exception("StoragePolicy must contain at least one Volume.", ErrorCodes::UNKNOWN_POLICY); throw Exception("Storage policy " + backQuote(name) + " must contain at least one Volume.", ErrorCodes::NO_ELEMENTS_IN_CONFIG);
if (move_factor > 1) if (move_factor > 1)
throw Exception("Disk move factor have to be in [0., 1.] interval, but set to " + toString(move_factor), ErrorCodes::LOGICAL_ERROR); throw Exception("Disk move factor have to be in [0., 1.] interval, but set to " + toString(move_factor) + " in storage policy " + backQuote(name), ErrorCodes::LOGICAL_ERROR);
for (size_t i = 0; i < volumes.size(); ++i) buildVolumeIndices();
}
StoragePolicy::StoragePolicy(const StoragePolicy & storage_policy,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr disks)
: StoragePolicy(storage_policy.getName(), config, config_prefix, disks)
{
for (auto & volume : volumes)
{ {
if (volumes_names.find(volumes[i]->getName()) != volumes_names.end()) if (storage_policy.volume_index_by_volume_name.count(volume->getName()) > 0)
throw Exception("Volumes names must be unique (" + volumes[i]->getName() + " duplicated).", ErrorCodes::UNKNOWN_POLICY); {
volumes_names[volumes[i]->getName()] = i; auto old_volume = storage_policy.getVolumeByName(volume->getName());
try
{
auto new_volume = updateVolumeFromConfig(old_volume, config, config_prefix + ".volumes." + volume->getName(), disks);
volume = std::move(new_volume);
}
catch (Exception & e)
{
/// Default policies are allowed to be missed in configuration.
if (e.code() != ErrorCodes::NO_ELEMENTS_IN_CONFIG || storage_policy.getName() != DEFAULT_STORAGE_POLICY_NAME)
throw;
Poco::Util::AbstractConfiguration::Keys keys;
config.keys(config_prefix, keys);
if (!keys.empty())
throw;
}
}
} }
} }
@ -93,20 +128,20 @@ bool StoragePolicy::isDefaultPolicy() const
{ {
/// Guessing if this policy is default, not 100% correct though. /// Guessing if this policy is default, not 100% correct though.
if (getName() != "default") if (getName() != DEFAULT_STORAGE_POLICY_NAME)
return false; return false;
if (volumes.size() != 1) if (volumes.size() != 1)
return false; return false;
if (volumes[0]->getName() != "default") if (volumes[0]->getName() != DEFAULT_VOLUME_NAME)
return false; return false;
const auto & disks = volumes[0]->getDisks(); const auto & disks = volumes[0]->getDisks();
if (disks.size() != 1) if (disks.size() != 1)
return false; return false;
if (disks[0]->getName() != "default") if (disks[0]->getName() != DEFAULT_DISK_NAME)
return false; return false;
return true; return true;
@ -128,10 +163,10 @@ DiskPtr StoragePolicy::getAnyDisk() const
/// StoragePolicy must contain at least one Volume /// StoragePolicy must contain at least one Volume
/// Volume must contain at least one Disk /// Volume must contain at least one Disk
if (volumes.empty()) if (volumes.empty())
throw Exception("StoragePolicy has no volumes. It's a bug.", ErrorCodes::LOGICAL_ERROR); throw Exception("Storage policy " + backQuote(name) + " has no volumes. It's a bug.", ErrorCodes::LOGICAL_ERROR);
if (volumes[0]->getDisks().empty()) if (volumes[0]->getDisks().empty())
throw Exception("Volume '" + volumes[0]->getName() + "' has no disks. It's a bug.", ErrorCodes::LOGICAL_ERROR); throw Exception("Volume " + backQuote(name) + "." + backQuote(volumes[0]->getName()) + " has no disks. It's a bug.", ErrorCodes::LOGICAL_ERROR);
return volumes[0]->getDisks()[0]; return volumes[0]->getDisks()[0];
} }
@ -195,6 +230,24 @@ ReservationPtr StoragePolicy::makeEmptyReservationOnLargestDisk() const
} }
VolumePtr StoragePolicy::getVolume(size_t index) const
{
if (index < volume_index_by_volume_name.size())
return volumes[index];
else
throw Exception("No volume with index " + std::to_string(index) + " in storage policy " + backQuote(name), ErrorCodes::UNKNOWN_VOLUME);
}
VolumePtr StoragePolicy::getVolumeByName(const String & volume_name) const
{
auto it = volume_index_by_volume_name.find(volume_name);
if (it == volume_index_by_volume_name.end())
throw Exception("No such volume " + backQuote(volume_name) + " in storage policy " + backQuote(name), ErrorCodes::UNKNOWN_VOLUME);
return getVolume(it->second);
}
void StoragePolicy::checkCompatibleWith(const StoragePolicyPtr & new_storage_policy) const void StoragePolicy::checkCompatibleWith(const StoragePolicyPtr & new_storage_policy) const
{ {
std::unordered_set<String> new_volume_names; std::unordered_set<String> new_volume_names;
@ -204,7 +257,7 @@ void StoragePolicy::checkCompatibleWith(const StoragePolicyPtr & new_storage_pol
for (const auto & volume : getVolumes()) for (const auto & volume : getVolumes())
{ {
if (new_volume_names.count(volume->getName()) == 0) if (new_volume_names.count(volume->getName()) == 0)
throw Exception("New storage policy shall contain volumes of old one", ErrorCodes::BAD_ARGUMENTS); throw Exception("New storage policy " + backQuote(name) + " shall contain volumes of old one", ErrorCodes::BAD_ARGUMENTS);
std::unordered_set<String> new_disk_names; std::unordered_set<String> new_disk_names;
for (const auto & disk : new_storage_policy->getVolumeByName(volume->getName())->getDisks()) for (const auto & disk : new_storage_policy->getVolumeByName(volume->getName())->getDisks())
@ -212,21 +265,46 @@ void StoragePolicy::checkCompatibleWith(const StoragePolicyPtr & new_storage_pol
for (const auto & disk : volume->getDisks()) for (const auto & disk : volume->getDisks())
if (new_disk_names.count(disk->getName()) == 0) if (new_disk_names.count(disk->getName()) == 0)
throw Exception("New storage policy shall contain disks of old one", ErrorCodes::BAD_ARGUMENTS); throw Exception("New storage policy " + backQuote(name) + " shall contain disks of old one", ErrorCodes::BAD_ARGUMENTS);
} }
} }
size_t StoragePolicy::getVolumeIndexByDisk(const DiskPtr & disk_ptr) const size_t StoragePolicy::getVolumeIndexByDisk(const DiskPtr & disk_ptr) const
{ {
for (size_t i = 0; i < volumes.size(); ++i) auto it = volume_index_by_disk_name.find(disk_ptr->getName());
if (it != volume_index_by_disk_name.end())
return it->second;
else
throw Exception("No disk " + backQuote(disk_ptr->getName()) + " in policy " + backQuote(name), ErrorCodes::UNKNOWN_DISK);
}
void StoragePolicy::buildVolumeIndices()
{
for (size_t index = 0; index < volumes.size(); ++index)
{ {
const auto & volume = volumes[i]; const VolumePtr & volume = volumes[index];
if (volume_index_by_volume_name.find(volume->getName()) != volume_index_by_volume_name.end())
throw Exception("Volume names must be unique in storage policy "
+ backQuote(name) + " (" + backQuote(volume->getName()) + " is duplicated)"
, ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);
volume_index_by_volume_name[volume->getName()] = index;
for (const auto & disk : volume->getDisks()) for (const auto & disk : volume->getDisks())
if (disk->getName() == disk_ptr->getName()) {
return i; const String & disk_name = disk->getName();
if (volume_index_by_disk_name.find(disk_name) != volume_index_by_disk_name.end())
throw Exception("Disk names must be unique in storage policy "
+ backQuote(name) + " (" + backQuote(disk_name) + " is duplicated)"
, ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);
volume_index_by_disk_name[disk_name] = index;
}
} }
throw Exception("No disk " + disk_ptr->getName() + " in policy " + name, ErrorCodes::UNKNOWN_DISK);
} }
@ -242,44 +320,40 @@ StoragePolicySelector::StoragePolicySelector(
{ {
if (!std::all_of(name.begin(), name.end(), isWordCharASCII)) if (!std::all_of(name.begin(), name.end(), isWordCharASCII))
throw Exception( throw Exception(
"StoragePolicy name can contain only alphanumeric and '_' (" + name + ")", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG); "Storage policy name can contain only alphanumeric and '_' (" + backQuote(name) + ")", ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG);
policies.emplace(name, std::make_shared<StoragePolicy>(name, config, config_prefix + "." + name, disks)); policies.emplace(name, std::make_shared<StoragePolicy>(name, config, config_prefix + "." + name, disks));
LOG_INFO(&Poco::Logger::get("StoragePolicySelector"), "Storage policy {} loaded", backQuote(name)); LOG_INFO(&Poco::Logger::get("StoragePolicySelector"), "Storage policy {} loaded", backQuote(name));
} }
constexpr auto default_storage_policy_name = "default"; /// Add default policy if it isn't explicitly specified.
constexpr auto default_volume_name = "default"; if (policies.find(DEFAULT_STORAGE_POLICY_NAME) == policies.end())
constexpr auto default_disk_name = "default";
/// Add default policy if it's not specified explicetly
if (policies.find(default_storage_policy_name) == policies.end())
{ {
auto default_volume = std::make_shared<VolumeJBOD>(default_volume_name, std::vector<DiskPtr>{disks->get(default_disk_name)}, 0); auto default_policy = std::make_shared<StoragePolicy>(DEFAULT_STORAGE_POLICY_NAME, config, config_prefix + "." + DEFAULT_STORAGE_POLICY_NAME, disks);
policies.emplace(DEFAULT_STORAGE_POLICY_NAME, std::move(default_policy));
auto default_policy = std::make_shared<StoragePolicy>(default_storage_policy_name, Volumes{default_volume}, 0.0);
policies.emplace(default_storage_policy_name, default_policy);
} }
} }
StoragePolicySelectorPtr StoragePolicySelector::updateFromConfig(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, DiskSelectorPtr disks) const StoragePolicySelectorPtr StoragePolicySelector::updateFromConfig(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, DiskSelectorPtr disks) const
{ {
Poco::Util::AbstractConfiguration::Keys keys;
config.keys(config_prefix, keys);
std::shared_ptr<StoragePolicySelector> result = std::make_shared<StoragePolicySelector>(config, config_prefix, disks); std::shared_ptr<StoragePolicySelector> result = std::make_shared<StoragePolicySelector>(config, config_prefix, disks);
constexpr auto default_storage_policy_name = "default"; /// First pass, check.
for (const auto & [name, policy] : policies) for (const auto & [name, policy] : policies)
{ {
if (name != default_storage_policy_name && result->policies.count(name) == 0) if (result->policies.count(name) == 0)
throw Exception("Storage policy " + backQuote(name) + " is missing in new configuration", ErrorCodes::BAD_ARGUMENTS); throw Exception("Storage policy " + backQuote(name) + " is missing in new configuration", ErrorCodes::BAD_ARGUMENTS);
policy->checkCompatibleWith(result->policies[name]); policy->checkCompatibleWith(result->policies[name]);
} }
/// Second pass, load.
for (const auto & [name, policy] : policies)
{
result->policies[name] = std::make_shared<StoragePolicy>(*policy, config, config_prefix + "." + name, disks);
}
return result; return result;
} }
@ -288,7 +362,7 @@ StoragePolicyPtr StoragePolicySelector::get(const String & name) const
{ {
auto it = policies.find(name); auto it = policies.find(name);
if (it == policies.end()) if (it == policies.end())
throw Exception("Unknown StoragePolicy " + name, ErrorCodes::UNKNOWN_POLICY); throw Exception("Unknown storage policy " + backQuote(name), ErrorCodes::UNKNOWN_POLICY);
return it->second; return it->second;
} }

View File

@ -14,6 +14,7 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <unordered_map>
#include <unistd.h> #include <unistd.h>
#include <boost/noncopyable.hpp> #include <boost/noncopyable.hpp>
#include <Poco/Util/AbstractConfiguration.h> #include <Poco/Util/AbstractConfiguration.h>
@ -36,6 +37,13 @@ public:
StoragePolicy(String name_, Volumes volumes_, double move_factor_); StoragePolicy(String name_, Volumes volumes_, double move_factor_);
StoragePolicy(
const StoragePolicy & storage_policy,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr disks
);
bool isDefaultPolicy() const; bool isDefaultPolicy() const;
/// Returns disks ordered by volumes priority /// Returns disks ordered by volumes priority
@ -72,16 +80,10 @@ public:
/// which should be kept with help of background moves /// which should be kept with help of background moves
double getMoveFactor() const { return move_factor; } double getMoveFactor() const { return move_factor; }
/// Get volume by index from storage_policy /// Get volume by index.
VolumePtr getVolume(size_t i) const { return (i < volumes_names.size() ? volumes[i] : VolumePtr()); } VolumePtr getVolume(size_t index) const;
VolumePtr getVolumeByName(const String & volume_name) const VolumePtr getVolumeByName(const String & volume_name) const;
{
auto it = volumes_names.find(volume_name);
if (it == volumes_names.end())
return {};
return getVolume(it->second);
}
/// Checks if storage policy can be replaced by another one. /// Checks if storage policy can be replaced by another one.
void checkCompatibleWith(const StoragePolicyPtr & new_storage_policy) const; void checkCompatibleWith(const StoragePolicyPtr & new_storage_policy) const;
@ -89,12 +91,15 @@ public:
private: private:
Volumes volumes; Volumes volumes;
const String name; const String name;
std::map<String, size_t> volumes_names; std::unordered_map<String, size_t> volume_index_by_volume_name;
std::unordered_map<String, size_t> volume_index_by_disk_name;
/// move_factor from interval [0., 1.] /// move_factor from interval [0., 1.]
/// We move something if disk from this policy /// We move something if disk from this policy
/// filled more than total_size * move_factor /// filled more than total_size * move_factor
double move_factor = 0.1; /// by default move factor is 10% double move_factor = 0.1; /// by default move factor is 10%
void buildVolumeIndices();
}; };

View File

@ -56,11 +56,23 @@ VolumeJBOD::VolumeJBOD(
/// Default value is 'true' due to backward compatibility. /// Default value is 'true' due to backward compatibility.
perform_ttl_move_on_insert = config.getBool(config_prefix + ".perform_ttl_move_on_insert", true); perform_ttl_move_on_insert = config.getBool(config_prefix + ".perform_ttl_move_on_insert", true);
are_merges_avoided = config.getBool(config_prefix + ".prefer_not_to_merge", false);
}
VolumeJBOD::VolumeJBOD(const VolumeJBOD & volume_jbod,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr disk_selector)
: VolumeJBOD(volume_jbod.name, config, config_prefix, disk_selector)
{
are_merges_avoided_user_override = volume_jbod.are_merges_avoided_user_override.load(std::memory_order_relaxed);
last_used = volume_jbod.last_used.load(std::memory_order_relaxed);
} }
DiskPtr VolumeJBOD::getDisk(size_t /* index */) const DiskPtr VolumeJBOD::getDisk(size_t /* index */) const
{ {
size_t start_from = last_used.fetch_add(1u, std::memory_order_relaxed); size_t start_from = last_used.fetch_add(1u, std::memory_order_acq_rel);
size_t index = start_from % disks.size(); size_t index = start_from % disks.size();
return disks[index]; return disks[index];
} }
@ -73,7 +85,7 @@ ReservationPtr VolumeJBOD::reserve(UInt64 bytes)
if (max_data_part_size != 0 && bytes > max_data_part_size) if (max_data_part_size != 0 && bytes > max_data_part_size)
return {}; return {};
size_t start_from = last_used.fetch_add(1u, std::memory_order_relaxed); size_t start_from = last_used.fetch_add(1u, std::memory_order_acq_rel);
size_t disks_num = disks.size(); size_t disks_num = disks.size();
for (size_t i = 0; i < disks_num; ++i) for (size_t i = 0; i < disks_num; ++i)
{ {
@ -87,4 +99,19 @@ ReservationPtr VolumeJBOD::reserve(UInt64 bytes)
return {}; return {};
} }
bool VolumeJBOD::areMergesAvoided() const
{
auto are_merges_avoided_user_override_value = are_merges_avoided_user_override.load(std::memory_order_acquire);
if (are_merges_avoided_user_override_value)
return *are_merges_avoided_user_override_value;
else
return are_merges_avoided;
}
void VolumeJBOD::setAvoidMergesUserOverride(bool avoid)
{
are_merges_avoided_user_override.store(avoid, std::memory_order_release);
}
} }

View File

@ -1,10 +1,19 @@
#pragma once #pragma once
#include <memory>
#include <optional>
#include <Disks/IVolume.h> #include <Disks/IVolume.h>
namespace DB namespace DB
{ {
class VolumeJBOD;
using VolumeJBODPtr = std::shared_ptr<VolumeJBOD>;
using VolumesJBOD = std::vector<VolumeJBODPtr>;
/** /**
* Implements something similar to JBOD (https://en.wikipedia.org/wiki/Non-RAID_drive_architectures#JBOD). * Implements something similar to JBOD (https://en.wikipedia.org/wiki/Non-RAID_drive_architectures#JBOD).
* When MergeTree engine wants to write part it requests VolumeJBOD to reserve space on the next available * When MergeTree engine wants to write part it requests VolumeJBOD to reserve space on the next available
@ -13,8 +22,9 @@ namespace DB
class VolumeJBOD : public IVolume class VolumeJBOD : public IVolume
{ {
public: public:
VolumeJBOD(String name_, Disks disks_, UInt64 max_data_part_size_) VolumeJBOD(String name_, Disks disks_, UInt64 max_data_part_size_, bool are_merges_avoided_)
: IVolume(name_, disks_, max_data_part_size_) : IVolume(name_, disks_, max_data_part_size_)
, are_merges_avoided(are_merges_avoided_)
{ {
} }
@ -25,6 +35,13 @@ public:
DiskSelectorPtr disk_selector DiskSelectorPtr disk_selector
); );
VolumeJBOD(
const VolumeJBOD & volume_jbod,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr disk_selector
);
VolumeType getType() const override { return VolumeType::JBOD; } VolumeType getType() const override { return VolumeType::JBOD; }
/// Always returns next disk (round-robin), ignores argument. /// Always returns next disk (round-robin), ignores argument.
@ -38,11 +55,19 @@ public:
/// Returns valid reservation or nullptr if there is no space left on any disk. /// Returns valid reservation or nullptr if there is no space left on any disk.
ReservationPtr reserve(UInt64 bytes) override; ReservationPtr reserve(UInt64 bytes) override;
bool areMergesAvoided() const override;
void setAvoidMergesUserOverride(bool avoid) override;
/// True if parts on this volume participate in merges according to configuration.
bool are_merges_avoided = true;
private: private:
/// Index of last used disk.
mutable std::atomic<size_t> last_used = 0; mutable std::atomic<size_t> last_used = 0;
/// True if parts on this volume participate in merges according to START/STOP MERGES ON VOLUME.
std::atomic<std::optional<bool>> are_merges_avoided_user_override{std::nullopt};
}; };
using VolumeJBODPtr = std::shared_ptr<VolumeJBOD>;
using VolumesJBOD = std::vector<VolumeJBODPtr>;
} }

View File

@ -3,18 +3,23 @@
#include <Disks/createVolume.h> #include <Disks/createVolume.h>
#include <Disks/VolumeJBOD.h> #include <Disks/VolumeJBOD.h>
namespace DB namespace DB
{ {
/// Volume which reserserves space on each underlying disk. class VolumeRAID1;
using VolumeRAID1Ptr = std::shared_ptr<VolumeRAID1>;
/// Volume which reserves space on each underlying disk.
/// ///
/// NOTE: Just interface implementation, doesn't used in codebase, /// NOTE: Just interface implementation, doesn't used in codebase,
/// also not available for user. /// also not available for user.
class VolumeRAID1 : public VolumeJBOD class VolumeRAID1 : public VolumeJBOD
{ {
public: public:
VolumeRAID1(String name_, Disks disks_, UInt64 max_data_part_size_) VolumeRAID1(String name_, Disks disks_, UInt64 max_data_part_size_, bool are_merges_avoided_in_config_)
: VolumeJBOD(name_, disks_, max_data_part_size_) : VolumeJBOD(name_, disks_, max_data_part_size_, are_merges_avoided_in_config_)
{ {
} }
@ -27,11 +32,18 @@ public:
{ {
} }
VolumeRAID1(
VolumeRAID1 & volume_raid1,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr disk_selector)
: VolumeJBOD(volume_raid1, config, config_prefix, disk_selector)
{
}
VolumeType getType() const override { return VolumeType::RAID1; } VolumeType getType() const override { return VolumeType::RAID1; }
ReservationPtr reserve(UInt64 bytes) override; ReservationPtr reserve(UInt64 bytes) override;
}; };
using VolumeRAID1Ptr = std::shared_ptr<VolumeRAID1>;
} }

View File

@ -12,6 +12,7 @@ namespace DB
namespace ErrorCodes namespace ErrorCodes
{ {
extern const int UNKNOWN_RAID_TYPE; extern const int UNKNOWN_RAID_TYPE;
extern const int INVALID_RAID_TYPE;
} }
VolumePtr createVolumeFromReservation(const ReservationPtr & reservation, VolumePtr other_volume) VolumePtr createVolumeFromReservation(const ReservationPtr & reservation, VolumePtr other_volume)
@ -20,12 +21,12 @@ VolumePtr createVolumeFromReservation(const ReservationPtr & reservation, Volume
{ {
/// Since reservation on JBOD chooses one of disks and makes reservation there, volume /// Since reservation on JBOD chooses one of disks and makes reservation there, volume
/// for such type of reservation will be with one disk. /// for such type of reservation will be with one disk.
return std::make_shared<SingleDiskVolume>(other_volume->getName(), reservation->getDisk()); return std::make_shared<SingleDiskVolume>(other_volume->getName(), reservation->getDisk(), other_volume->max_data_part_size);
} }
if (other_volume->getType() == VolumeType::RAID1) if (other_volume->getType() == VolumeType::RAID1)
{ {
auto volume = std::dynamic_pointer_cast<VolumeRAID1>(other_volume); auto volume = std::dynamic_pointer_cast<VolumeRAID1>(other_volume);
return std::make_shared<VolumeRAID1>(volume->getName(), reservation->getDisks(), volume->max_data_part_size); return std::make_shared<VolumeRAID1>(volume->getName(), reservation->getDisks(), volume->max_data_part_size, volume->are_merges_avoided);
} }
return nullptr; return nullptr;
} }
@ -37,17 +38,31 @@ VolumePtr createVolumeFromConfig(
DiskSelectorPtr disk_selector DiskSelectorPtr disk_selector
) )
{ {
auto has_raid_type = config.has(config_prefix + ".raid_type"); String raid_type = config.getString(config_prefix + ".raid_type", "JBOD");
if (!has_raid_type)
{
return std::make_shared<VolumeJBOD>(name, config, config_prefix, disk_selector);
}
String raid_type = config.getString(config_prefix + ".raid_type");
if (raid_type == "JBOD") if (raid_type == "JBOD")
{ {
return std::make_shared<VolumeJBOD>(name, config, config_prefix, disk_selector); return std::make_shared<VolumeJBOD>(name, config, config_prefix, disk_selector);
} }
throw Exception("Unknown raid type '" + raid_type + "'", ErrorCodes::UNKNOWN_RAID_TYPE); throw Exception("Unknown RAID type '" + raid_type + "'", ErrorCodes::UNKNOWN_RAID_TYPE);
}
VolumePtr updateVolumeFromConfig(
VolumePtr volume,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr & disk_selector
)
{
String raid_type = config.getString(config_prefix + ".raid_type", "JBOD");
if (raid_type == "JBOD")
{
VolumeJBODPtr volume_jbod = std::dynamic_pointer_cast<VolumeJBOD>(volume);
if (!volume_jbod)
throw Exception("Invalid RAID type '" + raid_type + "', shall be JBOD", ErrorCodes::INVALID_RAID_TYPE);
return std::make_shared<VolumeJBOD>(*volume_jbod, config, config_prefix, disk_selector);
}
throw Exception("Unknown RAID type '" + raid_type + "'", ErrorCodes::UNKNOWN_RAID_TYPE);
} }
} }

View File

@ -6,6 +6,7 @@ namespace DB
{ {
VolumePtr createVolumeFromReservation(const ReservationPtr & reservation, VolumePtr other_volume); VolumePtr createVolumeFromReservation(const ReservationPtr & reservation, VolumePtr other_volume);
VolumePtr createVolumeFromConfig( VolumePtr createVolumeFromConfig(
String name_, String name_,
const Poco::Util::AbstractConfiguration & config, const Poco::Util::AbstractConfiguration & config,
@ -13,4 +14,11 @@ VolumePtr createVolumeFromConfig(
DiskSelectorPtr disk_selector DiskSelectorPtr disk_selector
); );
VolumePtr updateVolumeFromConfig(
VolumePtr volume,
const Poco::Util::AbstractConfiguration & config,
const String & config_prefix,
DiskSelectorPtr & disk_selector
);
} }

View File

@ -49,6 +49,7 @@ static FormatSettings getInputFormatSetting(const Settings & settings, const Con
format_settings.csv.allow_double_quotes = settings.format_csv_allow_double_quotes; format_settings.csv.allow_double_quotes = settings.format_csv_allow_double_quotes;
format_settings.csv.unquoted_null_literal_as_null = settings.input_format_csv_unquoted_null_literal_as_null; format_settings.csv.unquoted_null_literal_as_null = settings.input_format_csv_unquoted_null_literal_as_null;
format_settings.csv.empty_as_default = settings.input_format_defaults_for_omitted_fields; format_settings.csv.empty_as_default = settings.input_format_defaults_for_omitted_fields;
format_settings.csv.input_format_enum_as_number = settings.input_format_csv_enum_as_number;
format_settings.null_as_default = settings.input_format_null_as_default; format_settings.null_as_default = settings.input_format_null_as_default;
format_settings.values.interpret_expressions = settings.input_format_values_interpret_expressions; format_settings.values.interpret_expressions = settings.input_format_values_interpret_expressions;
format_settings.values.deduce_templates_of_expressions = settings.input_format_values_deduce_templates_of_expressions; format_settings.values.deduce_templates_of_expressions = settings.input_format_values_deduce_templates_of_expressions;
@ -63,6 +64,7 @@ static FormatSettings getInputFormatSetting(const Settings & settings, const Con
format_settings.template_settings.row_format = settings.format_template_row; format_settings.template_settings.row_format = settings.format_template_row;
format_settings.template_settings.row_between_delimiter = settings.format_template_rows_between_delimiter; format_settings.template_settings.row_between_delimiter = settings.format_template_rows_between_delimiter;
format_settings.tsv.empty_as_default = settings.input_format_tsv_empty_as_default; format_settings.tsv.empty_as_default = settings.input_format_tsv_empty_as_default;
format_settings.tsv.input_format_enum_as_number = settings.input_format_tsv_enum_as_number;
format_settings.schema.format_schema = settings.format_schema; format_settings.schema.format_schema = settings.format_schema;
format_settings.schema.format_schema_path = context.getFormatSchemaPath(); format_settings.schema.format_schema_path = context.getFormatSchemaPath();
format_settings.schema.is_server = context.hasGlobalContext() && (context.getGlobalContext().getApplicationType() == Context::ApplicationType::SERVER); format_settings.schema.is_server = context.hasGlobalContext() && (context.getGlobalContext().getApplicationType() == Context::ApplicationType::SERVER);

View File

@ -34,6 +34,7 @@ struct FormatSettings
bool unquoted_null_literal_as_null = false; bool unquoted_null_literal_as_null = false;
bool empty_as_default = false; bool empty_as_default = false;
bool crlf_end_of_line = false; bool crlf_end_of_line = false;
bool input_format_enum_as_number = false;
}; };
CSV csv; CSV csv;
@ -81,6 +82,7 @@ struct FormatSettings
bool empty_as_default = false; bool empty_as_default = false;
bool crlf_end_of_line = false; bool crlf_end_of_line = false;
String null_representation = "\\N"; String null_representation = "\\N";
bool input_format_enum_as_number = false;
}; };
TSV tsv; TSV tsv;

View File

@ -92,7 +92,7 @@ struct ToStartOfWeekImpl
template <typename FromType, typename ToType, typename Transform> template <typename FromType, typename ToType, typename Transform>
struct Transformer struct Transformer
{ {
Transformer(Transform transform_) explicit Transformer(Transform transform_)
: transform(std::move(transform_)) : transform(std::move(transform_))
{} {}
@ -116,29 +116,29 @@ template <typename FromDataType, typename ToDataType>
struct CustomWeekTransformImpl struct CustomWeekTransformImpl
{ {
template <typename Transform> template <typename Transform>
static void execute(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t /*input_rows_count*/, Transform transform = {}) static ColumnPtr execute(ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t /*input_rows_count*/, Transform transform = {})
{ {
const auto op = Transformer<typename FromDataType::FieldType, typename ToDataType::FieldType, Transform>{std::move(transform)}; const auto op = Transformer<typename FromDataType::FieldType, typename ToDataType::FieldType, Transform>{std::move(transform)};
UInt8 week_mode = DEFAULT_WEEK_MODE; UInt8 week_mode = DEFAULT_WEEK_MODE;
if (arguments.size() > 1) if (arguments.size() > 1)
{ {
if (const auto week_mode_column = checkAndGetColumnConst<ColumnUInt8>(columns[arguments[1]].column.get())) if (const auto * week_mode_column = checkAndGetColumnConst<ColumnUInt8>(arguments[1].column.get()))
week_mode = week_mode_column->getValue<UInt8>(); week_mode = week_mode_column->getValue<UInt8>();
} }
const DateLUTImpl & time_zone = extractTimeZoneFromFunctionArguments(columns, arguments, 2, 0); const DateLUTImpl & time_zone = extractTimeZoneFromFunctionArguments(arguments, 2, 0);
const ColumnPtr source_col = columns[arguments[0]].column; const ColumnPtr source_col = arguments[0].column;
if (const auto * sources = checkAndGetColumn<typename FromDataType::ColumnType>(source_col.get())) if (const auto * sources = checkAndGetColumn<typename FromDataType::ColumnType>(source_col.get()))
{ {
auto col_to = ToDataType::ColumnType::create(); auto col_to = ToDataType::ColumnType::create();
op.vector(sources->getData(), col_to->getData(), week_mode, time_zone); op.vector(sources->getData(), col_to->getData(), week_mode, time_zone);
columns[result].column = std::move(col_to); return col_to;
} }
else else
{ {
throw Exception( throw Exception(
"Illegal column " + columns[arguments[0]].column->getName() + " of first argument of function " "Illegal column " + arguments[0].column->getName() + " of first argument of function "
+ Transform::name, + Transform::name,
ErrorCodes::ILLEGAL_COLUMN); ErrorCodes::ILLEGAL_COLUMN);
} }

View File

@ -683,25 +683,25 @@ struct Transformer
template <typename FromDataType, typename ToDataType, typename Transform> template <typename FromDataType, typename ToDataType, typename Transform>
struct DateTimeTransformImpl struct DateTimeTransformImpl
{ {
static void execute(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t /*input_rows_count*/, const Transform & transform = {}) static ColumnPtr execute(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t /*input_rows_count*/, const Transform & transform = {})
{ {
using Op = Transformer<typename FromDataType::FieldType, typename ToDataType::FieldType, Transform>; using Op = Transformer<typename FromDataType::FieldType, typename ToDataType::FieldType, Transform>;
const DateLUTImpl & time_zone = extractTimeZoneFromFunctionArguments(columns, arguments, 1, 0); const DateLUTImpl & time_zone = extractTimeZoneFromFunctionArguments(arguments, 1, 0);
const ColumnPtr source_col = columns[arguments[0]].column; const ColumnPtr source_col = arguments[0].column;
if (const auto * sources = checkAndGetColumn<typename FromDataType::ColumnType>(source_col.get())) if (const auto * sources = checkAndGetColumn<typename FromDataType::ColumnType>(source_col.get()))
{ {
auto mutable_result_col = columns[result].type->createColumn(); auto mutable_result_col = result_type->createColumn();
auto * col_to = assert_cast<typename ToDataType::ColumnType *>(mutable_result_col.get()); auto * col_to = assert_cast<typename ToDataType::ColumnType *>(mutable_result_col.get());
Op::vector(sources->getData(), col_to->getData(), time_zone, transform); Op::vector(sources->getData(), col_to->getData(), time_zone, transform);
columns[result].column = std::move(mutable_result_col); return mutable_result_col;
} }
else else
{ {
throw Exception("Illegal column " + columns[arguments[0]].column->getName() throw Exception("Illegal column " + arguments[0].column->getName()
+ " of first argument of function " + Transform::name, + " of first argument of function " + Transform::name,
ErrorCodes::ILLEGAL_COLUMN); ErrorCodes::ILLEGAL_COLUMN);
} }

View File

@ -91,14 +91,14 @@ public:
return std::make_shared<DataTypeString>(); return std::make_shared<DataTypeString>();
} }
void executeImpl(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{ {
const ColumnPtr column_string = columns[arguments[0]].column; const ColumnPtr column_string = arguments[0].column;
const ColumnString * input = checkAndGetColumn<ColumnString>(column_string.get()); const ColumnString * input = checkAndGetColumn<ColumnString>(column_string.get());
if (!input) if (!input)
throw Exception( throw Exception(
"Illegal column " + columns[arguments[0]].column->getName() + " of first argument of function " + getName(), "Illegal column " + arguments[0].column->getName() + " of first argument of function " + getName(),
ErrorCodes::ILLEGAL_COLUMN); ErrorCodes::ILLEGAL_COLUMN);
auto dst_column = ColumnString::create(); auto dst_column = ColumnString::create();
@ -111,9 +111,9 @@ public:
const ColumnString::Offsets & src_offsets = input->getOffsets(); const ColumnString::Offsets & src_offsets = input->getOffsets();
auto source = input->getChars().data(); const auto * source = input->getChars().data();
auto dst = dst_data.data(); auto * dst = dst_data.data();
auto dst_pos = dst; auto * dst_pos = dst;
size_t src_offset_prev = 0; size_t src_offset_prev = 0;
@ -141,7 +141,7 @@ public:
{ {
// during decoding character array can be partially polluted // during decoding character array can be partially polluted
// if fail, revert back and clean // if fail, revert back and clean
auto savepoint = dst_pos; auto * savepoint = dst_pos;
outlen = _tb64d(reinterpret_cast<const uint8_t *>(source), srclen, reinterpret_cast<uint8_t *>(dst_pos)); outlen = _tb64d(reinterpret_cast<const uint8_t *>(source), srclen, reinterpret_cast<uint8_t *>(dst_pos));
if (!outlen) if (!outlen)
{ {
@ -166,7 +166,7 @@ public:
dst_data.resize(dst_pos - dst); dst_data.resize(dst_pos - dst);
columns[result].column = std::move(dst_column); return dst_column;
} }
}; };
} }

View File

@ -613,17 +613,17 @@ class FunctionBinaryArithmetic : public IFunction
} }
/// Multiply aggregation state by integer constant: by merging it with itself specified number of times. /// Multiply aggregation state by integer constant: by merging it with itself specified number of times.
void executeAggregateMultiply(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const ColumnPtr executeAggregateMultiply(ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const
{ {
ColumnNumbers new_arguments = arguments; ColumnsWithTypeAndName new_arguments = arguments;
if (WhichDataType(columns[new_arguments[1]].type).isAggregateFunction()) if (WhichDataType(new_arguments[1].type).isAggregateFunction())
std::swap(new_arguments[0], new_arguments[1]); std::swap(new_arguments[0], new_arguments[1]);
if (!isColumnConst(*columns[new_arguments[1]].column)) if (!isColumnConst(*new_arguments[1].column))
throw Exception{"Illegal column " + columns[new_arguments[1]].column->getName() throw Exception{"Illegal column " + new_arguments[1].column->getName()
+ " of argument of aggregation state multiply. Should be integer constant", ErrorCodes::ILLEGAL_COLUMN}; + " of argument of aggregation state multiply. Should be integer constant", ErrorCodes::ILLEGAL_COLUMN};
const IColumn & agg_state_column = *columns[new_arguments[0]].column; const IColumn & agg_state_column = *new_arguments[0].column;
bool agg_state_is_const = isColumnConst(agg_state_column); bool agg_state_is_const = isColumnConst(agg_state_column);
const ColumnAggregateFunction & column = typeid_cast<const ColumnAggregateFunction &>( const ColumnAggregateFunction & column = typeid_cast<const ColumnAggregateFunction &>(
agg_state_is_const ? assert_cast<const ColumnConst &>(agg_state_column).getDataColumn() : agg_state_column); agg_state_is_const ? assert_cast<const ColumnConst &>(agg_state_column).getDataColumn() : agg_state_column);
@ -647,7 +647,7 @@ class FunctionBinaryArithmetic : public IFunction
auto & vec_to = column_to->getData(); auto & vec_to = column_to->getData();
auto & vec_from = column_from->getData(); auto & vec_from = column_from->getData();
UInt64 m = typeid_cast<const ColumnConst *>(columns[new_arguments[1]].column.get())->getValue<UInt64>(); UInt64 m = typeid_cast<const ColumnConst *>(new_arguments[1].column.get())->getValue<UInt64>();
// Since we merge the function states by ourselves, we have to have an // Since we merge the function states by ourselves, we have to have an
// Arena for this. Pass it to the resulting column so that the arena // Arena for this. Pass it to the resulting column so that the arena
@ -674,16 +674,16 @@ class FunctionBinaryArithmetic : public IFunction
} }
if (agg_state_is_const) if (agg_state_is_const)
columns[result].column = ColumnConst::create(std::move(column_to), input_rows_count); return ColumnConst::create(std::move(column_to), input_rows_count);
else else
columns[result].column = std::move(column_to); return column_to;
} }
/// Merge two aggregation states together. /// Merge two aggregation states together.
void executeAggregateAddition(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const ColumnPtr executeAggregateAddition(ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const
{ {
const IColumn & lhs_column = *columns[arguments[0]].column; const IColumn & lhs_column = *arguments[0].column;
const IColumn & rhs_column = *columns[arguments[1]].column; const IColumn & rhs_column = *arguments[1].column;
bool lhs_is_const = isColumnConst(lhs_column); bool lhs_is_const = isColumnConst(lhs_column);
bool rhs_is_const = isColumnConst(rhs_column); bool rhs_is_const = isColumnConst(rhs_column);
@ -707,37 +707,33 @@ class FunctionBinaryArithmetic : public IFunction
} }
if (lhs_is_const && rhs_is_const) if (lhs_is_const && rhs_is_const)
columns[result].column = ColumnConst::create(std::move(column_to), input_rows_count); return ColumnConst::create(std::move(column_to), input_rows_count);
else else
columns[result].column = std::move(column_to); return column_to;
} }
void executeDateTimeIntervalPlusMinus(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, ColumnPtr executeDateTimeIntervalPlusMinus(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type,
size_t result, size_t input_rows_count, const FunctionOverloadResolverPtr & function_builder) const size_t input_rows_count, const FunctionOverloadResolverPtr & function_builder) const
{ {
ColumnNumbers new_arguments = arguments; ColumnsWithTypeAndName new_arguments = arguments;
/// Interval argument must be second. /// Interval argument must be second.
if (WhichDataType(columns[arguments[1]].type).isDateOrDateTime()) if (WhichDataType(arguments[1].type).isDateOrDateTime())
std::swap(new_arguments[0], new_arguments[1]); std::swap(new_arguments[0], new_arguments[1]);
/// Change interval argument type to its representation /// Change interval argument type to its representation
ColumnsWithTypeAndName new_columns = columns; new_arguments[1].type = std::make_shared<DataTypeNumber<DataTypeInterval::FieldType>>();
new_columns[new_arguments[1]].type = std::make_shared<DataTypeNumber<DataTypeInterval::FieldType>>();
ColumnsWithTypeAndName new_arguments_with_type_and_name = auto function = function_builder->build(new_arguments);
{new_columns[new_arguments[0]], new_columns[new_arguments[1]]};
auto function = function_builder->build(new_arguments_with_type_and_name);
function->execute(new_columns, new_arguments, result, input_rows_count); return function->execute(new_arguments, result_type, input_rows_count);
columns[result].column = new_columns[result].column;
} }
public: public:
static constexpr auto name = Name::name; static constexpr auto name = Name::name;
static FunctionPtr create(const Context & context) { return std::make_shared<FunctionBinaryArithmetic>(context); } static FunctionPtr create(const Context & context) { return std::make_shared<FunctionBinaryArithmetic>(context); }
FunctionBinaryArithmetic(const Context & context_) explicit FunctionBinaryArithmetic(const Context & context_)
: context(context_), : context(context_),
check_decimal_overflow(decimalCheckArithmeticOverflow(context)) check_decimal_overflow(decimalCheckArithmeticOverflow(context))
{} {}
@ -790,7 +786,7 @@ public:
new_arguments[1].type = std::make_shared<DataTypeNumber<DataTypeInterval::FieldType>>(); new_arguments[1].type = std::make_shared<DataTypeNumber<DataTypeInterval::FieldType>>();
auto function = function_builder->build(new_arguments); auto function = function_builder->build(new_arguments);
return function->getReturnType(); return function->getResultType();
} }
DataTypePtr type_res; DataTypePtr type_res;
@ -851,20 +847,20 @@ public:
return type_res; return type_res;
} }
bool executeFixedString(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result) const ColumnPtr executeFixedString(ColumnsWithTypeAndName & arguments) const
{ {
using OpImpl = FixedStringOperationImpl<Op<UInt8, UInt8>>; using OpImpl = FixedStringOperationImpl<Op<UInt8, UInt8>>;
auto col_left_raw = columns[arguments[0]].column.get(); const auto * col_left_raw = arguments[0].column.get();
auto col_right_raw = columns[arguments[1]].column.get(); const auto * col_right_raw = arguments[1].column.get();
if (auto col_left_const = checkAndGetColumnConst<ColumnFixedString>(col_left_raw)) if (const auto * col_left_const = checkAndGetColumnConst<ColumnFixedString>(col_left_raw))
{ {
if (auto col_right_const = checkAndGetColumnConst<ColumnFixedString>(col_right_raw)) if (const auto * col_right_const = checkAndGetColumnConst<ColumnFixedString>(col_right_raw))
{ {
auto col_left = checkAndGetColumn<ColumnFixedString>(col_left_const->getDataColumn()); const auto * col_left = checkAndGetColumn<ColumnFixedString>(col_left_const->getDataColumn());
auto col_right = checkAndGetColumn<ColumnFixedString>(col_right_const->getDataColumn()); const auto * col_right = checkAndGetColumn<ColumnFixedString>(col_right_const->getDataColumn());
if (col_left->getN() != col_right->getN()) if (col_left->getN() != col_right->getN())
return false; return nullptr;
auto col_res = ColumnFixedString::create(col_left->getN()); auto col_res = ColumnFixedString::create(col_left->getN());
auto & out_chars = col_res->getChars(); auto & out_chars = col_res->getChars();
out_chars.resize(col_left->getN()); out_chars.resize(col_left->getN());
@ -872,25 +868,24 @@ public:
col_right->getChars().data(), col_right->getChars().data(),
out_chars.data(), out_chars.data(),
out_chars.size()); out_chars.size());
columns[result].column = ColumnConst::create(std::move(col_res), col_left_raw->size()); return ColumnConst::create(std::move(col_res), col_left_raw->size());
return true;
} }
} }
bool is_left_column_const = checkAndGetColumnConst<ColumnFixedString>(col_left_raw) != nullptr; bool is_left_column_const = checkAndGetColumnConst<ColumnFixedString>(col_left_raw) != nullptr;
bool is_right_column_const = checkAndGetColumnConst<ColumnFixedString>(col_right_raw) != nullptr; bool is_right_column_const = checkAndGetColumnConst<ColumnFixedString>(col_right_raw) != nullptr;
auto col_left = is_left_column_const const auto * col_left = is_left_column_const
? checkAndGetColumn<ColumnFixedString>(checkAndGetColumnConst<ColumnFixedString>(col_left_raw)->getDataColumn()) ? checkAndGetColumn<ColumnFixedString>(checkAndGetColumnConst<ColumnFixedString>(col_left_raw)->getDataColumn())
: checkAndGetColumn<ColumnFixedString>(col_left_raw); : checkAndGetColumn<ColumnFixedString>(col_left_raw);
auto col_right = is_right_column_const const auto * col_right = is_right_column_const
? checkAndGetColumn<ColumnFixedString>(checkAndGetColumnConst<ColumnFixedString>(col_right_raw)->getDataColumn()) ? checkAndGetColumn<ColumnFixedString>(checkAndGetColumnConst<ColumnFixedString>(col_right_raw)->getDataColumn())
: checkAndGetColumn<ColumnFixedString>(col_right_raw); : checkAndGetColumn<ColumnFixedString>(col_right_raw);
if (col_left && col_right) if (col_left && col_right)
{ {
if (col_left->getN() != col_right->getN()) if (col_left->getN() != col_right->getN())
return false; return nullptr;
auto col_res = ColumnFixedString::create(col_left->getN()); auto col_res = ColumnFixedString::create(col_left->getN());
auto & out_chars = col_res->getChars(); auto & out_chars = col_res->getChars();
@ -922,14 +917,13 @@ public:
out_chars.size(), out_chars.size(),
col_left->getN()); col_left->getN());
} }
columns[result].column = std::move(col_res); return col_res;
return true;
} }
return false; return nullptr;
} }
template <typename A, typename B> template <typename A, typename B>
bool executeNumeric(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result [[maybe_unused]], const A & left, const B & right) const ColumnPtr executeNumeric(ColumnsWithTypeAndName & arguments, const A & left, const B & right) const
{ {
using LeftDataType = std::decay_t<decltype(left)>; using LeftDataType = std::decay_t<decltype(left)>;
using RightDataType = std::decay_t<decltype(right)>; using RightDataType = std::decay_t<decltype(right)>;
@ -944,8 +938,8 @@ public:
using ColVecT1 = std::conditional_t<IsDecimalNumber<T1>, ColumnDecimal<T1>, ColumnVector<T1>>; using ColVecT1 = std::conditional_t<IsDecimalNumber<T1>, ColumnDecimal<T1>, ColumnVector<T1>>;
using ColVecResult = std::conditional_t<IsDecimalNumber<ResultType>, ColumnDecimal<ResultType>, ColumnVector<ResultType>>; using ColVecResult = std::conditional_t<IsDecimalNumber<ResultType>, ColumnDecimal<ResultType>, ColumnVector<ResultType>>;
auto col_left_raw = columns[arguments[0]].column.get(); const auto * col_left_raw = arguments[0].column.get();
auto col_right_raw = columns[arguments[1]].column.get(); const auto * col_right_raw = arguments[1].column.get();
auto col_left_const = checkAndGetColumnConst<ColVecT0>(col_left_raw); auto col_left_const = checkAndGetColumnConst<ColVecT0>(col_left_raw);
auto col_right_const = checkAndGetColumnConst<ColVecT1>(col_right_raw); auto col_right_const = checkAndGetColumnConst<ColVecT1>(col_right_raw);
@ -981,9 +975,8 @@ public:
OpImplCheck::template constantConstant<dec_a, dec_b>(const_a, const_b, scale_a, scale_b) : OpImplCheck::template constantConstant<dec_a, dec_b>(const_a, const_b, scale_a, scale_b) :
OpImpl::template constantConstant<dec_a, dec_b>(const_a, const_b, scale_a, scale_b); OpImpl::template constantConstant<dec_a, dec_b>(const_a, const_b, scale_a, scale_b);
columns[result].column = ResultDataType(type.getPrecision(), type.getScale()).createColumnConst( return ResultDataType(type.getPrecision(), type.getScale()).createColumnConst(
col_left_const->size(), toField(res, type.getScale())); col_left_const->size(), toField(res, type.getScale()));
return true;
} }
col_res = ColVecResult::create(0, type.getScale()); col_res = ColVecResult::create(0, type.getScale());
@ -1016,7 +1009,7 @@ public:
OpImpl::template vectorConstant<dec_a, dec_b>(col_left->getData(), const_b, vec_res, scale_a, scale_b); OpImpl::template vectorConstant<dec_a, dec_b>(col_left->getData(), const_b, vec_res, scale_a, scale_b);
} }
else else
return false; return nullptr;
} }
else else
{ {
@ -1026,8 +1019,7 @@ public:
if (col_left_const && col_right_const) if (col_left_const && col_right_const)
{ {
auto res = OpImpl::constantConstant(col_left_const->template getValue<T0>(), col_right_const->template getValue<T1>()); auto res = OpImpl::constantConstant(col_left_const->template getValue<T0>(), col_right_const->template getValue<T1>());
columns[result].column = ResultDataType().createColumnConst(col_left_const->size(), toField(res)); return ResultDataType().createColumnConst(col_left_const->size(), toField(res));
return true;
} }
col_res = ColVecResult::create(); col_res = ColVecResult::create();
@ -1047,43 +1039,40 @@ public:
OpImpl::vectorConstant(col_left->getData().data(), col_right_const->template getValue<T1>(), vec_res.data(), vec_res.size()); OpImpl::vectorConstant(col_left->getData().data(), col_right_const->template getValue<T1>(), vec_res.data(), vec_res.size());
} }
else else
return false; return nullptr;
} }
columns[result].column = std::move(col_res); return col_res;
return true;
} }
return false; return nullptr;
} }
void executeImpl(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
{ {
/// Special case when multiply aggregate function state /// Special case when multiply aggregate function state
if (isAggregateMultiply(columns[arguments[0]].type, columns[arguments[1]].type)) if (isAggregateMultiply(arguments[0].type, arguments[1].type))
{ {
executeAggregateMultiply(columns, arguments, result, input_rows_count); return executeAggregateMultiply(arguments, result_type, input_rows_count);
return;
} }
/// Special case - addition of two aggregate functions states /// Special case - addition of two aggregate functions states
if (isAggregateAddition(columns[arguments[0]].type, columns[arguments[1]].type)) if (isAggregateAddition(arguments[0].type, arguments[1].type))
{ {
executeAggregateAddition(columns, arguments, result, input_rows_count); return executeAggregateAddition(arguments, result_type, input_rows_count);
return;
} }
/// Special case when the function is plus or minus, one of arguments is Date/DateTime and another is Interval. /// Special case when the function is plus or minus, one of arguments is Date/DateTime and another is Interval.
if (auto function_builder if (auto function_builder
= getFunctionForIntervalArithmetic(columns[arguments[0]].type, columns[arguments[1]].type, context)) = getFunctionForIntervalArithmetic(arguments[0].type, arguments[1].type, context))
{ {
executeDateTimeIntervalPlusMinus(columns, arguments, result, input_rows_count, function_builder); return executeDateTimeIntervalPlusMinus(arguments, result_type, input_rows_count, function_builder);
return;
} }
const auto & left_argument = columns[arguments[0]]; const auto & left_argument = arguments[0];
const auto & right_argument = columns[arguments[1]]; const auto & right_argument = arguments[1];
auto * left_generic = left_argument.type.get(); const auto * left_generic = left_argument.type.get();
auto * right_generic = right_argument.type.get(); const auto * right_generic = right_argument.type.get();
ColumnPtr res;
bool valid = castBothTypes(left_generic, right_generic, [&](const auto & left, const auto & right) bool valid = castBothTypes(left_generic, right_generic, [&](const auto & left, const auto & right)
{ {
using LeftDataType = std::decay_t<decltype(left)>; using LeftDataType = std::decay_t<decltype(left)>;
@ -1093,10 +1082,10 @@ public:
if constexpr (!Op<DataTypeFixedString, DataTypeFixedString>::allow_fixed_string) if constexpr (!Op<DataTypeFixedString, DataTypeFixedString>::allow_fixed_string)
return false; return false;
else else
return executeFixedString(columns, arguments, result); return (res = executeFixedString(arguments)) != nullptr;
} }
else else
return executeNumeric(columns, arguments, result, left, right); return (res = executeNumeric(arguments, left, right)) != nullptr;
}); });
if (!valid) if (!valid)
@ -1109,6 +1098,8 @@ public:
left_argument.name, left_argument.type->getName(), left_argument.name, left_argument.type->getName(),
right_argument.name, right_argument.type->getName()); right_argument.name, right_argument.type->getName());
} }
return res;
} }
#if USE_EMBEDDED_COMPILER #if USE_EMBEDDED_COMPILER
@ -1190,30 +1181,26 @@ public:
{ {
} }
void executeImpl(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
{ {
if (left.column && isColumnConst(*left.column) && arguments.size() == 1) if (left.column && isColumnConst(*left.column) && arguments.size() == 1)
{ {
ColumnsWithTypeAndName columns_with_constant ColumnsWithTypeAndName columns_with_constant
= {{left.column->cloneResized(input_rows_count), left.type, left.name}, = {{left.column->cloneResized(input_rows_count), left.type, left.name},
columns[arguments[0]], arguments[0]};
columns[result]};
Base::executeImpl(columns_with_constant, {0, 1}, 2, input_rows_count); return Base::executeImpl(columns_with_constant, result_type, input_rows_count);
columns[result] = columns_with_constant[2];
} }
else if (right.column && isColumnConst(*right.column) && arguments.size() == 1) else if (right.column && isColumnConst(*right.column) && arguments.size() == 1)
{ {
ColumnsWithTypeAndName columns_with_constant ColumnsWithTypeAndName columns_with_constant
= {columns[arguments[0]], = {arguments[0],
{right.column->cloneResized(input_rows_count), right.type, right.name}, {right.column->cloneResized(input_rows_count), right.type, right.name}};
columns[result]};
Base::executeImpl(columns_with_constant, {0, 1}, 2, input_rows_count); return Base::executeImpl(columns_with_constant, result_type, input_rows_count);
columns[result] = columns_with_constant[2];
} }
else else
Base::executeImpl(columns, arguments, result, input_rows_count); return Base::executeImpl(arguments, result_type, input_rows_count);
} }
bool hasInformationAboutMonotonicity() const override bool hasInformationAboutMonotonicity() const override
@ -1246,12 +1233,11 @@ public:
{ {
ColumnsWithTypeAndName columns_with_constant ColumnsWithTypeAndName columns_with_constant
= {{left.column->cloneResized(1), left.type, left.name}, = {{left.column->cloneResized(1), left.type, left.name},
{right.type->createColumnConst(1, point), right.type, right.name}, {right.type->createColumnConst(1, point), right.type, right.name}};
{nullptr, return_type, ""}};
Base::executeImpl(columns_with_constant, {0, 1}, 2, 1); auto col = Base::executeImpl(columns_with_constant, return_type, 1);
Field point_transformed; Field point_transformed;
columns_with_constant[2].column->get(0, point_transformed); col->get(0, point_transformed);
return point_transformed; return point_transformed;
}; };
transform(left_point); transform(left_point);
@ -1282,12 +1268,11 @@ public:
{ {
ColumnsWithTypeAndName columns_with_constant ColumnsWithTypeAndName columns_with_constant
= {{left.type->createColumnConst(1, point), left.type, left.name}, = {{left.type->createColumnConst(1, point), left.type, left.name},
{right.column->cloneResized(1), right.type, right.name}, {right.column->cloneResized(1), right.type, right.name}};
{nullptr, return_type, ""}};
Base::executeImpl(columns_with_constant, {0, 1}, 2, 1); auto col = Base::executeImpl(columns_with_constant, return_type, 1);
Field point_transformed; Field point_transformed;
columns_with_constant[2].column->get(0, point_transformed); col->get(0, point_transformed);
return point_transformed; return point_transformed;
}; };

View File

@ -54,32 +54,35 @@ public:
return std::make_shared<DataTypeUInt8>(); return std::make_shared<DataTypeUInt8>();
} }
void executeImpl(ColumnsWithTypeAndName & columns , const ColumnNumbers & arguments, size_t result, size_t /*input_rows_count*/) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t /*input_rows_count*/) const override
{ {
const auto value_col = columns[arguments.front()].column.get(); const auto * value_col = arguments.front().column.get();
if (!execute<UInt8>(columns, arguments, result, value_col) ColumnPtr res;
&& !execute<UInt16>(columns, arguments, result, value_col) if (!((res = execute<UInt8>(arguments, result_type, value_col))
&& !execute<UInt32>(columns, arguments, result, value_col) || (res = execute<UInt16>(arguments, result_type, value_col))
&& !execute<UInt64>(columns, arguments, result, value_col) || (res = execute<UInt32>(arguments, result_type, value_col))
&& !execute<Int8>(columns, arguments, result, value_col) || (res = execute<UInt64>(arguments, result_type, value_col))
&& !execute<Int16>(columns, arguments, result, value_col) || (res = execute<Int8>(arguments, result_type, value_col))
&& !execute<Int32>(columns, arguments, result, value_col) || (res = execute<Int16>(arguments, result_type, value_col))
&& !execute<Int64>(columns, arguments, result, value_col)) || (res = execute<Int32>(arguments, result_type, value_col))
|| (res = execute<Int64>(arguments, result_type, value_col))))
throw Exception{"Illegal column " + value_col->getName() + " of argument of function " + getName(), ErrorCodes::ILLEGAL_COLUMN}; throw Exception{"Illegal column " + value_col->getName() + " of argument of function " + getName(), ErrorCodes::ILLEGAL_COLUMN};
return res;
} }
private: private:
template <typename T> template <typename T>
bool execute( ColumnPtr execute(
ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, const size_t result, ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type,
const IColumn * const value_col_untyped) const const IColumn * const value_col_untyped) const
{ {
if (const auto value_col = checkAndGetColumn<ColumnVector<T>>(value_col_untyped)) if (const auto value_col = checkAndGetColumn<ColumnVector<T>>(value_col_untyped))
{ {
const auto size = value_col->size(); const auto size = value_col->size();
bool is_const; bool is_const;
const auto const_mask = createConstMaskIfConst<T>(columns, arguments, is_const); const auto const_mask = createConstMaskIfConst<T>(arguments, is_const);
const auto & val = value_col->getData(); const auto & val = value_col->getData();
auto out_col = ColumnVector<UInt8>::create(size); auto out_col = ColumnVector<UInt8>::create(size);
@ -92,29 +95,28 @@ private:
} }
else else
{ {
const auto mask = createMask<T>(size, columns, arguments); const auto mask = createMask<T>(size, arguments);
for (const auto i : ext::range(0, size)) for (const auto i : ext::range(0, size))
out[i] = Impl::apply(val[i], mask[i]); out[i] = Impl::apply(val[i], mask[i]);
} }
columns[result].column = std::move(out_col); return out_col;
return true;
} }
else if (const auto value_col_const = checkAndGetColumnConst<ColumnVector<T>>(value_col_untyped)) else if (const auto value_col_const = checkAndGetColumnConst<ColumnVector<T>>(value_col_untyped))
{ {
const auto size = value_col_const->size(); const auto size = value_col_const->size();
bool is_const; bool is_const;
const auto const_mask = createConstMaskIfConst<T>(columns, arguments, is_const); const auto const_mask = createConstMaskIfConst<T>(arguments, is_const);
const auto val = value_col_const->template getValue<T>(); const auto val = value_col_const->template getValue<T>();
if (is_const) if (is_const)
{ {
columns[result].column = columns[result].type->createColumnConst(size, toField(Impl::apply(val, const_mask))); return result_type->createColumnConst(size, toField(Impl::apply(val, const_mask)));
} }
else else
{ {
const auto mask = createMask<T>(size, columns, arguments); const auto mask = createMask<T>(size, arguments);
auto out_col = ColumnVector<UInt8>::create(size); auto out_col = ColumnVector<UInt8>::create(size);
auto & out = out_col->getData(); auto & out = out_col->getData();
@ -122,24 +124,22 @@ private:
for (const auto i : ext::range(0, size)) for (const auto i : ext::range(0, size))
out[i] = Impl::apply(val, mask[i]); out[i] = Impl::apply(val, mask[i]);
columns[result].column = std::move(out_col); return out_col;
} }
return true;
} }
return false; return nullptr;
} }
template <typename ValueType> template <typename ValueType>
ValueType createConstMaskIfConst(const ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, bool & out_is_const) const ValueType createConstMaskIfConst(const ColumnsWithTypeAndName & arguments, bool & out_is_const) const
{ {
out_is_const = true; out_is_const = true;
ValueType mask = 0; ValueType mask = 0;
for (const auto i : ext::range(1, arguments.size())) for (const auto i : ext::range(1, arguments.size()))
{ {
if (auto pos_col_const = checkAndGetColumnConst<ColumnVector<ValueType>>(columns[arguments[i]].column.get())) if (auto pos_col_const = checkAndGetColumnConst<ColumnVector<ValueType>>(arguments[i].column.get()))
{ {
const auto pos = pos_col_const->getUInt(0); const auto pos = pos_col_const->getUInt(0);
if (pos < 8 * sizeof(ValueType)) if (pos < 8 * sizeof(ValueType))
@ -156,13 +156,13 @@ private:
} }
template <typename ValueType> template <typename ValueType>
PaddedPODArray<ValueType> createMask(const size_t size, const ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments) const PaddedPODArray<ValueType> createMask(const size_t size, const ColumnsWithTypeAndName & arguments) const
{ {
PaddedPODArray<ValueType> mask(size, ValueType{}); PaddedPODArray<ValueType> mask(size, ValueType{});
for (const auto i : ext::range(1, arguments.size())) for (const auto i : ext::range(1, arguments.size()))
{ {
const auto pos_col = columns[arguments[i]].column.get(); const auto * pos_col = arguments[i].column.get();
if (!addToMaskImpl<UInt8>(mask, pos_col) if (!addToMaskImpl<UInt8>(mask, pos_col)
&& !addToMaskImpl<UInt16>(mask, pos_col) && !addToMaskImpl<UInt16>(mask, pos_col)

View File

@ -96,26 +96,26 @@ public:
bool useDefaultImplementationForConstants() const override { return true; } bool useDefaultImplementationForConstants() const override { return true; }
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2}; } ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2}; }
void executeImpl(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
{ {
const IDataType * from_type = columns[arguments[0]].type.get(); const IDataType * from_type = arguments[0].type.get();
WhichDataType which(from_type); WhichDataType which(from_type);
if (which.isDate()) if (which.isDate())
CustomWeekTransformImpl<DataTypeDate, ToDataType>::execute( return CustomWeekTransformImpl<DataTypeDate, ToDataType>::execute(
columns, arguments, result, input_rows_count, Transform{}); arguments, result_type, input_rows_count, Transform{});
else if (which.isDateTime()) else if (which.isDateTime())
CustomWeekTransformImpl<DataTypeDateTime, ToDataType>::execute( return CustomWeekTransformImpl<DataTypeDateTime, ToDataType>::execute(
columns, arguments, result, input_rows_count, Transform{}); arguments, result_type, input_rows_count, Transform{});
else if (which.isDateTime64()) else if (which.isDateTime64())
{ {
CustomWeekTransformImpl<DataTypeDateTime64, ToDataType>::execute( return CustomWeekTransformImpl<DataTypeDateTime64, ToDataType>::execute(
columns, arguments, result, input_rows_count, arguments, result_type, input_rows_count,
TransformDateTime64<Transform>{assert_cast<const DataTypeDateTime64 *>(from_type)->getScale()}); TransformDateTime64<Transform>{assert_cast<const DataTypeDateTime64 *>(from_type)->getScale()});
} }
else else
throw Exception( throw Exception(
"Illegal type " + columns[arguments[0]].type->getName() + " of argument of function " + getName(), "Illegal type " + arguments[0].type->getName() + " of argument of function " + getName(),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
} }

View File

@ -305,7 +305,7 @@ private:
template <typename FromDataType, typename ToDataType, typename Transform> template <typename FromDataType, typename ToDataType, typename Transform>
struct DateTimeAddIntervalImpl struct DateTimeAddIntervalImpl
{ {
static void execute(Transform transform, ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result) static ColumnPtr execute(Transform transform, ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type)
{ {
using FromValueType = typename FromDataType::FieldType; using FromValueType = typename FromDataType::FieldType;
using FromColumnType = typename FromDataType::ColumnType; using FromColumnType = typename FromDataType::ColumnType;
@ -313,16 +313,16 @@ struct DateTimeAddIntervalImpl
auto op = Adder<Transform>{std::move(transform)}; auto op = Adder<Transform>{std::move(transform)};
const DateLUTImpl & time_zone = extractTimeZoneFromFunctionArguments(columns, arguments, 2, 0); const DateLUTImpl & time_zone = extractTimeZoneFromFunctionArguments(arguments, 2, 0);
const ColumnPtr source_col = columns[arguments[0]].column; const ColumnPtr source_col = arguments[0].column;
auto result_col = columns[result].type->createColumn(); auto result_col = result_type->createColumn();
auto col_to = assert_cast<ToColumnType *>(result_col.get()); auto col_to = assert_cast<ToColumnType *>(result_col.get());
if (const auto * sources = checkAndGetColumn<FromColumnType>(source_col.get())) if (const auto * sources = checkAndGetColumn<FromColumnType>(source_col.get()))
{ {
const IColumn & delta_column = *columns[arguments[1]].column; const IColumn & delta_column = *arguments[1].column;
if (const auto * delta_const_column = typeid_cast<const ColumnConst *>(&delta_column)) if (const auto * delta_const_column = typeid_cast<const ColumnConst *>(&delta_column))
op.vectorConstant(sources->getData(), col_to->getData(), delta_const_column->getInt(0), time_zone); op.vectorConstant(sources->getData(), col_to->getData(), delta_const_column->getInt(0), time_zone);
@ -334,16 +334,16 @@ struct DateTimeAddIntervalImpl
op.constantVector( op.constantVector(
sources_const->template getValue<FromValueType>(), sources_const->template getValue<FromValueType>(),
col_to->getData(), col_to->getData(),
*columns[arguments[1]].column, time_zone); *arguments[1].column, time_zone);
} }
else else
{ {
throw Exception("Illegal column " + columns[arguments[0]].column->getName() throw Exception("Illegal column " + arguments[0].column->getName()
+ " of first argument of function " + Transform::name, + " of first argument of function " + Transform::name,
ErrorCodes::ILLEGAL_COLUMN); ErrorCodes::ILLEGAL_COLUMN);
} }
columns[result].column = std::move(result_col); return result_col;
} }
}; };
@ -463,28 +463,28 @@ public:
bool useDefaultImplementationForConstants() const override { return true; } bool useDefaultImplementationForConstants() const override { return true; }
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {2}; } ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {2}; }
void executeImpl(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t /*input_rows_count*/) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t /*input_rows_count*/) const override
{ {
const IDataType * from_type = columns[arguments[0]].type.get(); const IDataType * from_type = arguments[0].type.get();
WhichDataType which(from_type); WhichDataType which(from_type);
if (which.isDate()) if (which.isDate())
{ {
DateTimeAddIntervalImpl<DataTypeDate, TransformResultDataType<DataTypeDate>, Transform>::execute( return DateTimeAddIntervalImpl<DataTypeDate, TransformResultDataType<DataTypeDate>, Transform>::execute(
Transform{}, columns, arguments, result); Transform{}, arguments, result_type);
} }
else if (which.isDateTime()) else if (which.isDateTime())
{ {
DateTimeAddIntervalImpl<DataTypeDateTime, TransformResultDataType<DataTypeDateTime>, Transform>::execute( return DateTimeAddIntervalImpl<DataTypeDateTime, TransformResultDataType<DataTypeDateTime>, Transform>::execute(
Transform{}, columns, arguments, result); Transform{}, arguments, result_type);
} }
else if (const auto * datetime64_type = assert_cast<const DataTypeDateTime64 *>(from_type)) else if (const auto * datetime64_type = assert_cast<const DataTypeDateTime64 *>(from_type))
{ {
DateTimeAddIntervalImpl<DataTypeDateTime64, TransformResultDataType<DataTypeDateTime64>, Transform>::execute( return DateTimeAddIntervalImpl<DataTypeDateTime64, TransformResultDataType<DataTypeDateTime64>, Transform>::execute(
Transform{datetime64_type->getScale()}, columns, arguments, result); Transform{datetime64_type->getScale()}, arguments, result_type);
} }
else else
throw Exception("Illegal type " + columns[arguments[0]].type->getName() + " of first argument of function " + getName(), throw Exception("Illegal type " + arguments[0].type->getName() + " of first argument of function " + getName(),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
} }
}; };

View File

@ -95,23 +95,23 @@ public:
bool useDefaultImplementationForConstants() const override { return true; } bool useDefaultImplementationForConstants() const override { return true; }
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1}; } ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1}; }
void executeImpl(ColumnsWithTypeAndName & columns, const ColumnNumbers & arguments, size_t result, size_t input_rows_count) const override ColumnPtr executeImpl(ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
{ {
const IDataType * from_type = columns[arguments[0]].type.get(); const IDataType * from_type = arguments[0].type.get();
WhichDataType which(from_type); WhichDataType which(from_type);
if (which.isDate()) if (which.isDate())
DateTimeTransformImpl<DataTypeDate, ToDataType, Transform>::execute(columns, arguments, result, input_rows_count); return DateTimeTransformImpl<DataTypeDate, ToDataType, Transform>::execute(arguments, result_type, input_rows_count);
else if (which.isDateTime()) else if (which.isDateTime())
DateTimeTransformImpl<DataTypeDateTime, ToDataType, Transform>::execute(columns, arguments, result, input_rows_count); return DateTimeTransformImpl<DataTypeDateTime, ToDataType, Transform>::execute(arguments, result_type, input_rows_count);
else if (which.isDateTime64()) else if (which.isDateTime64())
{ {
const auto scale = static_cast<const DataTypeDateTime64 *>(from_type)->getScale(); const auto scale = static_cast<const DataTypeDateTime64 *>(from_type)->getScale();
const TransformDateTime64<Transform> transformer(scale); const TransformDateTime64<Transform> transformer(scale);
DateTimeTransformImpl<DataTypeDateTime64, ToDataType, decltype(transformer)>::execute(columns, arguments, result, input_rows_count, transformer); return DateTimeTransformImpl<DataTypeDateTime64, ToDataType, decltype(transformer)>::execute(arguments, result_type, input_rows_count, transformer);
} }
else else
throw Exception("Illegal type " + columns[arguments[0]].type->getName() + " of argument of function " + getName(), throw Exception("Illegal type " + arguments[0].type->getName() + " of argument of function " + getName(),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
} }

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