From a938be4594ca67299f7dfb1cc250845b6ec67bda Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Fri, 13 Nov 2026 15:35:17 +0000 Subject: [PATCH 001/116] Backport #130755 to 26.3: Fix Keeper crash on `CheckWatch` request with an unknown watch type --- .gitmodules | 3 - .../Foundation/include/Poco/FileChannel.h | 1 + base/poco/Foundation/src/FileChannel.cpp | 40 +- .../include/Poco/Net/DistrustedCertificates.h | 44 + .../src/DistrustedCertificates.cpp | 95 + base/poco/NetSSL_OpenSSL/src/SSLManager.cpp | 15 + base/poco/XML/CMakeLists.txt | 1 + base/poco/XML/include/Poco/XML/expat.h | 5 +- .../XML/include/Poco/XML/expat_external.h | 2 +- base/poco/XML/src/ascii.h | 3 +- base/poco/XML/src/entities.h | 99 + base/poco/XML/src/internal.h | 8 +- base/poco/XML/src/xcs.h | 2 + base/poco/XML/src/xmlparse.cpp | 871 +++++-- base/poco/XML/src/xmltok.h | 4 +- base/poco/XML/src/xmltok_impl.c | 6 +- base/poco/XML/src/xmlxcs.c | 21 + .../integration/dotnet_client/Dockerfile | 11 +- contrib/CMakeLists.txt | 2 +- contrib/arrow-cmake/CMakeLists.txt | 156 +- contrib/arrow-cmake/orc_check.cmake | 14 - contrib/brotli | 2 +- contrib/brotli-cmake/CMakeLists.txt | 51 +- contrib/c-ares | 2 +- contrib/grpc | 2 +- contrib/hive-metastore-cmake/CMakeLists.txt | 14 +- contrib/mongo-c-driver | 2 +- contrib/mongo-c-driver-cmake/CMakeLists.txt | 8 +- contrib/mongo-cxx-driver | 2 +- contrib/orc | 1 - contrib/sqlite-amalgamation | 2 +- .../table-engines/integrations/azure-queue.md | 4 + .../table-engines/integrations/s3queue.md | 2 + docs/en/operations/settings/settings-users.md | 1 + programs/client/Client.cpp | 13 +- src/Access/AccessBackup.cpp | 73 +- src/Access/AccessBackup.h | 8 +- src/Access/AccessControl.cpp | 38 +- src/Access/Authentication.cpp | 77 +- src/Access/ContextAccess.cpp | 4 + src/Access/EnabledQuota.cpp | 13 + src/Access/EnabledQuota.h | 7 + src/Access/HTTPAuthClient.h | 15 +- src/Access/IAccessStorage.cpp | 2 + src/Access/QuotaCache.cpp | 28 +- src/Access/QuotaCache.h | 7 +- src/Access/SettingsConstraints.cpp | 49 +- src/Access/SettingsConstraints.h | 12 +- .../AggregateFunctionGroupArray.cpp | 31 +- .../FunctionSecretArgumentsFinderTreeNode.cpp | 8 +- .../FunctionSecretArgumentsFinderTreeNode.h | 3 +- .../Passes/FunctionToSubcolumnsPass.cpp | 4 + src/Analyzer/QueryTreeBuilder.cpp | 34 +- .../evaluateScalarSubqueryIfNeeded.cpp | 2 +- src/Backups/BackupIO_AzureBlobStorage.cpp | 20 +- src/Backups/BackupMetadataFinder.cpp | 11 + src/Backups/RestorerFromBackup.cpp | 25 +- src/CMakeLists.txt | 13 +- src/Client/ClientBase.cpp | 6 +- src/Client/ClientBaseHelpers.cpp | 10 +- src/Client/ClientBaseHelpers.h | 4 +- src/Client/ReplxxLineReader.cpp | 17 +- src/Client/ReplxxLineReader.h | 19 +- src/Columns/ColumnArray.cpp | 24 +- src/Columns/ColumnDynamic.cpp | 29 + src/Columns/ColumnDynamic.h | 35 +- src/Columns/ColumnLowCardinality.cpp | 10 +- src/Columns/ColumnLowCardinality.h | 1 + src/Columns/ReverseIndex.h | 99 +- .../gtest_reverse_index_exception_safety.cpp | 123 + src/Common/CurrentMetrics.cpp | 2 + src/Common/DateLUTImpl.h | 14 +- src/Common/FailPoint.cpp | 3 + src/Common/RemoteHostFilter.cpp | 4 + src/Common/Scheduler/CPUSlotsAllocation.cpp | 7 +- src/Common/Scheduler/CPUSlotsAllocation.h | 4 + .../tests/gtest_workload_resource_manager.cpp | 38 + src/Common/ThreadStatus.cpp | 5 +- src/Common/ZooKeeper/ZooKeeperConstants.h | 2 + src/Common/ZooKeeper/ZooKeeperIO.cpp | 23 +- src/Common/maskURIPassword.h | 55 + src/Common/mysqlxx/Connection.cpp | 8 + src/Common/mysqlxx/Pool.cpp | 53 + .../tests/gtest_distrusted_certificates.cpp | 137 ++ .../gtest_file_channel_rotation_failure.cpp | 133 ++ src/Coordination/Changelog.cpp | 2 + src/Coordination/KeeperStorage.cpp | 13 +- src/Coordination/tests/gtest_coordination.cpp | 63 + .../tests/gtest_coordination_changelog.cpp | 39 + src/Core/Field.cpp | 4 + src/Core/FormatFactorySettings.h | 7 + src/Core/Settings.cpp | 4 + src/Core/SettingsChangesHistory.cpp | 1 + .../SerializationLowCardinality.cpp | 7 + .../gtest_low_cardinality_serialization.cpp | 179 ++ src/Databases/DataLake/GlueCatalog.cpp | 47 +- src/Databases/DataLake/GlueCatalog.h | 11 +- src/Databases/DataLake/HiveCatalog.cpp | 18 +- src/Databases/DatabaseReplicated.cpp | 134 +- src/Databases/DatabaseReplicated.h | 22 +- src/Databases/DatabaseReplicatedWorker.cpp | 65 +- src/Databases/DatabaseReplicatedWorker.h | 25 + src/Databases/MySQL/DatabaseMySQL.cpp | 9 + src/Dictionaries/MongoDBDictionarySource.cpp | 7 +- src/Dictionaries/SSDCacheDictionaryStorage.h | 3 +- .../AzureBlobStorageCommon.cpp | 30 + .../AzureBlobStorage/AzureBlobStorageCommon.h | 6 + .../AzureBlobStorage/AzureObjectStorage.cpp | 4 +- .../IO/AsynchronousBoundedReadBuffer.cpp | 1 + .../IO/ReadBufferFromAzureBlobStorage.cpp | 2 +- .../gtest_azure_read_buffer_missing_etag.cpp | 106 + src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 8 + src/Formats/ProtobufSerializer.cpp | 3 + src/Functions/HasSubsequenceImpl.h | 2 + src/Functions/URL/protocol.h | 3 + src/IO/CachedInMemoryReadBufferFromFile.cpp | 2 + src/IO/ReadWriteBufferFromHTTP.cpp | 3 +- src/IO/S3/Client.cpp | 21 +- src/IO/S3/Client.h | 2 + src/IO/SharedThreadPools.cpp | 9 + src/IO/SharedThreadPools.h | 2 + src/IO/tests/gtest_brotli_decoder.cpp | 58 + src/Interpreters/AsynchronousInsertQueue.cpp | 38 +- src/Interpreters/AsynchronousInsertQueue.h | 13 +- src/Interpreters/Context.cpp | 67 +- src/Interpreters/Context.h | 26 +- .../ExecuteScalarSubqueriesVisitor.cpp | 2 +- src/Interpreters/InterpreterAlterQuery.cpp | 120 + src/Interpreters/InterpreterCreateQuery.cpp | 89 + src/Interpreters/InterpreterCreateQuery.h | 4 + src/Interpreters/JIT/CHJIT.cpp | 9 +- src/Interpreters/JIT/CHJIT.h | 3 +- src/Interpreters/executeDDLQueryOnCluster.cpp | 6 + src/Interpreters/executeDDLQueryOnCluster.h | 8 + .../tests/gtest_async_insert_key.cpp | 54 +- src/Parsers/FunctionSecretArgumentsFinder.cpp | 228 +- src/Parsers/FunctionSecretArgumentsFinder.h | 28 + .../FunctionSecretArgumentsFinderAST.h | 2 + src/Parsers/Lexer.cpp | 2 +- src/Parsers/tests/gtest_Parser.cpp | 8 + src/Processors/Chunk.cpp | 12 +- src/Processors/Formats/IInputFormat.h | 2 + .../Formats/Impl/ArrowBatchRowLimit.cpp | 319 +++ .../Formats/Impl/ArrowBatchRowLimit.h | 47 + .../Formats/Impl/ArrowBlockOutputFormat.cpp | 1 + .../Formats/Impl/ArrowBufferedStreams.cpp | 2 +- .../Formats/Impl/ArrowBufferedStreams.h | 2 +- .../Formats/Impl/ArrowColumnToCHColumn.cpp | 2 +- .../Formats/Impl/ArrowColumnToCHColumn.h | 2 +- .../Formats/Impl/CHColumnToArrowColumn.cpp | 105 +- .../Formats/Impl/CHColumnToArrowColumn.h | 3 + .../Formats/Impl/MsgPackRowInputFormat.cpp | 8 +- .../Formats/Impl/MsgPackRowInputFormat.h | 3 +- .../Formats/Impl/MySQLDumpRowInputFormat.cpp | 9 +- .../Impl/NativeORCBlockInputFormat.cpp | 2088 ++++++++++++----- .../Formats/Impl/NativeORCBlockInputFormat.h | 77 +- .../Formats/Impl/ORC/ColumnReader.cpp | 1218 ++++++++++ .../Formats/Impl/ORC/ColumnReader.h | 63 + .../Formats/Impl/ORC/Compression.cpp | 437 ++++ src/Processors/Formats/Impl/ORC/Compression.h | 42 + src/Processors/Formats/Impl/ORC/Proto.cpp | 944 ++++++++ src/Processors/Formats/Impl/ORC/Proto.h | 343 +++ src/Processors/Formats/Impl/ORC/RLE.cpp | 1129 +++++++++ src/Processors/Formats/Impl/ORC/RLE.h | 151 ++ src/Processors/Formats/Impl/ORC/Reader.cpp | 842 +++++++ src/Processors/Formats/Impl/ORC/Reader.h | 188 ++ .../Formats/Impl/ORC/SearchArgument.cpp | 1075 +++++++++ .../Formats/Impl/ORC/SearchArgument.h | 198 ++ .../Formats/Impl/ORC/Statistics.cpp | 462 ++++ src/Processors/Formats/Impl/ORC/Statistics.h | 71 + src/Processors/Formats/Impl/ORC/Stream.cpp | 248 ++ src/Processors/Formats/Impl/ORC/Stream.h | 140 ++ src/Processors/Formats/Impl/ORC/Timezone.cpp | 87 + src/Processors/Formats/Impl/ORC/Timezone.h | 25 + src/Processors/Formats/Impl/ORC/Type.cpp | 380 +++ src/Processors/Formats/Impl/ORC/Type.h | 114 + src/Processors/Formats/Impl/ORC/Vector.cpp | 143 ++ src/Processors/Formats/Impl/ORC/Vector.h | 174 ++ src/Processors/Formats/Impl/ORC/Writer.cpp | 1493 ++++++++++++ src/Processors/Formats/Impl/ORC/Writer.h | 78 + .../Formats/Impl/ORCBlockInputFormat.cpp | 276 --- .../Formats/Impl/ORCBlockInputFormat.h | 85 - .../Formats/Impl/ORCBlockOutputFormat.cpp | 551 ++--- .../Formats/Impl/ORCBlockOutputFormat.h | 49 +- .../Formats/Impl/Parquet/Decoding.cpp | 21 +- .../Formats/Impl/Parquet/Decoding.h | 3 + .../Formats/Impl/Parquet/SchemaConverter.cpp | 4 +- .../Formats/Impl/ParquetBlockOutputFormat.cpp | 52 +- .../Formats/Impl/ParquetBlockOutputFormat.h | 12 +- .../Impl/ParquetV3BlockInputFormat.cpp | 32 +- .../Formats/Impl/ParquetV3BlockInputFormat.h | 11 +- .../Formats/Impl/RawBLOBRowOutputFormat.cpp | 20 +- .../Formats/Impl/RawBLOBRowOutputFormat.h | 8 +- .../QueryPlan/ReadFromMergeTree.cpp | 13 +- .../Transforms/AddingDefaultsTransform.cpp | 3 +- ...umn_to_arrow_column_record_batch_split.cpp | 127 + src/Server/HTTP/ReadHeaders.cpp | 7 +- src/Server/HTTP/exceptionCodeToHTTPStatus.cpp | 4 +- src/Server/TCPHandler.cpp | 6 +- src/Storages/AlterCommands.cpp | 38 + src/Storages/AlterCommands.h | 3 + .../DistributedAsyncInsertBatch.cpp | 20 +- .../DistributedAsyncInsertDirectoryQueue.cpp | 6 + .../DistributedAsyncInsertHelpers.cpp | 8 + .../DistributedAsyncInsertHelpers.h | 9 + src/Storages/Distributed/DistributedSink.cpp | 18 +- src/Storages/Hive/HiveFile.cpp | 109 +- src/Storages/Hive/HiveFile.h | 9 +- src/Storages/Hive/StorageHive.cpp | 4 + src/Storages/IStorage.h | 3 + src/Storages/IndicesDescription.cpp | 124 + src/Storages/IndicesDescription.h | 15 + .../MergeTree/MergeTreeBlockReadUtils.cpp | 3 +- src/Storages/MergeTree/MergeTreeData.cpp | 21 +- src/Storages/MergeTree/MergeTreeData.h | 7 + .../MergeTree/MergeTreeDataWriter.cpp | 5 + .../MergeTree/MergeTreeIndexBloomFilter.cpp | 19 +- .../MergeTree/MergeTreeRangeReader.cpp | 8 + .../MergeTree/MergeTreeSelectProcessor.cpp | 11 +- .../MergeTree/MergeTreeSelectProcessor.h | 6 +- src/Storages/MergeTree/MergeTreeSettings.cpp | 2 +- .../MergeTreeSplitPrewhereIntoReadSteps.cpp | 57 +- .../MergeTreeSplitPrewhereIntoReadSteps.h | 5 +- .../MergeTree/MergeTreeWhereOptimizer.cpp | 20 +- .../MergeTree/MergeTreeWhereOptimizer.h | 4 - .../MergeTree/MutateFromLogEntryTask.cpp | 2 +- .../ReplicatedMergeTreeCleanupThread.cpp | 2 +- .../gtest_merge_tree_index_bloom_filter.cpp | 74 + .../ObjectStorage/Azure/Configuration.cpp | 13 +- .../ObjectStorage/Azure/Configuration.h | 2 +- .../Common/AvroForIcebergDeserializer.cpp | 1 + .../Common/AvroForIcebergDeserializer.h | 5 + .../DataLakes/DeltaLake/TableSnapshot.cpp | 36 +- .../DataLakes/DeltaLake/WriteTransaction.cpp | 80 +- .../DataLakes/Iceberg/IcebergIterator.cpp | 3 +- .../Iceberg/IcebergMetadataFilesCache.h | 2 +- .../DataLakes/Iceberg/MultipleFileWriter.cpp | 3 + .../DataLakes/Iceberg/Mutations.cpp | 4 + .../Iceberg/StatelessMetadataFileGetter.cpp | 9 +- .../Iceberg/StatelessMetadataFileGetter.h | 3 +- src/Storages/ObjectStorage/IObjectIterator.h | 1 + .../StorageObjectStorageSource.cpp | 27 +- .../StorageObjectStorageSource.h | 5 +- .../ObjectStorageQueue/AzureQueue_fwd.h | 7 +- ...bjectStorageQueueMoveDestinationAccess.cpp | 119 + .../ObjectStorageQueueMoveDestinationAccess.h | 37 + .../ObjectStorageQueuePostProcessor.cpp | 17 + .../ObjectStorageQueueSettings.cpp | 30 +- .../ObjectStorageQueueSettings.h | 3 +- .../StorageObjectStorageQueue.cpp | 117 +- .../StorageObjectStorageQueue.h | 2 + .../registerQueueStorage.cpp | 3 + .../StorageMaterializedPostgreSQL.cpp | 8 + .../StorageMaterializedPostgreSQL.h | 2 + src/Storages/StorageAlias.cpp | 25 + src/Storages/StorageAlias.h | 3 +- src/Storages/StorageBuffer.cpp | 7 + src/Storages/StorageBuffer.h | 1 + src/Storages/StorageDistributed.cpp | 21 + src/Storages/StorageFactory.cpp | 36 + src/Storages/StorageFactory.h | 15 + src/Storages/StorageInMemoryMetadata.cpp | 43 + src/Storages/StorageMaterializedView.cpp | 17 +- src/Storages/StorageMaterializedView.h | 1 + src/Storages/StorageMerge.cpp | 6 + src/Storages/StorageMerge.h | 1 + src/Storages/StorageMergeTree.cpp | 22 +- src/Storages/StorageMongoDB.cpp | 53 + src/Storages/StorageMongoDB.h | 3 + src/Storages/StorageProxy.h | 1 + src/Storages/StorageReplicatedMergeTree.cpp | 48 +- .../System/StorageSystemMutations.cpp | 112 +- src/Storages/System/StorageSystemMutations.h | 3 +- ...torageSystemObjectStorageQueueSettings.cpp | 4 +- src/TableFunctions/ITableFunction.cpp | 15 +- src/TableFunctions/ITableFunction.h | 9 +- src/configure_config.cmake | 3 + tests/integration/conftest.py | 30 + .../configs/config_with_hosts.xml | 1 + .../test_allowed_url_from_config/test.py | 120 + .../test_arrowflight_interface/test.py | 37 + .../test_backup_restore_new/test.py | 125 + tests/integration/test_crash_log/test.py | 5 + tests/integration/test_database_glue/test.py | 56 + .../integration/test_database_iceberg/test.py | 497 ++++ tests/integration/test_dotnet_client/test.py | 9 +- tests/integration/test_git_import/test.py | 29 +- .../test_keeper_persistent_watches/test.py | 55 + .../test_keeper_remove_rejoin_leader/test.py | 65 + .../test_mask_sensitive_info/test.py | 24 +- .../__init__.py | 0 .../configs/remote_servers.xml | 11 + .../test.py | 102 + .../test.py | 73 + .../test_manifest_length_cache_weight.py | 99 + tests/integration/test_storage_s3/test.py | 35 + tests/integration/test_storage_url/test.py | 3 +- .../__init__.py | 0 .../configs/rabbitmq.xml | 6 + .../configs/remote_servers.xml | 14 + .../configs/users.xml | 23 + .../test.py | 299 +++ tests/integration/test_totp_auth/test_totp.py | 43 +- .../map_bucketed_serialization.xml | 8 +- tests/performance/map_subcolumns_prewhere.xml | 10 +- .../prewhere_subcolumn_read_steps.xml | 19 + .../0_stateless/00900_long_parquet_load_2.sh | 4 + tests/queries/0_stateless/01035_avg.reference | 8 +- tests/queries/0_stateless/01035_avg.sql | 2 +- .../01252_weird_time_zone.reference | 38 + .../0_stateless/01252_weird_time_zone.sql | 53 + .../01308_orc_output_format_arrays.reference | 2 +- ...01514_distributed_cancel_query_on_error.sh | 44 +- .../01721_join_implicit_cast_long.sql.j2 | 6 +- ...302_defaults_in_columnar_formats.reference | 2 + .../02302_defaults_in_columnar_formats.sql | 10 + ...x_add_with_invalid_alter_command.reference | 1 + ...t_index_add_with_invalid_alter_command.sql | 24 + ...2346_text_index_transform_access.reference | 19 + .../02346_text_index_transform_access.sql | 124 + ...sform_access_replicated_database.reference | 3 + ...x_transform_access_replicated_database.sql | 40 + ...text_index_transform_data_access.reference | 6 + ...02346_text_index_transform_data_access.sql | 68 + ..._text_index_transform_on_cluster.reference | 14 + .../02346_text_index_transform_on_cluster.sh | 77 + .../0_stateless/02372_analyzer_join.sql.j2 | 2 +- .../0_stateless/02426_orc_bug.reference | 2 +- .../02884_authentication_quota.reference | 12 +- .../0_stateless/02884_authentication_quota.sh | 6 +- ...runing_empty_partition_zookeeper.reference | 6 + ...wu_58_pruning_empty_partition_zookeeper.sh | 140 ++ .../03595_read_orc_file_segfault.sh | 2 +- .../0_stateless/03784_bad_base_backup.sh | 12 + .../03822_file_function_read_on_file_grant.sh | 2 +- .../03923_kafka2_keeper_offsets.sh | 2 +- ...subcolumn_function_to_subcolumns.reference | 2 +- ...9_map_subcolumn_function_to_subcolumns.sql | 11 +- .../04000_map_subcolumns_prewhere.reference | 2 +- .../04000_map_subcolumns_prewhere.sql | 7 +- .../04039_text_index_map_values_subcolumn.sql | 5 +- ...3_has_subsequence_empty_haystack.reference | 8 + .../04113_has_subsequence_empty_haystack.sql | 9 + ...66_ttl_with_subcolumn_expression.reference | 3 + .../04266_ttl_with_subcolumn_expression.sql | 34 + ...337_orc_schema_inference_deep_recursion.sh | 23 +- .../04338_async_insert_current_user.reference | 6 + .../04338_async_insert_current_user.sql | 43 + ..._async_insert_authenticated_user.reference | 3 + .../04339_async_insert_authenticated_user.sh | 77 + ...ultistep_prewhere_default_column.reference | 9 + ...4628_multistep_prewhere_default_column.sql | 23 + ...where_default_column_patch_parts.reference | 6 + ...ep_prewhere_default_column_patch_parts.sql | 25 + .../04856_orc_corrupt_stripe_footer.reference | 4 + .../04856_orc_corrupt_stripe_footer.sh | 29 + ...orc_unimplemented_codec_no_abort.reference | 14 + .../05036_orc_unimplemented_codec_no_abort.sh | 59 + ...replicated_max_logs_to_keep_zero.reference | 4 + .../05053_replicated_max_logs_to_keep_zero.sh | 42 + ...5_arrow_split_large_record_batch.reference | 9 + .../05055_arrow_split_large_record_batch.sh | 55 + ...t_schema_source_query_background_access.sh | 7 +- ...055_http_conflict_is_not_retried.reference | 2 + .../05055_http_conflict_is_not_retried.sh | 62 + ...ow_record_batch_split_boundaries.reference | 4 + ...056_arrow_record_batch_split_boundaries.sh | 49 + ...raints_nested_settings_effective.reference | 22 + ...s_constraints_nested_settings_effective.sh | 117 + ...ttings_equal_value_marks_changed.reference | 18 + ...sted_settings_equal_value_marks_changed.sh | 48 + ...ble_from_path_read_on_file_grant.reference | 7 + ...tach_table_from_path_read_on_file_grant.sh | 67 + ...8_quota_client_key_stale_context.reference | 12 + .../05218_quota_client_key_stale_context.sh | 54 + ...91_system_mutations_hide_secrets.reference | 5 + .../05291_system_mutations_hide_secrets.sql | 47 + ...icy_scalar_subquery_cache_bypass.reference | 6 + ...row_policy_scalar_subquery_cache_bypass.sh | 68 + ...rupt_stripe_footer_stream_column.reference | 3 + ...orc_corrupt_stripe_footer_stream_column.sh | 49 + ...9_http_header_rfc2047_line_break.reference | 18 + .../05339_http_header_rfc2047_line_break.sh | 29 + ...39_prewhere_subcolumn_read_steps.reference | 7 + .../05339_prewhere_subcolumn_read_steps.sql | 79 + ...ement_to_subcolumn_bucketed_only.reference | 30 + ...map_element_to_subcolumn_bucketed_only.sql | 75 + ...rite_many_partitions_thread_pool.reference | 3 + ...eberg_write_many_partitions_thread_pool.sh | 40 + ...mic_deep_value_column_operations.reference | 4 + ...07_dynamic_deep_value_column_operations.sh | 50 + ...407_orc_timezone_traversal_abort.reference | 5 + .../05407_orc_timezone_traversal_abort.sh | 137 ++ .../05427_azure_sas_url_parsing.reference | 0 .../05427_azure_sas_url_parsing.sql | 9 + ...mysqldump_create_without_columns.reference | 51 + .../05428_mysqldump_create_without_columns.sh | 38 + ...tobuf_map_with_unsupported_value.reference | 3 + ...429_protobuf_map_with_unsupported_value.sh | 13 + ...ema_inference_untypeable_map_key.reference | 4 + ...ck_schema_inference_untypeable_map_key.sql | 22 + ...05441_rawblob_aggregate_function.reference | 5 + .../05441_rawblob_aggregate_function.sh | 18 + ..._s3queue_move_destination_access.reference | 35 + .../05441_s3queue_move_destination_access.sh | 377 +++ ...t_mv_dedup_empty_partition_block.reference | 3 + ..._insert_mv_dedup_empty_partition_block.sql | 39 + ...uted_insert_select_source_access.reference | 7 + ...distributed_insert_select_source_access.sh | 77 + ...nt96_date_time_overflow_behavior.reference | 13 + ...rquet_int96_date_time_overflow_behavior.sh | 19 + ...444_parquet_int96_lower_boundary.reference | 2 + .../05444_parquet_int96_lower_boundary.sh | 16 + ...uted_async_insert_batch_per_user.reference | 1 + ...distributed_async_insert_batch_per_user.sh | 41 + ...sas_url_hidden_in_table_function.reference | 13 + ..._azure_sas_url_hidden_in_table_function.sh | 43 + .../05447_orc_native_reader_writer.reference | 14 + .../05447_orc_native_reader_writer.sh | 46 + .../05448_orc_date_after_2059.reference | 12 + .../0_stateless/05448_orc_date_after_2059.sh | 20 + ...mats_read_padding_object_storage.reference | 5 + ...ext_formats_read_padding_object_storage.sh | 29 + .../05453_orc_bad_bloom_filter.reference | 8 + .../0_stateless/05453_orc_bad_bloom_filter.sh | 27 + ...entials_hidden_in_logged_queries.reference | 39 + ...re_credentials_hidden_in_logged_queries.sh | 62 + .../05473_orc_footer_content_length.reference | 2 + .../05473_orc_footer_content_length.sh | 53 + .../05474_orc_decimal64_v2.reference | 20 + .../0_stateless/05474_orc_decimal64_v2.sh | 13 + ..._storage_parquet_footer_prefetch.reference | 4 + ..._object_storage_parquet_footer_prefetch.sh | 39 + ..._record_batch_split_many_batches.reference | 2 + ...3_arrow_record_batch_split_many_batches.sh | 40 + ...abase_ddl_during_restore_replica.reference | 1 + ...ted_database_ddl_during_restore_replica.sh | 65 + ..._replica_waits_for_initial_query.reference | 5 + ...restore_replica_waits_for_initial_query.sh | 58 + ...ictionary_cache_file_cannot_grow.reference | 6 + ...cache_dictionary_cache_file_cannot_grow.sh | 57 + ...on_create_temporary_table_access.reference | 25 + ..._function_create_temporary_table_access.sh | 102 + ...async_insert_after_invalid_entry.reference | 6 + ...sgpack_async_insert_after_invalid_entry.sh | 36 + ...5493_mysql_host_connector_syntax.reference | 13 + .../05493_mysql_host_connector_syntax.sh | 77 + ...ttings_system_table_hide_secrets.reference | 4 + ...eue_settings_system_table_hide_secrets.sql | 22 + ...498_s3_disk_sse_c_key_validation.reference | 1 + .../05498_s3_disk_sse_c_key_validation.sql | 31 + .../05507_orc_malformed_timestamps.reference | 16 + .../05507_orc_malformed_timestamps.sh | 19 + ...8_orc_writer_out_of_range_values.reference | 7 + .../05508_orc_writer_out_of_range_values.sh | 26 + ...05509_orc_malformed_dictionaries.reference | 16 + .../05509_orc_malformed_dictionaries.sh | 21 + ...510_orc_allocation_amplification.reference | 32 + .../05510_orc_allocation_amplification.sh | 27 + ...rc_malformed_stripes_and_streams.reference | 16 + ...05511_orc_malformed_stripes_and_streams.sh | 19 + .../05512_orc_malformed_row_groups.reference | 32 + .../05512_orc_malformed_row_groups.sh | 26 + ...c_metadata_repeated_field_limits.reference | 16 + ...5513_orc_metadata_repeated_field_limits.sh | 17 + ...imestamp_statistics_before_epoch.reference | 21 + ...4_orc_timestamp_statistics_before_epoch.sh | 45 + .../05515_orc_nullable_floats.reference | 2 + .../0_stateless/05515_orc_nullable_floats.sh | 30 + ..._replica_waits_for_initial_alter.reference | 6 + ...restore_replica_waits_for_initial_alter.sh | 58 + ...rquet_encoder_shared_thread_pool.reference | 1 + ...5565_parquet_encoder_shared_thread_pool.sh | 31 + ...up_array_sample_counter_overflow.reference | 3 + ...67_group_array_sample_counter_overflow.sql | 28 + ...05567_mongodb_server_credentials.reference | 21 + .../05567_mongodb_server_credentials.sh | 87 + ...db_dictionary_server_credentials.reference | 12 + ...8_mongodb_dictionary_server_credentials.sh | 85 + ...c_requested_type_of_another_kind.reference | 18 + ...5574_orc_requested_type_of_another_kind.sh | 56 + ...ing_result_memory_limit_in_local.reference | 6 + ...cumulating_result_memory_limit_in_local.sh | 18 + ...imestamp_before_first_transition.reference | 9 + ...6_orc_timestamp_before_first_transition.sh | 50 + .../data_orc/bad_bloom_filter_1.6.0.orc | Bin 0 -> 709 bytes .../data_orc/bad_bloom_filter_1.6.11.orc | Bin 0 -> 717 bytes .../0_stateless/data_orc/decimal64_v2.orc | Bin 0 -> 738 bytes .../malformed_compression_block_1g.orc | Bin 0 -> 414 bytes .../data_orc/malformed_dictionary_empty.orc | Bin 0 -> 170 bytes .../malformed_dictionary_size_max.orc | Bin 0 -> 174 bytes .../malformed_footer_too_many_statistics.orc | Bin 0 -> 353 bytes .../malformed_metadata_too_many_stripes.orc | Bin 0 -> 673 bytes ...med_patched_base_terminal_continuation.orc | Bin 0 -> 83 bytes .../malformed_row_group_count_overflow.orc | Bin 0 -> 237 bytes .../malformed_row_index_seek_past_stream.orc | Bin 0 -> 213 bytes .../data_orc/malformed_snappy_chunk_size.orc | Bin 0 -> 31 bytes .../malformed_stream_offset_overflow.orc | Bin 0 -> 301 bytes .../malformed_stripe_offset_overflow.orc | Bin 0 -> 301 bytes .../malformed_timestamp_nanoseconds.orc | Bin 0 -> 238 bytes ...ormed_timestamp_statistics_nanoseconds.orc | Bin 0 -> 264 bytes .../data_orc/malformed_zstd_chunk_size.orc | Bin 0 -> 38 bytes .../data_orc/orc_nested_union_type.orc | Bin 0 -> 666 bytes .../0_stateless/data_orc/orc_union_type.orc | Bin 0 -> 398 bytes .../data_orc/row_index_seek_control.orc | Bin 0 -> 213 bytes .../timestamps_before_epoch_arrow.orc | Bin 0 -> 294 bytes ...amps_before_epoch_pyarrow_bloom_filter.orc | Bin 0 -> 517 bytes .../05443_int96_out_of_range.parquet | Bin 0 -> 700 bytes .../05444_int96_lower_boundary.parquet | Bin 0 -> 535 bytes ..._protobuf_map_with_unsupported_value.proto | 21 + tests/queries/0_stateless/orc_malformed.lib | 55 + 512 files changed, 24382 insertions(+), 2628 deletions(-) create mode 100644 base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h create mode 100644 base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp create mode 100644 base/poco/XML/src/entities.h delete mode 100644 contrib/arrow-cmake/orc_check.cmake delete mode 160000 contrib/orc create mode 100644 src/Columns/tests/gtest_reverse_index_exception_safety.cpp create mode 100644 src/Common/tests/gtest_distrusted_certificates.cpp create mode 100644 src/Common/tests/gtest_file_channel_rotation_failure.cpp create mode 100644 src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp create mode 100644 src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp create mode 100644 src/IO/tests/gtest_brotli_decoder.cpp create mode 100644 src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp create mode 100644 src/Processors/Formats/Impl/ArrowBatchRowLimit.h create mode 100644 src/Processors/Formats/Impl/ORC/ColumnReader.cpp create mode 100644 src/Processors/Formats/Impl/ORC/ColumnReader.h create mode 100644 src/Processors/Formats/Impl/ORC/Compression.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Compression.h create mode 100644 src/Processors/Formats/Impl/ORC/Proto.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Proto.h create mode 100644 src/Processors/Formats/Impl/ORC/RLE.cpp create mode 100644 src/Processors/Formats/Impl/ORC/RLE.h create mode 100644 src/Processors/Formats/Impl/ORC/Reader.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Reader.h create mode 100644 src/Processors/Formats/Impl/ORC/SearchArgument.cpp create mode 100644 src/Processors/Formats/Impl/ORC/SearchArgument.h create mode 100644 src/Processors/Formats/Impl/ORC/Statistics.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Statistics.h create mode 100644 src/Processors/Formats/Impl/ORC/Stream.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Stream.h create mode 100644 src/Processors/Formats/Impl/ORC/Timezone.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Timezone.h create mode 100644 src/Processors/Formats/Impl/ORC/Type.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Type.h create mode 100644 src/Processors/Formats/Impl/ORC/Vector.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Vector.h create mode 100644 src/Processors/Formats/Impl/ORC/Writer.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Writer.h delete mode 100644 src/Processors/Formats/Impl/ORCBlockInputFormat.cpp delete mode 100644 src/Processors/Formats/Impl/ORCBlockInputFormat.h create mode 100644 src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp create mode 100644 src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp create mode 100644 src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp create mode 100644 src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h create mode 100644 tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py create mode 100644 tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml create mode 100644 tests/integration/test_refreshable_mv_definer_interserver_secret/test.py create mode 100644 tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/test.py create mode 100644 tests/performance/prewhere_subcolumn_read_steps.xml create mode 100644 tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference create mode 100644 tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access.reference create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_data_access.reference create mode 100644 tests/queries/0_stateless/02346_text_index_transform_data_access.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference create mode 100755 tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh create mode 100644 tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference create mode 100755 tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh create mode 100644 tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference create mode 100644 tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql create mode 100644 tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference create mode 100644 tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql create mode 100644 tests/queries/0_stateless/04338_async_insert_current_user.reference create mode 100644 tests/queries/0_stateless/04338_async_insert_current_user.sql create mode 100644 tests/queries/0_stateless/04339_async_insert_authenticated_user.reference create mode 100755 tests/queries/0_stateless/04339_async_insert_authenticated_user.sh create mode 100644 tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference create mode 100644 tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql create mode 100644 tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference create mode 100644 tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql create mode 100644 tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference create mode 100755 tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh create mode 100644 tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference create mode 100755 tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh create mode 100644 tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference create mode 100755 tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh create mode 100644 tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference create mode 100755 tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh create mode 100644 tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference create mode 100755 tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh create mode 100644 tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference create mode 100755 tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh create mode 100644 tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference create mode 100755 tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh create mode 100644 tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference create mode 100755 tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh create mode 100644 tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference create mode 100755 tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh create mode 100644 tests/queries/0_stateless/05218_quota_client_key_stale_context.reference create mode 100755 tests/queries/0_stateless/05218_quota_client_key_stale_context.sh create mode 100644 tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference create mode 100644 tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql create mode 100644 tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference create mode 100755 tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh create mode 100644 tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference create mode 100755 tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh create mode 100644 tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference create mode 100755 tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh create mode 100644 tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference create mode 100644 tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql create mode 100644 tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference create mode 100644 tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql create mode 100644 tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference create mode 100755 tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh create mode 100644 tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference create mode 100755 tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh create mode 100644 tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference create mode 100755 tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh create mode 100644 tests/queries/0_stateless/05427_azure_sas_url_parsing.reference create mode 100644 tests/queries/0_stateless/05427_azure_sas_url_parsing.sql create mode 100644 tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference create mode 100755 tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh create mode 100644 tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference create mode 100755 tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh create mode 100644 tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference create mode 100644 tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql create mode 100644 tests/queries/0_stateless/05441_rawblob_aggregate_function.reference create mode 100755 tests/queries/0_stateless/05441_rawblob_aggregate_function.sh create mode 100644 tests/queries/0_stateless/05441_s3queue_move_destination_access.reference create mode 100755 tests/queries/0_stateless/05441_s3queue_move_destination_access.sh create mode 100644 tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference create mode 100644 tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql create mode 100644 tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference create mode 100755 tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh create mode 100644 tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference create mode 100755 tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh create mode 100644 tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference create mode 100755 tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh create mode 100644 tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference create mode 100755 tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh create mode 100644 tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference create mode 100755 tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh create mode 100644 tests/queries/0_stateless/05447_orc_native_reader_writer.reference create mode 100755 tests/queries/0_stateless/05447_orc_native_reader_writer.sh create mode 100644 tests/queries/0_stateless/05448_orc_date_after_2059.reference create mode 100755 tests/queries/0_stateless/05448_orc_date_after_2059.sh create mode 100644 tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference create mode 100755 tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh create mode 100644 tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference create mode 100755 tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh create mode 100644 tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference create mode 100755 tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh create mode 100644 tests/queries/0_stateless/05473_orc_footer_content_length.reference create mode 100755 tests/queries/0_stateless/05473_orc_footer_content_length.sh create mode 100644 tests/queries/0_stateless/05474_orc_decimal64_v2.reference create mode 100755 tests/queries/0_stateless/05474_orc_decimal64_v2.sh create mode 100644 tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference create mode 100755 tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh create mode 100644 tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference create mode 100755 tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh create mode 100644 tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference create mode 100755 tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh create mode 100644 tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference create mode 100755 tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh create mode 100644 tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference create mode 100755 tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh create mode 100644 tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference create mode 100755 tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh create mode 100644 tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference create mode 100755 tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh create mode 100644 tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference create mode 100755 tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh create mode 100644 tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference create mode 100644 tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql create mode 100644 tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference create mode 100644 tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql create mode 100644 tests/queries/0_stateless/05507_orc_malformed_timestamps.reference create mode 100755 tests/queries/0_stateless/05507_orc_malformed_timestamps.sh create mode 100644 tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference create mode 100755 tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh create mode 100644 tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference create mode 100755 tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh create mode 100644 tests/queries/0_stateless/05510_orc_allocation_amplification.reference create mode 100755 tests/queries/0_stateless/05510_orc_allocation_amplification.sh create mode 100644 tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference create mode 100755 tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh create mode 100644 tests/queries/0_stateless/05512_orc_malformed_row_groups.reference create mode 100755 tests/queries/0_stateless/05512_orc_malformed_row_groups.sh create mode 100644 tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference create mode 100755 tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh create mode 100644 tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference create mode 100755 tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh create mode 100644 tests/queries/0_stateless/05515_orc_nullable_floats.reference create mode 100755 tests/queries/0_stateless/05515_orc_nullable_floats.sh create mode 100644 tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference create mode 100755 tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh create mode 100644 tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference create mode 100755 tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh create mode 100644 tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference create mode 100644 tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql create mode 100644 tests/queries/0_stateless/05567_mongodb_server_credentials.reference create mode 100755 tests/queries/0_stateless/05567_mongodb_server_credentials.sh create mode 100644 tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference create mode 100755 tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh create mode 100644 tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference create mode 100755 tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh create mode 100644 tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference create mode 100755 tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh create mode 100644 tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference create mode 100755 tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh create mode 100644 tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc create mode 100644 tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc create mode 100644 tests/queries/0_stateless/data_orc/decimal64_v2.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_compression_block_1g.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_dictionary_empty.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_metadata_too_many_stripes.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_row_group_count_overflow.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_row_index_seek_past_stream.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_snappy_chunk_size.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_stream_offset_overflow.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_stripe_offset_overflow.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_timestamp_statistics_nanoseconds.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc create mode 100644 tests/queries/0_stateless/data_orc/orc_nested_union_type.orc create mode 100644 tests/queries/0_stateless/data_orc/orc_union_type.orc create mode 100644 tests/queries/0_stateless/data_orc/row_index_seek_control.orc create mode 100644 tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc create mode 100644 tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc create mode 100644 tests/queries/0_stateless/data_parquet/05443_int96_out_of_range.parquet create mode 100644 tests/queries/0_stateless/data_parquet/05444_int96_lower_boundary.parquet create mode 100644 tests/queries/0_stateless/format_schemas/05429_protobuf_map_with_unsupported_value.proto create mode 100644 tests/queries/0_stateless/orc_malformed.lib diff --git a/.gitmodules b/.gitmodules index 4959a04c45dc..73baf268fde7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -76,9 +76,6 @@ [submodule "contrib/fastops"] path = contrib/fastops url = https://github.com/ClickHouse/fastops -[submodule "contrib/orc"] - path = contrib/orc - url = https://github.com/ClickHouse/orc [submodule "contrib/sparsehash-c11"] path = contrib/sparsehash-c11 url = https://github.com/sparsehash/sparsehash-c11 diff --git a/base/poco/Foundation/include/Poco/FileChannel.h b/base/poco/Foundation/include/Poco/FileChannel.h index 7db27772c0a2..028f1766aaa9 100644 --- a/base/poco/Foundation/include/Poco/FileChannel.h +++ b/base/poco/Foundation/include/Poco/FileChannel.h @@ -246,6 +246,7 @@ class Foundation_API FileChannel : public Channel void unsafeOpen(); private: + void unsafeRotate(); LogFile * newLogFile(); void archiveCorrupted(const std::string & path); bool setNoPurge(const std::string & value); diff --git a/base/poco/Foundation/src/FileChannel.cpp b/base/poco/Foundation/src/FileChannel.cpp index 9f5c10013c2f..4a48894f2fb4 100644 --- a/base/poco/Foundation/src/FileChannel.cpp +++ b/base/poco/Foundation/src/FileChannel.cpp @@ -25,6 +25,7 @@ #include "Poco/Exception.h" #include "Poco/Ascii.h" #include "Poco/CombinedRotateStrategy.h" +#include namespace Poco { @@ -111,15 +112,7 @@ void FileChannel::log(const Message& msg) if (_pRotateStrategy && _pArchiveStrategy && _pRotateStrategy->mustRotate(_pFile)) { - try - { - _pFile = _pArchiveStrategy->archive(_pFile, _streamCompress); - purge(); - } - catch (...) - { - _pFile = newLogFile(); - } + unsafeRotate(); // we must call mustRotate() again to give the // RotateByIntervalStrategy a chance to write its timestamp // to the new file. @@ -340,17 +333,24 @@ void FileChannel::unsafeOpen() { _pFile = newLogFile(); if (_rotateOnOpen && _pFile->size() > 0) - { - try - { - _pFile = _pArchiveStrategy->archive(_pFile, _streamCompress); - purge(); - } - catch (...) - { - _pFile = newLogFile(); - } - } + unsafeRotate(); + } +} + + +void FileChannel::unsafeRotate() +{ + /// `archive` deletes the current file, so `_pFile` must not dangle if opening the new one fails. + /// The raw pointer is intentional: `archive` owns `pFile` and deletes it, so it must not be deleted here. + LogFile * pFile = std::exchange(_pFile, nullptr); + try + { + _pFile = _pArchiveStrategy->archive(pFile, _streamCompress); + purge(); + } + catch (...) + { + _pFile = newLogFile(); } } diff --git a/base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h b/base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h new file mode 100644 index 000000000000..5aca47d6be88 --- /dev/null +++ b/base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h @@ -0,0 +1,44 @@ +// +// DistrustedCertificates.h +// +// Library: NetSSL_OpenSSL +// Package: SSLCore +// Module: DistrustedCertificates +// +// Copyright (c) 2026, ClickHouse, Inc. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef NetSSL_DistrustedCertificates_INCLUDED +#define NetSSL_DistrustedCertificates_INCLUDED + + +#include +#include "Poco/Net/NetSSL.h" + + +namespace Poco +{ +namespace Net +{ + + + NetSSL_API int checkDistrustedCertificate(X509 * certificate); + /// Checks the certificate against the list of distrusted public keys built into + /// the binary, and returns `X509_V_OK` if it is not on the list, `X509_V_ERR_CERT_REVOKED` + /// if it is, or another `X509_V_ERR_*` code if the check itself failed. + /// + /// The list contains the keys of CA certificates that must not be trusted even if + /// the trust store of the operating system still contains them, e.g. because their + /// private keys are compromised. A key is identified by the SHA-256 of its DER-encoded + /// `SubjectPublicKeyInfo`, so that every certificate of the same key is rejected, + /// including cross-signed ones. + + +} +} // namespace Poco::Net + + +#endif // NetSSL_DistrustedCertificates_INCLUDED diff --git a/base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp b/base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp new file mode 100644 index 000000000000..448d4f601d9d --- /dev/null +++ b/base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp @@ -0,0 +1,95 @@ +// +// DistrustedCertificates.cpp +// +// Library: NetSSL_OpenSSL +// Package: SSLCore +// Module: DistrustedCertificates +// +// Copyright (c) 2026, ClickHouse, Inc. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Net/DistrustedCertificates.h" +#include +#include +#include +#include + + +namespace +{ + using SPKIHash = std::array; + + consteval unsigned char hexDigit(char c) + { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + throw "Invalid hex digit"; + } + + consteval SPKIHash fromHex(const char (&hex)[65]) + { + SPKIHash result{}; + for (size_t i = 0; i < result.size(); ++i) + result[i] = static_cast(hexDigit(hex[2 * i]) << 4 | hexDigit(hex[2 * i + 1])); + return result; + } + + /// SHA-256 of the DER-encoded `SubjectPublicKeyInfo` of every distrusted key. + constexpr SPKIHash distrusted_keys[] = + { + /// eMudhra: the private keys of the intermediate CAs below, issued in 2025, can be recovered + /// from their certificates. Each of them is issued by `emSign Root TLS CA - G3` or `emSign Root CS CA - G3` + /// and cross-signed by Sectigo `AAA Certificate Services`; the cross-signed certificates have the same keys. + /// The roots that issued or cross-signed them are distrusted as well. + /// https://emudhra.we-have-a-problem.com/ + fromHex("EBED6475C2C2D80FCB199F3FE8DD6E6B3CE60B77EB15D4E42C3DEC0C6F5B5105"), /// EM DV TLS CA - G3B + fromHex("43BFFA19D6EF651451F6841E019931E96F6F2EAEFF28AB4B6F1CE4576DE2717B"), /// EM OV TLS CA - G3B + fromHex("E0254C7FCDC265E2F0F8A428DABB75AB4AE039B4872D62F5EE57F0877D5A8A41"), /// EM EV TLS CA - G3B + fromHex("49DD353DC2B919A3770645117D0E60C16115E7D1BC259EEFE734B00EA434FE5F"), /// EM DV TLS CA - G3C + fromHex("63ECEFEE431D49523BC1136C4E72D0206A477086CAF606CD5CF025686C109CF8"), /// EM OV TLS CA - G3C + fromHex("5C0660A2B164910D8FF589C18E14552E9E0EC237DCEFE2CB736D41A4811F81A0"), /// EM EV TLS CA - G3C + fromHex("EC4FFA1AD0AC88081314B7AAFFEF6A91F97CD57291BB5BA686C5415F5EB4F6B6"), /// EM OV CS CA - G3B + fromHex("92C063D67E8F14DB71D288E11266FFDAF69CBF115F7BAB14F3BC2F68D25E0E30"), /// EM OV CS CA - G3C + fromHex("C619E4780ED8E0ABEDA24AD732567DE4383A7EA941338F6D1A7D1B49AC792FE9"), /// emSign Root TLS CA - G3 + fromHex("0A6C2B2CA5B364207954171987AC9D2178561569D8205457E77CA90C32EDE282"), /// emSign Root CS CA - G3 + fromHex("8D417DB2DD8BF5E3084D1E3F196D583849D81BDD4C00C70B9D39369E96B8C782"), /// emSign ECC Root CA - G3 + }; +} + + +namespace Poco { +namespace Net { + + +int checkDistrustedCertificate(X509 * certificate) +{ + X509_PUBKEY * key = X509_get_X509_PUBKEY(certificate); + if (key == nullptr) + return X509_V_ERR_UNSPECIFIED; + + /// Not `X509_pubkey_digest`: it hashes only the key bits, without the algorithm identifier. + unsigned char * der = nullptr; + int der_size = i2d_X509_PUBKEY(key, &der); + if (der_size <= 0) + return X509_V_ERR_OUT_OF_MEM; + + SPKIHash hash; + unsigned int hash_size = 0; + int ok = EVP_Digest(der, der_size, hash.data(), &hash_size, EVP_sha256(), nullptr); + OPENSSL_free(der); + if (ok != 1 || hash_size != hash.size()) + return X509_V_ERR_UNSPECIFIED; + + if (std::find(std::begin(distrusted_keys), std::end(distrusted_keys), hash) != std::end(distrusted_keys)) + return X509_V_ERR_CERT_REVOKED; + + return X509_V_OK; +} + + +} } // namespace Poco::Net diff --git a/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp b/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp index 80d85855fe3c..e7764a5ece98 100644 --- a/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp +++ b/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp @@ -14,6 +14,7 @@ #include "Poco/Net/SSLManager.h" #include "Poco/Net/Context.h" +#include "Poco/Net/DistrustedCertificates.h" #include "Poco/Net/Utility.h" #include "Poco/Net/PrivateKeyPassphraseHandler.h" #include "Poco/Net/RejectCertificateHandler.h" @@ -196,6 +197,20 @@ SSLManager::InvalidCertificateHandlerPtr SSLManager::clientCertificateHandler() int SSLManager::verifyCallback(bool server, int ok, X509_STORE_CTX* pStore) { + /// OpenSSL calls this for every certificate of the chain, with `ok` set to 1 if it has + /// no other errors, so this rejects a chain that contains a distrusted certificate at any + /// depth, whichever trust store (the system one, the configured one or the embedded one) + /// it was built from. The rejection is reported like any other verification error. + if (X509 * cert = X509_STORE_CTX_get_current_cert(pStore)) + { + int distrusted = checkDistrustedCertificate(cert); + if (distrusted != X509_V_OK) + { + X509_STORE_CTX_set_error(pStore, distrusted); + ok = 0; + } + } + if (!ok) { int depth = X509_STORE_CTX_get_error_depth(pStore); diff --git a/base/poco/XML/CMakeLists.txt b/base/poco/XML/CMakeLists.txt index 1d3c8d332f1b..d0d9f26fc268 100644 --- a/base/poco/XML/CMakeLists.txt +++ b/base/poco/XML/CMakeLists.txt @@ -9,6 +9,7 @@ add_library (Poco::XML::Expat ALIAS _poco_xml_expat) target_compile_options (_poco_xml_expat PRIVATE -Wno-cast-qual + -Wno-declaration-after-statement -Wno-disabled-macro-expansion -Wno-empty-translation-unit -Wno-extra-semi-stmt diff --git a/base/poco/XML/include/Poco/XML/expat.h b/base/poco/XML/include/Poco/XML/expat.h index 4a57c70fec8d..2d14d53b4e36 100644 --- a/base/poco/XML/include/Poco/XML/expat.h +++ b/base/poco/XML/include/Poco/XML/expat.h @@ -21,6 +21,7 @@ Copyright (c) 2024 Taichi Haradaguchi <20001722@ymail.ne.jp> Copyright (c) 2025 Matthew Fernandez Copyright (c) 2026 Braian Plaku + Copyright (c) 2026 Xisco Fauli Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -1084,7 +1085,7 @@ enum XML_Parser_Property { # if defined(XML_TESTING) XML_PROP_INVALID = 0, # endif -# if XML_GE == 1 +# if defined(XML_GE) && XML_GE == 1 XML_PROP_ALLOC_TRACKER_ACTIVATION_THRESHOLD = 1, // of type `uint64_t` XML_PROP_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION = 2, // of type `double` XML_PROP_BILLION_LAUGHS_ACTIVATION_THRESHOLD = 3, // of type `uint64_t` @@ -1146,7 +1147,7 @@ XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled); See https://semver.org */ # define XML_MAJOR_VERSION 2 -# define XML_MINOR_VERSION 9 +# define XML_MINOR_VERSION 10 # define XML_MICRO_VERSION 0 # ifdef __cplusplus diff --git a/base/poco/XML/include/Poco/XML/expat_external.h b/base/poco/XML/include/Poco/XML/expat_external.h index 9fb80149acd3..f34750afbddc 100644 --- a/base/poco/XML/include/Poco/XML/expat_external.h +++ b/base/poco/XML/include/Poco/XML/expat_external.h @@ -12,7 +12,7 @@ Copyright (c) 2001-2002 Greg Stein Copyright (c) 2002-2006 Karl Waclawek Copyright (c) 2016 Cristian Rodríguez - Copyright (c) 2016-2025 Sebastian Pipping + Copyright (c) 2016-2026 Sebastian Pipping Copyright (c) 2017 Rhodri James Copyright (c) 2018 Yury Gribov Copyright (c) 2026 Matthew Fernandez diff --git a/base/poco/XML/src/ascii.h b/base/poco/XML/src/ascii.h index 56c8807aa574..656c95e28ddb 100644 --- a/base/poco/XML/src/ascii.h +++ b/base/poco/XML/src/ascii.h @@ -10,7 +10,7 @@ Copyright (c) 2000 Clark Cooper Copyright (c) 2002 Fred L. Drake, Jr. Copyright (c) 2007 Karl Waclawek - Copyright (c) 2017 Sebastian Pipping + Copyright (c) 2017-2026 Sebastian Pipping Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -113,6 +113,7 @@ #define ASCII_LT 0x3C #define ASCII_EQUALS 0x3D #define ASCII_GT 0x3E +#define ASCII_QUEST 0x3F #define ASCII_LSQB 0x5B #define ASCII_RSQB 0x5D #define ASCII_UNDERSCORE 0x5F diff --git a/base/poco/XML/src/entities.h b/base/poco/XML/src/entities.h new file mode 100644 index 000000000000..d0cd309c1111 --- /dev/null +++ b/base/poco/XML/src/entities.h @@ -0,0 +1,99 @@ +/* Internal helpers related to entities + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 2026 Sebastian Pipping + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. + + SPDX-License-Identifier: MIT +*/ + +#if ! defined(EXPAT_ENTITIES_H) +# define EXPAT_ENTITIES_H 1 + +# include "expat_config.h" // for XML_GE +# include "Poco/XML/expat_external.h" // for XML_Char +# include "internal.h" // for XML_NONTESTING_STATIC +# include // for size_t +# include // for size_t + +typedef struct { + const XML_Char *name; + const XML_Char *textPtr; + size_t textLen; /* length in XML_Chars */ + size_t processed; /* # of processed bytes - when suspended */ + const XML_Char *systemId; + const XML_Char *base; + const XML_Char *publicId; + const XML_Char *notation; + bool open; + bool hasMore; /* true if entity has not been completely processed */ + /* An entity can be open while being already completely processed (!hasMore). + The reason is the delayed closing of entities until their inner + entities are processed and closed */ + bool is_param; + bool is_internal; /* true if declared in internal subset outside PE */ +# if XML_GE == 1 + /* Indirect accounting bytes charged when this entity is expanded: 1 per text + character, plus each reference's "&name;"/"%name;" token length and its own + expansion. Matches XML_ACCOUNT_ENTITY_EXPANSION, so it is not the + replacement-text size. 0 means "not computed yet" (an empty entity is 0 + too, told apart by textLen == 0). */ + XmlBigCount expandedSize; + bool beingAnalyzed; /* on the resolveEntityClosureExpandedSize depth-first + search stack; used for cycle detection */ + const XML_Char + *scanPtr; /* cursor position into the entity's replacement text; NULL when + `textPtr` is NULL, else a pointer into the entity value, + ranging from `.textPtr` to `.textPtr + .textLen`. */ +# endif /* XML_GE == 1 */ +} ENTITY; + +# if XML_GE == 1 +/* How a scanEntityText call ended. */ +enum EntityScanResult { + ENTITY_SCAN_COMPLETE, /* reached end of text; *expandedSize is final */ + ENTITY_SCAN_BLOCKED, /* stopped at a defined entity whose expanded + size has not been computed yet; *blockerOut + names the entity whose size to compute + first */ + ENTITY_SCAN_OVERFLOW /* the expanded size would exceed XmlBigCount; + callers must abort parsing */ +}; + +XML_NONTESTING_STATIC int isCDataCommentOrPIStart(const XML_Char *pos, + size_t maxLen, + size_t *openTextLen); + +XML_NONTESTING_STATIC int isPredefinedEntityName(const XML_Char *name, + size_t nameLen); + +XML_NONTESTING_STATIC enum EntityScanResult +scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr, + XmlBigCount *expandedSize, ENTITY **blockerOut); +# endif /* XML_GE == 1 */ + +#endif // ! defined(EXPAT_ENTITIES_H) diff --git a/base/poco/XML/src/internal.h b/base/poco/XML/src/internal.h index d0465449a399..58ea8e2b4dc2 100644 --- a/base/poco/XML/src/internal.h +++ b/base/poco/XML/src/internal.h @@ -29,6 +29,7 @@ Copyright (c) 2026 Matthew Wozniczka Copyright (c) 2026 Braian Plaku Copyright (c) 2026 Florian Schmaus + Copyright (c) 2026 Brooks Davis Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -90,11 +91,10 @@ # define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u" # endif # else -# include // PRIdPTR, PRIuPTR # define EXPAT_FMT_LLX(midpart) "%" midpart "llx" # define EXPAT_FMT_ULL(midpart) "%" midpart "llu" -# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart PRIdPTR -# define EXPAT_FMT_SIZE_T(midpart) "%" midpart PRIuPTR +# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "td" +# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "zu" # endif # ifndef UNUSED_P @@ -131,6 +131,8 @@ union expat_align { extern "C" { #endif +typedef unsigned long long XmlBigCount; + void _INTERNAL_trim_to_complete_utf8_characters(const char *from, const char **fromLimRef); diff --git a/base/poco/XML/src/xcs.h b/base/poco/XML/src/xcs.h index 1e63a9b1de2f..2b4268716cce 100644 --- a/base/poco/XML/src/xcs.h +++ b/base/poco/XML/src/xcs.h @@ -44,6 +44,8 @@ extern size_t xcslen(const XML_Char *s); extern int xcscmp(const XML_Char *a, const XML_Char *b); extern int xcsncmp(const XML_Char *a, const XML_Char *b, size_t len); +extern const XML_Char *xcsnstr(const XML_Char *haystack, const XML_Char *needle, + size_t maxLen); #ifdef __cplusplus } diff --git a/base/poco/XML/src/xmlparse.cpp b/base/poco/XML/src/xmlparse.cpp index 001de556c891..56c76bf33034 100644 --- a/base/poco/XML/src/xmlparse.cpp +++ b/base/poco/XML/src/xmlparse.cpp @@ -1,4 +1,4 @@ -/* e3ca845466942140c9af531ac57808c4650116df5d6dbeda3b6546d2548a586e (2.9.0+) +/* d0712c5efef760b5355ed61473a927256c6474aecb853016d2e335e571c64b0c (2.10.0+) __ __ _ ___\ \/ /_ __ __ _| |_ / _ \\ /| '_ \ / _` | __| @@ -58,6 +58,8 @@ Copyright (c) 2026 Braian Plaku Copyright (c) 2026 Filippo Tedeschi Copyright (c) 2026 Junki Lee + Copyright (c) 2026 Shani Yosef + Copyright (c) 2026 Pu Cheng Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -233,11 +235,13 @@ typedef char ICHAR; /* Do safe (NULL-aware) pointer arithmetic */ #define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0) +#define EXPAT_SAFE_PTR_ADD(p, a) ((p) ? ((p) + (a)) : NULL) #define EXPAT_MIN(a, b) (((a) < (b)) ? (a) : (b)) #include "internal.h" #include "hash_table.h" +#include "entities.h" #include "xmltok.h" #include "xmlrole.h" @@ -315,24 +319,6 @@ typedef struct tag { BINDING *bindings; } TAG; -typedef struct { - const XML_Char *name; - const XML_Char *textPtr; - int textLen; /* length in XML_Chars */ - int processed; /* # of processed bytes - when suspended */ - const XML_Char *systemId; - const XML_Char *base; - const XML_Char *publicId; - const XML_Char *notation; - bool open; - bool hasMore; /* true if entity has not been completely processed */ - /* An entity can be open while being already completely processed (!hasMore). - The reason is the delayed closing of entities until their inner - entities are processed and closed */ - bool is_param; - bool is_internal; /* true if declared in internal subset outside PE */ -} ENTITY; - typedef struct { enum XML_Content_Type type; enum XML_Content_Quant quant; @@ -371,7 +357,7 @@ typedef struct attribute_id { typedef struct { const ATTRIBUTE_ID *id; - XML_Bool isCdata; + bool isCdata; const XML_Char *value; } DEFAULT_ATTRIBUTE; @@ -461,7 +447,6 @@ enum XML_Account { }; #if XML_GE == 1 -typedef unsigned long long XmlBigCount; typedef struct accounting { XmlBigCount countBytesDirect; XmlBigCount countBytesIndirect; @@ -473,6 +458,7 @@ typedef struct accounting { typedef struct MALLOC_TRACKER { size_t bytesAllocated; size_t peakBytesAllocated; // updated live only for debug level >=2 + size_t bytesAllocatedWhenLastReset; unsigned long debugLevel; float maximumAmplificationFactor; // >=1.0 XmlBigCount activationThresholdBytes; @@ -484,6 +470,13 @@ typedef struct entity_stats { unsigned int maximumDepthSeen; unsigned long debugLevel; } ENTITY_STATS; + +/* One pending entity-analysis task on the explicit stack used by + resolveEntityClosureExpandedSize's depth-first search over the entity + reference graph. */ +typedef struct { + ENTITY *entity; /* entity currently being scanned */ +} ENTITY_ANALYSIS_TASK; #endif /* XML_GE == 1 */ typedef enum XML_Error Processor(XML_Parser parser, const char *start, @@ -543,15 +536,15 @@ static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr); static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, - XML_Bool isCdata, XML_Bool isId, - const XML_Char *value, XML_Parser parser); + bool isCdata, bool isId, const XML_Char *value, + XML_Parser parser); static enum XML_Error storeAttributeValue(XML_Parser parser, - const ENCODING *enc, XML_Bool isCdata, + const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account); static enum XML_Error -appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, +appendAttributeValue(XML_Parser parser, const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account, const char **nextPtr); static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc, @@ -566,6 +559,9 @@ static enum XML_Error callStoreEntityValue(XML_Parser parser, const ENCODING *enc, const char *start, const char *end, enum XML_Account account); +static enum XML_Error resolveEntityClosureExpandedSize(XML_Parser parser, + HASH_TABLE *table, + ENTITY *root); #else static enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity); #endif @@ -603,7 +599,7 @@ static const XML_Char *poolCopyString(STRING_POOL *pool, const XML_Char *s); static const XML_Char *poolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s); static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s, - int n); + size_t n); static const XML_Char *poolAppendString(STRING_POOL *pool, const XML_Char *s); static int nextScaffoldPart(XML_Parser parser); @@ -621,12 +617,17 @@ static XML_Parser parserCreate(const XML_Char *encodingName, const XML_Char *nameSep, DTD *dtd, XML_Parser parentParser); -static void parserInit(XML_Parser parser, const XML_Char *encodingName); +static void parserInit(XML_Parser parser, const XML_Char *encodingName, + bool isReset); #if XML_GE == 1 -static float accountingGetCurrentAmplification(XML_Parser rootParser); -static void accountingReportStats(XML_Parser originParser, const char *epilog); -static void accountingOnAbort(XML_Parser originParser); +static float accountingGetCurrentAmplification(XML_Parser rootParser, + XmlBigCount extraIndirectBytes); +static void accountingReportStats(XML_Parser originParser, const char *epilog, + XmlBigCount extraIndirectBytes, + int sourceLine); +static void accountingOnAbort(XML_Parser originParser, + XmlBigCount extraIndirectBytes, int sourceLine); static void accountingReportDiff(XML_Parser rootParser, unsigned int levelsAwayFromRootParser, const char *before, const char *after, @@ -636,6 +637,9 @@ static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok, const char *before, const char *after, int source_line, enum XML_Account account); +static XML_Bool +accountingCurrentAmplificationTolerated(XML_Parser rootParser, + XmlBigCount extraIndirectBytes); static void entityTrackingReportStats(XML_Parser parser, ENTITY *entity, const char *action, int sourceLine); @@ -643,6 +647,10 @@ static void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity, int sourceLine); static void entityTrackingOnClose(XML_Parser parser, ENTITY *entity, int sourceLine); +static void entityTrackingOnScanStart(XML_Parser parser, ENTITY *entity, + int sourceLine); +static void entityTrackingOnScanStop(XML_Parser parser, ENTITY *entity, + int sourceLine); #endif /* XML_GE == 1 */ static XML_Parser getRootParserOf(XML_Parser parser, @@ -798,8 +806,8 @@ struct XML_ParserStruct { const XML_Char *m_declNotationPublicId; ELEMENT_TYPE *m_declElementType; ATTRIBUTE_ID *m_declAttributeId; - XML_Bool m_declAttributeIsCdata; - XML_Bool m_declAttributeIsId; + bool m_declAttributeIsCdata; + bool m_declAttributeIsId; DTD *m_dtd; const XML_Char *m_curBase; TAG *m_tagStack; @@ -871,11 +879,22 @@ expat_heap_increase_tolerable(XML_Parser rootParser, size_t increase, size_t newTotal = 0; bool tolerable = true; + // The idea is to subtract the amount of memory that was already + // allocated the last time that `XML_ParserReset` was called for + // this parser, the memory use of one document could skew the + // memory statso of the next document. + const size_t bytesAllocated + = (rootParser->m_alloc_tracker.bytesAllocatedWhenLastReset + > rootParser->m_alloc_tracker.bytesAllocated) + ? 0 + : (rootParser->m_alloc_tracker.bytesAllocated + - rootParser->m_alloc_tracker.bytesAllocatedWhenLastReset); + // Detect integer overflow - if (SIZE_MAX - rootParser->m_alloc_tracker.bytesAllocated < increase) { + if (SIZE_MAX - bytesAllocated < increase) { tolerable = false; } else { - newTotal = rootParser->m_alloc_tracker.bytesAllocated + increase; + newTotal = bytesAllocated + increase; if (newTotal >= rootParser->m_alloc_tracker.activationThresholdBytes) { assert(newTotal > 0); @@ -1472,7 +1491,7 @@ parserCreate(const XML_Char *encodingName, poolInit(&parser->m_tempPool, parser); poolInit(&parser->m_temp2Pool, parser); - parserInit(parser, encodingName); + parserInit(parser, encodingName, /*isReset=*/false); if (encodingName && ! parser->m_protocolEncodingName) { if (dtd) { @@ -1499,7 +1518,7 @@ parserCreate(const XML_Char *encodingName, } static void -parserInit(XML_Parser parser, const XML_Char *encodingName) { +parserInit(XML_Parser parser, const XML_Char *encodingName, bool isReset) { parser->m_processor = prologInitProcessor; XmlPrologStateInit(&parser->m_prologState); if (encodingName != NULL) { @@ -1547,8 +1566,8 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) { parser->m_declAttributeType = NULL; parser->m_declNotationName = NULL; parser->m_declNotationPublicId = NULL; - parser->m_declAttributeIsCdata = XML_FALSE; - parser->m_declAttributeIsId = XML_FALSE; + parser->m_declAttributeIsCdata = false; + parser->m_declAttributeIsId = false; memset(&parser->m_position, 0, sizeof(POSITION)); parser->m_errorCode = XML_ERROR_NONE; parser->m_eventPtr = NULL; @@ -1567,6 +1586,7 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) { parser->m_unknownEncodingRelease = NULL; parser->m_unknownEncodingData = NULL; parser->m_parsingStatus.parsing = XML_INITIALIZED; + parser->m_parsingStatus.finalBuffer = XML_FALSE; // Reentry can only be triggered inside m_processor calls parser->m_reenter = XML_FALSE; parser->m_handlerCallDepth = 0; @@ -1580,15 +1600,24 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) { parser->m_hash_secret_salt_set = XML_FALSE; #if XML_GE == 1 - memset(&parser->m_accounting, 0, sizeof(ACCOUNTING)); - parser->m_accounting.debugLevel = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u); - parser->m_accounting.maximumAmplificationFactor - = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT; - parser->m_accounting.activationThresholdBytes - = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT; - - memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS)); - parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u); + parser->m_accounting.countBytesDirect = 0; + parser->m_accounting.countBytesIndirect = 0; + if (! isReset) { + parser->m_accounting.debugLevel + = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u); + parser->m_accounting.maximumAmplificationFactor + = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT; + parser->m_accounting.activationThresholdBytes + = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT; + } + + parser->m_entity_stats.countEverOpened = 0; + parser->m_entity_stats.currentDepth = 0; + parser->m_entity_stats.maximumDepthSeen = 0; + if (! isReset) + parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u); +#else + UNUSED_P(isReset); #endif } @@ -1651,8 +1680,16 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) { poolClear(&parser->m_temp2Pool); FREE(parser, (void *)parser->m_protocolEncodingName); parser->m_protocolEncodingName = NULL; - parserInit(parser, encodingName); + parserInit(parser, encodingName, /*isReset=*/true); dtdReset(parser->m_dtd, parser); + +#if XML_GE == 1 + parser->m_alloc_tracker.bytesAllocatedWhenLastReset + = parser->m_alloc_tracker.bytesAllocated; +#endif + + // NOTE: This effectively checks for `copyString` having failed during the + // call to `parserInit` above if (encodingName && ! parser->m_protocolEncodingName) { parser->m_errorCode = XML_ERROR_NO_MEMORY; return XML_FALSE; @@ -2322,13 +2359,12 @@ XML_SetHashSalt16Bytes(XML_Parser parser, const uint8_t entropy[16]) { enum XML_Status XMLCALL XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { - if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) { - if (parser != NULL) - parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; + if (parser == NULL || isCalledFromInsideHandler(parser)) return XML_STATUS_ERROR; - } - if (isCalledFromInsideHandler(parser)) + if ((len < 0) || ((s == NULL) && (len != 0))) { + parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; return XML_STATUS_ERROR; + } switch (parser->m_parsingStatus.parsing) { case XML_SUSPENDED: parser->m_errorCode = XML_ERROR_SUSPENDED; @@ -2348,8 +2384,15 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { #if XML_CONTEXT_BYTES == 0 if (parser->m_bufferPtr == parser->m_bufferEnd) { - const char *end; - int nLeftOver; + // This null-object trick allows us to stop worrying about case `s == NULL` + // within this branch, e.g. with `s + len - end`. + const char *const empty = ""; + if (s == NULL) { + assert(len == 0); + s = empty; + } + const char *end = s + len; + size_t nLeftOver; enum XML_Status result; /* Detect overflow (a+b > MAX <==> b > MAX-a) */ if ((uint64_t)len > UINT64_MAX - parser->m_parseEndByteIndex) { @@ -2366,7 +2409,7 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; parser->m_errorCode - = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end); + = callProcessor(parser, s, parser->m_parseEndPtr = end, &end); if (parser->m_errorCode != XML_ERROR_NONE) { parser->m_eventEndPtr = parser->m_eventPtr; @@ -2396,8 +2439,14 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED // (and XML_ERROR_FINISHED) from XML_GetBuffer. const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing; + if (nLeftOver > INT_MAX) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } parser->m_parsingStatus.parsing = XML_PARSING; - void *const temp = XML_GetBuffer(parser, nLeftOver); + void *const temp = XML_GetBuffer(parser, (int)nLeftOver); parser->m_parsingStatus.parsing = originalStatus; // GetBuffer may have overwritten this, but we want to remember what the // app requested, not how many bytes were left over after parsing. @@ -2415,7 +2464,7 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { memcpy(parser->m_buffer, end, nLeftOver); } parser->m_bufferPtr = parser->m_buffer; - parser->m_bufferEnd = parser->m_buffer + nLeftOver; + parser->m_bufferEnd = EXPAT_SAFE_PTR_ADD(parser->m_buffer, nLeftOver); parser->m_positionPtr = parser->m_bufferPtr; parser->m_parseEndPtr = parser->m_bufferEnd; parser->m_eventPtr = parser->m_bufferPtr; @@ -3497,7 +3546,7 @@ externalEntityInitProcessor2(XML_Parser parser, const char *start, #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, start, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif /* XML_GE == 1 */ @@ -3527,6 +3576,11 @@ externalEntityInitProcessor2(XML_Parser parser, const char *start, } parser->m_eventPtr = start; return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_NONE: + if (! parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + } + return XML_ERROR_NONE; } parser->m_processor = externalEntityInitProcessor3; return externalEntityInitProcessor3(parser, start, end, endPtr); @@ -3626,7 +3680,7 @@ doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, : next; if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -4058,10 +4112,12 @@ doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, const enum XML_Convert_Result convert_res = XmlConvert( enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd); *eventEndPP = s; - beforeHandler(parser); - charDataHandler(parser->m_handlerArg, parser->m_dataBuf, - (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); - afterHandler(parser); + if (parser->m_characterDataHandler) { + beforeHandler(parser); + charDataHandler(parser->m_handlerArg, parser->m_dataBuf, + (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + afterHandler(parser); + } if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) break; @@ -4158,9 +4214,9 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, TAG_NAME *tagNamePtr, BINDING **bindingsPtr, enum XML_Account account) { DTD *const dtd = parser->m_dtd; /* save one level of indirection */ - int attIndex = 0; + size_t attIndex = 0; XML_Char *uri; - int nPrefixes = 0; + size_t nPrefixes = 0; BINDING *binding; const XML_Char *localPart; @@ -4187,8 +4243,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, return XML_ERROR_NO_MEMORY; /* get the attributes from the tokenizer */ - size_t n = (size_t)XmlGetAttributes(enc, attStr, (int)parser->m_attsSize, - parser->m_atts); + size_t n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts); /* Detect and prevent integer overflow */ if (n > SIZE_MAX - nDefaultAtts) { @@ -4223,11 +4278,22 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, /* Detect and prevent integer overflow. */ if (n > (size_t)INT_MAX) return XML_ERROR_NO_MEMORY; - XmlGetAttributes(enc, attStr, (int)n, parser->m_atts); + XmlGetAttributes(enc, attStr, n, parser->m_atts); } } /* the attribute list for the application */ + // NOTE: `parser->m_atts` is used to read `ATTRIBUTE` elements + // from start to end while at the same time writing `XML_Char *` + // elements from start to end *to the same block of memory*. + // That black magic only works because the first member `.name` in + // `ATTRIBUTE` is no longer being read after `appAtts[attIndex]` + // has been written, which for the first element is the very same + // address in memory. + // And because `attIndex` is increased twice for default attributes + // further down, struct `ATTRIBUTE` must be at least twice the size + // of a pointer, or the allocation size math for `m_attsSize` starts + // to underallocate. const XML_Char **const appAtts = (const XML_Char **)parser->m_atts; for (size_t i = 0; i < n; i++) { ATTRIBUTE *currAtt = &parser->m_atts[i]; @@ -4247,9 +4313,11 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, return XML_ERROR_DUPLICATE_ATTRIBUTE; } (attId->name)[-1] = 1; + // NOTE: The next call overwrites `parser->m_atts`, so we cannot use + // e.g. `parser->m_atts[i].name;` after this line! appAtts[attIndex++] = attId->name; if (! parser->m_atts[i].normalized) { - XML_Bool isCdata = XML_TRUE; + bool isCdata = true; /* figure out whether declared as other than CDATA */ if (attId->maybeTokenized) { @@ -4301,11 +4369,16 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, } /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */ - parser->m_nSpecifiedAtts = attIndex; + // Detect and reject integer overflow + if (attIndex > INT_MAX) + return XML_ERROR_NO_MEMORY; + parser->m_nSpecifiedAtts = (int)attIndex; if (elementType->idAtt && (elementType->idAtt->name)[-1]) { - for (int i = 0; i < attIndex; i += 2) + for (size_t i = 0; i < attIndex; i += 2) if (appAtts[i] == elementType->idAtt->name) { - parser->m_idAttIndex = i; + if (i > INT_MAX) + return XML_ERROR_NO_MEMORY; + parser->m_idAttIndex = (int)i; break; } } else @@ -4338,7 +4411,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, /* expand prefixed attribute names, check for duplicates, and clear flags that say whether attributes were specified */ - int i = 0; + size_t i = 0; if (nPrefixes) { unsigned int j; /* hash table index */ unsigned long version = parser->m_nsAttsVersion; @@ -4894,7 +4967,7 @@ doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr, int tok = XmlCdataSectionTok(enc, s, end, &next); #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #else @@ -5066,7 +5139,7 @@ doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr, # if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } # endif @@ -5158,7 +5231,7 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s, #if XML_GE == 1 if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -5379,7 +5452,7 @@ entityValueInitProcessor(XML_Parser parser, const char *s, const char *end, # if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } # endif @@ -5432,7 +5505,7 @@ externalParEntProcessor(XML_Parser parser, const char *s, const char *end, else if (tok == XML_TOK_BOM) { if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } @@ -5611,7 +5684,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, break; default: if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } } @@ -5708,7 +5781,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, return XML_ERROR_INVALID_TOKEN; } - if (parser->m_doctypeName) { + if (parser->m_doctypeName && parser->m_startDoctypeDeclHandler) { beforeHandler(parser); parser->m_startDoctypeDeclHandler( parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, @@ -5774,7 +5847,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, handleDefault = XML_FALSE; } break; - case XML_ROLE_INSTANCE_START: + case XML_ROLE_INSTANCE_START: { #ifdef XML_DTD /* if there is no DOCTYPE declaration then now is the last chance to read the foreign DTD @@ -5818,6 +5891,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, #endif /* XML_DTD */ parser->m_processor = contentProcessor; return contentProcessor(parser, s, end, nextPtr); + } case XML_ROLE_ATTLIST_ELEMENT_NAME: parser->m_declElementType = getElementType(parser, enc, s, next); if (! parser->m_declElementType) @@ -5827,16 +5901,16 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, parser->m_declAttributeId = getAttributeId(parser, enc, s, next); if (! parser->m_declAttributeId) return XML_ERROR_NO_MEMORY; - parser->m_declAttributeIsCdata = XML_FALSE; + parser->m_declAttributeIsCdata = false; parser->m_declAttributeType = NULL; - parser->m_declAttributeIsId = XML_FALSE; + parser->m_declAttributeIsId = false; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_CDATA: - parser->m_declAttributeIsCdata = XML_TRUE; + parser->m_declAttributeIsCdata = true; parser->m_declAttributeType = atypeCDATA; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ID: - parser->m_declAttributeIsId = XML_TRUE; + parser->m_declAttributeIsId = true; parser->m_declAttributeType = atypeID; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_IDREF: @@ -5924,7 +5998,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, /* ID attributes aren't allowed to have a default */ if (! defineAttribute( parser->m_declElementType, parser->m_declAttributeId, - parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser)) + parser->m_declAttributeIsCdata, false, attVal, parser)) return XML_ERROR_NO_MEMORY; if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) @@ -5954,17 +6028,23 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, #if XML_GE == 1 // This will store the given replacement text in // parser->m_declEntity->textPtr. - enum XML_Error result = callStoreEntityValue( + const enum XML_Error result = callStoreEntityValue( parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar, XML_ACCOUNT_NONE); + if (result != XML_ERROR_NONE) { + poolDiscard(&dtd->entityValuePool); + return result; + } if (parser->m_declEntity) { /* Detect and prevent signed integer overflow */ if ((size_t)poolLength(&dtd->entityValuePool) > (size_t)INT_MAX) { + poolDiscard(&dtd->entityValuePool); return XML_ERROR_NO_MEMORY; } - parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool); - parser->m_declEntity->textLen - = (int)(poolLength(&dtd->entityValuePool)); + const XML_Char *const valueStart = poolStart(&dtd->entityValuePool); + parser->m_declEntity->textPtr = valueStart; + parser->m_declEntity->textLen = poolLength(&dtd->entityValuePool); + parser->m_declEntity->scanPtr = valueStart; poolFinish(&dtd->entityValuePool); if (parser->m_entityDeclHandler) { *eventEndPP = s; @@ -5972,14 +6052,12 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, parser->m_declEntity->textPtr, - parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); + (int)parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); afterHandler(parser); handleDefault = XML_FALSE; } } else poolDiscard(&dtd->entityValuePool); - if (result != XML_ERROR_NONE) - return result; #else // This will store "&entity123;" in parser->m_declEntity->textPtr // to end up as "&entity123;" in the handler. @@ -5995,7 +6073,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, parser->m_declEntity->textPtr, - parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); + (int)parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); afterHandler(parser); handleDefault = XML_FALSE; } @@ -6114,6 +6192,17 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, } break; case XML_ROLE_GENERAL_ENTITY_NAME: { + // NOTE: XML 1.0 fourth edition demands in section + // "4.6 Predefined Entities" that bad redefinitions of predefined + // general entities must be detected and rejected. Expat has been + // ignoring both conforming and non-conforming redefinitions and + // thus has been failing to reject bad redefinitions, for years. + // As a result, users learned that they can get away with + // `` in practice. We cannot start conforming to + // that part of the spec now, or we risk rejecting many documents + // that parsed fine for years and that may not be fixable now or + // in time. So Expat continues to discard redefinitions of + // predefined entities altogether. if (XmlPredefinedEntityName(enc, s, next)) { parser->m_declEntity = NULL; break; @@ -6640,7 +6729,7 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end, #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -6707,6 +6796,415 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end, } } +#if XML_GE == 1 +// Checks `name` for being a predefined entity (i.e. one of "amp", "apos", "gt", +// "lt", "quot"). Similar in implementation to function +// `PREFIX(predefinedEntityName)` but operating on an `XML_Char` string with an +// explicit length, instead. Returns +// ASCII_AMP/ASCII_APOS/ASCII_GT/ASCII_LT/ASCII_QUOT for a match or 0 for no +// match. +XML_NONTESTING_STATIC int +isPredefinedEntityName(const XML_Char *name, size_t nameLen) { + switch (nameLen) { + case 2: + // Wanted: "lt" or "gt" + if (name[1] != XML_T(ASCII_t)) + break; + switch (name[0]) { + case XML_T(ASCII_l): + return ASCII_LT; + case XML_T(ASCII_g): + return ASCII_GT; + } + break; + case 3: + // Wanted: "amp" + if (name[0] == XML_T(ASCII_a) && name[1] == XML_T(ASCII_m) + && name[2] == XML_T(ASCII_p)) + return ASCII_AMP; + break; + case 4: + // Wanted: "apos" or "quot" + switch (name[0]) { + case XML_T(ASCII_a): + if (name[1] == XML_T(ASCII_p) && name[2] == XML_T(ASCII_o) + && name[3] == XML_T(ASCII_s)) + return ASCII_APOS; + break; + case XML_T(ASCII_q): + if (name[1] == XML_T(ASCII_u) && name[2] == XML_T(ASCII_o) + && name[3] == XML_T(ASCII_t)) + return ASCII_QUOT; + break; + } + } + return 0; +} + +static const XML_Char cdataOpen[] + = {ASCII_LT, ASCII_EXCL, ASCII_LSQB, ASCII_C, ASCII_D, + ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB, '\0'}; // i.e. "" +static const XML_Char commentOpen[] + = {ASCII_LT, ASCII_EXCL, ASCII_MINUS, ASCII_MINUS, '\0'}; // i.e. "" +static const XML_Char piClose[] = {ASCII_QUEST, ASCII_GT, '\0'}; // i.e. "?>" + +static const size_t cdataOpenLen = sizeof(cdataOpen) / sizeof(cdataOpen[0]) - 1; +static const size_t cdataCloseLen + = sizeof(cdataClose) / sizeof(cdataClose[0]) - 1; +static const size_t commentOpenLen + = sizeof(commentOpen) / sizeof(commentOpen[0]) - 1; +static const size_t commentCloseLen + = sizeof(commentClose) / sizeof(commentClose[0]) - 1; +static const size_t piCloseLen = sizeof(piClose) / sizeof(piClose[0]) - 1; + +// Checks the string starting at `pos` for starting a CDATA section, a comment +// or processing instructions. Returns +// XML_TOK_CDATA_SECT_OPEN/XML_TOK_COMMENT/XML_TOK_PI for a match or +// XML_TOK_INVALID (=0) for no match. Only in the success case, the length +// of the token is written to `*openTextLen`. +XML_NONTESTING_STATIC int +isCDataCommentOrPIStart(const XML_Char *pos, size_t maxLen, + size_t *openTextLen) { + assert(pos != NULL); + assert(openTextLen != NULL); + + if (maxLen < 2) + return XML_TOK_INVALID; + + if (pos[0] != XML_T(ASCII_LT)) + return XML_TOK_INVALID; + + if (pos[1] == XML_T(ASCII_QUEST)) { + *openTextLen = 2; + return XML_TOK_PI; + } + + if (pos[1] != XML_T(ASCII_EXCL)) + return XML_TOK_INVALID; + + if (maxLen >= cdataOpenLen && xcsncmp(pos, cdataOpen, cdataOpenLen) == 0) { + *openTextLen = cdataOpenLen; + return XML_TOK_CDATA_SECT_OPEN; + } + + if (maxLen >= commentOpenLen + && xcsncmp(pos, commentOpen, commentOpenLen) == 0) { + *openTextLen = commentOpenLen; + return XML_TOK_COMMENT; + } + + return XML_TOK_INVALID; +} + +/* Scan `entity`'s body, starting at `*posPtr`, accumulating the expanded + size into `*expandedSize`. + + Return value: how the scan ended, see enum EntityScanResult. + + *blockerOut (out, set only for ENTITY_SCAN_BLOCKED): + The non-empty entity the scan stopped at because its expanded size + has not been computed yet. The caller computes that size first and + calls again with *posPtr unchanged to resume. + The pointer is borrowed from the entity hash table (via lookup), not + a new allocation, so it must not be freed. + + *posPtr (in/out, scan cursor): + Advanced to end-of-text on a complete scan, or parked at the + offending reference otherwise, so a follow-up call resumes from + the same position. Not meaningful after ENTITY_SCAN_OVERFLOW. + + *expandedSize (in/out, expanded-byte accumulator): + The expanded size of this one `entity` (its text plus the expandedSize + of entities it references), not a total across all entities. Not + meaningful after ENTITY_SCAN_OVERFLOW; the overflowing value is never + stored anywhere. */ +XML_NONTESTING_STATIC enum EntityScanResult +scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr, + XmlBigCount *expandedSize, ENTITY **blockerOut) { + if (blockerOut != NULL) + *blockerOut = NULL; + const XML_Char refChar = entity->is_param ? XML_T('%') : XML_T('&'); + HASH_TABLE *const refTable +# ifdef XML_DTD + = entity->is_param ? &parser->m_dtd->paramEntities + : &parser->m_dtd->generalEntities; +# else + = &parser->m_dtd->generalEntities; +# endif + + const XML_Char *pos = *posPtr; + const XML_Char *const end = entity->textPtr + entity->textLen; + + while (pos < end) { + // Detect and skip CDATA/comment/PI sections + // because entities have no effect in these places + if (*pos == XML_T('<')) { + // Detect CDATA/comment/PI section start + size_t openTextLen = 0; + const int tok = isCDataCommentOrPIStart(pos, end - pos, &openTextLen); + if (tok != XML_TOK_INVALID) { + assert(openTextLen != 0); + + // Detect and avoid integer overflow + if (openTextLen > (XmlBigCount)(-1) - *expandedSize) + return ENTITY_SCAN_OVERFLOW; + + *expandedSize += openTextLen; + pos += openTextLen; + + // Detect CDATA/comment/PI section end + const XML_Char *closeText = NULL; + size_t closeLen = 0; + + switch (tok) { + case XML_TOK_CDATA_SECT_OPEN: + closeText = cdataClose; + closeLen = cdataCloseLen; + break; + case XML_TOK_COMMENT: + closeText = commentClose; + closeLen = commentCloseLen; + break; + case XML_TOK_PI: + closeText = piClose; + closeLen = piCloseLen; + break; + default: + assert(0 && "never gets here"); + break; + } + + const size_t remainderLen = end - pos; + const XML_Char *const closeStart + = xcsnstr(pos, closeText, remainderLen); + if (closeStart == NULL) { + // The CDATA/comment/PI section is NOT terminated + if (remainderLen > (XmlBigCount)(-1) - *expandedSize) + return ENTITY_SCAN_OVERFLOW; + *expandedSize += remainderLen; + *posPtr = end; + return ENTITY_SCAN_COMPLETE; + } + + // The CDATA/comment/PI section is NOT terminated + const size_t skippedLen = closeStart + closeLen - pos; + + // Detect and avoid integer overflow + if (skippedLen > (XmlBigCount)(-1) - *expandedSize) + return ENTITY_SCAN_OVERFLOW; + + *expandedSize += skippedLen; + pos += skippedLen; + + continue; + } + } + + // Detect an entity reference + if (*pos != refChar) { + // Detect and avoid integer overflow + if (*expandedSize == (XmlBigCount)(-1)) + return ENTITY_SCAN_OVERFLOW; + (*expandedSize)++; + pos++; + continue; + } + + const XML_Char *nameStart = pos + 1; + const XML_Char *nameEnd = nameStart; + while (nameEnd < end && *nameEnd != XML_T(';')) + nameEnd++; + + if (nameEnd >= end) { + /* Unterminated reference at end of text: treat the trailing + bytes as literal characters. */ + XmlBigCount addend = (XmlBigCount)(end - pos); + // Detect and avoid integer overflow + if (*expandedSize > (XmlBigCount)(-1) - addend) + return ENTITY_SCAN_OVERFLOW; + *expandedSize += addend; + *posPtr = end; + return ENTITY_SCAN_COMPLETE; + } + + const size_t nameLen = (size_t)(nameEnd - nameStart); + + /* At runtime the whole "&name;"/"%name;" token is re-scanned and charged to + the indirect accounting, then its expansion is charged separately; so + every reference below counts this token length plus its expansion. */ + const XmlBigCount refTokenLen + = (XmlBigCount)(/*sigil*/ 1 + nameLen + /*semicolon*/ 1); + + ENTITY *refEntity + = (ENTITY *)lookupWithLength(parser, refTable, nameStart, nameLen, 0); + + XmlBigCount addend = 0; + if (! refEntity) { + /* Predefined entities (amp/lt/gt/quot/apos) are general-only, hence the + `! entity->is_param` guard, and expand to a single character. */ + if (! entity->is_param && isPredefinedEntityName(nameStart, nameLen)) { + addend = refTokenLen + 1; + } else { + /* Undefined entity: expands to nothing, so only the token. */ + addend = refTokenLen; + } + } else if (refEntity->beingAnalyzed) { + /* Cycle: refEntity is already on the depth-first search stack, so its + expandedSize is not final yet; charge just the token. Do not fail the + parse here: per XML 1.0r4, + "A parsed entity MUST NOT contain a recursive reference to + itself, either directly or indirectly", but also "Only parsed + entities that are referenced directly or indirectly within the + document are required to be well-formed" - so a declared-but- + never-expanded cycle must be accepted; if the cycle is actually + expanded, the runtime recursive-ref check reports + XML_ERROR_RECURSIVE_ENTITY_REF. */ + addend = refTokenLen; + } else if (refEntity->textLen > 0 && refEntity->expandedSize == 0) { + /* Non-empty entity whose expanded size has not been computed yet; + report refEntity as a blocker so the caller can compute its size + first. */ + *posPtr = pos; + if (blockerOut != NULL) + *blockerOut = refEntity; + return ENTITY_SCAN_BLOCKED; + } else if (refEntity->expandedSize > 0) { + /* refEntity is fully resolved: expandedSize holds its final expanded + size (a non-zero value is never a partial here - the only entity that + briefly holds a partial is one currently on the resolve stack, which + is caught by the beingAnalyzed branch above). Add the token plus that + expansion. */ + if (refEntity->expandedSize > (XmlBigCount)(-1) - refTokenLen) + return ENTITY_SCAN_OVERFLOW; + addend = refTokenLen + refEntity->expandedSize; + } else { + /* Empty entity (textLen == 0): expands to nothing, so only the token. */ + addend = refTokenLen; + } + + // Detect and avoid integer overflow + if (*expandedSize > (XmlBigCount)(-1) - addend) + return ENTITY_SCAN_OVERFLOW; + *expandedSize += addend; + pos = nameEnd + 1; + } + + /* Loop only exits here with pos == end (a complete scan). */ + assert(pos == end); + *posPtr = end; + return ENTITY_SCAN_COMPLETE; +} + +/* Resolve expandedSize using an iterative depth-first search over the + reference graph. Each entity is scanned at most twice (once on push, + once after its blocker resolves), so the total work is O(N + T) where + N is the number of entities and T is the sum of all entities' textLen. + `entity->beingAnalyzed` marks the entities currently on the stack for + cycle detection; it is cleared again on pop. + Returns XML_ERROR_NO_MEMORY if the stack cannot be allocated, and + XML_ERROR_AMPLIFICATION_LIMIT_BREACH if an entity's expanded size + overflows XmlBigCount. */ +static enum XML_Error +resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table, + ENTITY *root) { + if (root == NULL || root->expandedSize != 0 || root->textPtr == NULL + || root->textLen == 0) + return XML_ERROR_NONE; + + if (table->used == 0) + return XML_ERROR_NONE; + + // Detect and avoid integer overflow + if (table->used > SIZE_MAX / sizeof(ENTITY_ANALYSIS_TASK)) + return XML_ERROR_NO_MEMORY; + + ENTITY_ANALYSIS_TASK *stack + = MALLOC(parser, sizeof(ENTITY_ANALYSIS_TASK) * table->used); + if (stack == NULL) + return XML_ERROR_NO_MEMORY; + + const XML_Parser rootParser = getRootParserOf(parser, NULL); + assert(! rootParser->m_parentParser); + + size_t top = 0; + stack[top].entity = root; + root->beingAnalyzed = XML_TRUE; + top++; + rootParser->m_entity_stats.currentDepth++; + if (rootParser->m_entity_stats.currentDepth + > rootParser->m_entity_stats.maximumDepthSeen) { + rootParser->m_entity_stats.maximumDepthSeen++; + } + + while (top > 0) { + ENTITY_ANALYSIS_TASK *task = &stack[top - 1]; + ENTITY *e = task->entity; + XmlBigCount sizeSoFar = e->expandedSize; + ENTITY *blocker = NULL; + + entityTrackingOnScanStart(parser, e, __LINE__); + + const enum EntityScanResult scanResult + = scanEntityText(parser, e, &e->scanPtr, &sizeSoFar, &blocker); + switch (scanResult) { + case ENTITY_SCAN_COMPLETE: + case ENTITY_SCAN_BLOCKED: + /* Save the size accumulated so far; together with task->pos it is + the state that lets the scan resume once the blocker's size has + been computed. This is the one place where expandedSize briefly + holds neither 0 nor the final size - only while the entity is + on the stack, where the beingAnalyzed check in scanEntityText + keeps every other reader away from the intermediate value. */ + e->expandedSize = sizeSoFar; + break; + default: + break; + } + + entityTrackingOnScanStop(parser, e, __LINE__); + + switch (scanResult) { + case ENTITY_SCAN_OVERFLOW: + /* Abort parsing right away; the beingAnalyzed marks still set on + the stacked entities do not matter once the parse is dead. */ + FREE(parser, stack); + /* expandedSize overflowed; pass SIZE_MAX (unrepresentable size). */ + accountingOnAbort(parser, SIZE_MAX, __LINE__); + return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; + + case ENTITY_SCAN_COMPLETE: + e->beingAnalyzed = XML_FALSE; + top--; + rootParser->m_entity_stats.currentDepth--; + break; + + case ENTITY_SCAN_BLOCKED: + /* Push the blocker. A blocker's expanded size is always still + uncomputed and it is never already on the stack, so each entity + is pushed at most once and top <= table->used. */ + assert(! blocker->beingAnalyzed); + assert(top < table->used); + stack[top].entity = blocker; + blocker->beingAnalyzed = XML_TRUE; + top++; + rootParser->m_entity_stats.currentDepth++; + if (rootParser->m_entity_stats.currentDepth + > rootParser->m_entity_stats.maximumDepthSeen) { + rootParser->m_entity_stats.maximumDepthSeen++; + } + break; + } + } + + FREE(parser, stack); + return XML_ERROR_NONE; +} +#endif /* XML_GE == 1 */ + static enum XML_Error processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl, enum EntityType type) { @@ -6735,6 +7233,37 @@ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl, /* LCOV_EXCL_STOP */ } +#if XML_GE == 1 + // Compute entity size assuming immediate access + if (entity->textLen > 0 && entity->expandedSize == 0) { + HASH_TABLE *const table +# ifdef XML_DTD + = entity->is_param ? &parser->m_dtd->paramEntities + : &parser->m_dtd->generalEntities; +# else + = &parser->m_dtd->generalEntities; +# endif + const enum XML_Error result + = resolveEntityClosureExpandedSize(parser, table, entity); + if (result != XML_ERROR_NONE) + return result; + } + + /* Reject an amplification attack before acquiring openEntity, so a rejected + entity leaks nothing and leaves entity state untouched. */ + if (entity->expandedSize > 0) { + const XML_Parser rootParser = getRootParserOf(parser, NULL); + /* Overflow of expandedSize aborts parsing during resolution + (on first expansion), so the stored value here is always exact. */ + const XmlBigCount expandedBytes = entity->expandedSize; + if (accountingCurrentAmplificationTolerated(rootParser, expandedBytes) + != XML_TRUE) { + accountingOnAbort(rootParser, expandedBytes, __LINE__); + return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; + } + } +#endif /* XML_GE == 1 */ + if (*freeEntityList) { openEntity = *freeEntityList; *freeEntityList = openEntity->next; @@ -6747,7 +7276,7 @@ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl, entity->hasMore = true; #if XML_GE == 1 entityTrackingOnOpen(parser, entity, __LINE__); -#endif +#endif /* XML_GE == 1 */ entity->processed = 0; openEntity->next = *openEntityList; *openEntityList = openEntity; @@ -6809,7 +7338,7 @@ internalEntityProcessor(XML_Parser parser, const char *s, const char *end, && (parser->m_parsingStatus.parsing == XML_SUSPENDED || (parser->m_parsingStatus.parsing == XML_PARSING && parser->m_reenter))) { - entity->processed = (int)(next - (const char *)entity->textPtr); + entity->processed = next - (const char *)entity->textPtr; return result; } @@ -6858,7 +7387,7 @@ errorProcessor(XML_Parser parser, const char *s, const char *end, } static enum XML_Error -storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, +storeAttributeValue(XML_Parser parser, const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account) { const char *next = ptr; @@ -6890,8 +7419,7 @@ storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, // processed. A XML_SUSPENDED check here is not required as // appendAttributeValue will never suspend the parser. if (nextInEntity < textEnd) { - entity->processed - = (int)(nextInEntity - (const char *)entity->textPtr); + entity->processed = nextInEntity - (const char *)entity->textPtr; continue; } assert(nextInEntity == textEnd); @@ -6936,7 +7464,7 @@ storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, } static enum XML_Error -appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, +appendAttributeValue(XML_Parser parser, const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account, const char **nextPtr) { DTD *const dtd = parser->m_dtd; /* save one level of indirection */ @@ -6950,7 +7478,7 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, int tok = XmlAttributeValueTok(enc, ptr, end, &next); #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -7166,7 +7694,7 @@ storeEntityValue(XML_Parser parser, const ENCODING *enc, if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH; goto endEntityValue; } @@ -7351,8 +7879,7 @@ callStoreEntityValue(XML_Parser parser, const ENCODING *enc, // processed. A XML_SUSPENDED check here is not required as // appendAttributeValue will never suspend the parser. if (textEnd != nextInEntity) { - entity->processed - = (int)(nextInEntity - (const char *)entity->textPtr); + entity->processed = nextInEntity - (const char *)entity->textPtr; continue; } @@ -7412,8 +7939,9 @@ storeSelfEntityValue(XML_Parser parser, ENTITY *entity) { poolDiscard(pool); return XML_ERROR_NO_MEMORY; } - entity->textPtr = poolStart(pool); - entity->textLen = (int)(poolLength(pool)); + const XML_Char *const valueStart = poolStart(pool); + entity->textPtr = valueStart; + entity->textLen = poolLength(pool); poolFinish(pool); return XML_ERROR_NONE; @@ -7546,8 +8074,8 @@ reportDefault(XML_Parser parser, const ENCODING *enc, const char *s, } static int -defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, - XML_Bool isId, const XML_Char *value, XML_Parser parser) { +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, bool isCdata, + bool isId, const XML_Char *value, XML_Parser parser) { DEFAULT_ATTRIBUTE *att; if (value || isId) { /* The handling of default attributes gets messed up if we have @@ -7708,7 +8236,7 @@ static const XML_Char * getContext(XML_Parser parser) { DTD *const dtd = parser->m_dtd; /* save one level of indirection */ HASH_TABLE_ITER iter; - XML_Bool needSep = XML_FALSE; + bool needSep = false; if (dtd->defaultPrefix.binding) { if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) @@ -7739,7 +8267,7 @@ getContext(XML_Parser parser) { */ return NULL; /* LCOV_EXCL_LINE */ } - needSep = XML_TRUE; + needSep = true; } hashTableIterInit(&iter, &(dtd->prefixes)); @@ -7768,7 +8296,7 @@ getContext(XML_Parser parser) { len--; if (! poolAppendChars(&parser->m_tempPool, prefix->binding->uri, len)) return NULL; - needSep = XML_TRUE; + needSep = true; } hashTableIterInit(&iter, &(dtd->generalEntities)); @@ -7782,7 +8310,7 @@ getContext(XML_Parser parser) { return NULL; if (! poolAppendChars(&parser->m_tempPool, e->name, xcslen(e->name))) return NULL; - needSep = XML_TRUE; + needSep = true; } if (! poolAppendChar(&parser->m_tempPool, XML_T('\0'))) @@ -8190,6 +8718,9 @@ copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable, return 0; newE->textPtr = tem; newE->textLen = oldE->textLen; +#if XML_GE == 1 + newE->scanPtr = tem; +#endif /* XML_GE == 1 */ } if (oldE->notation) { const XML_Char *tem = poolCopyString(newPool, oldE->notation); @@ -8512,7 +9043,7 @@ poolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s) { } static const XML_Char * -poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) { +poolCopyStringN(STRING_POOL *pool, const XML_Char *s, size_t n) { if (! pool->ptr && ! poolGrow(pool)) { /* The following line is unreachable given the current usage of * poolCopyStringN(). Currently it is called from exactly one @@ -8957,25 +9488,27 @@ copyString(const XML_Char *s, XML_Parser parser) { #if XML_GE == 1 static float -accountingGetCurrentAmplification(XML_Parser rootParser) { +accountingGetCurrentAmplification(XML_Parser rootParser, + XmlBigCount extraIndirectBytes) { // 1.........1.........12 => 22 const size_t lenOfShortestInclude = sizeof("") - 1; - const XmlBigCount countBytesOutput - = rootParser->m_accounting.countBytesDirect - + rootParser->m_accounting.countBytesIndirect; + /* Add as floats: u64 counts (max ~1.8e19) are far below FLT_MAX, so the sum + is always finite and cannot wrap the way an unsigned integer add could. */ + const float indirect = (float)rootParser->m_accounting.countBytesIndirect + + (float)extraIndirectBytes; const float amplificationFactor = rootParser->m_accounting.countBytesDirect - ? ((float)countBytesOutput + ? (((float)rootParser->m_accounting.countBytesDirect + indirect) / (float)(rootParser->m_accounting.countBytesDirect)) - : ((float)(lenOfShortestInclude - + rootParser->m_accounting.countBytesIndirect) + : (((float)lenOfShortestInclude + indirect) / (float)lenOfShortestInclude); assert(! rootParser->m_parentParser); return amplificationFactor; } static void -accountingReportStats(XML_Parser originParser, const char *epilog) { +accountingReportStats(XML_Parser originParser, const char *epilog, + XmlBigCount extraIndirectBytes, int sourceLine) { const XML_Parser rootParser = getRootParserOf(originParser, NULL); assert(! rootParser->m_parentParser); @@ -8983,19 +9516,33 @@ accountingReportStats(XML_Parser originParser, const char *epilog) { return; } + /* On an early abort the amplifying bytes have not been charged to the + indirect counter yet; fold extraIndirectBytes in (with overflow detection) + so the reported byte count and amplification reflect what was detected. */ + const XmlBigCount indirect = rootParser->m_accounting.countBytesIndirect; + const XmlBigCount indirectWithExtra + = (extraIndirectBytes > (XmlBigCount)(-1) - indirect) + ? (XmlBigCount)(-1) + : indirect + extraIndirectBytes; const float amplificationFactor - = accountingGetCurrentAmplification(rootParser); + = accountingGetCurrentAmplification(rootParser, extraIndirectBytes); fprintf(stderr, "expat: Accounting(%p): Direct " EXPAT_FMT_ULL( "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s", (void *)rootParser, rootParser->m_accounting.countBytesDirect, - rootParser->m_accounting.countBytesIndirect, - (double)amplificationFactor, epilog); + indirectWithExtra, (double)amplificationFactor, epilog); + /* An abort has no accountingReportDiff before it, so append the originating + source line here to show which rejection site these stats belong to. */ + if (sourceLine > 0) { + fprintf(stderr, " (xmlparse.c:%d)\n", sourceLine); + } } static void -accountingOnAbort(XML_Parser originParser) { - accountingReportStats(originParser, " ABORTING\n"); +accountingOnAbort(XML_Parser originParser, XmlBigCount extraIndirectBytes, + int sourceLine) { + accountingReportStats(originParser, " ABORTING", extraIndirectBytes, + sourceLine); } static void @@ -9035,6 +9582,32 @@ accountingReportDiff(XML_Parser rootParser, fprintf(stderr, "\"\n"); } +static XML_Bool +accountingCurrentAmplificationTolerated(XML_Parser rootParser, + XmlBigCount extraIndirectBytes) { + assert(! rootParser->m_parentParser); + + const XmlBigCount countBytesOutput + = rootParser->m_accounting.countBytesDirect + + rootParser->m_accounting.countBytesIndirect; + /* Overflow check: extraIndirectBytes can be SIZE_MAX, which would otherwise + wrap the unsigned total around to a small value and wrongly report the + output as tolerated. */ + const XmlBigCount countBytesOutputWithExtra + = (extraIndirectBytes > (XmlBigCount)(-1) - countBytesOutput) + ? (XmlBigCount)(-1) + : countBytesOutput + extraIndirectBytes; + const float amplificationFactor + = accountingGetCurrentAmplification(rootParser, extraIndirectBytes); + const XML_Bool tolerated + = (countBytesOutputWithExtra + < rootParser->m_accounting.activationThresholdBytes) + || (amplificationFactor + <= rootParser->m_accounting.maximumAmplificationFactor); + + return tolerated; +} + static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok, const char *before, const char *after, int source_line, @@ -9071,18 +9644,11 @@ accountingDiffTolerated(XML_Parser originParser, int tok, const char *before, return XML_FALSE; *additionTarget += bytesMore; - const XmlBigCount countBytesOutput - = rootParser->m_accounting.countBytesDirect - + rootParser->m_accounting.countBytesIndirect; - const float amplificationFactor - = accountingGetCurrentAmplification(rootParser); const XML_Bool tolerated - = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes) - || (amplificationFactor - <= rootParser->m_accounting.maximumAmplificationFactor); + = accountingCurrentAmplificationTolerated(rootParser, 0); if (rootParser->m_accounting.debugLevel >= 2u) { - accountingReportStats(rootParser, ""); + accountingReportStats(rootParser, "", 0, 0); accountingReportDiff(rootParser, levelsAwayFromRootParser, before, after, bytesMore, source_line, account); } @@ -9128,14 +9694,21 @@ entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity, = limitingNeeded ? (maxLimitedDepth - /* make space for ellipis */ 2) : candidateIndentDepth; + const ptrdiff_t scannedLength + = EXPAT_SAFE_PTR_DIFF(entity->scanPtr, entity->textPtr); + const char *const confidenceMarker + = ((size_t)scannedLength == entity->textLen) ? "!" : "?"; + fprintf( stderr, - "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s length %d (xmlparse.c:%d)\n", + "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s scanned " EXPAT_FMT_PTRDIFF_T( + "") "/" EXPAT_FMT_SIZE_T("") ", expanded " EXPAT_FMT_ULL("") "%s (xmlparse.c:%d)\n", (void *)rootParser, rootParser->m_entity_stats.countEverOpened, rootParser->m_entity_stats.currentDepth, rootParser->m_entity_stats.maximumDepthSeen, indentDepth * 2, "", ellipisOrEmpty, entity->is_param ? "%" : "&", entityName, action, - entity->textLen, sourceLine); + scannedLength, entity->textLen, entity->expandedSize, confidenceMarker, + sourceLine); } static void @@ -9150,6 +9723,7 @@ entityTrackingOnOpen(XML_Parser originParser, ENTITY *entity, int sourceLine) { rootParser->m_entity_stats.maximumDepthSeen++; } + // NOTE: The space at the end of "OPEN " is for length alignment with "CLOSE" entityTrackingReportStats(rootParser, entity, "OPEN ", sourceLine); } @@ -9162,6 +9736,25 @@ entityTrackingOnClose(XML_Parser originParser, ENTITY *entity, int sourceLine) { rootParser->m_entity_stats.currentDepth--; } +static void +entityTrackingOnScanStart(XML_Parser originParser, ENTITY *entity, + int sourceLine) { + const XML_Parser rootParser = getRootParserOf(originParser, NULL); + assert(! rootParser->m_parentParser); + + entityTrackingReportStats(rootParser, entity, "START", sourceLine); +} + +static void +entityTrackingOnScanStop(XML_Parser originParser, ENTITY *entity, + int sourceLine) { + const XML_Parser rootParser = getRootParserOf(originParser, NULL); + assert(! rootParser->m_parentParser); + + // NOTE: The space at the end of "STOP " is for length alignment with "START" + entityTrackingReportStats(rootParser, entity, "STOP ", sourceLine); +} + #endif /* XML_GE == 1 */ static XML_Parser diff --git a/base/poco/XML/src/xmltok.h b/base/poco/XML/src/xmltok.h index 4f6fb3850caf..fb8329e06394 100644 --- a/base/poco/XML/src/xmltok.h +++ b/base/poco/XML/src/xmltok.h @@ -180,8 +180,8 @@ struct encoding { const char *); int (*nameLength)(const ENCODING *, const char *); const char *(*skipS)(const ENCODING *, const char *); - int (*getAtts)(const ENCODING *enc, const char *ptr, int attsMax, - ATTRIBUTE *atts); + size_t (*getAtts)(const ENCODING *enc, const char *ptr, size_t attsMax, + ATTRIBUTE *atts); int (*charRefNumber)(const ENCODING *enc, const char *ptr); int (*predefinedEntityName)(const ENCODING *, const char *, const char *); void (*updatePosition)(const ENCODING *, const char *ptr, const char *end, diff --git a/base/poco/XML/src/xmltok_impl.c b/base/poco/XML/src/xmltok_impl.c index 571af3698af7..67fececb1f61 100644 --- a/base/poco/XML/src/xmltok_impl.c +++ b/base/poco/XML/src/xmltok_impl.c @@ -1505,11 +1505,11 @@ PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end, first attsMax attributes are stored in atts. */ -static int -PREFIX(getAtts)(const ENCODING *enc, const char *ptr, int attsMax, +static size_t +PREFIX(getAtts)(const ENCODING *enc, const char *ptr, size_t attsMax, ATTRIBUTE *atts) { enum { other, inName, inValue } state = inName; - int nAtts = 0; + size_t nAtts = 0; int open = 0; /* defined when state == inValue; initialization just to shut up compilers */ diff --git a/base/poco/XML/src/xmlxcs.c b/base/poco/XML/src/xmlxcs.c index ae5e042d778f..a97647fa9d69 100644 --- a/base/poco/XML/src/xmlxcs.c +++ b/base/poco/XML/src/xmlxcs.c @@ -88,3 +88,24 @@ xcsncmp(const XML_Char *a, const XML_Char *b, size_t len) { return strncmp(a, b, len); #endif } + +// A port of `strnstr(3bsd)` to `XML_Char` +const XML_Char * +xcsnstr(const XML_Char *haystack, const XML_Char *needle, size_t maxLen) { + // NOTE: We are not calling `xcsnlen(haystack, maxLen)` because + // `haystack` could be long and `xcsnlen` could be used in a loop + // and we need to avoid quadratic runtime behavior. + if (! *needle) + return haystack; // i.e. empty needle is always a match + const size_t needleLen = xcslen(needle); + if (needleLen > maxLen) + return NULL; + const size_t maxTries = (maxLen - needleLen) + 1; + for (size_t i = 0; i < maxTries && haystack[i]; i++) { + if (haystack[i] == needle[0] + && xcsncmp(haystack + i, needle, needleLen) == 0) { + return haystack + i; + } + } + return NULL; +} diff --git a/ci/docker/integration/dotnet_client/Dockerfile b/ci/docker/integration/dotnet_client/Dockerfile index 3fe1ba7dafc5..82bf1d686718 100644 --- a/ci/docker/integration/dotnet_client/Dockerfile +++ b/ci/docker/integration/dotnet_client/Dockerfile @@ -1,5 +1,5 @@ # docker build . -# docker run -it --rm --network=host 14f23e59669c dotnet run --host localhost --port 8123 --user default --database default +# docker run -it --rm --network=host 14f23e59669c dotnet /client/out/clickhouse.test.dll --host localhost --port 8123 --user default --database default # Rebuild to enable SBOM/provenance attestations (see #97903, #98511) FROM mcr.microsoft.com/dotnet/sdk:8.0 @@ -9,3 +9,12 @@ COPY *.cs *.csproj /client/ ARG VERSION=4.1.0 RUN dotnet add package ClickHouse.Client -v ${VERSION} + +# Build here, not in the test. `dotnet run` restores, builds and runs, which starts an MSBuild node +# and a Roslyn compiler server alongside the application: three .NET processes where the test needs +# one, and the two extra ones are not what this test covers. They are already a known source of +# noise in this suite - the analyzer crash that +# https://github.com/ClickHouse/ClickHouse/pull/107375 had to work around came from the in-test +# build. Publishing here leaves the test with a single `dotnet ` process. +ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 MSBUILDDISABLENODEREUSE=1 +RUN dotnet publish -c Release -o /client/out && rm -rf /client/obj /client/bin diff --git a/contrib/CMakeLists.txt b/contrib/CMakeLists.txt index 84f8af4c260b..e82c71acc8de 100644 --- a/contrib/CMakeLists.txt +++ b/contrib/CMakeLists.txt @@ -86,7 +86,7 @@ add_contrib (minizip-ng-cmake minizip-ng) add_contrib (snappy-cmake snappy) add_contrib (thrift-cmake thrift) add_contrib (StringZilla-cmake StringZilla) -# parquet/arrow/orc +# parquet/arrow add_contrib (xsimd-cmake xsimd) # required by arrow add_contrib (arrow-cmake arrow) # requires: snappy, thrift, double-conversion, xsimd add_contrib (avro-cmake avro) # requires: snappy diff --git a/contrib/arrow-cmake/CMakeLists.txt b/contrib/arrow-cmake/CMakeLists.txt index 9cd962825e53..1fdf41db8821 100644 --- a/contrib/arrow-cmake/CMakeLists.txt +++ b/contrib/arrow-cmake/CMakeLists.txt @@ -57,18 +57,9 @@ else() endif() -# === orc -set(ORC_SOURCE_DIR "${ClickHouse_SOURCE_DIR}/contrib/orc/c++") -set(ORC_INCLUDE_DIR "${ORC_SOURCE_DIR}/include") -set(ORC_SOURCE_SRC_DIR "${ORC_SOURCE_DIR}/src") -# set(ORC_SOURCE_WRAP_DIR "${ORC_SOURCE_DIR}/wrap") - -set(ORC_BUILD_SRC_DIR "${CMAKE_CURRENT_BINARY_DIR}/../orc/c++/src") -set(ORC_BUILD_INCLUDE_DIR "${CMAKE_CURRENT_BINARY_DIR}/../orc/c++/include") - -set(ORC_ADDITION_SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}) set(ARROW_SRC_DIR "${ClickHouse_SOURCE_DIR}/contrib/arrow/cpp/src") +# Used by `flight.cmake` to generate the Arrow Flight sources. if (NOT CMAKE_HOST_SYSTEM_NAME STREQUAL CMAKE_SYSTEM_NAME OR NOT CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL CMAKE_SYSTEM_PROCESSOR) set(PROTOBUF_EXECUTABLE "${PROJECT_BINARY_DIR}/native/contrib/google-protobuf-cmake/protoc") set(GRPC_EXECUTABLE "${PROJECT_BINARY_DIR}/native/contrib/grpc-cmake/grpc_cpp_plugin") @@ -76,16 +67,6 @@ else () set(PROTOBUF_EXECUTABLE $) set(GRPC_EXECUTABLE $) endif() -set(PROTO_DIR "${ORC_SOURCE_DIR}/../proto") - -add_custom_command(OUTPUT orc_proto.pb.h orc_proto.pb.cc - COMMAND ${PROTOBUF_EXECUTABLE} - -I ${PROTO_DIR} - --cpp_out="${CMAKE_CURRENT_BINARY_DIR}" - "${PROTO_DIR}/orc_proto.proto" - # Without these, the generated sources are not regenerated when the schema or - # `protoc` itself changes, and a stale `orc_proto.pb.h` is compiled instead. - DEPENDS "${PROTO_DIR}/orc_proto.proto" ${PROTOBUF_EXECUTABLE}) # === flatbuffers set(FLATBUFFERS_SRC_DIR "${ClickHouse_SOURCE_DIR}/contrib/flatbuffers") @@ -107,128 +88,6 @@ target_compile_definitions(_flatbuffers PRIVATE -DFLATBUFFERS_LOCALE_INDEPENDENT # NOTE: cannot use ch_contrib::hdfs since it's INCLUDE_DIRECTORIES does not includes trailing "hdfs/" set(HDFS_INCLUDE_DIR "${ClickHouse_SOURCE_DIR}/contrib/libhdfs3/include/hdfs/") -# arrow-cmake cmake file calling orc cmake subroutine which detects certain compiler features. -# Apple Clang compiler failed to compile this code without specifying c++11 standard. -# As result these compiler features detected as absent. In result it failed to compile orc itself. -# In orc makefile there is code that sets flags, but arrow-cmake ignores these flags. -if (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") - set(CXX11_FLAGS "-std=c++0x") -endif () - -set (ORC_CXX_HAS_INITIALIZER_LIST 1) -set (ORC_CXX_HAS_NOEXCEPT 1) -set (ORC_CXX_HAS_NULLPTR 1) -set (ORC_CXX_HAS_OVERRIDE 1) -set (ORC_CXX_HAS_UNIQUE_PTR 1) -set (ORC_CXX_HAS_CSTDINT 1) -set (ORC_CXX_HAS_THREAD_LOCAL 1) - -include(orc_check.cmake) -configure_file("${ORC_SOURCE_SRC_DIR}/Adaptor.hh.in" "${ORC_BUILD_INCLUDE_DIR}/Adaptor.hh") - - -# ARROW_ORC + adapters/orc/CMakefiles -set(ORC_SRCS - "${CMAKE_CURRENT_BINARY_DIR}/orc_proto.pb.h" - "${ORC_ADDITION_SOURCE_DIR}/orc_proto.pb.cc" - "${ORC_SOURCE_SRC_DIR}/Adaptor.cc" - "${ORC_SOURCE_SRC_DIR}/Adaptor.hh.in" - "${ORC_SOURCE_SRC_DIR}/BlockBuffer.cc" - "${ORC_SOURCE_SRC_DIR}/BlockBuffer.hh" - "${ORC_SOURCE_SRC_DIR}/BloomFilter.cc" - "${ORC_SOURCE_SRC_DIR}/BloomFilter.hh" - "${ORC_SOURCE_SRC_DIR}/Bpacking.hh" - "${ORC_SOURCE_SRC_DIR}/BpackingDefault.cc" - "${ORC_SOURCE_SRC_DIR}/BpackingDefault.hh" - "${ORC_SOURCE_SRC_DIR}/ByteRLE.cc" - "${ORC_SOURCE_SRC_DIR}/ByteRLE.hh" - "${ORC_SOURCE_SRC_DIR}/ColumnPrinter.cc" - "${ORC_SOURCE_SRC_DIR}/ColumnReader.cc" - "${ORC_SOURCE_SRC_DIR}/ColumnReader.hh" - "${ORC_SOURCE_SRC_DIR}/ColumnWriter.cc" - "${ORC_SOURCE_SRC_DIR}/ColumnWriter.hh" - "${ORC_SOURCE_SRC_DIR}/Common.cc" - "${ORC_SOURCE_SRC_DIR}/Dictionary.cc" - "${ORC_SOURCE_SRC_DIR}/DictionaryLoader.cc" - "${ORC_SOURCE_SRC_DIR}/Compression.cc" - "${ORC_SOURCE_SRC_DIR}/Compression.hh" - "${ORC_SOURCE_SRC_DIR}/ConvertColumnReader.cc" - "${ORC_SOURCE_SRC_DIR}/ConvertColumnReader.hh" - "${ORC_SOURCE_SRC_DIR}/CpuInfoUtil.cc" - "${ORC_SOURCE_SRC_DIR}/CpuInfoUtil.hh" - "${ORC_SOURCE_SRC_DIR}/Dispatch.hh" - "${ORC_SOURCE_SRC_DIR}/Exceptions.cc" - "${ORC_SOURCE_SRC_DIR}/Geospatial.cc" - "${ORC_SOURCE_SRC_DIR}/Int128.cc" - "${ORC_SOURCE_SRC_DIR}/LzoDecompressor.cc" - "${ORC_SOURCE_SRC_DIR}/LzoDecompressor.hh" - "${ORC_SOURCE_SRC_DIR}/MemoryPool.cc" - "${ORC_SOURCE_SRC_DIR}/Murmur3.cc" - "${ORC_SOURCE_SRC_DIR}/Murmur3.hh" - "${ORC_SOURCE_SRC_DIR}/Options.hh" - "${ORC_SOURCE_SRC_DIR}/OrcFile.cc" - "${ORC_SOURCE_SRC_DIR}/RLE.cc" - "${ORC_SOURCE_SRC_DIR}/RLE.hh" - "${ORC_SOURCE_SRC_DIR}/RLEV2Util.cc" - "${ORC_SOURCE_SRC_DIR}/RLEV2Util.hh" - "${ORC_SOURCE_SRC_DIR}/RLEv1.cc" - "${ORC_SOURCE_SRC_DIR}/RLEv1.hh" - "${ORC_SOURCE_SRC_DIR}/RLEv2.hh" - "${ORC_SOURCE_SRC_DIR}/Reader.cc" - "${ORC_SOURCE_SRC_DIR}/Reader.hh" - "${ORC_SOURCE_SRC_DIR}/RleDecoderV2.cc" - "${ORC_SOURCE_SRC_DIR}/RleEncoderV2.cc" - "${ORC_SOURCE_SRC_DIR}/SchemaEvolution.cc" - "${ORC_SOURCE_SRC_DIR}/SchemaEvolution.hh" - "${ORC_SOURCE_SRC_DIR}/Statistics.cc" - "${ORC_SOURCE_SRC_DIR}/Statistics.hh" - "${ORC_SOURCE_SRC_DIR}/StripeStream.cc" - "${ORC_SOURCE_SRC_DIR}/StripeStream.hh" - "${ORC_SOURCE_SRC_DIR}/Timezone.cc" - "${ORC_SOURCE_SRC_DIR}/Timezone.hh" - "${ORC_SOURCE_SRC_DIR}/TypeImpl.cc" - "${ORC_SOURCE_SRC_DIR}/TypeImpl.hh" - "${ORC_SOURCE_SRC_DIR}/Utils.hh" - "${ORC_SOURCE_SRC_DIR}/Vector.cc" - "${ORC_SOURCE_SRC_DIR}/Writer.cc" - "${ORC_SOURCE_SRC_DIR}/io/InputStream.cc" - "${ORC_SOURCE_SRC_DIR}/io/InputStream.hh" - "${ORC_SOURCE_SRC_DIR}/io/OutputStream.cc" - "${ORC_SOURCE_SRC_DIR}/io/OutputStream.hh" - "${ORC_SOURCE_SRC_DIR}/io/Cache.cc" - "${ORC_SOURCE_SRC_DIR}/io/Cache.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/ExpressionTree.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/ExpressionTree.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/Literal.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/PredicateLeaf.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/PredicateLeaf.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/SargsApplier.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/SargsApplier.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/SearchArgument.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/SearchArgument.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/TruthValue.cc" - ) - -add_library(_orc ${ORC_SRCS}) -target_link_libraries(_orc PRIVATE - ch_contrib::protobuf - ch_contrib::lz4 - ch_contrib::snappy - ch_contrib::zlib - ch_contrib::zstd) -target_include_directories(_orc SYSTEM BEFORE PUBLIC - ${ORC_INCLUDE_DIR} - "${ClickHouse_SOURCE_DIR}/contrib/arrow-cmake/cpp/src/orc/c++/include") -target_compile_options(_orc PRIVATE - -include "${ClickHouse_SOURCE_DIR}/contrib/google-protobuf/src/google/protobuf/stubs/port.h" -) -target_include_directories(_orc SYSTEM BEFORE PUBLIC ${ORC_BUILD_INCLUDE_DIR}) -target_include_directories(_orc SYSTEM PRIVATE - ${ORC_SOURCE_SRC_DIR} - ${ORC_SOURCE_WRAP_DIR} - ${ORC_BUILD_SRC_DIR} - ${ORC_ADDITION_SOURCE_DIR} - ${ARROW_SRC_DIR}) # === arrow @@ -240,11 +99,8 @@ configure_file("${LIBRARY_DIR}/util/config_internal.h.cmake" "${ARROW_GENERATED_ # arrow/cpp/src/arrow/CMakeLists.txt (ARROW_SRCS + ARROW_COMPUTE + ARROW_IPC) # find . \( -iname \*.cc -o -iname \*.cpp -o -iname \*.c \) | sort | awk '{print "\"${LIBRARY_DIR}" substr($1,2) "\"" }' | grep -v 'test.cc' | grep -v 'json' | grep -v 'flight' \| -# grep -v 'csv' | grep -v 'acero' | grep -v 'dataset' | grep -v 'testing' | grep -v 'gpu' | grep -v 'engine' | grep -v 'filesystem' | grep -v 'benchmark.cc' +# grep -v 'csv' | grep -v 'acero' | grep -v 'dataset' | grep -v 'testing' | grep -v 'gpu' | grep -v 'engine' | grep -v 'filesystem' | grep -v 'benchmark.cc' | grep -v 'adapters/orc' set(ARROW_SRCS - "${LIBRARY_DIR}/adapters/orc/adapter.cc" - "${LIBRARY_DIR}/adapters/orc/options.cc" - "${LIBRARY_DIR}/adapters/orc/util.cc" "${LIBRARY_DIR}/array/array_base.cc" "${LIBRARY_DIR}/array/array_binary.cc" "${LIBRARY_DIR}/array/array_decimal.cc" @@ -466,10 +322,6 @@ set(ARROW_SRCS "${LIBRARY_DIR}/vendored/uriparser/UriResolve.c" "${LIBRARY_DIR}/vendored/uriparser/UriShorten.c" "${LIBRARY_DIR}/visitor.cc" - - "${ARROW_SRC_DIR}/arrow/adapters/orc/adapter.cc" - "${ARROW_SRC_DIR}/arrow/adapters/orc/util.cc" - "${ARROW_SRC_DIR}/arrow/adapters/orc/options.cc" ) add_definitions(-DARROW_WITH_BROTLI) @@ -514,10 +366,6 @@ target_link_libraries(_arrow PRIVATE # ARROW_HAVE_* SIMD defines. PUBLIC so the headers are visible to _parquet too (it links _arrow # PUBLIC). target_link_libraries(_arrow PUBLIC ch_contrib::xsimd) -target_link_libraries(_arrow PUBLIC _orc) - -add_dependencies(_arrow protoc) - target_include_directories(_arrow SYSTEM BEFORE PUBLIC ${ARROW_SRC_DIR}) target_include_directories(_arrow SYSTEM BEFORE PUBLIC "${ClickHouse_SOURCE_DIR}/contrib/arrow-cmake/cpp/src") diff --git a/contrib/arrow-cmake/orc_check.cmake b/contrib/arrow-cmake/orc_check.cmake deleted file mode 100644 index 523e1cf1d86b..000000000000 --- a/contrib/arrow-cmake/orc_check.cmake +++ /dev/null @@ -1,14 +0,0 @@ -set (HAS_PREAD 1) -set (HAS_STRPTIME 1) -set (HAS_STOLL 1) -set (INT64_IS_LL 1) -set (HAS_DIAGNOSTIC_PUSH 1) -set (HAS_STD_ISNAN 1) -set (HAS_STD_MUTEX 1) -set (NEEDS_REDUNDANT_MOVE 1) -set (HAS_PRE_1970 1) -set (HAS_POST_2038 1) -set (NEEDS_Z_PREFIX 0) - -set(CMAKE_REQUIRED_INCLUDES) -set(CMAKE_REQUIRED_LIBRARIES) diff --git a/contrib/brotli b/contrib/brotli index d224526f8fa7..2d9c9b61f4e7 160000 --- a/contrib/brotli +++ b/contrib/brotli @@ -1 +1 @@ -Subproject commit d224526f8fa736f24b2339e6f421a142de6586c8 +Subproject commit 2d9c9b61f4e7d3523c9dfb62e48fe91aaf86e812 diff --git a/contrib/brotli-cmake/CMakeLists.txt b/contrib/brotli-cmake/CMakeLists.txt index b89e81ecda19..8c2b41721dc9 100644 --- a/contrib/brotli-cmake/CMakeLists.txt +++ b/contrib/brotli-cmake/CMakeLists.txt @@ -9,35 +9,41 @@ set(BROTLI_SOURCE_DIR "${ClickHouse_SOURCE_DIR}/contrib/brotli/c") set(BROTLI_BINARY_DIR "${ClickHouse_BINARY_DIR}/contrib/brotli/c") set(SRCS - "${BROTLI_SOURCE_DIR}/enc/command.c" - "${BROTLI_SOURCE_DIR}/enc/fast_log.c" + "${BROTLI_SOURCE_DIR}/common/constants.c" + "${BROTLI_SOURCE_DIR}/common/context.c" + "${BROTLI_SOURCE_DIR}/common/dictionary.c" + "${BROTLI_SOURCE_DIR}/common/platform.c" + "${BROTLI_SOURCE_DIR}/common/shared_dictionary.c" + "${BROTLI_SOURCE_DIR}/common/transform.c" "${BROTLI_SOURCE_DIR}/dec/bit_reader.c" - "${BROTLI_SOURCE_DIR}/dec/state.c" - "${BROTLI_SOURCE_DIR}/dec/huffman.c" "${BROTLI_SOURCE_DIR}/dec/decode.c" - "${BROTLI_SOURCE_DIR}/enc/encode.c" - "${BROTLI_SOURCE_DIR}/enc/dictionary_hash.c" + "${BROTLI_SOURCE_DIR}/dec/huffman.c" + "${BROTLI_SOURCE_DIR}/dec/prefix.c" + "${BROTLI_SOURCE_DIR}/dec/state.c" + "${BROTLI_SOURCE_DIR}/dec/static_init.c" + "${BROTLI_SOURCE_DIR}/enc/backward_references.c" + "${BROTLI_SOURCE_DIR}/enc/backward_references_hq.c" + "${BROTLI_SOURCE_DIR}/enc/bit_cost.c" + "${BROTLI_SOURCE_DIR}/enc/block_splitter.c" + "${BROTLI_SOURCE_DIR}/enc/brotli_bit_stream.c" "${BROTLI_SOURCE_DIR}/enc/cluster.c" + "${BROTLI_SOURCE_DIR}/enc/command.c" + "${BROTLI_SOURCE_DIR}/enc/compound_dictionary.c" + "${BROTLI_SOURCE_DIR}/enc/compress_fragment.c" + "${BROTLI_SOURCE_DIR}/enc/compress_fragment_two_pass.c" + "${BROTLI_SOURCE_DIR}/enc/dictionary_hash.c" + "${BROTLI_SOURCE_DIR}/enc/encode.c" + "${BROTLI_SOURCE_DIR}/enc/encoder_dict.c" "${BROTLI_SOURCE_DIR}/enc/entropy_encode.c" + "${BROTLI_SOURCE_DIR}/enc/fast_log.c" + "${BROTLI_SOURCE_DIR}/enc/histogram.c" "${BROTLI_SOURCE_DIR}/enc/literal_cost.c" - "${BROTLI_SOURCE_DIR}/enc/compress_fragment_two_pass.c" + "${BROTLI_SOURCE_DIR}/enc/memory.c" + "${BROTLI_SOURCE_DIR}/enc/metablock.c" "${BROTLI_SOURCE_DIR}/enc/static_dict.c" - "${BROTLI_SOURCE_DIR}/enc/compress_fragment.c" - "${BROTLI_SOURCE_DIR}/enc/block_splitter.c" - "${BROTLI_SOURCE_DIR}/enc/backward_references_hq.c" - "${BROTLI_SOURCE_DIR}/enc/histogram.c" - "${BROTLI_SOURCE_DIR}/enc/brotli_bit_stream.c" + "${BROTLI_SOURCE_DIR}/enc/static_dict_lut.c" + "${BROTLI_SOURCE_DIR}/enc/static_init.c" "${BROTLI_SOURCE_DIR}/enc/utf8_util.c" - "${BROTLI_SOURCE_DIR}/enc/encoder_dict.c" - "${BROTLI_SOURCE_DIR}/enc/backward_references.c" - "${BROTLI_SOURCE_DIR}/enc/bit_cost.c" - "${BROTLI_SOURCE_DIR}/enc/metablock.c" - "${BROTLI_SOURCE_DIR}/enc/memory.c" - "${BROTLI_SOURCE_DIR}/common/dictionary.c" - "${BROTLI_SOURCE_DIR}/common/transform.c" - "${BROTLI_SOURCE_DIR}/common/platform.c" - "${BROTLI_SOURCE_DIR}/common/context.c" - "${BROTLI_SOURCE_DIR}/common/constants.c" ) add_library(_brotli ${SRCS}) @@ -45,4 +51,3 @@ add_library(ch_contrib::brotli ALIAS _brotli) target_include_directories(_brotli SYSTEM BEFORE PUBLIC "${BROTLI_SOURCE_DIR}/include") -target_compile_definitions(_brotli PRIVATE BROTLI_BUILD_PORTABLE=1) diff --git a/contrib/c-ares b/contrib/c-ares index c7a3138dcfe3..bc91829cce98 160000 --- a/contrib/c-ares +++ b/contrib/c-ares @@ -1 +1 @@ -Subproject commit c7a3138dcfe3bb0eaaf10c0c24c36dc66dc790ab +Subproject commit bc91829cce983a35ec01f5dbc05465858a3df469 diff --git a/contrib/grpc b/contrib/grpc index a703d1f9448f..68b2fe0b2b13 160000 --- a/contrib/grpc +++ b/contrib/grpc @@ -1 +1 @@ -Subproject commit a703d1f9448ff77deca3beb36dfc7d337a209d3e +Subproject commit 68b2fe0b2b1318f18aadee9027e86e8ceaa20af2 diff --git a/contrib/hive-metastore-cmake/CMakeLists.txt b/contrib/hive-metastore-cmake/CMakeLists.txt index a5e16c739afb..bf92db62d1b9 100644 --- a/contrib/hive-metastore-cmake/CMakeLists.txt +++ b/contrib/hive-metastore-cmake/CMakeLists.txt @@ -1,7 +1,15 @@ -if (TARGET ch_contrib::hdfs) +if (NOT TARGET ch_contrib::hdfs) + if (ENABLE_HIVE) + message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use Hive without HDFS") + endif() +# `Storages/Hive/HiveFile.h` uses the ORC reader and `parquet/arrow/reader.h` outright, +# so Hive needs both readers, not just the metastore client. The ORC reader needs only snappy. +elseif (NOT TARGET ch_contrib::snappy OR NOT TARGET _parquet) + if (ENABLE_HIVE) + message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use Hive without ORC and Parquet") + endif() +else() option(ENABLE_HIVE "Enable Hive" ${ENABLE_LIBRARIES}) -elseif(ENABLE_HIVE) - message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use Hive without HDFS") endif() if (NOT ENABLE_HIVE) diff --git a/contrib/mongo-c-driver b/contrib/mongo-c-driver index 70de9e880072..58b4e1f39c6f 160000 --- a/contrib/mongo-c-driver +++ b/contrib/mongo-c-driver @@ -1 +1 @@ -Subproject commit 70de9e880072b120ccbb48c77de334775747d7a9 +Subproject commit 58b4e1f39c6f8bcf4da4204deb84f9b3527388d4 diff --git a/contrib/mongo-c-driver-cmake/CMakeLists.txt b/contrib/mongo-c-driver-cmake/CMakeLists.txt index 7a270790f140..79ad23b40d8d 100644 --- a/contrib/mongo-c-driver-cmake/CMakeLists.txt +++ b/contrib/mongo-c-driver-cmake/CMakeLists.txt @@ -6,12 +6,12 @@ endif() set(libbson_VERSION_MAJOR 2) set(libbson_VERSION_MINOR 5) -set(libbson_VERSION_PATCH 5) -set(libbson_VERSION 2.5.5) +set(libbson_VERSION_PATCH 8) +set(libbson_VERSION 2.5.8) set(libmongoc_VERSION_MAJOR 2) set(libmongoc_VERSION_MINOR 5) -set(libmongoc_VERSION_PATCH 5) -set(libmongoc_VERSION 2.5.5) +set(libmongoc_VERSION_PATCH 8) +set(libmongoc_VERSION 2.5.8) set(LIBBSON_SOURCES_ROOT "${ClickHouse_SOURCE_DIR}/contrib/mongo-c-driver/src") set(LIBBSON_SOURCE_DIR "${LIBBSON_SOURCES_ROOT}/libbson/src") diff --git a/contrib/mongo-cxx-driver b/contrib/mongo-cxx-driver index fa9ee6ed008e..35424a5cc597 160000 --- a/contrib/mongo-cxx-driver +++ b/contrib/mongo-cxx-driver @@ -1 +1 @@ -Subproject commit fa9ee6ed008e84b9562a7a55d70681de8a6bc1c6 +Subproject commit 35424a5cc597391d3737ae5e00f029cd2afc03c4 diff --git a/contrib/orc b/contrib/orc deleted file mode 160000 index 8ca5eeed390f..000000000000 --- a/contrib/orc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 8ca5eeed390f57fe6d1d4f7f8d97da19de6c08cb diff --git a/contrib/sqlite-amalgamation b/contrib/sqlite-amalgamation index 23c7b7692961..f48768e9089b 160000 --- a/contrib/sqlite-amalgamation +++ b/contrib/sqlite-amalgamation @@ -1 +1 @@ -Subproject commit 23c7b76929611997c5f0315b3149372b1bee1d41 +Subproject commit f48768e9089bf66717e8c393dce5dd80c86761f5 diff --git a/docs/en/engines/table-engines/integrations/azure-queue.md b/docs/en/engines/table-engines/integrations/azure-queue.md index 2147a8bbb0e1..bbf5046a163b 100644 --- a/docs/en/engines/table-engines/integrations/azure-queue.md +++ b/docs/en/engines/table-engines/integrations/azure-queue.md @@ -53,6 +53,8 @@ Below are the settings only compatible with AzureQueue and not applicable for S3 Connection string for Azure Blob Storage to move successfully processed files to, if the destination is another Azure container. +Setting it requires the `WRITE` grant on the `AZURE` source. A grant limited by a URL filter is not enough, because a move has no single blob path and writes keys that are built from `after_processing_move_prefix` and the source keys. `ALTER TABLE ... MODIFY SETTING` also requires `SELECT` on the table. The destination must be allowed by `remote_url_allow_hosts`. + Possible values: - String. @@ -63,6 +65,8 @@ Default value: empty string. Container name to move successfully processed files to, if the destination is another Azure container. +Changing it redirects the move to another container of the same account, so it needs the same grants as `after_processing_move_connection_string`: the `WRITE` grant on the `AZURE` source without a URL filter, and `SELECT` on the table for `ALTER TABLE ... MODIFY SETTING`. + Possible values: - String. diff --git a/docs/en/engines/table-engines/integrations/s3queue.md b/docs/en/engines/table-engines/integrations/s3queue.md index 9ee0c93147e4..48d82ab2db78 100644 --- a/docs/en/engines/table-engines/integrations/s3queue.md +++ b/docs/en/engines/table-engines/integrations/s3queue.md @@ -186,6 +186,8 @@ Default value: empty string. URI of S3 bucket to move successfully processed files to, if the destination is another S3 bucket. +Setting it is the same data flow as `INSERT INTO FUNCTION s3('') SELECT * FROM `, so it requires the `WRITE` grant on the `S3` source. A grant limited by a URL filter is not enough, because the move writes keys that are built from `after_processing_move_prefix` and the source keys, not from the URI. `ALTER TABLE ... MODIFY SETTING` also requires `SELECT` on the table. The destination must be allowed by `remote_url_allow_hosts`. + Possible values: - String. diff --git a/docs/en/operations/settings/settings-users.md b/docs/en/operations/settings/settings-users.md index d7d61ff6ee9c..d029b4cca3ad 100644 --- a/docs/en/operations/settings/settings-users.md +++ b/docs/en/operations/settings/settings-users.md @@ -110,6 +110,7 @@ It's not yet supported in SQL-driven Access Control. To authenticate using TOTP, users must provide a primary password along with a one-time password generated by their TOTP application via the `--one-time-password` command line option or concatenated to main password together with a '+' character. For example if the primary password is `some_password` and the generated TOTP code is `345123`, user may specify `--password some_password+345123` or `--password some_password --one-time-password 345123` when connecting to ClickHouse. If no password specified `clickhouse-client` will prompt for it interactively. +When no code is supplied for an account with TOTP, the server replies with the error `REQUIRED_SECOND_FACTOR` whether or not the password is correct, and `clickhouse-client` prompts for the code; the password is verified only together with the code. Each code is accepted at most once, as required by [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238#section-5.2), so a user can successfully authenticate at most once per `period`. Keep this in mind for clients that authenticate on every request or connection (for example, scripts using the HTTP interface): each authentication needs a fresh code. diff --git a/programs/client/Client.cpp b/programs/client/Client.cpp index d37218c596e4..e7d0ad5281c8 100644 --- a/programs/client/Client.cpp +++ b/programs/client/Client.cpp @@ -408,6 +408,16 @@ try if (should_ask_2fa) { + /// The server asks for the second factor before it checks the password, so the first attempt + /// without any password ends here too. Ask for the password alone first: it may already contain + /// the code (`password+code`); otherwise the server asks again and the code is prompted. + if (!asked_password && !config().has("password") && !config().getBool("ask-password", false)) + { + asked_password = true; + config().setBool("ask-password", true); + continue; + } + asked_2fa = true; if (!connection_parameters.password.empty()) config().setString("password", connection_parameters.password); @@ -567,7 +577,8 @@ void Client::connect() catch (Exception & e) { /// This problem can't be fixed with reconnection so it is not attempted - if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD) + if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD + || e.code() == ErrorCodes::REQUIRED_SECOND_FACTOR) throw; if (attempted_address_index == hosts_and_ports.size() - 1) diff --git a/src/Access/AccessBackup.cpp b/src/Access/AccessBackup.cpp index d22edd007e2f..6af476b88b1b 100644 --- a/src/Access/AccessBackup.cpp +++ b/src/Access/AccessBackup.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -176,6 +177,23 @@ namespace } } }; + + AccessRights getRequiredAccessToRestoreGrants(const AccessRights & access) + { + AccessRights required_access; + for (const auto & element : access.getElements()) + { + /// Restoring a grant requires `GRANT OPTION` even if the backed-up entity does not have it. + if (element.is_partial_revoke && element.grant_option) + continue; + + if (element.is_partial_revoke) + required_access.revoke(element); + else + required_access.grantWithGrantOption(element); + } + return required_access; + } } @@ -338,12 +356,14 @@ void AccessRestorerFromBackup::loadFromBackup() } -AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const +AccessRights AccessRestorerFromBackup::getRequiredAccess() const { if (!loaded) throw Exception(ErrorCodes::LOGICAL_ERROR, "Access entities not loaded"); - AccessRightsElements res; + AccessRights res; + /// Like `CREATE ... OR REPLACE`, replacement requires `DROP` even if the entity does not exist. + const bool replace = (creation_mode == RestoreAccessCreationMode::kReplace); for (const auto & [id, entity_info] : entity_infos) { if (!entity_info.restore) @@ -355,57 +375,56 @@ AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const case User::TYPE: { const auto & user = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_USER, user.getName()); + AccessFlags flags = AccessType::CREATE_USER; + if (replace) + flags |= AccessType::DROP_USER; + res.grant(flags, user.getName()); if (!restore_with_current_grants) - { - auto elements = user.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(user.access)); if (!user.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case Role::TYPE: { const auto & role = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROLE, role.getName()); + AccessFlags flags = AccessType::CREATE_ROLE; + if (replace) + flags |= AccessType::DROP_ROLE; + res.grant(flags, role.getName()); if (!restore_with_current_grants) - { - auto elements = role.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(role.access)); if (!role.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case SettingsProfile::TYPE: { - res.emplace_back(AccessType::CREATE_SETTINGS_PROFILE); + AccessFlags flags = AccessType::CREATE_SETTINGS_PROFILE; + if (replace) + flags |= AccessType::DROP_SETTINGS_PROFILE; + res.grant(flags); break; } case RowPolicy::TYPE: { const auto & policy = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROW_POLICY, policy.getDatabase(), policy.getTableName()); + AccessFlags flags = AccessType::CREATE_ROW_POLICY; + if (replace) + flags |= AccessType::DROP_ROW_POLICY; + res.grant(flags, policy.getDatabase(), policy.getTableName()); break; } case Quota::TYPE: { - res.emplace_back(AccessType::CREATE_QUOTA); + AccessFlags flags = AccessType::CREATE_QUOTA; + if (replace) + flags |= AccessType::DROP_QUOTA; + res.grant(flags); break; } diff --git a/src/Access/AccessBackup.h b/src/Access/AccessBackup.h index 8219d1051035..da0f3088a033 100644 --- a/src/Access/AccessBackup.h +++ b/src/Access/AccessBackup.h @@ -11,7 +11,7 @@ class AccessControl; enum class AccessEntityType : uint8_t; struct IAccessEntity; using AccessEntityPtr = std::shared_ptr; -class AccessRightsElements; +class AccessRights; class IAccessStorage; class IBackup; using BackupPtr = std::shared_ptr; @@ -69,9 +69,9 @@ class AccessRestorerFromBackup /// Loads access entities from the backup. void loadFromBackup(); - /// Checks that the current user can do restoring. - /// Function loadFromBackup() must be called before that. - AccessRightsElements getRequiredAccess() const; + /// Returns the access required to restore the loaded entities. + /// `loadFromBackup` must be called first. + AccessRights getRequiredAccess() const; /// Generates random IDs for access entities we're restoring to insert them into an access storage; /// and finds IDs of existing access entities which are used as dependencies. diff --git a/src/Access/AccessControl.cpp b/src/Access/AccessControl.cpp index 03e25e9c513f..92f938920279 100644 --- a/src/Access/AccessControl.cpp +++ b/src/Access/AccessControl.cpp @@ -602,22 +602,25 @@ AuthResult AccessControl::authenticate(const Credentials & credentials, const Po // NOTE: In the case where the user has never been logged in using LDAP, // Then user_id is not generated, and the authentication quota will always be nullptr. auto authentication_quota = getAuthenticationQuota(credentials.getUserName(), address, client_info.getLastForwardedForHost()); - if (authentication_quota) - { - /// Reserve a single try from the quota to check whether we have another authentication try. - /// This is required for correct behavior in this situation: - /// User has 1 login failures quota. - /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. - /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. - /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED - /// and don't let the user authenticate. - /// - /// The authentication failures counter will be reset after successful authentication. - authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); - } try { + if (authentication_quota) + { + /// Reserve a single try from the quota to check whether we have another authentication try. + /// This is required for correct behavior in this situation: + /// User has 1 login failures quota. + /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. + /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. + /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED + /// and don't let the user authenticate. + /// + /// The authentication failures counter will be reset after successful authentication. + /// Inside the try block, so that an exceeded quota is reported like any other authentication failure + /// and doesn't reveal whether the user exists. + authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); + } + const auto auth_result = MultipleAccessStorage::authenticate(credentials, address, *external_authenticators, client_info, allow_no_password, allow_plaintext_password); if (authentication_quota) @@ -859,7 +862,7 @@ std::shared_ptr AccessControl::getEnabledQuota( const String & forwarded_address, const String & custom_quota_key) const { - return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key, true); + return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key); } std::shared_ptr AccessControl::getAuthenticationQuota( @@ -872,18 +875,13 @@ std::shared_ptr AccessControl::getAuthenticationQuota( const auto new_current_roles = user->granted_roles.findGranted(user->default_roles); const auto roles_info = getEnabledRolesInfo(new_current_roles, {}); - // client_key is not received at the moment of authentication during TCP connection - // if key type is set to QuotaKeyType::CLIENT_KEY - // QuotaCache::QuotaInfo::calculateKey will throw exception without throw_if_client_key_empty = false String quota_key; - bool throw_if_client_key_empty = false; return quota_cache->getEnabledQuota(*user_id, user->getName(), roles_info->enabled_roles, std::make_shared(address), forwarded_address, - quota_key, - throw_if_client_key_empty); + quota_key); } return nullptr; } diff --git a/src/Access/Authentication.cpp b/src/Access/Authentication.cpp index 055109dc596b..7745947d0fd2 100644 --- a/src/Access/Authentication.cpp +++ b/src/Access/Authentication.cpp @@ -183,80 +183,60 @@ namespace return {password_with_otp.substr(0, separator_pos), password_with_otp.substr(separator_pos + 1)}; } - Authentication::CredentialsCheckResult checkBasicAuthentication( - const BasicCredentials * basic_credentials, + /// Verifies the primary credential: the password without the one-time password part. + bool checkPrimaryCredential( + std::string_view password, + const BasicCredentials & basic_credentials, const AuthenticationData & authentication_method, const ExternalAuthenticators & external_authenticators, const ClientInfo & client_info, SettingsChanges & settings) { - const auto & provided_password = basic_credentials->getPassword(); - const auto & otp_secret = authentication_method.getOneTimePassword(); - auto [password, one_time_password] = splitOneTimePasswordAndPassword(provided_password, authentication_method); - Authentication::CredentialsCheckResult on_success = Authentication::CredentialsCheckResult::Success; - if (otp_secret) - { - /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after - /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. - if (one_time_password.empty()) - on_success = Authentication::CredentialsCheckResult::NeedSecondFactor; - else if (!checkOneTimePassword(one_time_password, *otp_secret)) - return Authentication::CredentialsCheckResult::Fail; - } - switch (authentication_method.getType()) { case AuthenticationType::NO_PASSWORD: { - return on_success; // N.B. even if the password is not empty! + return true; // N.B. even if the password is not empty! } case AuthenticationType::PLAINTEXT_PASSWORD: { const auto & password_plaintext = authentication_method.getPasswordHashBinary(); - return constantTimeEquals(Util::stringToDigest(password), password_plaintext) ? on_success : Authentication::CredentialsCheckResult::Fail; + return constantTimeEquals(Util::stringToDigest(password), password_plaintext); } case AuthenticationType::SHA256_PASSWORD: { const auto & password_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); String salted_password = String(password).append(salt); - return Util::encodeSHA256(salted_password) == password_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeSHA256(salted_password) == password_sha256; } case AuthenticationType::SCRAM_SHA256_PASSWORD: { const auto & password_scram_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); auto digest = Util::encodeScramSHA256(password, salt); - return digest == password_scram_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return digest == password_scram_sha256; } case AuthenticationType::DOUBLE_SHA1_PASSWORD: { const auto & password_double_sha1 = authentication_method.getPasswordHashBinary(); - return Util::encodeDoubleSHA1(password) == password_double_sha1 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeDoubleSHA1(password) == password_double_sha1; } case AuthenticationType::LDAP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; - return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), *basic_credentials) ? - on_success : Authentication::CredentialsCheckResult::Fail; + return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), basic_credentials); } case AuthenticationType::BCRYPT_PASSWORD: { const auto & password_bcrypt = authentication_method.getPasswordHashBinary(); - return Util::checkPasswordBcrypt(password, password_bcrypt) ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::checkPasswordBcrypt(password, password_bcrypt); } case AuthenticationType::HTTP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; if (authentication_method.getHTTPAuthenticationScheme() == HTTPAuthenticationScheme::BASIC) { return external_authenticators.checkHTTPBasicCredentials( - authentication_method.getHTTPAuthenticationServerName(), *basic_credentials, client_info, settings) ? - on_success : Authentication::CredentialsCheckResult::Fail; + authentication_method.getHTTPAuthenticationServerName(), basic_credentials, client_info, settings); } break; } @@ -264,7 +244,38 @@ namespace break; } - return Authentication::CredentialsCheckResult::Fail; + return false; + } + + Authentication::CredentialsCheckResult checkBasicAuthentication( + const BasicCredentials * basic_credentials, + const AuthenticationData & authentication_method, + const ExternalAuthenticators & external_authenticators, + const ClientInfo & client_info, + SettingsChanges & settings) + { + const auto & otp_secret = authentication_method.getOneTimePassword(); + auto [password, one_time_password] = splitOneTimePasswordAndPassword(basic_credentials->getPassword(), authentication_method); + + const auto auth_type = authentication_method.getType(); + if (otp_secret && (auth_type == AuthenticationType::LDAP || auth_type == AuthenticationType::HTTP)) + /// One-time password supported only with password-based authentication methods. + return Authentication::CredentialsCheckResult::Fail; + + /// Decided before the primary credential is looked at, so that the response (and its timing) is the same + /// for a right and a wrong password: otherwise an attacker could confirm a guessed password without the code. + if (otp_secret && one_time_password.empty()) + return Authentication::CredentialsCheckResult::NeedSecondFactor; + + const bool primary_ok = checkPrimaryCredential(password, *basic_credentials, authentication_method, external_authenticators, client_info, settings); + if (!otp_secret) + return primary_ok ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; + + /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after + /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. + /// Both factors are evaluated unconditionally, so that the timing does not tell which one failed. + const bool otp_ok = checkOneTimePassword(one_time_password, *otp_secret); + return (primary_ok && otp_ok) ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; } #if USE_SSL diff --git a/src/Access/ContextAccess.cpp b/src/Access/ContextAccess.cpp index 98cd4af879ed..aedfc9fa08a5 100644 --- a/src/Access/ContextAccess.cpp +++ b/src/Access/ContextAccess.cpp @@ -586,6 +586,10 @@ std::shared_ptr ContextAccess::getQuota() const } } + /// Outside the branch above on purpose: `QuotaCache` refreshes the quota set in place, so an already + /// memoised object has to be re-checked on every call. + enabled_quota->checkClientKeySupplied(); + return enabled_quota; } diff --git a/src/Access/EnabledQuota.cpp b/src/Access/EnabledQuota.cpp index 92518d5506ea..c5333af77e4d 100644 --- a/src/Access/EnabledQuota.cpp +++ b/src/Access/EnabledQuota.cpp @@ -14,6 +14,7 @@ namespace DB namespace ErrorCodes { extern const int QUOTA_EXCEEDED; + extern const int QUOTA_REQUIRES_CLIENT_KEY; } @@ -307,6 +308,18 @@ void EnabledQuota::checkExceeded(QuotaType quota_type) const } +void EnabledQuota::checkClientKeySupplied() const +{ + if (!requires_client_key) + return; + throw Exception( + ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, + "Quota {} (for user {}) requires a client supplied key.", + intervals.load()->quota_name, + getUserName()); +} + + void EnabledQuota::reset(QuotaType quota_type) const { const auto loaded = intervals.load(); diff --git a/src/Access/EnabledQuota.h b/src/Access/EnabledQuota.h index 2513bed9622c..587c97f108f4 100644 --- a/src/Access/EnabledQuota.h +++ b/src/Access/EnabledQuota.h @@ -52,6 +52,10 @@ class EnabledQuota : public boost::noncopyable void checkExceeded() const; void checkExceeded(QuotaType quota_type) const; + /// Throws if a governing quota is keyed by `client_key` and this context supplied none. Authentication + /// is metered before a client key can exist, so only the query path calls this. + void checkClientKeySupplied() const; + void reset(QuotaType quota_type) const; /// Returns the information about quota consumption. @@ -97,6 +101,9 @@ class EnabledQuota : public boost::noncopyable const Params params; boost::atomic_shared_ptr intervals; /// atomically changed by QuotaUsageManager std::atomic empty = false; /// Use a separate flag to avoid loading intervals, which is way more expensive than an atomic bool + /// The chosen quota is keyed by `client_key` and this context supplied none, so it cannot be metered. + /// Refreshed in place by `QuotaCache` together with `intervals`; see `checkClientKeySupplied`. + std::atomic requires_client_key = false; }; } diff --git a/src/Access/HTTPAuthClient.h b/src/Access/HTTPAuthClient.h index 27e0d5dc507b..2768639cb709 100644 --- a/src/Access/HTTPAuthClient.h +++ b/src/Access/HTTPAuthClient.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -12,6 +13,11 @@ namespace DB { +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + struct HTTPAuthClientParams { Poco::URI uri; @@ -95,8 +101,13 @@ class HTTPBasicAuthClient : private HTTPAuthClient for (const auto & k : headers) { - if (this->getForwardHeaders().contains(k.first)) - request.add(k.first, k.second); + if (!this->getForwardHeaders().contains(k.first)) + continue; + /// Poco writes header values verbatim, so a line break would let the value inject extra headers + /// (e.g. an `Authorization` placed before ours) into the request to the authentication server. + if (k.second.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Forwarded HTTP header \"{}\" contains CR, LF or NUL", k.first); + request.add(k.first, k.second); } Poco::Net::HTTPBasicCredentials basic_credentials{user_name, password}; diff --git a/src/Access/IAccessStorage.cpp b/src/Access/IAccessStorage.cpp index 2beb46691b4b..7c2ed52f88e7 100644 --- a/src/Access/IAccessStorage.cpp +++ b/src/Access/IAccessStorage.cpp @@ -598,6 +598,8 @@ std::optional IAccessStorage::authenticateImpl( "check allow_no_password and allow_plaintext_password settings in the server configuration"); } + /// Reported for a missing code before the password is checked (see `checkBasicAuthentication`), + /// so this error does not confirm the password. if (need_second_factor) throw Exception(ErrorCodes::REQUIRED_SECOND_FACTOR, "Authentication requires second factor"); throw Exception(ErrorCodes::WRONG_PASSWORD, "Invalid credentials"); diff --git a/src/Access/QuotaCache.cpp b/src/Access/QuotaCache.cpp index d5a019639a2f..338b09a34e73 100644 --- a/src/Access/QuotaCache.cpp +++ b/src/Access/QuotaCache.cpp @@ -26,7 +26,6 @@ namespace DB { namespace ErrorCodes { - extern const int QUOTA_REQUIRES_CLIENT_KEY; extern const int LOGICAL_ERROR; } @@ -40,7 +39,7 @@ void QuotaCache::QuotaInfo::setQuota(const QuotaPtr & quota_, const UUID & quota } -String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool throw_if_client_key_empty) const +String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled) const { const auto & params = enabled.params; switch (quota->key_type) @@ -65,14 +64,9 @@ String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool th { if (!params.client_key.empty()) return params.client_key; - - if (throw_if_client_key_empty) - throw Exception( - ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, - "Quota {} (for user {}) requires a client supplied key.", - quota->getName(), - params.user_name); - return ""; // Authentication quota has no client key at time of authentication. + /// An empty key is a legitimate state: at the time of authentication no client key exists yet. + /// The requirement is published as `EnabledQuota::requires_client_key` and enforced on the query path. + return ""; } case QuotaKeyType::CLIENT_KEY_OR_USER_NAME: { @@ -187,8 +181,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( const boost::container::flat_set & enabled_roles, const std::shared_ptr & client_address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty) + const String & client_key) { std::lock_guard lock{mutex}; ensureAllQuotasRead(); @@ -211,7 +204,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( auto res = std::shared_ptr(new EnabledQuota(params)); enabled_quotas.emplace(std::move(params), res); - chooseQuotaToConsumeFor(*res, throw_if_client_key_empty); + chooseQuotaToConsumeFor(*res); return res; } @@ -294,7 +287,7 @@ void QuotaCache::chooseQuotaToConsume() i = enabled_quotas.erase(i); else { - chooseQuotaToConsumeFor(*elem, true); + chooseQuotaToConsumeFor(*elem); ++i; } } @@ -308,16 +301,18 @@ void QuotaCache::chooseQuotaToConsume() LOG_DEBUG(getLogger("QuotaCache"), "Re-chose quotas for {} enabled set(s) over {} quotas in {} ms", enabled_quotas.size(), all_quotas.size(), elapsed_ms); } -void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_client_key_empty) +void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled) { /// `mutex` is already locked. boost::shared_ptr intervals; + bool requires_client_key = false; for (auto & info : all_quotas | boost::adaptors::map_values) { if (info.roles->match(enabled.params.user_id, enabled.params.enabled_roles)) { - String key = info.calculateKey(enabled, throw_if_client_key_empty); + String key = info.calculateKey(enabled); intervals = info.getOrBuildIntervals(key); + requires_client_key = (info.quota->key_type == QuotaKeyType::CLIENT_KEY) && enabled.params.client_key.empty(); break; } } @@ -332,6 +327,7 @@ void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_c enabled.intervals.store(intervals); enabled.empty = false; } + enabled.requires_client_key = requires_client_key; } diff --git a/src/Access/QuotaCache.h b/src/Access/QuotaCache.h index 4c4cd955bac1..29df5ebe50b6 100644 --- a/src/Access/QuotaCache.h +++ b/src/Access/QuotaCache.h @@ -28,8 +28,7 @@ class QuotaCache const boost::container::flat_set & enabled_roles, const std::shared_ptr & address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty); + const String & client_key); std::vector getAllQuotasUsage() const; @@ -42,7 +41,7 @@ class QuotaCache QuotaInfo(const QuotaPtr & quota_, const UUID & quota_id_) { setQuota(quota_, quota_id_); } void setQuota(const QuotaPtr & quota_, const UUID & quota_id_); - String calculateKey(const EnabledQuota & enabled_quota, bool throw_if_client_key_empty) const; + String calculateKey(const EnabledQuota & enabled_quota) const; boost::shared_ptr getOrBuildIntervals(const String & key); boost::shared_ptr rebuildIntervals(const String & key, std::chrono::system_clock::time_point current_time); void rebuildAllIntervals(); @@ -58,7 +57,7 @@ class QuotaCache void quotaRemoved(const UUID & quota_id); void chooseQuotaToConsume(); void chooseQuotaToConsumeIfNeeded(); - void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota, bool throw_if_client_key_empty); + void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota); const AccessControl & access_control; mutable std::mutex mutex; diff --git a/src/Access/SettingsConstraints.cpp b/src/Access/SettingsConstraints.cpp index bb47d78c603f..dcf8d39879f0 100644 --- a/src/Access/SettingsConstraints.cpp +++ b/src/Access/SettingsConstraints.cpp @@ -287,6 +287,18 @@ void SettingsConstraints::clamp(const Settings & current_settings, SettingsChang }); } +void SettingsConstraints::clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const +{ + /// The surviving list is stored on the query node as the settings set explicitly on that node, + /// so a change equal to the current value must stay in the list. + std::erase_if( + changes, + [&](SettingChange & change) -> bool + { + return !checkImpl(current_settings, change, CLAMP_ON_VIOLATION_THROW_ON_INVALID, source, /*ignore_unchanged_settings=*/ true); + }); +} + /// The value a setting holds now. /// /// `Settings` keeps a `merge_tree_`-prefixed name as a custom setting, under the exact name that wrote it. @@ -321,13 +333,13 @@ Field castValueOfSetting(const String & name, const Field & value) } template -bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool throw_on_failure) +bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool ignore_unchanged_settings, bool throw_on_failure) { Field current_value; bool has_current_value = getCurrentValueOfSetting(current_settings, change.name, current_value); /// Setting isn't checked if value has not changed. - if (has_current_value && change.value == current_value) + if (!ignore_unchanged_settings && has_current_value && change.value == current_value) return false; /// Put the value into the type of the setting. This throws when the value does not fit, as @@ -358,7 +370,7 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan /// stores a Bool, the same 1 in a query arrives as a UInt64, and comparing them as they are would /// make a change that keeps the value look like a real one. Field cast_current_value; - if (has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) + if (!ignore_unchanged_settings && has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) return false; return true; @@ -367,14 +379,18 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan bool SettingsConstraints::checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const + SettingSource source, + bool ignore_unchanged_settings) const { std::string_view setting_name = Settings::resolveName(change.name); if (setting_name == "profile") return true; - if (reaction == THROW_ON_VIOLATION) + /// Invalid changes (an unknown or disallowed name, an uncastable value) throw in every mode but `CLAMP_ON_VIOLATION`. + const bool throw_on_invalid_change = reaction != CLAMP_ON_VIOLATION; + + if (throw_on_invalid_change) { try { @@ -396,7 +412,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, return false; Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, ignore_unchanged_settings, /*throw_on_failure=*/ throw_on_invalid_change)) return false; return getChecker(current_settings, setting_name).check(change, new_value, reaction, source); @@ -405,7 +421,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, bool SettingsConstraints::checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const { Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, /*ignore_unchanged_settings=*/ false, reaction == THROW_ON_VIOLATION)) return false; if (isAnyTierRestricted()) @@ -422,9 +438,12 @@ bool SettingsConstraints::Checker::check(SettingChange & change, ReactionOnViolation reaction, SettingSource source) const { + /// Every reaction other than `THROW_ON_VIOLATION` clamps or drops a violating change. + const bool throw_on_violation = reaction == THROW_ON_VIOLATION; + if (!explain.text.empty()) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(explain, code); return false; } @@ -433,7 +452,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto less_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateLess(left, right); try { @@ -447,7 +466,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto equals_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateEquals(left, right); try { @@ -462,7 +481,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (constraint.writability == SettingConstraintWritability::CONST) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} should not be changed", setting_name); return false; } @@ -473,7 +492,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && !max_value.isNull() && less_or_cannot_compare(max_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception( ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "The maximum ({}) value is less than the minimum ({}) value for setting {}", @@ -485,7 +504,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && less_or_cannot_compare(new_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be less than {}", setting_name, applyVisitor(FieldVisitorToString(), min_value)); @@ -495,7 +514,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!max_value.isNull() && less_or_cannot_compare(max_value, new_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be greater than {}", setting_name, applyVisitor(FieldVisitorToString(), max_value)); @@ -513,7 +532,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!getSettingSourceRestrictions(setting_name).isSourceAllowed(source)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::READONLY, "Setting {} is not allowed to be set by {}", setting_name, toString(source)); return false; } diff --git a/src/Access/SettingsConstraints.h b/src/Access/SettingsConstraints.h index dc87368a62e2..2231cda9cfd6 100644 --- a/src/Access/SettingsConstraints.h +++ b/src/Access/SettingsConstraints.h @@ -95,8 +95,13 @@ class SettingsConstraints void check(const MergeTreeSettings & current_settings, const SettingsChanges & changes) const; /// Checks whether `change` violates these and clamps the `change` if so. + /// A change equal to the current value is dropped from `changes`. void clamp(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + /// Same as `clamp`, but an unknown or disallowed setting name and an uncastable value throw, as in `check`, + /// and a change equal to the current value is kept in `changes`. + void clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + friend bool operator ==(const SettingsConstraints & left, const SettingsConstraints & right); friend bool operator !=(const SettingsConstraints & left, const SettingsConstraints & right) { return !(left == right); } @@ -104,8 +109,12 @@ class SettingsConstraints private: enum ReactionOnViolation { + /// Any violation, an unknown name or an uncastable value throws. THROW_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value is dropped. CLAMP_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value throws. + CLAMP_ON_VIOLATION_THROW_ON_INVALID, }; struct Constraint @@ -165,7 +174,8 @@ class SettingsConstraints bool checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const; + SettingSource source, + bool ignore_unchanged_settings = false) const; bool checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const; diff --git a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp index b1bf4f7edb96..7df726a74610 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp @@ -24,6 +24,8 @@ #include +#include + #include constexpr size_t AGGREGATE_FUNCTION_GROUP_ARRAY_MAX_ELEMENT_SIZE = 0xFFFFFF; @@ -90,6 +92,17 @@ struct GroupArraySamplerData size_t total_values = 0; pcg32_fast rng; + /// The counter may come from a deserialized state, so it can be arbitrarily large, + /// and wrapping it around would make `genRandom` divide by zero. + void addTotalValues(UInt64 count) + { + UInt64 new_total_values = 0; + if (common::addOverflow(static_cast(total_values), count, new_total_values)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The number of values in groupArraySample state overflows: {} + {}", total_values, count); + total_values = new_total_values; + } + UInt64 genRandom(size_t lim) { chassert(lim != 0); @@ -160,7 +173,7 @@ class GroupArrayNumericImpl final void insertWithSampler(Data & a, const T & v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v, arena); else @@ -183,7 +196,10 @@ class GroupArrayNumericImpl final const auto & row_value = assert_cast &>(*columns[0]).getData()[row_num]; auto & cur_elems = this->data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -275,8 +291,8 @@ class GroupArrayNumericImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); @@ -525,7 +541,7 @@ class GroupArrayGeneralImpl final void insertWithSampler(Data & a, const Node * v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v->clone(arena), arena); else @@ -547,7 +563,10 @@ class GroupArrayGeneralImpl final { auto & cur_elems = data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -642,8 +661,8 @@ class GroupArrayGeneralImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp index 8c61d13923ca..610937b52f5f 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp @@ -61,8 +61,14 @@ void forEachSecretArgumentNode( continue; } + if (const auto masked = secret_arguments.masked_arguments.find(n); masked != secret_arguments.masked_arguments.end()) + { + on_secret(n, masked->second ? secretValueSlot(arguments[n]) : arguments[n]); + continue; + } + const bool in_span = secret_arguments.start <= n && n < secret_arguments.start + secret_arguments.count; - if (in_span || secret_arguments.masked_arguments.contains(n) || secret_arguments.replaced_arguments.contains(n)) + if (in_span || secret_arguments.replaced_arguments.contains(n)) on_secret(n, secretValueSlot(arguments[n])); } } diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h index 6afdd5d3a952..ecd7322afc29 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h @@ -122,7 +122,8 @@ using FunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeN using TableFunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeNodeImpl; /// Visits the secret value slots selected by a finder result in a resolved argument list, for the -/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members and the arguments +/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members, the individually +/// masked arguments (whole, unless masked as a named `key = value`) and the arguments /// with a partial replacement (for a `key = value` argument, its value; a tree dump cannot represent /// partial masking, so the whole value is masked: fail closed), and the values of the nested secret /// maps (`headers(..)` / `extra_credentials(..)`; a malformed child is visited whole). The callback diff --git a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp index 44c9ee3df51b..b95cc0fd9410 100644 --- a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp +++ b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp @@ -550,6 +550,10 @@ std::tuple getTypedNodesForOptimizati if (!storage->supportsOptimizationToSubcolumns() || storage->isVirtualColumn(column.name, storage_snapshot->metadata)) return {}; + /// Without buckets the key subcolumn `m.key_` reads the whole Map, so `m['key']` is not rewritten to it. + if (function_node->getFunctionName() == "arrayElement" && isMap(column.type) && !storage->hasBucketedMapSerialization()) + return {}; + auto column_in_table = storage_snapshot->tryGetColumn(GetColumnsOptions(GetColumnsOptions::All).withSubcolumns(), column.name); if (!column_in_table || !column_in_table->type->equals(*column.type)) return {}; diff --git a/src/Analyzer/QueryTreeBuilder.cpp b/src/Analyzer/QueryTreeBuilder.cpp index 285edf278e72..16cab878c838 100644 --- a/src/Analyzer/QueryTreeBuilder.cpp +++ b/src/Analyzer/QueryTreeBuilder.cpp @@ -302,22 +302,28 @@ QueryTreeNodePtr QueryTreeBuilder::buildSelectExpression( set_query.changes.removeSetting("offset"); } - /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) used to be applied to - /// the per-node context unchecked, letting a user override `readonly`, `CONST` and `MIN`/`MAX` - /// constraints - e.g. `additional_table_filters`, which the Planner reads from this context. - /// Clamp it instead of throwing, as done for other settings crossing execution contexts - /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are - /// dropped, out-of-bounds values are clamped, so a view whose inner clause violates the - /// reader's constraints keeps working. A top-level clause still throws - /// (`applySettingsFromQuery`). Clamp a copy: the `QueryNode` keeps the clause as written, so - /// the tree's AST and hash are unchanged, and every node executing the subquery clamps it - /// against its own constraints. `SETTINGS name = DEFAULT` stays ignored here - see #115415. + /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) is clamped to the session's + /// settings constraints, as done for other settings crossing execution contexts + /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are dropped, + /// out-of-bounds values are clamped, so a view whose inner clause violates the reader's constraints + /// keeps working. A top-level clause still throws (`applySettingsFromQuery`). An unknown name or an + /// uncastable value throws as for a top-level clause, on every server that executes the query. The + /// node records the effective `changes`: the ones that survive, with their clamped values and the + /// literals as written, so `toAST`, the tree hash, the `Planner` and the shards receiving the + /// subquery see what was applied. `SETTINGS name = DEFAULT` stays ignored here - see #115415. if (!set_query.changes.empty()) { - auto checked_changes = set_query.changes; - updated_context->clampToSettingsConstraints(checked_changes, SettingSource::QUERY); - updated_context->applySettingsChanges(checked_changes); - settings_changes = set_query.changes; + /// One change at a time, so that each is clamped against the context as the preceding changes + /// left it. Clamping the whole clause as a batch checks every change against the context as it + /// was before the clause - so `SETTINGS use_query_cache = 1, use_query_cache = 0` could resolve + /// differently from the last-wins reading the clause has everywhere else. + for (const auto & change : set_query.changes) + { + SettingsChanges single_change{change}; + updated_context->clampToSettingsConstraintsRejectingInvalidChanges(single_change, SettingSource::QUERY); + updated_context->applySettingsChanges(single_change); + settings_changes.insert(settings_changes.end(), single_change.begin(), single_change.end()); + } } } diff --git a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp index e5ec3cc7c4e1..56109118b128 100644 --- a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp +++ b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp @@ -114,7 +114,7 @@ void QueryAnalyzer::evaluateScalarSubqueryIfNeeded(QueryTreeNodePtr & node, Iden scalar_block = scalars_cache.at(node_with_hash); } - else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasScalar(str_hash)) + else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasComputedScalar(str_hash)) { scalar_block = context->getQueryContext()->getScalar(str_hash); scalar_subquery_to_scalar_value_global.emplace(node_with_hash, scalar_block); diff --git a/src/Backups/BackupIO_AzureBlobStorage.cpp b/src/Backups/BackupIO_AzureBlobStorage.cpp index eb2126f1dd9f..cd08f6e339e3 100644 --- a/src/Backups/BackupIO_AzureBlobStorage.cpp +++ b/src/Backups/BackupIO_AzureBlobStorage.cpp @@ -2,6 +2,7 @@ #include #if USE_AZURE_BLOB_STORAGE +#include #include #include #include @@ -29,6 +30,17 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +namespace +{ + /// An Azure disk configured with `connection_string` is described by that whole string. + String maskedDescription(const DataSourceDescription & description) + { + String result = description.description; + maskAzureConnectionStringSecrets(result); + return result; + } +} + BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const AzureBlobStorage::ConnectionParams & connection_params_, const String & blob_path_, @@ -37,7 +49,7 @@ BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const WriteSettings & write_settings_, const ContextPtr & context_) : BackupReaderDefault(read_settings_, write_settings_, getLogger("BackupReaderAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -85,7 +97,7 @@ void BackupReaderAzureBlobStorage::copyFileToDisk(const String & path_in_backup, DiskPtr destination_disk, const String & destination_path, WriteMode write_mode) { auto destination_data_source_description = destination_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, destination_data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, maskedDescription(destination_data_source_description)); if (destination_data_source_description.object_storage_type == ObjectStorageType::Azure && destination_data_source_description.is_encrypted == encrypted_in_backup) { @@ -132,7 +144,7 @@ BackupWriterAzureBlobStorage::BackupWriterAzureBlobStorage( const ContextPtr & context_, bool attempt_to_create_container) : BackupWriterDefault(read_settings_, write_settings_, getLogger("BackupWriterAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -162,7 +174,7 @@ void BackupWriterAzureBlobStorage::copyFileFromDisk( { /// Use the native copy as a more optimal way to copy a file from AzureBlobStorage to AzureBlobStorage if it's possible. auto source_data_source_description = src_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", source_data_source_description.description, data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", maskedDescription(source_data_source_description), data_source_description.description); if (source_data_source_description.object_storage_type == ObjectStorageType::Azure && source_data_source_description.is_encrypted == copy_encrypted) { diff --git a/src/Backups/BackupMetadataFinder.cpp b/src/Backups/BackupMetadataFinder.cpp index 46115481a708..4b3534b9b24b 100644 --- a/src/Backups/BackupMetadataFinder.cpp +++ b/src/Backups/BackupMetadataFinder.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -287,6 +288,16 @@ void BackupMetadataFinder::findTableInBackupImpl( ParserCreateQuery create_parser; ASTPtr create_table_query = parseQuery(create_parser, create_query_str, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + /// `BACKUP` writes the full definition, without `AS` (see `cleanupObjectDefinitionFromTemporaryFlags`). A definition that + /// inherits its engine with `AS` would let the access check of the restore see no engine, so it is rejected. + if (const auto & create = create_table_query->as(); !create.as_table.empty()) + throw Exception( + ErrorCodes::CANNOT_RESTORE_TABLE, + "The definition of {} in the backup uses AS {}, which BACKUP never writes", + tableNameWithTypeToString(table_name_in_backup.database, table_name_in_backup.table, false), + backQuoteIfNeed(create.as_table)); + applyCustomStoragePolicy(create_table_query); renameDatabaseAndTableNameInCreateQuery(create_table_query, renaming_map, context->getGlobalContext()); String create_table_query_str = create_table_query->formatWithSecretsOneLine(); diff --git a/src/Backups/RestorerFromBackup.cpp b/src/Backups/RestorerFromBackup.cpp index b1cfe0451a94..5c47fd9cea18 100644 --- a/src/Backups/RestorerFromBackup.cpp +++ b/src/Backups/RestorerFromBackup.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ namespace Setting extern const SettingsUInt64 backup_restore_keeper_max_retries; extern const SettingsSeconds lock_acquire_timeout; extern const SettingsBool restore_replicated_merge_tree_to_shared_merge_tree; + extern const SettingsBool restore_replace_external_engines_to_null; } namespace ErrorCodes @@ -276,6 +278,7 @@ void RestorerFromBackup::loadSystemAccessTables() void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const { AccessRightsElements required_access; + AccessRights required_access_rights; { std::lock_guard lock{mutex}; @@ -310,7 +313,17 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const continue; } - if (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE) + const ASTCreateQuery & create = table_info.create_table_query->as(); + const bool is_temporary = (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE); + + /// The definition comes from the backup, and the table is created by an internal query that checks + /// nothing, so settings that send the data elsewhere are authorized here, as for `CREATE`. + /// An external engine replaced by `Null` sends nothing, but temporary tables keep their engine. + if (restore_settings.create_table != RestoreTableCreationMode::kMustExist + && (is_temporary || !context->getSettingsRef()[Setting::restore_replace_external_engines_to_null])) + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + + if (is_temporary) { if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) required_access.emplace_back(AccessType::CREATE_TEMPORARY_TABLE); @@ -318,7 +331,6 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const } AccessFlags flags; - const ASTCreateQuery & create = table_info.create_table_query->as(); if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) { @@ -346,15 +358,12 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const required_access.emplace_back(flags, table_name.database, table_name.table); } + required_access_rights = AccessRights{required_access}; + /// Partial revokes in restored grants must not remove the rights required to restore other objects. if (access_restorer) - insertAtEnd(required_access, access_restorer->getRequiredAccess()); + required_access_rights.makeUnion(access_restorer->getRequiredAccess()); } - /// We convert to AccessRights to check if we have the rights contained in our current access. - /// This handles the situation when restoring partial revoked grants: - /// GRANT SELECT ON *.* - /// REVOKE SELECT FROM systems.* - const auto & required_access_rights = AccessRights{required_access}; const auto & current_user_access_rights = context->getAccess()->getAccessRightsWithImplicit(); if (current_user_access_rights->contains(required_access_rights)) return; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 88dcaa1fa6ab..469b3b3ad16f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -359,6 +359,10 @@ if (USE_PARQUET) add_object_library(clickhouse_processors_formats_impl_parquet Processors/Formats/Impl/Parquet) endif() +if (USE_ORC) + add_object_library(clickhouse_processors_formats_impl_orc Processors/Formats/Impl/ORC) +endif() + if (TARGET ch_contrib::nuraft) add_object_library(clickhouse_coordination Coordination) endif() @@ -642,11 +646,6 @@ endif() target_link_libraries (clickhouse_common_io PUBLIC ch_contrib::fast_float) -if (USE_ORC) - target_link_libraries(dbms PUBLIC ${ORC_LIBRARIES}) - target_include_directories(dbms SYSTEM BEFORE PUBLIC ${ORC_INCLUDE_DIR} "${PROJECT_BINARY_DIR}/contrib/orc/c++/include") -endif () - if (TARGET ch_contrib::rocksdb) target_link_libraries(dbms PUBLIC ch_contrib::rocksdb) endif() @@ -773,6 +772,10 @@ if (ENABLE_TESTS) clickhouse_common_config clickhouse_common_zookeeper) + if (TARGET ch_contrib::brotli) + target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::brotli) + endif() + if (TARGET ch_contrib::simdjson) target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::simdjson) endif() diff --git a/src/Client/ClientBase.cpp b/src/Client/ClientBase.cpp index dfa4234f2042..aa2e00344b73 100644 --- a/src/Client/ClientBase.cpp +++ b/src/Client/ClientBase.cpp @@ -3582,13 +3582,13 @@ void ClientBase::runInteractive() #if USE_REPLXX - replxx::Replxx::highlighter_callback_with_pos_t highlight_callback{}; + ReplxxLineReader::Highlighter highlight_callback{}; if (getClientConfiguration().getBool("highlight", true)) { - highlight_callback = [this](const String & query, std::vector & colors, int pos) + highlight_callback = [this](const String & query, std::vector & colors, int pos, bool & last_is_delimiter) { - highlight(query, colors, *client_context, pos); + highlight(query, colors, *client_context, pos, &last_is_delimiter); }; } diff --git a/src/Client/ClientBaseHelpers.cpp b/src/Client/ClientBaseHelpers.cpp index 3955d1d8edf2..28e01896beb4 100644 --- a/src/Client/ClientBaseHelpers.cpp +++ b/src/Client/ClientBaseHelpers.cpp @@ -155,7 +155,7 @@ static size_t countCodePointsWithSeqLength(const String & query, const char * en return code_points; } -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position) +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter) { using namespace replxx; @@ -512,14 +512,16 @@ void highlight(const String & query, std::vector & colors } /// This is a callback for the client/local app to better find query end. Note: this is a kludge, remove it. + if (!last_is_delimiter) + return; if (last_token.type == TokenType::Semicolon || last_token.type == TokenType::VerticalDelimiter || query.ends_with(';') || query.ends_with("\\G")) /// This is for raw data in INSERT queries, which is not necessarily tokenized. { - ReplxxLineReader::setLastIsDelimiter(true); + *last_is_delimiter = true; } else if (last_token.type != TokenType::Whitespace) { - ReplxxLineReader::setLastIsDelimiter(false); + *last_is_delimiter = false; } } @@ -528,7 +530,7 @@ String highlighted(const String & query, const Context & context) const size_t num_code_points = countCodePointsWithSeqLength(query, query.data() + query.size()); std::vector colors(num_code_points, replxx::Replxx::Color::DEFAULT); - highlight(query, colors, context, 0); + highlight(query, colors, context, 0, nullptr); String res; size_t query_size = query.size(); diff --git a/src/Client/ClientBaseHelpers.h b/src/Client/ClientBaseHelpers.h index 4e41e605f3f7..ad02976550df 100644 --- a/src/Client/ClientBaseHelpers.h +++ b/src/Client/ClientBaseHelpers.h @@ -24,7 +24,9 @@ std::string getChineseZodiac(); bool isCloudEndpoint(const std::string & host); #if USE_REPLXX -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position); +/// If `last_is_delimiter` is not null, it is set to whether the query ends with a delimiter (and left +/// intact if the query ends with whitespace). +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter); String highlighted(const String & query, const Context & context); #endif diff --git a/src/Client/ReplxxLineReader.cpp b/src/Client/ReplxxLineReader.cpp index 14842dbfd77e..c909f14beb44 100644 --- a/src/Client/ReplxxLineReader.cpp +++ b/src/Client/ReplxxLineReader.cpp @@ -286,12 +286,6 @@ void convertHistoryFile(const std::string & path, replxx::Replxx & rx) namespace DB { -static bool replxx_last_is_delimiter = false; -void ReplxxLineReader::setLastIsDelimiter(bool flag) -{ - replxx_last_is_delimiter = flag; -} - ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) : LineReader ( @@ -360,7 +354,12 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) rx.set_indent_multiline(false); if (highlighter) - rx.set_highlighter_callback(highlighter); + { + rx.set_highlighter_callback([this](const String & query, std::vector & colors, int cursor_position) + { + highlighter(query, colors, cursor_position, last_is_delimiter); + }); + } /// By default C-p/C-n bound to COMPLETE_NEXT/COMPLETE_PREV, /// bind C-p/C-n to history-previous/history-next like readline. @@ -376,9 +375,9 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) { /// If we allow multiline and there is already something in the input, start a newline. /// NOTE: Lexer is only available if we use highlighter. - if (highlighter && multiline && !replxx_last_is_delimiter) + if (highlighter && multiline && !last_is_delimiter) return rx.invoke(Replxx::ACTION::NEW_LINE, code); - replxx_last_is_delimiter = false; + last_is_delimiter = false; return rx.invoke(Replxx::ACTION::COMMIT_LINE, code); }; /// bind C-j to ENTER action. diff --git a/src/Client/ReplxxLineReader.h b/src/Client/ReplxxLineReader.h index cdaa5cab6be1..0dae383f8d53 100644 --- a/src/Client/ReplxxLineReader.h +++ b/src/Client/ReplxxLineReader.h @@ -12,6 +12,11 @@ namespace DB class ReplxxLineReader : public LineReader { public: + /// The highlighter callback of replxx, which also reports whether the last token of the + /// query is a delimiter: it sets `last_is_delimiter` to true or false, or leaves it intact + /// when this cannot be determined (e.g. the query ends with whitespace). + using Highlighter = std::function & colors, int cursor_position, bool & last_is_delimiter)>; + struct Options { Suggest & suggest; @@ -24,7 +29,7 @@ class ReplxxLineReader : public LineReader Patterns extenders; Patterns delimiters; std::span word_break_characters; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; std::istream & input_stream = std::cin; std::ostream & output_stream = std::cout; int in_fd = STDIN_FILENO; @@ -38,10 +43,6 @@ class ReplxxLineReader : public LineReader void enableBracketedPaste() override; void disableBracketedPaste() override; - /// If highlight is on, we will set a flag to denote whether the last token is a delimiter. - /// This is useful to determine the behavior of key when multiline is enabled. - static void setLastIsDelimiter(bool flag); - /// Set text to be prepopulated in the next readLine call void setInitialText(const String & text) override; private: @@ -51,7 +52,13 @@ class ReplxxLineReader : public LineReader void openEditor(bool format_query); replxx::Replxx rx; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; + + /// If highlight is on, the highlighter reports whether the last token is a delimiter. + /// This is used to determine the behavior of key when multiline is enabled. + /// It is a member rather than a global, because several readers can work concurrently + /// in one process (client sessions embedded into the server). + bool last_is_delimiter = false; const char * word_break_characters; diff --git a/src/Columns/ColumnArray.cpp b/src/Columns/ColumnArray.cpp index d572873dca0b..b1bc0921a153 100644 --- a/src/Columns/ColumnArray.cpp +++ b/src/Columns/ColumnArray.cpp @@ -978,17 +978,17 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi memset(&nested_filt[offsetAt(i)], 0, sizeAt(i)); } - auto res = ColumnArray::create(data->cloneEmpty()); - ssize_t nested_result_size_hint = 0; if (result_size_hint < 0) nested_result_size_hint = result_size_hint; else if (result_size_hint && result_size_hint < 1000000000 && data->size() < 1000000000) /// Avoid overflow. nested_result_size_hint = result_size_hint * data->size() / size; - res->data = data->filter(nested_filt, nested_result_size_hint); + /// See the comment in `indexImpl` about building the nested result first. + ColumnPtr res_data = data->filter(nested_filt, nested_result_size_hint); - Offsets & res_offsets = res->getOffsets(); + auto res_offsets_column = ColumnOffsets::create(); + Offsets & res_offsets = res_offsets_column->getData(); if (result_size_hint) res_offsets.reserve_exact(result_size_hint > 0 ? result_size_hint : size); @@ -1002,7 +1002,7 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi } } - return res; + return ColumnArray::create(res_data, std::move(res_offsets_column)); } ColumnPtr ColumnArray::filterNullable(const Filter & filt, ssize_t result_size_hint) const @@ -1236,10 +1236,8 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit PaddedPODArray & nested_indexes = nested_indexes_column->getData(); nested_indexes.reserve_exact(getOffsets().back()); - auto res = ColumnArray::create(data->cloneEmpty()); - - Offsets & res_offsets = res->getOffsets(); - res_offsets.resize_exact(limit); + auto res_offsets_column = ColumnOffsets::create(limit); + Offsets & res_offsets = res_offsets_column->getData(); size_t current_offset = 0; for (size_t i = 0; i < limit; ++i) @@ -1250,10 +1248,10 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit res_offsets[i] = current_offset; } - if (current_offset != 0) - res->data = data->index(*nested_indexes_column, current_offset); - - return res; + /// Build the nested result first: an empty clone of `data` copies its whole nested structure, which for + /// `Dynamic` is as deep as the data, and every level of this recursion would hold one. + ColumnPtr res_data = current_offset != 0 ? data->index(*nested_indexes_column, current_offset) : data->cloneEmpty(); + return ColumnArray::create(res_data, std::move(res_offsets_column)); } INSTANTIATE_INDEX_IMPL(ColumnArray) diff --git a/src/Columns/ColumnDynamic.cpp b/src/Columns/ColumnDynamic.cpp index 59ed075737df..446f5c38042e 100644 --- a/src/Columns/ColumnDynamic.cpp +++ b/src/Columns/ColumnDynamic.cpp @@ -314,6 +314,8 @@ void ColumnDynamic::get(size_t n, Field & res) const void ColumnDynamic::getValueNameImpl(WriteBufferFromOwnString & name_buf, size_t n, const Options & options) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); /// Check if value is not in shared variant. if (variant_col.globalDiscriminatorAt(n) != getSharedVariantDiscriminator()) @@ -338,6 +340,8 @@ void ColumnDynamic::insertFrom(const IColumn & src_, size_t n) void ColumnDynamic::doInsertFrom(const IColumn & src_, size_t n) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); /// Same variants: copy the Variant column directly. Skip this fast path when the source has values in @@ -417,6 +421,8 @@ void ColumnDynamic::insertRangeFrom(const IColumn & src_, size_t start, size_t l void ColumnDynamic::doInsertRangeFrom(const IColumn & src_, size_t start, size_t length) #endif { + checkStackSize(); + if (start + length > src_.size()) throw Exception(ErrorCodes::PARAMETER_OUT_OF_BOUND, "Parameter out of bound in ColumnDynamic::insertRangeFrom method. " "[start({}) + length({}) > src.size()({})]", start, length, src_.size()); @@ -649,6 +655,8 @@ void ColumnDynamic::insertManyFrom(const IColumn & src_, size_t position, size_t void ColumnDynamic::doInsertManyFrom(const IColumn & src_, size_t position, size_t length) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); auto & variant_col = getVariantColumn(); @@ -862,6 +870,8 @@ void ColumnDynamic::skipSerializedInArena(ReadBuffer & in) const void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); auto discr = variant_col.globalDiscriminatorAt(n); if (discr == ColumnVariant::NULL_DISCRIMINATOR) @@ -892,6 +902,7 @@ void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const void ColumnDynamic::updateHashWithValueRange(size_t begin, size_t end, SipHash & hash) const { + checkStackSize(); variant_column_ptr->updateHashWithValueRange(begin, end, hash); } @@ -901,6 +912,8 @@ int ColumnDynamic::compareAt(size_t n, size_t m, const IColumn & rhs, int nan_di int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_direction_hint) const #endif { + checkStackSize(); + const auto & left_variant = getVariantColumn(); const auto & right_dynamic = assert_cast(rhs); const auto & right_variant = right_dynamic.getVariantColumn(); @@ -1050,6 +1063,7 @@ void ColumnDynamic::updatePermutation(IColumn::PermutationSortDirection directio ColumnPtr ColumnDynamic::compress(bool force_compression) const { + checkStackSize(); ColumnPtr variant_compressed = variant_column_ptr->compress(force_compression); size_t byte_size = variant_compressed->byteSize(); return ColumnCompressed::create(size(), byte_size, @@ -1061,6 +1075,7 @@ ColumnPtr ColumnDynamic::compress(bool force_compression) const ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const { + checkStackSize(); std::unordered_map variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) variants_checkpoints[name] = variant_column_ptr->getVariantByGlobalDiscriminator(discr).getCheckpoint(); @@ -1069,6 +1084,7 @@ ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const { + checkStackSize(); auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) @@ -1086,6 +1102,7 @@ void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const void ColumnDynamic::rollback(const ColumnCheckpoint & checkpoint) { + checkStackSize(); const auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; /// Manually rollback internals of Variant column @@ -1158,6 +1175,7 @@ void ColumnDynamic::getAllTypeNamesInto(UnorderedSetWithMemoryTracking & void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); if (source_columns.empty()) return; @@ -1181,6 +1199,7 @@ void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t f void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); /// Internal variants of source dynamic columns may differ. /// We want to preallocate memory for all variants we will have after squashing. /// It may happen that the total number of variants in source columns will @@ -1288,6 +1307,8 @@ void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const { + checkStackSize(); + if (const auto * rhs_concrete = typeid_cast(&rhs)) return max_dynamic_types == rhs_concrete->max_dynamic_types && global_max_dynamic_types == rhs_concrete->global_max_dynamic_types && variant_info.variant_name == rhs_concrete->variant_info.variant_name @@ -1297,6 +1318,8 @@ bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_columns, std::optional max_dynamic_subcolumns) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "chooseDynamicStructureForMerge should be called only on empty Dynamic column"); @@ -1431,6 +1454,8 @@ void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_column void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "takeExactDynamicStructureFrom should be called only on empty Dynamic column"); @@ -1453,6 +1478,8 @@ void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) void ColumnDynamic::fixDynamicStructure() { + checkStackSize(); + /// Reduce max_dynamic_types to the number of selected variants, so there will be no possibility /// to extend selected variants on inserts into this column. /// -1 because we don't count shared variant in the limit. @@ -1487,6 +1514,8 @@ ColumnDynamic::StatisticsPtr ColumnDynamic::getOrCalculateStatistics() const void ColumnDynamic::takeOrCalculateStatisticsFrom(const Columns & source_columns) { + checkStackSize(); + /// Assumes dynamic structure has already been set by `takeExactDynamicStructureFrom` or `chooseDynamicStructureForMerge`. Statistics new_statistics; /// Collect total sizes for variants that are not in our structure (candidates for shared variant statistics). diff --git a/src/Columns/ColumnDynamic.h b/src/Columns/ColumnDynamic.h index cac25ec194e5..594512677430 100644 --- a/src/Columns/ColumnDynamic.h +++ b/src/Columns/ColumnDynamic.h @@ -7,6 +7,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,10 @@ namespace DB * When the limit on number of dynamic types is exceeded, all values * with new types are inserted into special shared variant with type String * that contains values and their types in binary format. + * + * Values nest into each other through variants like Array(Dynamic) to a depth that comes + * from the data, not from the declared type, so methods that recurse into the Variant + * column call checkStackSize. */ class ColumnDynamic final : public COWHelper, ColumnDynamic> { @@ -116,12 +121,14 @@ class ColumnDynamic final : public COWHelper, Colum MutableColumnPtr cloneEmpty() const override { + checkStackSize(); /// Keep current dynamic structure return Base::create(variant_column->cloneEmpty(), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumnPtr cloneResized(size_t size) const override { + checkStackSize(); return Base::create(variant_column->cloneResized(size), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } @@ -181,6 +188,7 @@ class ColumnDynamic final : public COWHelper, Colum void popBack(size_t n) override { + checkStackSize(); variant_column_ptr->popBack(n); } @@ -204,42 +212,50 @@ class ColumnDynamic final : public COWHelper, Colum void updateHashFast(SipHash & hash) const override { + checkStackSize(); variant_column_ptr->updateHashFast(hash); } ColumnPtr filter(const Filter & filt, ssize_t result_size_hint) const override { + checkStackSize(); return create(variant_column_ptr->filter(filt, result_size_hint), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } void filter(const Filter & filt) override { + checkStackSize(); variant_column_ptr->filter(filt); statistics.reset(); } void expand(const Filter & mask, bool inverted) override { + checkStackSize(); variant_column_ptr->expand(mask, inverted); } ColumnPtr permute(const Permutation & perm, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->permute(perm, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr index(const IColumn & indexes, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->index(indexes, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr replicate(const Offsets & replicate_offsets) const override { + checkStackSize(); return create(variant_column_ptr->replicate(replicate_offsets), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumns scatter(size_t num_columns, const Selector & selector) const override { + checkStackSize(); MutableColumns scattered_variant_columns = variant_column_ptr->scatter(num_columns, selector); MutableColumns scattered_columns; scattered_columns.reserve(num_columns); @@ -257,6 +273,7 @@ class ColumnDynamic final : public COWHelper, Colum bool hasEqualValues() const override { + checkStackSize(); return variant_column_ptr->hasEqualValues(); } @@ -287,31 +304,37 @@ class ColumnDynamic final : public COWHelper, Colum void shrinkToFit() override { + checkStackSize(); variant_column_ptr->shrinkToFit(); } void ensureOwnership() override { + checkStackSize(); variant_column_ptr->ensureOwnership(); } size_t byteSize() const override { + checkStackSize(); return variant_column_ptr->byteSize(); } size_t byteSizeAt(size_t n) const override { + checkStackSize(); return variant_column_ptr->byteSizeAt(n); } size_t allocatedBytes() const override { + checkStackSize(); return variant_column_ptr->allocatedBytes(); } void protect() override { + checkStackSize(); variant_column_ptr->protect(); } @@ -323,11 +346,17 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumn(MutableColumnCallback callback) override { + /// Callers like IColumn::mutate recurse into the subcolumns through this method. + checkStackSize(); callback(variant_column); variant_column_ptr = assert_cast(variant_column.get()); } - void forEachSubcolumn(ColumnCallback callback) const override { callback(variant_column); } + void forEachSubcolumn(ColumnCallback callback) const override + { + checkStackSize(); + callback(variant_column); + } /// Dynamic columns manage their own variant_info type metadata. /// The default convertToFullIfNeeded recurses into subcolumns and strips LowCardinality @@ -337,6 +366,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumnRecursively(RecursiveMutableColumnCallback callback) override { + checkStackSize(); callback(*variant_column); variant_column_ptr = assert_cast(variant_column.get()); variant_column->forEachMutableSubcolumnRecursively(callback); @@ -344,6 +374,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachSubcolumnRecursively(RecursiveColumnCallback callback) const override { + checkStackSize(); callback(*variant_column); variant_column->forEachSubcolumnRecursively(callback); } @@ -374,11 +405,13 @@ class ColumnDynamic final : public COWHelper, Colum void finalize() override { + checkStackSize(); variant_column_ptr->finalize(); } bool isFinalized() const override { + checkStackSize(); return variant_column_ptr->isFinalized(); } diff --git a/src/Columns/ColumnLowCardinality.cpp b/src/Columns/ColumnLowCardinality.cpp index 9a76fde596b9..a6540dbf60c3 100644 --- a/src/Columns/ColumnLowCardinality.cpp +++ b/src/Columns/ColumnLowCardinality.cpp @@ -234,7 +234,7 @@ void ColumnLowCardinality::insertRangeFromFullColumn(const IColumn & src, size_t idx.insertIndexesRange(*inserted_indexes, 0, length); } -static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) +void ColumnLowCardinality::checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) { auto check_for_type = [&](auto type) { @@ -248,14 +248,14 @@ static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) size_t num_rows = data.size(); if (num_rows == 0) return true; - UInt64 max_position = 0; + ColumnType max_position = 0; for (size_t i = 0; i < num_rows; ++i) - max_position = std::max(max_position, data[i]); + max_position = std::max(max_position, data[i]); - if (max_position >= limit) + if (static_cast(max_position) >= limit) throw Exception(ErrorCodes::INCORRECT_DATA, "Index for LowCardinality is out of range. Dictionary size is {}, " - "but found index with value {}", limit, max_position); + "but found index with value {}", limit, static_cast(max_position)); return true; }; diff --git a/src/Columns/ColumnLowCardinality.h b/src/Columns/ColumnLowCardinality.h index 8538b4cededf..d03921bef1fe 100644 --- a/src/Columns/ColumnLowCardinality.h +++ b/src/Columns/ColumnLowCardinality.h @@ -94,6 +94,7 @@ class ColumnLowCardinality final : public COWHelper +#include #include #include #include @@ -16,6 +17,12 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace FailPoints +{ + extern const char reverse_index_build_index_throw[]; } template @@ -432,17 +439,25 @@ void ReverseIndex::buildIndex() if (!column) throw Exception(ErrorCodes::LOGICAL_ERROR, "ReverseIndex can't build index because index column wasn't set."); + /// Build everything into local variables and publish them only at the end, so that an exception + /// thrown midway (for example, `MEMORY_LIMIT_EXCEEDED` from an allocation in `calcHashes`) does not + /// leave a half-built index behind: a non-null `index` with a null `saved_hash` would make the next + /// `insert` dereference a null pointer. auto size = column->size(); - index = std::make_unique(size); + auto new_index = std::make_unique(size); + fiu_do_on(FailPoints::reverse_index_build_index_throw, + throw Exception(ErrorCodes::MEMORY_LIMIT_EXCEEDED, "Injected failure while building ReverseIndex");); + + ColumnUInt64::MutablePtr new_saved_hash; if constexpr (use_saved_hash) - saved_hash = calcHashes(); + new_saved_hash = calcHashes(); - auto & state = index->getState(); + auto & state = new_index->getState(); state.index_column = column; state.base_index = base_index; if constexpr (use_saved_hash) - state.saved_hash_column = &saved_hash->getData(); + state.saved_hash_column = &new_saved_hash->getData(); using IteratorType = typename IndexMapType::iterator; IteratorType iterator; @@ -452,15 +467,18 @@ void ReverseIndex::buildIndex() { UInt64 hash; if constexpr (use_saved_hash) - hash = saved_hash->getElement(row); + hash = new_saved_hash->getElement(row); else hash = getHash(column->getDataAt(row)); - index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); + new_index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); if (!inserted) throw Exception(ErrorCodes::LOGICAL_ERROR, "Duplicating keys found in ReverseIndex."); } + + index = std::move(new_index); + saved_hash = std::move(new_saved_hash); } template @@ -484,37 +502,58 @@ UInt64 ReverseIndex::insert(std::string_view data) if (!index) buildIndex(); - using IteratorType = typename IndexMapType::iterator; - IteratorType iterator; - bool inserted; - - auto hash = getHash(data); - UInt64 num_rows = size(); - - if constexpr (use_saved_hash) + try { - auto & column_data = saved_hash->getData(); - if (column_data.size() <= num_rows) - column_data.resize(num_rows + 1); - column_data[num_rows] = hash; - } - else - column->insertData(data.data(), data.size()); + using IteratorType = typename IndexMapType::iterator; + IteratorType iterator; + bool inserted = false; - index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + auto hash = getHash(data); + UInt64 num_rows = size(); - if constexpr (use_saved_hash) - { - if (inserted) + if constexpr (use_saved_hash) + { + auto & column_data = saved_hash->getData(); + if (column_data.size() <= num_rows) + column_data.resize(num_rows + 1); + column_data[num_rows] = hash; + } + else column->insertData(data.data(), data.size()); + + index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + + if constexpr (use_saved_hash) + { + if (inserted) + column->insertData(data.data(), data.size()); + } + else + { + if (!inserted) + column->popBack(1); + } + + return iterator->getValue(); } - else + catch (...) { - if (!inserted) - column->popBack(1); - } + /// The hash table may now disagree with the column: for example, the key was already added to the + /// hash table, but `insertData` failed, so the key refers to a row that does not exist. Drop the index, + /// it is rebuilt from the column on the next use. + index = nullptr; + saved_hash = nullptr; - return iterator->getValue(); + if constexpr (std::is_same_v) + { + /// `ColumnString::insertData` appends to `chars` before it grows `offsets`. If the latter failed, the bytes + /// of the row that was never added are still there and would become a prefix of the next inserted value. + const auto & offsets = column->getOffsets(); + column->getChars().resize_assume_reserved(offsets.empty() ? 0 : offsets.back()); + } + + throw; + } } template diff --git a/src/Columns/tests/gtest_reverse_index_exception_safety.cpp b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp new file mode 100644 index 000000000000..f0826e7359d1 --- /dev/null +++ b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace DB::FailPoints +{ + extern const char reverse_index_build_index_throw[]; +} + +using namespace DB; + +/// Mimics what happens during an asynchronous insert flush under memory pressure: the first insert into a +/// `LowCardinality` dictionary throws `MEMORY_LIMIT_EXCEEDED` while the reverse index is being built, the error +/// is handled by the caller, and the same dictionary is reused for the next entry. The index must either be +/// fully built or absent, never a non-null hash table paired with a null saved-hash array. +TEST(ReverseIndex, ExceptionWhileBuildingIndexLeavesNoHalfBuiltIndex) +{ + auto column = ColumnUnique::create(DataTypeString()); + + FailPointInjection::enableFailPoint(FailPoints::reverse_index_build_index_throw); + try + { + column->uniqueInsertData("a", 1); + FAIL() << "Expected an exception from the failpoint"; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::MEMORY_LIMIT_EXCEEDED); + } + FailPointInjection::disableFailPoint(FailPoints::reverse_index_build_index_throw); + + /// Index 0 is the default value (empty string). + EXPECT_EQ(column->size(), 1u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("b", 1), 2u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("", 0), 0u); + EXPECT_EQ(column->size(), 3u); + EXPECT_EQ(column->getDataAt(1), "a"); + EXPECT_EQ(column->getDataAt(2), "b"); +} + +/// The same reuse after a failure inside `insert` itself: the key is already in the hash table and the string bytes are +/// already appended to `chars` when growing `offsets` fails. The dictionary must come back to the state before the +/// insert, so that the next inserted value does not get the failed one as a prefix and lookups stay correct. +TEST(ReverseIndex, ExceptionWhileInsertingDataKeepsDictionaryConsistent) +{ + MainThreadStatus::getInstance(); + auto & thread_tracker = CurrentThread::get().memory_tracker; + + auto column = ColumnUnique::create(DataTypeString()); + ASSERT_EQ(column->uniqueInsertData("a", 1), 1u); + + /// Leave `offsets` without spare capacity and `chars` with plenty, so that growing `offsets` is the only + /// allocation of the next insert. + auto & nested = assert_cast(column->getNestedColumn()->assumeMutableRef()); + nested.getOffsets().shrink_to_fit(); + nested.getChars().reserve(nested.getChars().size() + 1024); + + const Int64 saved_untracked_limit = CurrentThread::get().untracked_memory_limit; + const Int64 saved_thread_hard_limit = thread_tracker.getHardLimit(); + const Int64 saved_total_hard_limit = total_memory_tracker.getHardLimit(); + + auto lift_limits = [&] + { + total_memory_tracker.setHardLimit(saved_total_hard_limit); + thread_tracker.setHardLimit(saved_thread_hard_limit); + CurrentThread::get().untracked_memory_limit = saved_untracked_limit; + }; + SCOPE_EXIT_SAFE(lift_limits()); + + /// Make even a tiny allocation reach the trackers and fail: no per-thread untracked buffer, limits of one byte. + CurrentThread::get().untracked_memory_limit = 0; + CurrentThread::flushUntrackedMemory(); + total_memory_tracker.resetCounters(); + thread_tracker.resetCounters(); + total_memory_tracker.setHardLimit(1); + thread_tracker.setHardLimit(1); + + bool thrown = false; + int code = 0; + try + { + column->uniqueInsertData("bb", 2); + } + catch (const Exception & e) + { + thrown = true; + code = e.code(); + } + + /// Lift the limits before anything else, the assertions allocate. + lift_limits(); + + ASSERT_TRUE(thrown) << "the insert was expected to fail under the memory limit"; + EXPECT_EQ(code, ErrorCodes::MEMORY_LIMIT_EXCEEDED); + + EXPECT_EQ(column->size(), 2u); + EXPECT_EQ(nested.getChars().size(), nested.getOffsets().back()); + + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->getDataAt(2), "c"); + EXPECT_EQ(column->uniqueInsertData("bb", 2), 3u); + EXPECT_EQ(column->getDataAt(3), "bb"); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->size(), 4u); +} diff --git a/src/Common/CurrentMetrics.cpp b/src/Common/CurrentMetrics.cpp index 84d3b3c5bd0e..c88478725f6e 100644 --- a/src/Common/CurrentMetrics.cpp +++ b/src/Common/CurrentMetrics.cpp @@ -323,6 +323,8 @@ M(AsyncInsertCacheSize, "Number of async insert hash id in cache") \ M(IcebergMetadataFilesCacheBytes, "Size of the Iceberg metadata cache in bytes") \ M(IcebergMetadataFilesCacheFiles, "Number of cached files in the Iceberg metadata cache") \ + M(GlueCatalogSchemaCacheBytes, "Size of the cache of current Iceberg schema field types in Glue catalogs in bytes") \ + M(GlueCatalogSchemaCacheEntries, "Number of entries in the cache of current Iceberg schema field types in Glue catalogs") \ M(ParquetMetadataCacheBytes, "Size of the Parquet metadata cache in bytes") \ M(ParquetMetadataCacheFiles, "Number of cached files in the Parquet metadata cache") \ M(AvroSchemaCacheBytes, "Size of the Avro schema cache in bytes") \ diff --git a/src/Common/DateLUTImpl.h b/src/Common/DateLUTImpl.h index 4ac32f91a97e..690a6496ab53 100644 --- a/src/Common/DateLUTImpl.h +++ b/src/Common/DateLUTImpl.h @@ -561,21 +561,15 @@ class DateLUTImpl { const LUTIndex index = findIndex(t); - /// Calculate daylight saving offset first. - /// Because the "amount_of_offset_change" in LUT entry only exists in the change day, it's costly to scan it from the very begin. - /// but we can figure out all the accumulated offsets from 1970-01-01 to that day just by get the whole difference between lut[].date, - /// and then, we can directly subtract multiple 86400s to get the real DST offsets for the leap seconds is not considered now. - Time res = (lut[index].date - lut[daynum_offset_epoch].date) % 86400; - - /// As so far to know, the maximal DST offset couldn't be more than 2 hours, so after the modulo operation the remainder - /// will sits between [-offset --> 0 --> offset] which respectively corresponds to moving clock forward or backward. - res = res > 43200 ? (86400 - res) : (0 - res); + /// The offset at the start of the day: local midnight is `day_number * 86400` seconds of local + /// time from the epoch, while `date` is the UTC instant of that same midnight. + Time res = (static_cast(index.toUnderType()) - daynum_offset_epoch) * 86400 - lut[index].date; /// Check if has a offset change during this day. Add the change when cross the line if (lut[index].amount_of_offset_change() != 0 && t >= lut[index].date + lut[index].time_at_offset_change()) res += lut[index].amount_of_offset_change(); - return res + offset_at_start_of_epoch; + return res; } diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 875173c92b8b..7dfb2f297886 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -34,6 +34,7 @@ static struct InitFiu #define APPLY_FOR_FAILPOINTS(ONCE, REGULAR, PAUSEABLE_ONCE, PAUSEABLE) \ ONCE(replicated_merge_tree_commit_zk_fail_after_op) \ ONCE(replicated_queue_fail_next_entry) \ + ONCE(reverse_index_build_index_throw) \ REGULAR(replicated_queue_unfail_entries) \ ONCE(replicated_merge_tree_insert_quorum_fail_0) \ REGULAR(replicated_merge_tree_commit_zk_fail_when_recovering_from_hw_fault) \ @@ -96,6 +97,7 @@ static struct InitFiu PAUSEABLE_ONCE(finish_clean_quorum_failed_parts) \ PAUSEABLE_ONCE(smt_wait_next_mutation) \ PAUSEABLE_ONCE(delta_lake_metadata_iterate_pause) \ + PAUSEABLE_ONCE(rmt_restore_replica_pause_before_metadata_version_raise) \ PAUSEABLE(dummy_pausable_failpoint) \ ONCE(execute_query_calling_empty_set_result_func_on_exception) \ ONCE(terminate_with_exception) \ @@ -129,6 +131,7 @@ static struct InitFiu REGULAR(database_replicated_delay_recovery) \ REGULAR(database_replicated_delay_entry_execution) \ PAUSEABLE(database_replicated_stop_entry_execution) \ + PAUSEABLE_ONCE(database_replicated_pause_before_initial_query_execution) \ REGULAR(remove_merge_tree_part_delay) \ REGULAR(plain_object_storage_copy_temp_source_file_fail_on_file_move) \ REGULAR(plain_object_storage_copy_temp_target_file_fail_on_file_move) \ diff --git a/src/Common/RemoteHostFilter.cpp b/src/Common/RemoteHostFilter.cpp index 6f953f48d48b..5b5da5ec7c6b 100644 --- a/src/Common/RemoteHostFilter.cpp +++ b/src/Common/RemoteHostFilter.cpp @@ -110,6 +110,10 @@ bool RemoteHostFilter::checkForDirectEntry(const std::string & str) const /// Allow everything by default. return true; + /// Connectors take the host as a C string and stop at the first NUL, so the checked string must not contain one. + if (str.contains('\0')) + return false; + std::lock_guard guard(hosts_mutex); if (primary_hosts.contains(str)) diff --git a/src/Common/Scheduler/CPUSlotsAllocation.cpp b/src/Common/Scheduler/CPUSlotsAllocation.cpp index a11e4a6feb9a..30d9d735e60d 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.cpp +++ b/src/Common/Scheduler/CPUSlotsAllocation.cpp @@ -7,6 +7,7 @@ #include #include #include +#include namespace ProfileEvents { @@ -72,6 +73,10 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker for (CPUSlotRequest & request : requests) request.allocation = this; + wait_thread_group = CurrentThread::getGroup(); + if (wait_thread_group) + wait_counters = &wait_thread_group->performance_counters; + std::unique_lock lock{schedule_mutex}; while (allocated < total_slots) { @@ -79,7 +84,7 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker { queue->enqueueRequest(current_request); scheduled_slot_increment.emplace(CurrentMetrics::ConcurrencyControlScheduled); - wait_timer.emplace(CurrentThread::getProfileEvents().timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); + wait_timer.emplace(wait_counters->timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); break; } else // noncompeting slot - provide for free diff --git a/src/Common/Scheduler/CPUSlotsAllocation.h b/src/Common/Scheduler/CPUSlotsAllocation.h index d8963f14b8cf..caaf37139b25 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.h +++ b/src/Common/Scheduler/CPUSlotsAllocation.h @@ -17,6 +17,7 @@ namespace DB { class CPUSlotsAllocation; +class ThreadGroup; // Represents a resource request for a cpu slot for a single thread class CPUSlotRequest final : public ResourceRequest @@ -113,6 +114,9 @@ class CPUSlotsAllocation final : public ISlotAllocation std::vector requests; // Requests per every slot CPUSlotRequest * current_request; std::optional scheduled_slot_increment; + /// `wait_timer` may end on another thread after the creating one has exited, so it counts into the query's group, kept alive here. + std::shared_ptr wait_thread_group; + ProfileEvents::Counters * wait_counters = &ProfileEvents::global_counters; std::optional wait_timer; }; diff --git a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp index 0c6ba16e64d4..cdc0b8f1ad07 100644 --- a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp +++ b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -49,6 +51,7 @@ namespace ProfileEvents { extern const Event ConcurrencyControlUpscales; extern const Event ConcurrencyControlDownscales; + extern const Event ConcurrencyControlWaitMicroseconds; } namespace CurrentMetrics @@ -1068,6 +1071,41 @@ TEST(SchedulerWorkloadResourceManager, CPUSchedulingRoundRobin) t.wait(); } +/// The wait for a CPU slot is accounted to the query even when the allocation outlives the thread that created it +/// (here: destroyed on another thread while its request is still queued, like a `KILL QUERY` of a waiting query). +TEST(SchedulerWorkloadResourceManager, CPUSlotsWaitTimerOutlivesCreatingThread) +{ + ResourceTest t; + t.query("CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD)"); + t.query("CREATE WORKLOAD all SETTINGS max_concurrent_threads = 1"); + ClassifierPtr c = t.manager->acquire("all"); + ResourceLink link = c->get("cpu"); + + /// Takes the only slot, so the next allocation keeps its request queued. + auto blocker = std::make_shared(1, 0, link, link); + auto blocker_slot = blocker->acquire(); + + std::weak_ptr weak_group; + SlotAllocationPtr allocation; + std::thread([&] + { + DB::ThreadStatus thread_status; + auto group = std::make_shared(Context::getGlobalContextInstance(), 0); + weak_group = group; + CurrentThread::attachToGroupIfDetached(group); + allocation = std::make_shared(1, 0, link, link); + CurrentThread::detachFromGroupIfNotDetached(); + }).join(); + + ASSERT_TRUE(allocation->isRequesting()); + /// The creating thread is gone, so only the allocation can still own the group. + ThreadGroupPtr group = weak_group.lock(); + ASSERT_NE(group, nullptr); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + allocation.reset(); + EXPECT_GE(group->performance_counters[ProfileEvents::ConcurrencyControlWaitMicroseconds], 10'000); +} + TEST(SchedulerWorkloadResourceManager, CPUSchedulingFairness) { ResourceTest t; diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 15b5d71e193c..3054e98b8259 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -116,7 +116,10 @@ ThreadStatus::ThreadStatus() last_rusage = std::make_unique(); memory_tracker.setDescription("Thread"); - log = getLogger("ThreadStatus"); + /// A `ThreadStatus` is created for every job of a thread pool, and `getLogger` locks the global mutex of the + /// registry of loggers, so all threads of the pools would contend on it. + static const LoggerPtr thread_status_log = getLogger("ThreadStatus"); + log = thread_status_log; current_thread = this; diff --git a/src/Common/ZooKeeper/ZooKeeperConstants.h b/src/Common/ZooKeeper/ZooKeeperConstants.h index d5c5cc119fb5..7e61d02e91c1 100644 --- a/src/Common/ZooKeeper/ZooKeeperConstants.h +++ b/src/Common/ZooKeeper/ZooKeeperConstants.h @@ -92,6 +92,8 @@ static constexpr int32_t PASSWORD_LENGTH = 16; static constexpr int32_t MAX_STRING_OR_ARRAY_SIZE = 1 << 28; /// 256 MiB /// Upper bound on elements reserved up front when reading an array; the declared size is attacker-controlled static constexpr int32_t MAX_ARRAY_PREALLOCATION = 4096; +/// Bytes read per step when reading a string; the declared size is attacker-controlled, so memory grows with the bytes received +static constexpr int32_t MAX_STRING_PREALLOCATION = 1 << 16; /// 64 KiB static constexpr int32_t DEFAULT_SESSION_TIMEOUT_MS = 30000; static constexpr int32_t DEFAULT_MIN_SESSION_TIMEOUT_MS = 10000; static constexpr int32_t DEFAULT_MAX_SESSION_TIMEOUT_MS = 100000; diff --git a/src/Common/ZooKeeper/ZooKeeperIO.cpp b/src/Common/ZooKeeper/ZooKeeperIO.cpp index 88de2b4dc01d..c872bdac795e 100644 --- a/src/Common/ZooKeeper/ZooKeeperIO.cpp +++ b/src/Common/ZooKeeper/ZooKeeperIO.cpp @@ -93,11 +93,24 @@ void read(std::string & s, ReadBuffer & in) if (size > MAX_STRING_OR_ARRAY_SIZE) throw Exception(Error::ZMARSHALLINGERROR,"Too large string size while reading from ZooKeeper {}", size); - s.resize(size); - size_t read_bytes = in.read(s.data(), size); - if (read_bytes != static_cast(size)) - throw Exception( - Error::ZMARSHALLINGERROR, "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", size, read_bytes); + /// Memory must track bytes actually read, not the declared size: + /// do not pre-allocate for an attacker-controlled length. + s.clear(); + size_t remaining = static_cast(size); + while (remaining > 0) + { + const size_t chunk = std::min(remaining, MAX_STRING_PREALLOCATION); + const size_t old_size = s.size(); + s.resize(old_size + chunk); + const size_t read_bytes = in.read(s.data() + old_size, chunk); + if (read_bytes != chunk) + throw Exception( + Error::ZMARSHALLINGERROR, + "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", + size, + old_size + read_bytes); + remaining -= chunk; + } } void read(ACL & acl, ReadBuffer & in) diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index d368e482aa8c..a4f762ec2d57 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -2,14 +2,69 @@ #include +#include #include #include #include +#include namespace DB { +/** Hides the secrets of an Azure connection string as the Azure SDK reads it (`Azure::Storage::_internal::ParseConnectionString`, + * `contrib/azure/sdk/storage/azure-storage-common/src/storage_credential.cpp`): a key runs to '=' and its value to ';', keys + * match exactly, and the last copy of a repeated key wins. Splitting at every ';' first can only hide more than the SDK reads. + * - secret keys: `AccountName=a;AccountKey=K;SharedAccessSignature=S` -> `AccountName=a;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]` + * - repeated keys: `AccountKey=K1;AccountKey=K2` -> `AccountKey=[HIDDEN];AccountKey=[HIDDEN]` + * - an endpoint is a url, so a query in it is a SAS: `BlobEndpoint=https://h/?sig=S` or `BlobEndpoint=https://u@h/` -> `BlobEndpoint=[HIDDEN]` + * - the whole string is hidden when a '?', '#' or '@' is still shown, or when it has one and holds a url outside the pair + * values (':' or '/' in a key or in a part without '='; no key has them): `https://h/?sig=S` or `https://u:p=s@h/` -> `[HIDDEN]` + * Returns whether anything was hidden. + */ +inline bool maskAzureConnectionStringSecrets(std::string & str) +{ + static constexpr std::array secret_keys = {"AccountKey", "SharedAccessSignature"}; + auto is_secret_key = [](std::string_view key) { return std::ranges::find(secret_keys, key) != secret_keys.end(); }; + + const bool has_url_delimiters = str.find_first_of("?#@") != std::string::npos; + bool url_outside_values = false; + std::string result; + size_t copied = 0; + bool masked = false; + for (size_t part_begin = 0; part_begin <= str.length();) + { + const size_t part_end = std::min(str.find(';', part_begin), str.length()); + const std::string_view part = std::string_view(str).substr(part_begin, part_end - part_begin); + const size_t equals = part.find('='); + if (part.substr(0, equals).find_first_of(":/") != std::string_view::npos) + url_outside_values = true; + if (equals != std::string_view::npos + && (is_secret_key(part.substr(0, equals)) || part.substr(equals + 1).find_first_of("?@") != std::string_view::npos)) + { + const size_t value_begin = part_begin + equals + 1; + result.append(str, copied, value_begin - copied); + result.append("[HIDDEN]"); + copied = part_end; + masked = true; + } + part_begin = part_end + 1; + } + + if (masked) + { + result.append(str, copied, std::string::npos); + str = std::move(result); + } + + if (str.find_first_of("?#@") != std::string::npos || (url_outside_values && has_url_delimiters)) + { + str = "[HIDDEN]"; + return true; + } + return masked; +} + inline bool maskURIPassword(std::string * uri) { return RE2::Replace(uri, R"(([^:]+://[^:]*):([^@]*)@(.*))", "\\1:[HIDDEN]@\\3"); diff --git a/src/Common/mysqlxx/Connection.cpp b/src/Common/mysqlxx/Connection.cpp index f9f2d3e5d1aa..8614bed72705 100644 --- a/src/Common/mysqlxx/Connection.cpp +++ b/src/Common/mysqlxx/Connection.cpp @@ -114,6 +114,14 @@ void Connection::connect(const char* db, if (mysql_ssl_set(driver.get(), ifNotEmpty(ssl_key), ifNotEmpty(ssl_cert), ifNotEmpty(ssl_ca), nullptr, nullptr)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// Without an explicit socket, use TCP to the given port: otherwise `localhost` goes to the library's default socket. + if (!ifNotEmpty(socket)) + { + unsigned protocol = MYSQL_PROTOCOL_TCP; + if (mysql_options(driver.get(), MYSQL_OPT_PROTOCOL, &protocol)) + throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + } + if (!mysql_real_connect(driver.get(), server, user, password, db, port, ifNotEmpty(socket), driver->client_flag)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); diff --git a/src/Common/mysqlxx/Pool.cpp b/src/Common/mysqlxx/Pool.cpp index 7173adf3326c..58d54882fa6c 100644 --- a/src/Common/mysqlxx/Pool.cpp +++ b/src/Common/mysqlxx/Pool.cpp @@ -9,11 +9,61 @@ #include #include #include +#include #include #include #include +namespace DB::ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + +namespace +{ + +/// `mysql_real_connect` reinterprets these hosts and port 0; reject them so it dials exactly what `remote_url_allow_hosts` checked. +void checkConnectionTarget(const std::string & server, unsigned port, const std::string & socket) +{ + std::string_view meaning; + if (server.contains('\0')) + meaning = "the end of the host"; + else if (server.find_first_of(";=") != std::string::npos) + meaning = "a connection string"; + else if (server.contains("://")) + meaning = "a connection plugin URL"; + else if (server.contains(',')) + meaning = "a list of hosts"; + + if (!meaning.empty()) + { + std::string printable; + for (const char c : server) + printable += c == '\0' ? std::string_view("\\0") : std::string_view(&c, 1); + + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL host '{}' contains syntax which the MySQL client library would read as {}. " + "Specify a plain host and port, and use the `socket` and `ssl_*` settings instead", + printable, meaning); + } + + if (socket.contains('\0')) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, "MySQL socket for host '{}' contains a NUL byte, where the MySQL client library would end it", server); + + /// The client library uses the socket only for an empty host or `localhost`, otherwise it connects over TCP. + const bool uses_socket = !socket.empty() && (server.empty() || server == "localhost"); + if (port == 0 && !uses_socket) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL port 0 for host '{}' would be replaced by the default port of the MySQL client library. Specify the port explicitly", + server); +} + +} + namespace mysqlxx { @@ -367,6 +417,9 @@ void Pool::initialize() Pool::Connection * Pool::allocConnection(bool dont_throw_if_failed_first_time) { + /// All connections of the pool are created here. + checkConnectionTarget(server, port, socket); + auto conn_ptr = std::make_unique(); try diff --git a/src/Common/tests/gtest_distrusted_certificates.cpp b/src/Common/tests/gtest_distrusted_certificates.cpp new file mode 100644 index 000000000000..5931feea9f6b --- /dev/null +++ b/src/Common/tests/gtest_distrusted_certificates.cpp @@ -0,0 +1,137 @@ +#include "config.h" + +#if USE_SSL + +#include + +#include +#include + +#include +#include +#include + +#include +#include + + +namespace +{ + +/// `emSign ECC Root CA - G3`, distrusted. +constexpr std::string_view emsign_ecc_root_g3 = R"( +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +)"; + +/// `EM DV TLS CA - G3B` cross-signed by `AAA Certificate Services`, distrusted by the key of the certificate issued by `emSign Root TLS CA - G3`. +constexpr std::string_view em_dv_tls_ca_g3b_cross_signed = R"( +-----BEGIN CERTIFICATE----- +MIIDzjCCAragAwIBAgIRAKAk/fS6Zlx4XOSgIEg4WLcwDQYJKoZIhvcNAQELBQAw +ezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV +BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0yNTA1MTQwMDAwMDBaFw0y +ODEyMzEyMzU5NTlaMD8xCzAJBgNVBAYTAk5MMRMwEQYDVQQKDAplTXVkaHJhIEJW +MRswGQYDVQQDDBJFTSBEViBUTFMgQ0EgLSBHM0IwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAATnntnASpdzxHNeUREdqFrCvV5kqzdLgOEsvCA47B5PDjuBL8mFnh5nr7BO +L4vJf3SFumWqkR7opORbYtXMA9Vr5nizw4y03JN8okYOI4RTyJKTXSnUT5HhVga2 +PM7atGijggE1MIIBMTAfBgNVHSMEGDAWgBSgEQojPpbxB+zirynvgqV/0DCktDAd +BgNVHQ4EFgQU4h4v5xwZOQ5VS2LBICRXNSSKJRQwDgYDVR0PAQH/BAQDAgEGMBIG +A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC +MDEGA1UdIAQqMCgwCAYGZ4EMAQIBMA0GCysGAQQBg44hAQABMA0GCysGAQQBg44h +AQJkMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0FB +QUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEF +BQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBCwUAA4IB +AQBzQ1IoqpdotM6gFrR4Q3YrKifOLeaj5XXunldpVE/vZn2TxC2y0s8oYiLR5ICE +wqVXSB7N6BM1Mp+Nif7Jbhb2IswAfSR4Iik8+B0iRmi7lYoNlycCgHjmsjOmZaxM +QkPmjXAJbG5f4V41OsvJZmS7lI3r0IuvEDVX3GAZ13on6IImSs9ybNpHQ7NCqkMQ +7wH4uAO1dtpFycgJSdHaCOhHjrox2BTYGLdpUrYwY3EOAjlZ8UGgsxs7mG+xquMl +bN1LFURwfnkVMP3T/DBIZ/ys2+lNFyxK3FlArrV4/000uTnVB1lO8oGORYdXoT5V +GUyRCEIDhF5TBUuKF4E3kf1h +-----END CERTIFICATE-----)"; + +/// `emSign Root CA - G1`, not affected. +constexpr std::string_view emsign_root_g1 = R"( +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +)"; + +using X509Ptr = std::unique_ptr; + +X509Ptr parseCertificate(std::string_view pem) +{ + std::unique_ptr bio(BIO_new_mem_buf(pem.data(), static_cast(pem.size())), BIO_free); + X509Ptr certificate(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr), X509_free); + EXPECT_NE(certificate, nullptr); + return certificate; +} + +/// Verifies a trusted self-signed certificate the same way a TLS connection of a Poco context does it. +int verifyTrustedRoot(std::string_view pem) +{ + Poco::Net::Context context(Poco::Net::Context::CLIENT_USE, Poco::Net::Context::Params{}); + X509Ptr certificate = parseCertificate(pem); + X509_STORE * store = SSL_CTX_get_cert_store(context.sslContext()); + EXPECT_EQ(X509_STORE_add_cert(store, certificate.get()), 1); + + std::unique_ptr store_ctx(X509_STORE_CTX_new(), X509_STORE_CTX_free); + EXPECT_EQ(X509_STORE_CTX_init(store_ctx.get(), store, certificate.get(), nullptr), 1); + X509_STORE_CTX_set_verify_cb(store_ctx.get(), SSL_CTX_get_verify_callback(context.sslContext())); + + if (X509_verify_cert(store_ctx.get()) == 1) + return X509_V_OK; + return X509_STORE_CTX_get_error(store_ctx.get()); +} + +} + + +TEST(DistrustedCertificates, Check) +{ + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_ecc_root_g3).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(em_dv_tls_ca_g3b_cross_signed).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_root_g1).get()), X509_V_OK); +} + +TEST(DistrustedCertificates, RejectedEvenIfTrusted) +{ + EXPECT_EQ(verifyTrustedRoot(emsign_ecc_root_g3), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(verifyTrustedRoot(emsign_root_g1), X509_V_OK); +} + +#endif diff --git a/src/Common/tests/gtest_file_channel_rotation_failure.cpp b/src/Common/tests/gtest_file_channel_rotation_failure.cpp new file mode 100644 index 000000000000..d4ca3bee239b --- /dev/null +++ b/src/Common/tests/gtest_file_channel_rotation_failure.cpp @@ -0,0 +1,133 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Log rotation must not leave `FileChannel` with a deleted `LogFile` when the process has no free file descriptors. + +namespace +{ + +/// glibc defines `RLIMIT_NOFILE` as a self-referential macro, which trips -Wdisabled-macro-expansion inside gtest macros. +const auto nofile_resource = RLIMIT_NOFILE; + +struct DescriptorTableGuard +{ + struct rlimit original_limit{}; + std::vector descriptors; + + void release() + { + for (int fd : descriptors) + ::close(fd); + descriptors.clear(); + EXPECT_EQ(0, setrlimit(nofile_resource, &original_limit)); + } + + ~DescriptorTableGuard() { release(); } +}; + +int setSoftLimit(rlim_t value, const struct rlimit & original_limit) +{ + struct rlimit limit = original_limit; + limit.rlim_cur = value; + return setrlimit(nofile_resource, &limit); +} + +int fillDescriptorTable(DescriptorTableGuard & guard) +{ + while (true) + { + int fd = ::open("/dev/null", O_RDONLY | O_CLOEXEC); + if (fd < 0) + return errno; + guard.descriptors.push_back(fd); + } +} + +Poco::Message makeMessage(const std::string & text) +{ + return Poco::Message("gtest_file_channel_rotation_failure", text, Poco::Message::PRIO_INFORMATION); +} + +void expectNoFreeDescriptors(Poco::FileChannel & channel, const std::string & text) +{ + try + { + channel.log(makeMessage(text)); + ADD_FAILURE() << "Expected EMFILE while logging: " << text; + } + catch (const Poco::FileException & e) + { + EXPECT_EQ(EMFILE, e.code()) << e.displayText(); + } +} + +std::string readFile(const std::string & path) +{ + std::ifstream in(path); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +} + +TEST(FileChannelRotation, NoFreeDescriptorsDuringRotation) +{ + const auto dir = std::filesystem::temp_directory_path() / ("gtest_file_channel_rotation_" + std::to_string(::getpid())); + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + struct DirectoryGuard + { + std::filesystem::path path; + ~DirectoryGuard() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + } directory_guard{dir}; + const std::string path = (dir / "server.log").string(); + + Poco::AutoPtr channel = new Poco::FileChannel(path); + channel->setProperty(Poco::FileChannel::PROP_ROTATION, "1K"); + channel->setProperty(Poco::FileChannel::PROP_ARCHIVE, "number"); + channel->setProperty(Poco::FileChannel::PROP_COMPRESS, "false"); + + DescriptorTableGuard guard; + ASSERT_EQ(0, getrlimit(nofile_resource, &guard.original_limit)); + const rlim_t limit = std::min({guard.original_limit.rlim_cur, guard.original_limit.rlim_max - 1, 1024}); + + /// The log file gets descriptor `limit`, so closing it in `archive` frees no descriptor below the limit. + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + ASSERT_EQ(EMFILE, fillDescriptorTable(guard)); + ASSERT_EQ(0, setSoftLimit(limit + 1, guard.original_limit)); + ASSERT_NO_THROW(channel->open()); + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + + ASSERT_NO_THROW(channel->log(makeMessage(std::string(2048, 'x')))); + + expectNoFreeDescriptors(*channel, "rotation without free descriptors"); + EXPECT_TRUE(std::filesystem::exists(path + ".0")); + EXPECT_EQ(0u, channel->size()); + expectNoFreeDescriptors(*channel, "still no free descriptors"); + + guard.release(); + + const std::string marker = "logged after descriptors were released"; + ASSERT_NO_THROW(channel->log(makeMessage(marker))); + channel->close(); + EXPECT_NE(std::string::npos, readFile(path).find(marker)); +} diff --git a/src/Coordination/Changelog.cpp b/src/Coordination/Changelog.cpp index 26f8cff05cae..dd4d3a9e8cff 100644 --- a/src/Coordination/Changelog.cpp +++ b/src/Coordination/Changelog.cpp @@ -2568,6 +2568,8 @@ void Changelog::applyEntriesFromBuffer(uint64_t index, nuraft::buffer & buffer) { uint64_t cur_index = index + i; int buf_size = buffer.get_int(); + if (buf_size < 0 || static_cast(buf_size) > buffer.size() - buffer.pos()) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Log entry {} in a log pack has invalid size {}", cur_index, buf_size); nuraft::ptr buf_local = nuraft::buffer::alloc(buf_size); buffer.get(buf_local); diff --git a/src/Coordination/KeeperStorage.cpp b/src/Coordination/KeeperStorage.cpp index 3319668b9508..dcb92d03788b 100644 --- a/src/Coordination/KeeperStorage.cpp +++ b/src/Coordination/KeeperStorage.cpp @@ -2573,7 +2573,9 @@ processImpl(const Coordination::ZooKeeperCheckWatchRequest & zk_request, Storage } } - if (!storage.containsWatch(zk_request.getPath(), zk_request.type)) + if (!magic_enum::enum_contains(zk_request.type)) + response->error = Coordination::Error::ZBADARGUMENTS; + else if (!storage.containsWatch(zk_request.getPath(), zk_request.type)) response->error = Coordination::Error::ZNOWATCHER; return response; } @@ -2610,7 +2612,9 @@ processImpl(const Coordination::ZooKeeperRemoveWatchRequest & zk_request, Storag } } - if (!storage.removePersistentWatch(zk_request.path, zk_request.type, session_id)) + if (!magic_enum::enum_contains(zk_request.type)) + response->error = Coordination::Error::ZBADARGUMENTS; + else if (!storage.removePersistentWatch(zk_request.path, zk_request.type, session_id)) response->error = Coordination::Error::ZNOWATCHER; return response; @@ -2648,7 +2652,10 @@ processImpl(const Coordination::ZooKeeperAddWatchRequest & zk_request, Storage & } } - storage.addPersistentWatch(zk_request.path, zk_request.mode, session_id); + if (!magic_enum::enum_contains(zk_request.mode)) + response->error = Coordination::Error::ZBADARGUMENTS; + else + storage.addPersistentWatch(zk_request.path, zk_request.mode, session_id); return response; } diff --git a/src/Coordination/tests/gtest_coordination.cpp b/src/Coordination/tests/gtest_coordination.cpp index 291bc4236055..6f0a8d868f51 100644 --- a/src/Coordination/tests/gtest_coordination.cpp +++ b/src/Coordination/tests/gtest_coordination.cpp @@ -172,6 +172,69 @@ TYPED_TEST(CoordinationTest, CreateRequestDoesNotPreallocateOversizedACLs) } } +TEST(CoordinationSerialization, StringReadDoesNotPreallocateDeclaredSize) +{ + /// Invariant: memory must track bytes actually read, not the declared string length. + const size_t chunk = Coordination::MAX_STRING_PREALLOCATION; + + auto expect_marshalling_error = [](DB::ReadBuffer & rbuf, std::string & s) + { + try + { + Coordination::read(s, rbuf); + FAIL() << "Expected ZMARSHALLINGERROR"; + } + catch (const Coordination::Exception & e) + { + EXPECT_EQ(e.code, Coordination::Error::ZMARSHALLINGERROR); + } + }; + + { + /// The largest allowed length is declared, but no payload bytes follow. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 2 * chunk); + } + + { + /// The input ends after one complete chunk. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + const std::string first_chunk(chunk, 'x'); + wbuf.write(first_chunk.data(), first_chunk.size()); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 4 * chunk); + } + + { + /// A string that needs more than one chunk is read completely, and the next field is aligned. + std::string expected(chunk + 1, '\0'); + for (size_t i = 0; i < expected.size(); ++i) + expected[i] = static_cast(i % 251); + + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(expected, wbuf); + Coordination::write(static_cast(42), wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + int32_t next = 0; + Coordination::read(s, rbuf); + Coordination::read(next, rbuf); + EXPECT_EQ(s, expected); + EXPECT_EQ(next, 42); + EXPECT_TRUE(rbuf.eof()); + } +} + template struct SimpliestRaftServer { diff --git a/src/Coordination/tests/gtest_coordination_changelog.cpp b/src/Coordination/tests/gtest_coordination_changelog.cpp index c0a33caadbdd..fa3ec468e04e 100644 --- a/src/Coordination/tests/gtest_coordination_changelog.cpp +++ b/src/Coordination/tests/gtest_coordination_changelog.cpp @@ -479,6 +479,45 @@ TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsEmpty) changelog_reader.init(5, 0); } +TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsInvalidSize) +{ + ChangelogDirTest test("./logs"); + this->setLogDirectory("./logs"); + + DB::KeeperLogStore changelog( + DB::LogFileSettings{.force_sync = true, .compress_logs = this->enable_compression, .rotate_interval = 100}, + DB::FlushSettings(), + this->keeper_context); + changelog.init(0, 0); + auto entry = getLogEntry("hello_world", 10); + changelog.append(entry); + changelog.end_of_append_batch(0, 0); + waitDurableLogs(changelog); + + /// A pack of one entry holds the entry count, the entry size and the entry itself. A peer controls the size, + /// so only the size is rewritten here. + auto entries = changelog.pack(1, 1); + const auto entry_size = static_cast(entries->size() - 2 * sizeof(int32_t)); + auto apply_with_size = [&](int32_t size) + { + entries->pos(sizeof(int32_t)); + entries->put(size); + changelog.apply_pack(2, *entries); + }; + + /// On master a size past the entry over-reads the pack in `nuraft::buffer::get` and a negative size + /// wraps the allocation size in `nuraft::buffer::alloc`. + EXPECT_THROW(apply_with_size(entry_size + 1), DB::Exception); + EXPECT_THROW(apply_with_size(-1), DB::Exception); + EXPECT_EQ(changelog.next_slot(), 2); + + apply_with_size(entry_size); + changelog.apply_pack(3, *changelog.pack(1, 0)); + changelog.end_of_append_batch(0, 0); + EXPECT_EQ(changelog.next_slot(), 3); + EXPECT_EQ(changelog.entry_at(2)->get_term(), 10); +} + TYPED_TEST(CoordinationChangelogTest, ChangelogTestWriteAtPreviousFile) { diff --git a/src/Core/Field.cpp b/src/Core/Field.cpp index 8afadfc8ac9e..ca0f375ed111 100644 --- a/src/Core/Field.cpp +++ b/src/Core/Field.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -369,6 +370,9 @@ bool Field::operator== (const Field & rhs) const Field getBinaryValue(UInt8 type, ReadBuffer & buf) { + /// Containers are read recursively, and the nesting depth comes from the data. + checkStackSize(); + switch (static_cast(type)) { case Field::Types::Null: diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 0042be8fe8a1..31643b8133cd 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -1408,6 +1408,13 @@ Compression method for Arrow output format. Supported codecs: lz4_frame, zstd, n )", 0) \ DECLARE(Bool, output_format_arrow_date_as_uint16, false, R"( Write Date values as plain 16-bit numbers (read back as UInt16), instead of converting to a 32-bit Arrow DATE32 type (read back as Date32). +)", 0) \ + DECLARE(UInt64, output_format_arrow_max_record_batch_size_bytes, 2147483646, R"( +Upper bound on the `Utf8`, `Binary` and `List` buffers of a single record batch in the `Arrow` and `ArrowStream` output formats. A block whose strings, binary values or list elements exceed this is written as several record batches. + +This is a limit that splits large blocks. The default is the largest value Arrow can address, because it offsets those buffers with 32-bit integers; a larger value has no effect. + +Only the buffers named above are bounded: a column of a fixed-width type has no offsets to overflow and stays in one batch. A single row never splits either, so a row above the limit still produces a batch that exceeds it. )", 0) \ \ DECLARE(Bool, output_format_orc_string_as_string, true, R"( diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index ac119469ccd0..6cbd2e052809 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -1270,6 +1270,10 @@ Possible values: - `2` — `SELECT` and `INSERT` will be executed on each shard from/to the underlying table of the distributed engine. Setting `enable_parallel_replicas = 1` is needed when using this setting. + +:::note +The rewritten query, including every expression of the `SELECT` (subqueries, UDFs, and so on), is executed on the shards under the credentials of the cluster configuration — the same trust model as other shard-side processing, such as the subqueries of a non-`GLOBAL` `IN`. Configure an interserver secret (the `secret` element of the cluster configuration) if shard-side reads must be authorized as the calling user. +::: )", 0) \ DECLARE(UInt64, distributed_group_by_no_merge, 0, R"( Do not merge aggregation states from different servers for distributed query processing, you can use this in case it is for certain that there are different keys on different shards diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 62e4d873e09d..caf53da95654 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -41,6 +41,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() /// Note: please check if the key already exists to prevent duplicate entries. addSettingsChanges(settings_changes_history, "26.3", { + {"output_format_arrow_max_record_batch_size_bytes", 2147483646, 2147483646, "New setting bounding the size of one record batch in `Arrow` and `ArrowStream` output. The default is Arrow's own addressing limit, so it does not change behavior."}, {"variant_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Variant implementation"}, {"dynamic_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Dynamic implementation"}, {"defer_partition_pruning_after_final", false, true, "Gates the FINAL planner's unconditional skipping of partition pruning when the partition-key column is not in the sorting key. The behavior change itself shipped silently in 26.3 via https://github.com/ClickHouse/ClickHouse/pull/98242; this entry retroactively documents it so `compatibility = '26.2'` restores the pre-regression behavior (0 = prune before FINAL, fast; 1 = defer pruning, correctness-safe)."}, diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp index 4b0be9872423..1b1665c4abff 100644 --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp @@ -607,6 +607,13 @@ void SerializationLowCardinality::deserializeBinaryBulkWithMultipleStreams( bool has_additional_keys = low_cardinality_state->index_type.has_additional_keys; bool column_is_empty = low_cardinality_column.empty(); + /// Indexes come from the stream. + if (low_cardinality_state->index_type.need_global_dictionary) + { + const size_t num_additional_keys = additional_keys ? additional_keys->size() : 0; + ColumnLowCardinality::checkIndexesAreLimited(*indexes_column, global_dictionary->size() + num_additional_keys); + } + if (!low_cardinality_state->index_type.need_global_dictionary) { if (additional_keys == nullptr) diff --git a/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp new file mode 100644 index 000000000000..4ea6070e820a --- /dev/null +++ b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp @@ -0,0 +1,179 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int INCORRECT_DATA; +} + +using namespace DB; + +namespace +{ + +/// The MergeTree layout: the dictionary in one stream, the indexes and the additional keys in another. +template +auto makeGetter(Buffer & keys, Buffer & indexes) +{ + return [&keys, &indexes](const ISerialization::SubstreamPath & path) -> BufferPtr + { + if (!path.empty() && path.back().type == ISerialization::Substream::DictionaryKeys) + return &keys; + return &indexes; + }; +} + +struct Streams +{ + std::string keys; + std::string indexes; +}; + +Streams serialize(const DataTypePtr & type, const IColumn & column, size_t max_dictionary_size) +{ + WriteBufferFromOwnString keys; + WriteBufferFromOwnString indexes; + auto serialization = type->getDefaultSerialization(); + ISerialization::SerializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.low_cardinality_max_dictionary_size = max_dictionary_size; + settings.low_cardinality_use_single_dictionary_for_part = false; + ISerialization::SerializeBinaryBulkStatePtr state; + serialization->serializeBinaryBulkStatePrefix(column, settings, state); + serialization->serializeBinaryBulkWithMultipleStreams(column, 0, column.size(), settings, state); + serialization->serializeBinaryBulkStateSuffix(settings, state); + keys.finalize(); + indexes.finalize(); + return {keys.str(), indexes.str()}; +} + +ColumnPtr deserialize(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + ReadBufferFromString keys(streams.keys); + ReadBufferFromString indexes(streams.indexes); + auto serialization = type->getDefaultSerialization(); + ISerialization::DeserializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.native_format = false; + ISerialization::DeserializeBinaryBulkStatePtr state; + serialization->deserializeBinaryBulkStatePrefix(settings, state, nullptr); + ColumnPtr column = type->createColumn(); + serialization->deserializeBinaryBulkWithMultipleStreams(column, 0, rows, settings, state, nullptr); + return column; +} + +void expectIncorrectData(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + try + { + deserialize(type, streams, rows); + FAIL() << "accepted an index past the keys"; + } + catch (const Exception & e) + { + ASSERT_EQ(e.code(), ErrorCodes::INCORRECT_DATA) << e.message(); + } +} + +/// Calls `check` for `LowCardinality(String)` and `LowCardinality(Nullable(UInt64))`, each serialized with a dictionary +/// of 2 keys (so most values become additional keys) and with one large enough for all values (no additional keys). +template +void forEachCase(Check && check) +{ + for (bool nullable : {false, true}) + { + DataTypePtr inner = nullable ? makeNullable(std::make_shared()) : std::make_shared(); + auto type = std::make_shared(inner); + auto column = type->createColumn(); + for (size_t i = 0; i < 20; ++i) + { + if (nullable) + column->insert(i % 6 == 0 ? Field() : Field(UInt64(i % 6))); + else + column->insert(String(1, static_cast('a' + i % 5))); + } + + for (size_t max_dictionary_size : {2, 8192}) + { + SCOPED_TRACE(type->getName() + " with max dictionary size " + std::to_string(max_dictionary_size)); + auto streams = serialize(type, *column, max_dictionary_size); + + constexpr UInt64 need_global_dictionary_bit = 1ULL << 8; + constexpr UInt64 has_additional_keys_bit = 1ULL << 9; + const UInt64 index_type = unalignedLoadLittleEndian(streams.indexes.data()); + const bool has_additional_keys = (index_type & has_additional_keys_bit) != 0; + ASSERT_NE(index_type & need_global_dictionary_bit, 0u); + ASSERT_EQ(has_additional_keys, max_dictionary_size == 2); + ASSERT_LE(index_type & 0xff, 3u); + + /// The keys stream starts with the version, then the number of keys; the indexes stream starts with the index type, + /// then the number of additional keys if there are any. + const UInt64 num_keys = unalignedLoadLittleEndian(streams.keys.data() + 8) + + (has_additional_keys ? unalignedLoadLittleEndian(streams.indexes.data() + 8) : 0); + const size_t index_width = 1ULL << (index_type & 0xff); + + check(type, *column, std::move(streams), num_keys, index_width); + } + } +} + +} + +TEST(SerializationLowCardinality, ValidStreamsRoundTrip) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64, size_t) + { + auto result = deserialize(type, streams, column.size()); + ASSERT_EQ(result->size(), column.size()); + for (size_t i = 0; i < column.size(); ++i) + ASSERT_EQ((*result)[i], column[i]) << "row " << i; + }); +} + +/// The indexes come from the data, so they have to be checked against the keys of the dictionary and the additional keys. +TEST(SerializationLowCardinality, IndexPastTheKeysIsRejected) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64 num_keys, size_t index_width) + { + const size_t rows = column.size(); + const size_t indexes_begin = streams.indexes.size() - rows * index_width; + + /// The same indexes as `UInt64` (index type 3, the low byte of the index type) read back the same values... + Streams wide{streams.keys, streams.indexes.substr(0, indexes_begin)}; + wide.indexes[0] = 3; + for (size_t row = 0; row < rows; ++row) + { + UInt64 index = 0; + for (size_t i = 0; i < index_width; ++i) + index |= UInt64(static_cast(streams.indexes[indexes_begin + row * index_width + i])) << (8 * i); + for (size_t i = 0; i < 8; ++i) + wide.indexes.push_back(static_cast(index >> (8 * i))); + } + auto result = deserialize(type, wide, rows); + ASSERT_EQ(result->size(), rows); + for (size_t row = 0; row < rows; ++row) + ASSERT_EQ((*result)[row], column[row]) << "row " << row; + + /// ...and the largest possible last index is rejected before `mapIndexWithAdditionalKeys` sizes its overflow map by it. + std::fill(wide.indexes.end() - 8, wide.indexes.end(), '\xff'); + expectIncorrectData(type, wide, rows); + + /// The last index of the original stream becomes the first value past the keys. + ASSERT_LE(num_keys, std::numeric_limits::max() >> (64 - 8 * index_width)); + for (size_t i = 0; i < index_width; ++i) + streams.indexes[streams.indexes.size() - index_width + i] = static_cast(num_keys >> (8 * i)); + expectIncorrectData(type, streams, rows); + }); +} diff --git a/src/Databases/DataLake/GlueCatalog.cpp b/src/Databases/DataLake/GlueCatalog.cpp index df08b71baf8a..3ab1c7067a12 100644 --- a/src/Databases/DataLake/GlueCatalog.cpp +++ b/src/Databases/DataLake/GlueCatalog.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -77,8 +78,8 @@ namespace DB::ServerSetting namespace CurrentMetrics { - extern const Metric MarkCacheBytes; - extern const Metric MarkCacheFiles; + extern const Metric GlueCatalogSchemaCacheBytes; + extern const Metric GlueCatalogSchemaCacheEntries; } namespace DataLake @@ -95,7 +96,7 @@ GlueCatalog::GlueCatalog( , region(settings_.region) , settings(settings_) , table_engine_definition(table_engine_definition_) - , metadata_objects(CurrentMetrics::MarkCacheBytes, CurrentMetrics::MarkCacheFiles, 1024) + , current_schema_field_types(CurrentMetrics::GlueCatalogSchemaCacheBytes, CurrentMetrics::GlueCatalogSchemaCacheEntries, 16_MiB) { DB::S3::CredentialsConfiguration creds_config; creds_config.use_environment_credentials = true; @@ -466,7 +467,7 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet const String & metadata_uri = table_specific_properties->iceberg_metadata_file_location; - if (!metadata_objects.get(metadata_uri)) + auto [field_types, _] = current_schema_field_types.getOrSet(metadata_uri, [&] { auto [object_storage, bucket_name, metadata_path] = createObjectStorageForEarlyTableAccess(metadata_uri, table_metadata); const auto & read_settings = getContext()->getReadSettings(); @@ -479,28 +480,42 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(metadata_file_content); auto metadata_object = result.extract(); - metadata_objects.set(metadata_uri, std::make_shared(metadata_object)); - } + return std::make_shared(getCurrentSchemaFieldTypes(metadata_object)); + }); + + auto it = field_types->find(column_name); + return it != field_types->end() && it->second == DB::Iceberg::f_timestamptz; +} - auto metadata_object = *metadata_objects.get(metadata_uri); +GlueCatalog::FieldTypes GlueCatalog::getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object) +{ + FieldTypes result; auto current_schema_id = metadata_object->getValue("current-schema-id"); auto schemas = metadata_object->getArray(DB::Iceberg::f_schemas); for (size_t i = 0; i < schemas->size(); ++i) { auto schema = schemas->getObject(static_cast(i)); - if (schema->getValue("schema-id") == current_schema_id) + if (schema->getValue("schema-id") != current_schema_id) + continue; + + auto fields = schema->getArray(DB::Iceberg::f_fields); + for (size_t j = 0; j < fields->size(); ++j) { - auto fields = schema->getArray(DB::Iceberg::f_fields); - for (size_t j = 0; j < fields->size(); ++j) - { - auto field = fields->getObject(static_cast(j)); - if (field->getValue(DB::Iceberg::f_name) == column_name) - return field->getValue(DB::Iceberg::f_type) == DB::Iceberg::f_timestamptz; - } + auto field = fields->getObject(static_cast(j)); + auto type = field->get(DB::Iceberg::f_type); + if (type.isString()) + result.emplace(field->getValue(DB::Iceberg::f_name), type.extract()); } } + return result; +} - return false; +size_t GlueCatalog::FieldTypesWeightFunction::operator()(const FieldTypes & field_types) const +{ + size_t result = 0; + for (const auto & [name, type] : field_types) + result += sizeof(FieldTypes::value_type) + name.size() + type.size(); + return result; } GlueCatalog::ObjectStorageWithPath GlueCatalog::createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const diff --git a/src/Databases/DataLake/GlueCatalog.h b/src/Databases/DataLake/GlueCatalog.h index c65c69a2a75a..e0485de5e0e0 100644 --- a/src/Databases/DataLake/GlueCatalog.h +++ b/src/Databases/DataLake/GlueCatalog.h @@ -83,9 +83,18 @@ class GlueCatalog final : public ICatalog, private DB::WithContext const String & column_name, const String & glue_column_type); + using FieldTypes = std::unordered_map; + + static FieldTypes getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object); + private: void createNamespaceIfNotExists(const String & namespace_name) const; + struct FieldTypesWeightFunction + { + size_t operator()(const FieldTypes & field_types) const; + }; + std::unique_ptr glue_client; const LoggerPtr log; std::shared_ptr credentials_provider; @@ -112,7 +121,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext ObjectStorageWithPath createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const; - mutable DB::CacheBase metadata_objects; + mutable DB::CacheBase, FieldTypesWeightFunction> current_schema_field_types; }; } diff --git a/src/Databases/DataLake/HiveCatalog.cpp b/src/Databases/DataLake/HiveCatalog.cpp index b86f70dfc4b5..918ed836737e 100644 --- a/src/Databases/DataLake/HiveCatalog.cpp +++ b/src/Databases/DataLake/HiveCatalog.cpp @@ -10,8 +10,10 @@ #include #include #include +#include #include #include +#include #include namespace DB::ErrorCodes @@ -64,11 +66,23 @@ std::pair parseHostPort(const String & url) } } +std::shared_ptr createSocket(const String & base_url, const DB::ContextPtr & context) +{ + auto [host, port] = parseHostPort(base_url); + + /// Also rejects control characters such as NUL, which `getaddrinfo` would truncate the host at. + context->getRemoteHostFilter().checkAndGetCanonicalHostAndPort( + host + ":" + std::to_string(port), static_cast(port), "Hive metastore address"); + + return std::make_shared(host, port); +} + } -HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr) +HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr context_) : ICatalog(warehouse_) - , socket(new apache::thrift::transport::TSocket(parseHostPort(base_url_).first, parseHostPort(base_url_).second)) + , DB::WithContext(context_) + , socket(createSocket(base_url_, context_)) , transport(new apache::thrift::transport::TBufferedTransport(socket)) , protocol(new apache::thrift::protocol::TBinaryProtocol(transport)) , client(protocol) diff --git a/src/Databases/DatabaseReplicated.cpp b/src/Databases/DatabaseReplicated.cpp index 94d0aa46efd8..8428ea1c4c20 100644 --- a/src/Databases/DatabaseReplicated.cpp +++ b/src/Databases/DatabaseReplicated.cpp @@ -63,6 +63,7 @@ #include #include #include +#include #include #include @@ -798,14 +799,14 @@ void DatabaseReplicated::createEmptyLogEntry(const ZooKeeperPtr & current_zookee bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, SyncReplicaMode mode) { chassert(mode == SyncReplicaMode::DEFAULT || mode == SyncReplicaMode::STRICT); - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - return false; - } + /// The worker can be stopped and replaced concurrently (`SYSTEM RESTORE DATABASE REPLICA`, `DROP DATABASE`): + /// the reference keeps it alive, and a stopped worker returns from the wait. + auto worker = tryGetDDLWorker(); + if (!worker) + return false; if (mode == SyncReplicaMode::DEFAULT) - return ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms); + return worker->waitForReplicaToProcessAllEntries(timeout_ms); Stopwatch elapsed; while (true) @@ -814,15 +815,19 @@ bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, Sy if (elapsed_ms > timeout_ms) return false; - if (ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) + if (worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) return true; - UInt32 our_log_ptr = ddl_worker->getLogPointer(); + UInt32 our_log_ptr = worker->getLogPointer(); UInt32 max_log_ptr = parse(getZooKeeper()->get(fs::path(zookeeper_path) / "max_log_ptr")); bool became_synced = our_log_ptr + db_settings[DatabaseReplicatedSetting::max_replication_lag_to_enqueue] >= max_log_ptr; if (became_synced) return true; + /// The worker was stopped (e.g. by `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE`), it will not make progress. + if (worker->isStopped()) + return false; + /// max_log_ptr might be increased while we were waiting - retry until replication lag is below the threshold } } @@ -995,11 +1000,36 @@ void DatabaseReplicated::initDDLWorkerUnlocked() chassert(!is_probably_dropped.load()); chassert(!ddl_worker_initialized.load()); - ddl_worker = std::make_unique(this, getContext()); + replaceDDLWorkerUnlocked(std::make_shared(this, getContext())); ddl_worker->startup(); ddl_worker_initialized = true; } +std::shared_ptr DatabaseReplicated::tryGetDDLWorker() const +{ + std::lock_guard lock{ddl_worker_mutex}; + if (!ddl_worker || is_probably_dropped) + return nullptr; + return ddl_worker; +} + +std::shared_ptr DatabaseReplicated::replaceDDLWorkerUnlocked(std::shared_ptr new_worker) +{ + std::lock_guard lock{ddl_worker_ptr_mutex}; + std::swap(ddl_worker, new_worker); + return new_worker; +} + +bool DatabaseReplicated::isDDLWorkerCurrentlyActive() const +{ + std::shared_ptr worker; + { + std::lock_guard lock{ddl_worker_ptr_mutex}; + worker = ddl_worker; + } + return worker && worker->isCurrentlyActive(); +} + void DatabaseReplicated::restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper) { auto local_context = getContext(); @@ -1058,7 +1088,7 @@ void DatabaseReplicated::reinitializeDDLWorker() ddl_worker->shutdown(); { ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } } @@ -1279,7 +1309,7 @@ bool DatabaseReplicated::checkDigestValid(const ContextPtr & local_context) cons LOG_TEST(log, "Current in-memory metadata digest: {}", tables_metadata_digest); /// Database is probably being dropped - if (!local_context->getZooKeeperMetadataTransaction() && (!ddl_worker || !ddl_worker->isCurrentlyActive())) + if (!local_context->getZooKeeperMetadataTransaction() && !isDDLWorkerCurrentlyActive()) return true; /// SYSTEM RESTART REPLICA temporarily removes a table from the in-memory tables map @@ -1385,13 +1415,12 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex if (is_readonly) throw Exception(ErrorCodes::NO_ZOOKEEPER, "Database is in readonly mode, because it cannot connect to ZooKeeper"); - String host_fqdn_id; - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); - host_fqdn_id = ddl_worker->getCommonHostID(); - } + /// Hold our own reference: `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE` can stop and replace the worker + /// while this query waits in `tryEnqueueAndExecuteEntry`. A stopped worker makes it throw instead of executing. + auto worker = tryGetDDLWorker(); + if (!worker) + throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); + String host_fqdn_id = worker->getCommonHostID(); if (!flags.internal && query_context->isDDLOrOnClusterInternal()) throw Exception(ErrorCodes::INCORRECT_QUERY, "It's not initial query. ON CLUSTER is not allowed for Replicated database."); @@ -1406,7 +1435,7 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex entry.tracing_context = OpenTelemetry::CurrentContext(); entry.initial_query_id = query_context->getClientInfo().initial_query_id; entry.is_backup_restore = flags.distributed_backup_restore; - String node_path = ddl_worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); + String node_path = worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); Strings hosts_to_wait; Strings unfiltered_hosts = getZooKeeper()->getChildren(zookeeper_path + "/replicas"); @@ -2078,10 +2107,63 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) auto component_guard = Coordination::setCurrentComponent("DatabaseReplicated::restoreDatabaseMetadataInKeeper"); waitDatabaseStarted(); + /// Concurrent restores of the same database would stop and re-create the DDL worker under each other + /// and race on the replication state that `initDatabaseReplica` rewrites (e.g. `max_log_ptr_at_creation`). + std::lock_guard restore_lock{restore_in_keeper_mutex}; + auto zookeeper = getZooKeeper(); if (!zookeeper) throw Exception(ErrorCodes::NO_ZOOKEEPER, "No ZooKeeper"); + /// Stop this replica's DDL worker before the calls below re-initialize replication state: + /// its recovery reads `max_log_ptr_at_creation` and compares the Keeper metadata with the + /// local table set, which those calls rewrite, and a recovery running against a half-updated + /// view detaches local tables into `_broken_replicated_tables`. + std::shared_ptr old_worker; + { + std::lock_guard lock{ddl_worker_mutex}; + old_worker = ddl_worker; + } + + /// Initial queries admitted by the worker execute and commit on their own threads, and `shutdown` does not wait + /// for them. Wait for them before rewriting the replication state: otherwise a query could commit its metadata + /// while the recovery of the new worker compares the Keeper snapshot with the local tables, and the recovery + /// would move the just created table to `_broken_replicated_tables` (or drop it). + /// Stop admitting new initial queries, but keep the worker running while waiting: an admitted query may depend + /// on it, e.g. an `ALTER` of a `ReplicatedMergeTree` table with `alter_sync` waits for its `ALTER_METADATA` entry, + /// which the table executes only while `canExecuteReplicatedMetadataAlter` is true. + /// Not under `ddl_worker_mutex`, because these queries may need it. + if (old_worker) + { + LOG_TRACE(log, "Waiting for initial queries before restoring database metadata in Keeper."); + old_worker->stopInitialQueries(); + old_worker->waitForForegroundTasks(); + } + + { + std::lock_guard lock{ddl_worker_mutex}; + /// Only `restoreDatabaseInKeeper` (serialized by `restore_in_keeper_mutex`) creates a new worker after startup, + /// so the worker is either still the same or was removed by a concurrent `DROP DATABASE`. + chassert(!ddl_worker || ddl_worker == old_worker); + if (ddl_worker) + { + LOG_TRACE(log, "Stopping DDL worker before restoring database metadata in Keeper."); + ddl_worker->shutdown(); + ddl_worker_initialized = false; + replaceDDLWorkerUnlocked(nullptr); + } + } + old_worker.reset(); + + /// If the restore fails, reinitialize the DDL worker so the database remains functional. + /// SAFE: the body runs while an exception propagates and can itself throw (thread + /// creation), which must not replace the restore's own error. + bool need_reinitialize_ddl_worker = true; + SCOPE_EXIT_SAFE({ + if (need_reinitialize_ddl_worker) + reinitializeDDLWorker(); + }); + try { restoreDatabaseNodesInKeeper(zookeeper); @@ -2099,6 +2181,8 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) /// Force the database to recover to update the restored metadata auto current_zookeeper = getZooKeeper(); current_zookeeper->set(replica_path + "/digest", DatabaseReplicatedDDLWorker::FORCE_AUTO_RECOVERY_DIGEST); + + need_reinitialize_ddl_worker = false; reinitializeDDLWorker(); } @@ -2173,7 +2257,7 @@ void DatabaseReplicated::shutdown() { std::lock_guard lock{ddl_worker_mutex}; ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } DatabaseAtomic::shutdown(); } @@ -2184,7 +2268,7 @@ void DatabaseReplicated::dropTable(ContextPtr local_context, const String & tabl waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); + assert(txn || !isDDLWorkerCurrentlyActive() || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); @@ -2293,7 +2377,7 @@ void DatabaseReplicated::commitCreateTable(const ASTCreateQuery & query, const S ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); String statement = getObjectDefinitionFromCreateQuery(query.clone()); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) @@ -2321,7 +2405,7 @@ void DatabaseReplicated::commitAlterTable(const StorageID & table_id, const String & statement, ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_id.table_name); @@ -2361,7 +2445,7 @@ void DatabaseReplicated::detachTablePermanently(ContextPtr local_context, const throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Support for DETACH TABLE PERMANENTLY is disabled"); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { /// We have to remove metadata from zookeeper, because we do not distinguish permanently detached tables @@ -2386,7 +2470,7 @@ void DatabaseReplicated::removeDetachedPermanentlyFlag(ContextPtr local_context, waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery() && attach) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); diff --git a/src/Databases/DatabaseReplicated.h b/src/Databases/DatabaseReplicated.h index aa1f030cb971..d0c6e9377560 100644 --- a/src/Databases/DatabaseReplicated.h +++ b/src/Databases/DatabaseReplicated.h @@ -230,6 +230,15 @@ class DatabaseReplicated : public DatabaseAtomic void stopLoading() override; void initDDLWorkerUnlocked() TSA_REQUIRES(ddl_worker_mutex); + /// Returns a reference to the DDL worker taken under `ddl_worker_mutex`, or nullptr if the database + /// is not initialized yet or is being dropped. + std::shared_ptr tryGetDDLWorker() const; + /// Assigns `ddl_worker` and returns the previous worker. Requires both mutexes, see `ddl_worker_ptr_mutex`. + std::shared_ptr replaceDDLWorkerUnlocked(std::shared_ptr new_worker) + TSA_REQUIRES(ddl_worker_mutex); + /// Whether the current DDL worker exists and is active. Does not take `ddl_worker_mutex`, + /// so it is safe to call from the callbacks of DDL queries executed by the worker. + bool isDDLWorkerCurrentlyActive() const; void restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper); void reinitializeDDLWorker(); @@ -257,9 +266,20 @@ class DatabaseReplicated : public DatabaseAtomic std::atomic_bool is_probably_dropped = false; std::atomic_bool is_recovering = false; std::atomic_bool ddl_worker_initialized = false; - std::unique_ptr ddl_worker; + /// Shared, so that a query thread that uses the worker outside of `ddl_worker_mutex` (e.g. waiting in + /// `tryEnqueueAndExecuteEntry`) keeps it alive while `shutdown`, `restoreDatabaseInKeeper` or + /// `reinitializeDDLWorker` concurrently stop and replace it. Such a thread must take its own reference + /// under the mutex with `tryGetDDLWorker` and never dereference this member without the lock. + std::shared_ptr ddl_worker; mutable std::mutex ddl_worker_mutex; + /// Protects only the `ddl_worker` pointer itself: it is assigned under both mutexes and can be read under either. + /// Unlike `ddl_worker_mutex`, it is never held while the worker is shut down (and its threads are joined), + /// so the callbacks of DDL queries (`commitCreateTable`, `dropTable`, ...) can take it with `isDDLWorkerCurrentlyActive` + /// even when they are executed by the worker's threads or concurrently with `SYSTEM RESTORE DATABASE REPLICA`. + mutable std::mutex ddl_worker_ptr_mutex; UInt32 max_log_ptr_at_creation = 0; + /// Serializes `restoreDatabaseInKeeper`. Taken before `ddl_worker_mutex`. + std::mutex restore_in_keeper_mutex; /// Usually operation with metadata are single-threaded because of the way replication works, /// but StorageReplicatedMergeTree may call alterTable outside from DatabaseReplicatedDDLWorker causing race conditions. diff --git a/src/Databases/DatabaseReplicatedWorker.cpp b/src/Databases/DatabaseReplicatedWorker.cpp index 9112adf427d9..b3e7c1edd804 100644 --- a/src/Databases/DatabaseReplicatedWorker.cpp +++ b/src/Databases/DatabaseReplicatedWorker.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -49,6 +50,7 @@ namespace FailPoints extern const char database_replicated_delay_recovery[]; extern const char database_replicated_delay_entry_execution[]; extern const char database_replicated_stop_entry_execution[]; + extern const char database_replicated_pause_before_initial_query_execution[]; } @@ -160,9 +162,35 @@ void DatabaseReplicatedDDLWorker::shutdown() active_node_holder.reset(); active_node_holder_zookeeper.reset(); + /// Waiters in `tryEnqueueAndExecuteEntry` and `waitForReplicaToProcessAllEntries` (which may outlive the + /// shutdown, holding a reference to this worker) check `stop_flag` under `mutex`. Taking it before notifying + /// guarantees that each of them either sees the flag or receives the notification. + { + std::lock_guard lock{mutex}; + for (const auto & event : log_ptr_waiters) + event->set(); + } + wait_current_task_change.notify_all(); +} + +void DatabaseReplicatedDDLWorker::stopInitialQueries() +{ + { + std::lock_guard lock{mutex}; + initial_queries_stopped = true; + } wait_current_task_change.notify_all(); } +void DatabaseReplicatedDDLWorker::waitForForegroundTasks() +{ + std::unique_lock lock{mutex}; + chassert(stop_flag || initial_queries_stopped); + if (foreground_tasks) + LOG_TRACE(log, "Waiting for {} admitted initial queries", foreground_tasks); + foreground_tasks_finished.wait(lock, [&] { return foreground_tasks == 0; }); +} + void DatabaseReplicatedDDLWorker::initializeReplication() { /// Check if we need to recover replica. @@ -357,19 +385,31 @@ bool DatabaseReplicatedDDLWorker::waitForReplicaToProcessAllEntries(UInt64 timeo return zookeeper->expired() || current_task >= max_log || stop_flag; }); - if (!processed) + if (!processed || stop_flag) return false; } - /// Lets now wait for max_log_ptr to be processed - Coordination::Stat stat; + /// Lets now wait for max_log_ptr to be processed. + /// The event is set either by the watch or by `shutdown`, so a stopped worker does not wait for the whole timeout. auto event_ptr = std::make_shared(); + { + std::lock_guard lock{mutex}; + if (stop_flag) + return false; + log_ptr_waiters.insert(event_ptr); + } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + log_ptr_waiters.erase(event_ptr); + }); + + Coordination::Stat stat; auto new_log = zookeeper->get(our_log_ptr_path, &stat, event_ptr); if (new_log == toString(max_log_ptr)) return true; - return event_ptr->tryWait(timeout_ms); + return event_ptr->tryWait(timeout_ms) && !stop_flag; } @@ -473,9 +513,9 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr { assert(zookeeper->expired() || current_task <= entry_name); - if (zookeeper->expired() || stop_flag) + if (zookeeper->expired() || stop_flag || initial_queries_stopped) { - LOG_TRACE(log, "Not enqueueing query: {}", stop_flag ? "replication stopped" : "ZooKeeper session expired"); + LOG_TRACE(log, "Not enqueueing query: {}", zookeeper->expired() ? "ZooKeeper session expired" : "replication stopped"); throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "ZooKeeper session expired or replication stopped, try again"); } @@ -491,8 +531,21 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr if (!processed) throw Exception(ErrorCodes::UNFINISHED, "Timeout: Cannot enqueue query on this replica, " "most likely because replica is busy with previous queue entries"); + + /// The predicate above has checked `stop_flag` and `initial_queries_stopped` under `mutex`, + /// so `waitForForegroundTasks` will wait for this query. + ++foreground_tasks; } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + --foreground_tasks; + if (foreground_tasks == 0) + foreground_tasks_finished.notify_all(); + }); + + FailPointInjection::pauseFailPoint(FailPoints::database_replicated_pause_before_initial_query_execution); + if (entry.parent_table_uuid.has_value() && !checkParentTableExists(entry.parent_table_uuid.value())) throw Exception(ErrorCodes::TABLE_IS_DROPPED, "Parent table doesn't exist"); diff --git a/src/Databases/DatabaseReplicatedWorker.h b/src/Databases/DatabaseReplicatedWorker.h index 5583f112662f..1f03d0722955 100644 --- a/src/Databases/DatabaseReplicatedWorker.h +++ b/src/Databases/DatabaseReplicatedWorker.h @@ -2,6 +2,9 @@ #include #include #include +#include + +#include namespace DB { @@ -31,8 +34,21 @@ class DatabaseReplicatedDDLWorker : public DDLWorker void shutdown() override; + /// Returns false on timeout or if the worker is stopped before or during the wait. bool waitForReplicaToProcessAllEntries(UInt64 timeout_ms); + /// The worker was shut down. A stopped worker is never restarted, the database replaces it with a new one. + bool isStopped() const { return stop_flag; } + + /// Makes `tryEnqueueAndExecuteEntry` reject new initial queries (as if the worker was stopped), + /// while the worker itself keeps running. Irreversible: the database replaces such a worker afterwards. + void stopInitialQueries(); + + /// Waits until the initial queries that `tryEnqueueAndExecuteEntry` admitted for execution finish. + /// They execute and commit on the submitting threads, so `shutdown` (which joins only the worker's + /// own threads) does not wait for them. Requires `stopInitialQueries` or `shutdown` to be called before. + void waitForForegroundTasks(); + static String enqueueQueryImpl(const ZooKeeperPtr & zookeeper, DDLLogEntry & entry, DatabaseReplicated * const database, bool committed = false, Coordination::Requests additional_checks = {}); /// NOLINT @@ -68,6 +84,15 @@ class DatabaseReplicatedDDLWorker : public DDLWorker std::condition_variable wait_current_task_change; String current_task; + /// The number of initial queries being executed by `tryEnqueueAndExecuteEntry` on the submitting threads. + /// Protected by `mutex`, see `waitForForegroundTasks`. + size_t foreground_tasks = 0; + std::condition_variable foreground_tasks_finished; + /// Set by `stopInitialQueries`. Protected by `mutex`. + bool initial_queries_stopped = false; + /// Events of `waitForReplicaToProcessAllEntries` waiting for our `log_ptr` in Keeper to change. + /// `shutdown` sets them, so that the waiters return without waiting for the timeout. + std::unordered_set> log_ptr_waiters; std::atomic logs_to_keep = std::numeric_limits::max(); std::atomic_bool unsynced_after_recovery = false; diff --git a/src/Databases/MySQL/DatabaseMySQL.cpp b/src/Databases/MySQL/DatabaseMySQL.cpp index 1c85c1ef38d7..ce3ca3203f83 100644 --- a/src/Databases/MySQL/DatabaseMySQL.cpp +++ b/src/Databases/MySQL/DatabaseMySQL.cpp @@ -38,6 +38,7 @@ # include # include # include +# include # include #if CLICKHOUSE_CLOUD @@ -643,6 +644,14 @@ void registerDatabaseMySQL(DatabaseFactory & factory) configuration.username = safeGetLiteralValue(arguments[2], engine_name); configuration.password = safeGetLiteralValue(arguments[3], engine_name); } + + /// Skip only the server's own metadata replay. + if (!(args.is_metadata_replay && args.mode >= LoadingStrictnessLevel::ATTACH)) + { + for (const auto & address : configuration.addresses) + args.context->getRemoteHostFilter().checkHostAndPort(address.first, toString(address.second)); + } + mysql_settings->loadFromQueryContext(args.context, *engine_define); if (engine_define->settings) mysql_settings->loadFromQuery(*engine_define); diff --git a/src/Dictionaries/MongoDBDictionarySource.cpp b/src/Dictionaries/MongoDBDictionarySource.cpp index 437dc9639d5b..21fc0088c6ba 100644 --- a/src/Dictionaries/MongoDBDictionarySource.cpp +++ b/src/Dictionaries/MongoDBDictionarySource.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -45,7 +46,7 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) Block & sample_block, ContextPtr context, const std::string & /* default_database */, - bool /* created_from_ddl */) + bool created_from_ddl) { const auto config_prefix = root_config_prefix + ".mongodb"; auto configuration = std::make_shared(); @@ -102,6 +103,10 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) configuration->checkHosts(context); configuration->checkCollection(); + /// A DDL dictionary is loaded by the server with the global context, so no session setting can permit server credentials here. + if (created_from_ddl && context->getApplicationType() != Context::ApplicationType::LOCAL) + configuration->checkServerCredentialsForDictionary(); + return std::make_unique(dict_struct, std::move(configuration), std::make_shared(sample_block)); }; #else diff --git a/src/Dictionaries/SSDCacheDictionaryStorage.h b/src/Dictionaries/SSDCacheDictionaryStorage.h index e6a732ef34a1..afbf9c3170e2 100644 --- a/src/Dictionaries/SSDCacheDictionaryStorage.h +++ b/src/Dictionaries/SSDCacheDictionaryStorage.h @@ -1370,9 +1370,10 @@ class SSDCacheDictionaryStorage final : public ICacheDictionaryStorage if (memory_buffer_partitions.size() < configuration.max_partitions_count) { /// Try tro create next partition without reusing old partitions - ++current_partition_index; file_buffer.allocateSizeForNextPartition(); memory_buffer_partitions.emplace_back(configuration.block_size, configuration.write_buffer_blocks_size); + /// Advance only after both calls succeed, so the index stays valid if one of them throws. + ++current_partition_index; } else { diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp index 41e7a8ced5cf..cc7273537fa2 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp @@ -88,6 +88,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int AZURE_BLOB_STORAGE_ERROR; extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; } @@ -227,6 +228,28 @@ String ConnectionParams::getConnectionURL() const return endpoint.storage_account_url; } +String ConnectionParams::getConnectionURLWithoutQuery() const +{ + if (std::holds_alternative(auth_method)) + { + try + { + /// `ParseConnectionString` appends the SAS of the connection string to `BlobServiceUrl` as its query. + auto url = Azure::Storage::_internal::ParseConnectionString(endpoint.storage_account_url).BlobServiceUrl; + const auto query = url.GetQueryParameters(); + for (const auto & [key, value] : query) + url.RemoveQueryParameter(key); + return url.GetAbsoluteUrl(); + } + catch (const std::logic_error & e) + { + translateAzureSdkParseError(e); + } + } + + return endpoint.storage_account_url.substr(0, endpoint.storage_account_url.find_first_of("?#")); +} + std::unique_ptr ConnectionParams::createForService() const { try @@ -359,6 +382,13 @@ std::unique_ptr getContainerClient(const ConnectionParams & par } } +String getETag(const Azure::ETag & etag, const String & blob_path) +{ + if (!etag.HasValue()) + throw Exception(ErrorCodes::AZURE_BLOB_STORAGE_ERROR, "Azure Blob Storage endpoint did not return an ETag for blob {}", blob_path); + return etag.ToString(); +} + AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { if (config.has(config_prefix + ".account_key") && config.has(config_prefix + ".account_name")) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h index b282df96fae8..7387f59df565 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h @@ -146,6 +146,8 @@ struct ConnectionParams String getContainer() const { return endpoint.container_name; } String getConnectionURL() const; + /// Without the query, which can be a SAS, for where the url only names the endpoint (logs, errors, cache keys). + String getConnectionURLWithoutQuery() const; std::unique_ptr createForService() const; std::unique_ptr createForContainer() const; @@ -163,6 +165,10 @@ BlobClientOptions getClientOptions( AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); +/// `ETag` is an optional response header, and `Azure::ETag::ToString` aborts the process when the tag is absent +/// (also in release builds). Use this function instead: it throws an exception when the endpoint did not send the tag. +String getETag(const Azure::ETag & etag, const String & blob_path); + #endif Endpoint processEndpoint(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp index 80d0714c83ab..d59df48d18a7 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp @@ -100,7 +100,7 @@ class AzureIteratorAsync final : public IObjectStorageIteratorAsync .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); @@ -209,7 +209,7 @@ void AzureObjectStorage::listObjects(const std::string & path, RelativePathsWith .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); diff --git a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp index 241e8c8f7550..ec6a692f6fe6 100644 --- a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp +++ b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp @@ -81,6 +81,7 @@ AsynchronousBoundedReadBuffer::AsynchronousBoundedReadBuffer( { use_page_cache = true; buffer_size = read_settings.page_cache_block_size; + padded = false; } LOG_TEST(log, "Using buffer size {} while reading {}", buffer_size, file_name); diff --git a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp index 672d1bfbf8fb..f206567eea2a 100644 --- a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp +++ b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp @@ -431,7 +431,7 @@ void ReadBufferFromAzureBlobStorage::setMetadataFromResponse(const Azure::Storag { ObjectMetadata new_metadata; new_metadata.size_bytes = blob_size; - new_metadata.etag = details.ETag.ToString(); + new_metadata.etag = AzureBlobStorage::getETag(details.ETag, path); new_metadata.last_modified = static_cast(details.LastModified).time_since_epoch().count(); if (!details.Metadata.empty()) { diff --git a/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp new file mode 100644 index 000000000000..161256caba5b --- /dev/null +++ b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp @@ -0,0 +1,106 @@ +#include "config.h" + +#if USE_AZURE_BLOB_STORAGE + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int AZURE_BLOB_STORAGE_ERROR; +} + +namespace +{ + +class OwningBodyStream : public Azure::Core::IO::BodyStream +{ +public: + explicit OwningBodyStream(std::vector data_) : data(std::move(data_)) { } + + int64_t Length() const override { return static_cast(data.size()); } + + void Rewind() override { position = 0; } + +private: + size_t OnRead(uint8_t * buffer, size_t count, const Azure::Core::Context &) override + { + const size_t to_read = std::min(count, data.size() - position); + if (to_read != 0) + memcpy(buffer, data.data() + position, to_read); + position += to_read; + return to_read; + } + + std::vector data; + size_t position = 0; +}; + +/// A fake Azure endpoint that serves a 10-byte blob in a response without the optional `ETag` header. +class EndpointWithoutETag : public Azure::Core::Http::HttpTransport +{ +public: + std::unique_ptr Send(Azure::Core::Http::Request &, const Azure::Core::Context &) override + { + constexpr size_t blob_size = 10; + auto response = std::make_unique( + 1, 1, Azure::Core::Http::HttpStatusCode::PartialContent, "Partial Content"); + response->SetHeader("Content-Length", std::to_string(blob_size)); + response->SetHeader("Content-Range", "bytes 0-" + std::to_string(blob_size - 1) + "/" + std::to_string(blob_size)); + response->SetHeader("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT"); + response->SetHeader("x-ms-blob-type", "BlockBlob"); + response->SetBodyStream(std::make_unique(std::vector(blob_size, 'a'))); + return response; + } +}; + +} + +/// `Azure::ETag::ToString` aborts the process on an absent tag, also in release builds. +/// A download response without `ETag` must fail the read with an exception instead. +TEST(AzureReadBuffer, MissingETagIsAnException) +{ + Azure::Storage::Blobs::BlobClientOptions client_options; + client_options.Retry.MaxRetries = 0; + client_options.Transport.Transport = std::make_shared(); + + auto container_client = std::make_shared( + Azure::Storage::Blobs::BlobContainerClient("http://azure.invalid/container", client_options), /* blob_prefix */ ""); + + DB::ReadBufferFromAzureBlobStorage buffer( + container_client, + "blob", + DB::ReadSettings{}, + /* max_single_read_retries */ 1, + /* max_single_download_retries */ 1); + + std::optional error_code; + try + { + std::string data; + DB::readStringUntilEOF(data, buffer); + } + catch (const DB::Exception & e) + { + error_code = e.code(); + } + ASSERT_EQ(error_code, std::optional(DB::ErrorCodes::AZURE_BLOB_STORAGE_ERROR)); +} + +#endif diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index 807bf03ce4f7..d82cf35bef76 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -313,6 +313,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se format_settings.arrow.output_fixed_string_as_fixed_byte_array = settings[Setting::output_format_arrow_fixed_string_as_fixed_byte_array]; format_settings.arrow.output_compression_method = settings[Setting::output_format_arrow_compression_method]; format_settings.arrow.output_date_as_uint16 = settings[Setting::output_format_arrow_date_as_uint16]; + format_settings.arrow.output_max_record_batch_bytes = settings[Setting::output_format_arrow_max_record_batch_size_bytes]; format_settings.orc.allow_missing_columns = settings[Setting::input_format_orc_allow_missing_columns]; format_settings.orc.row_batch_size = settings[Setting::input_format_orc_row_batch_size]; format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference = settings[Setting::input_format_orc_skip_columns_with_unsupported_types_in_schema_inference]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 8cc2792c21f8..7ad2d29e34f3 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -5,9 +5,15 @@ #include #include +#include + namespace DB { +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, and the Apache Arrow +/// builders additionally reject the last representable value. +constexpr UInt64 MAX_ARROW_BUFFER_SIZE = std::numeric_limits::max() - 1; + /** * Various tweaks for input/output formats. Text serialization/deserialization * of data types also depend on some of these settings. It is different from @@ -166,6 +172,8 @@ struct FormatSettings bool output_fixed_string_as_fixed_byte_array = true; ArrowCompression output_compression_method = ArrowCompression::NONE; bool output_date_as_uint16 = false; + /// Upper bound on one record batch. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; } arrow{}; struct diff --git a/src/Formats/ProtobufSerializer.cpp b/src/Formats/ProtobufSerializer.cpp index 420d951ed7c0..49089ea851d0 100644 --- a/src/Formats/ProtobufSerializer.cpp +++ b/src/Formats/ProtobufSerializer.cpp @@ -4122,6 +4122,9 @@ namespace if (!name_and_type) return std::nullopt; const auto * tuple_type = assert_cast(name_and_type->type.get()); + /// The key or the value of the map entry was skipped as unsupported, so the map is skipped as a whole. + if (tuple_type->getElements().size() != 2) + return std::nullopt; return NameAndTypePair{name_and_type->name, std::make_shared(tuple_type->getElements())}; } diff --git a/src/Functions/HasSubsequenceImpl.h b/src/Functions/HasSubsequenceImpl.h index 30a522ea50a6..17f370e68344 100644 --- a/src/Functions/HasSubsequenceImpl.h +++ b/src/Functions/HasSubsequenceImpl.h @@ -127,6 +127,8 @@ class HasSubsequenceImpl : public IFunction if (!needle_size) return 1; + if (!haystack_size) + return 0; auto haystack_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(haystack_pos), haystack_end - haystack_pos); auto needle_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(needle_pos), needle_end - needle_pos); diff --git a/src/Functions/URL/protocol.h b/src/Functions/URL/protocol.h index 5e90f538ff1e..5542458a75d9 100644 --- a/src/Functions/URL/protocol.h +++ b/src/Functions/URL/protocol.h @@ -10,6 +10,9 @@ namespace DB /// Extracts scheme from given url. inline std::string_view getURLScheme(const char * data, size_t size) { + if (size == 0) + return {}; + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) const char * pos = data; const char * end = data + size; diff --git a/src/IO/CachedInMemoryReadBufferFromFile.cpp b/src/IO/CachedInMemoryReadBufferFromFile.cpp index c3241d65aede..c2489460cad5 100644 --- a/src/IO/CachedInMemoryReadBufferFromFile.cpp +++ b/src/IO/CachedInMemoryReadBufferFromFile.cpp @@ -26,6 +26,8 @@ CachedInMemoryReadBufferFromFile::CachedInMemoryReadBufferFromFile( , inner_read_until_position(read_until_position) { cache_key.offset = 0; + /// The working buffer is a page cache cell, an exact-size allocation: nothing past its end is readable. + padded = false; } String CachedInMemoryReadBufferFromFile::getFileName() const diff --git a/src/IO/ReadWriteBufferFromHTTP.cpp b/src/IO/ReadWriteBufferFromHTTP.cpp index 02834987d538..29d108ac9ca2 100644 --- a/src/IO/ReadWriteBufferFromHTTP.cpp +++ b/src/IO/ReadWriteBufferFromHTTP.cpp @@ -28,7 +28,8 @@ bool isRetriableError(const Poco::Net::HTTPResponse::HTTPStatus http_status) noe Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND, Poco::Net::HTTPResponse::HTTPStatus::HTTP_FORBIDDEN, Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_IMPLEMENTED, - Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED}; + Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED, + Poco::Net::HTTPResponse::HTTPStatus::HTTP_CONFLICT}; return std::all_of( non_retriable_errors.begin(), non_retriable_errors.end(), [&](const auto status) { return http_status != status; }); diff --git a/src/IO/S3/Client.cpp b/src/IO/S3/Client.cpp index 33dd73a0f579..8e09316d4de7 100644 --- a/src/IO/S3/Client.cpp +++ b/src/IO/S3/Client.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -78,6 +79,7 @@ namespace Setting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; extern const int TOO_MANY_REDIRECTS; } @@ -1196,6 +1198,21 @@ std::unique_ptr ClientFactory::create( // NOLINT if (!server_side_encryption_customer_key_base64.empty()) { + /// `base64Decode` throws on characters outside the alphabet but skips whitespace and ignores padding bits, + /// so the round trip below accepts only the canonical base64 of an AES-256 key, the only key SSE-C takes. + String customer_key; + try + { + customer_key = base64Decode(server_side_encryption_customer_key_base64); + } + catch (const Poco::DataFormatException &) + { + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + } + + if (customer_key.size() != AES256_KEY_BYTES || base64Encode(customer_key) != server_side_encryption_customer_key_base64) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + /// See Client::GeneratePresignedUrlWithSSEC(). headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, @@ -1204,10 +1221,8 @@ std::unique_ptr ClientFactory::create( // NOLINT headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, server_side_encryption_customer_key_base64}); - Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode(server_side_encryption_customer_key_base64); - String str_buffer(reinterpret_cast(buffer.GetUnderlyingData()), buffer.GetLength()); headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, - Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(str_buffer))}); + Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(customer_key))}); } // These will be added after request signing diff --git a/src/IO/S3/Client.h b/src/IO/S3/Client.h index 61ee4ead3dc0..ac7fd172617b 100644 --- a/src/IO/S3/Client.h +++ b/src/IO/S3/Client.h @@ -333,6 +333,8 @@ class Client : private Aws::S3::S3Client class ClientFactory { public: + static constexpr size_t AES256_KEY_BYTES = 32; + ~ClientFactory(); static ClientFactory & instance(); diff --git a/src/IO/SharedThreadPools.cpp b/src/IO/SharedThreadPools.cpp index c299fc8175e5..29e65bf483a8 100644 --- a/src/IO/SharedThreadPools.cpp +++ b/src/IO/SharedThreadPools.cpp @@ -43,6 +43,9 @@ namespace CurrentMetrics extern const Metric MergeTreeSnapshotCommitThreads; extern const Metric MergeTreeSnapshotCommitThreadsActive; extern const Metric MergeTreeSnapshotCommitThreadsScheduled; + extern const Metric ParquetEncoderThreads; + extern const Metric ParquetEncoderThreadsActive; + extern const Metric ParquetEncoderThreadsScheduled; } namespace DB @@ -236,4 +239,10 @@ StaticThreadPool & getFormatParsingThreadPool() return instance; } +StaticThreadPool & getParquetEncoderThreadPool() +{ + static StaticThreadPool instance("ParquetEncoderThreadPool", CurrentMetrics::ParquetEncoderThreads, CurrentMetrics::ParquetEncoderThreadsActive, CurrentMetrics::ParquetEncoderThreadsScheduled); + return instance; +} + } diff --git a/src/IO/SharedThreadPools.h b/src/IO/SharedThreadPools.h index 505688083347..2e8d17d2529c 100644 --- a/src/IO/SharedThreadPools.h +++ b/src/IO/SharedThreadPools.h @@ -91,4 +91,6 @@ StaticThreadPool & getMergeTreePrefixesDeserializationThreadPool(); StaticThreadPool & getFormatParsingThreadPool(); +StaticThreadPool & getParquetEncoderThreadPool(); + } diff --git a/src/IO/tests/gtest_brotli_decoder.cpp b/src/IO/tests/gtest_brotli_decoder.cpp new file mode 100644 index 000000000000..d7b8ade6a3f3 --- /dev/null +++ b/src/IO/tests/gtest_brotli_decoder.cpp @@ -0,0 +1,58 @@ +#include "config.h" + +#if USE_BROTLI + +#include +#include + +#include +#include +#include +#include +#include + +TEST(BrotliDecoder, RejectInvalidBlockSwitch) +{ + // A block switch is invalid when the stream declares only one block type. + // From https://github.com/nodejs/node/blob/main/test/parallel/test-zlib-invalid-input.js. + constexpr std::array input = { + 0x20, 0x00, 0x10, 0x41, 0x41, 0x41, 0xfc, 0xff, 0xff, 0x07, 0x00, + 0x22, 0x28, 0xf0, 0x0b, 0x60, 0xf7, 0xf4, 0x1f, 0x00, 0x00, 0x00}; + + for (size_t chunk_size : {input.size(), size_t{1}}) + { + std::unique_ptr state( + BrotliDecoderCreateInstance(nullptr, nullptr, nullptr), &BrotliDecoderDestroyInstance); + ASSERT_NE(state.get(), nullptr); + + std::array output{}; + size_t total_output = 0; + BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + + for (size_t offset = 0; offset < input.size() && result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;) + { + size_t available_input = std::min(chunk_size, input.size() - offset); + const size_t provided_input = available_input; + const uint8_t * next_input = input.data() + offset; + do + { + uint8_t * next_output = output.data(); + size_t available_output = output.size(); + result = BrotliDecoderDecompressStream( + state.get(), &available_input, &next_input, &available_output, &next_output, nullptr); + total_output += output.size() - available_output; + ASSERT_LT(total_output, 64 * 1024 * 1024); + } + while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT); + offset += provided_input - available_input; + if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) + ASSERT_GT(provided_input - available_input, 0); + } + + EXPECT_EQ(result, BROTLI_DECODER_RESULT_ERROR); + // -17 is the `BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH` code added by the fix. + EXPECT_EQ(BrotliDecoderGetErrorCode(state.get()), static_cast(-17)); + } +} + +#endif diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index 8aa24023956f..b5599a2b6ee6 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -124,12 +124,18 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_) : query(query_->clone()) , query_str_with_secrets(query->formatWithSecretsOneLine()) , user_id(user_id_) , current_roles(current_roles_) + , current_user(current_user_) + , initial_user(initial_user_) + , authenticated_user(authenticated_user_) , settings(std::make_unique(settings_)) , data_kind(data_kind_) { @@ -147,6 +153,13 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( } } + /// Length-prefix each field: update(String) streams only bytes and the queue is keyed + /// by hash alone, so otherwise "a"/"a"/"aaa" and "aa"/"aa"/"a" would collide. + for (const String & identity_field : {current_user, initial_user, authenticated_user}) + { + siphash.update(identity_field.size()); + siphash.update(identity_field); + } setting_changes = settings->changes(); for (auto it = setting_changes.begin(); it != setting_changes.end();) @@ -172,6 +185,9 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -187,6 +203,9 @@ AsynchronousInsertQueue::InsertQuery::operator=(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -533,7 +552,16 @@ AsynchronousInsertQueue::PushResult AsynchronousInsertQueue::pushDataChunk(ASTPt if (insert_query.format == "Values") entry->query_parameters = query_context->getQueryParameters(); - InsertQuery key{query, query_context->getUserID(), query_context->getCurrentRoles(), settings, data_kind}; + const auto & client_info = query_context->getClientInfo(); + InsertQuery key{ + query, + query_context->getUserID(), + query_context->getCurrentRoles(), + client_info.current_user, + client_info.initial_user, + client_info.authenticated_user, + settings, + data_kind}; InsertDataPtr data_to_process; std::future progress_future; @@ -980,6 +1008,14 @@ try insert_context->setCurrentRoles(key.current_roles); } + /// Context::setUser only restores the access-control identity, not the ClientInfo user + /// names. Restore them from the originating query so currentUser()/user()/ + /// authenticatedUser() and the materialized views triggered by the flush observe the + /// inserting user instead of an empty string. + insert_context->setCurrentUserName(key.current_user); + insert_context->setInitialUserName(key.initial_user); + insert_context->setAuthenticatedUserName(key.authenticated_user); + insert_context->setSettings(*key.settings); /// Set initial_query_id, because it's used in InterpreterInsertQuery for table lock. diff --git a/src/Interpreters/AsynchronousInsertQueue.h b/src/Interpreters/AsynchronousInsertQueue.h index 81a6fb36ab6f..f9eed199e90a 100644 --- a/src/Interpreters/AsynchronousInsertQueue.h +++ b/src/Interpreters/AsynchronousInsertQueue.h @@ -85,6 +85,14 @@ class AsynchronousInsertQueue : public WithContext String query_str_with_secrets; std::optional user_id; std::vector current_roles; + /// Client identity of the originating INSERT query (ClientInfo user names). + /// Restored on the flush context so currentUser()/user()/authenticatedUser() and + /// the materialized views triggered by the flush observe the inserting user instead + /// of an empty string. Part of the batching key so inserts from different identities + /// (e.g. impersonation, forwarded distributed queries) are never coalesced. + String current_user; + String initial_user; + String authenticated_user; std::unique_ptr settings; AsynchronousInsertQueueDataKind data_kind; @@ -94,6 +102,9 @@ class AsynchronousInsertQueue : public WithContext const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_); @@ -103,7 +114,7 @@ class AsynchronousInsertQueue : public WithContext StorageID getStorageID() const; private: - auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, setting_changes); } + auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, current_user, initial_user, authenticated_user, setting_changes); } std::vector setting_changes; }; diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index aa63ec626fc7..c3f710e251d1 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1192,6 +1192,15 @@ void ContextSharedMutex::lockSharedImpl() ProfileEvents::increment(ProfileEvents::ContextLockWaitMicroseconds, watch.elapsedMicroseconds()); } +/// An entry of `ContextData::scalars`. `from_client` is true when the block arrived from the client +/// over the wire (`Context::addClientScalar`) rather than being computed by the server, so that +/// `Context::hasComputedScalar` can keep such a block out of the analyzer's scalar-subquery cache. +struct ScalarEntry +{ + Block block; + bool from_client = false; +}; + ContextData::ContextData() { settings = std::make_unique(); @@ -2383,7 +2392,10 @@ std::pair Context::setConcurrentThreadsSoftLimit(UInt64 num, UIn Scalars Context::getScalars() const { std::lock_guard lock(mutex); - return scalars; + Scalars res; + for (const auto & [name, entry] : scalars) + res.emplace(name, entry.block); + return res; } @@ -2398,7 +2410,7 @@ Block Context::getScalar(const String & name) const // often, so 'bad arguments' for now. throw Exception(ErrorCodes::BAD_ARGUMENTS, "Scalar {} doesn't exist (internal bug)", backQuoteIfNeed(name)); } - return it->second; + return it->second.block; } std::optional Context::tryGetSpecialScalar(const String & name) const @@ -2528,7 +2540,18 @@ void Context::addScalar(const String & name, const Block & block) throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); std::lock_guard lock(mutex); - scalars[name] = block; + /// A server-computed value overrides any client-supplied one of the same name and is trusted. + scalars[name] = ScalarEntry{block, /*from_client=*/ false}; +} + + +void Context::addClientScalar(const String & name, const Block & block) +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + scalars[name] = ScalarEntry{block, /*from_client=*/ true}; } @@ -2551,6 +2574,16 @@ bool Context::hasScalar(const String & name) const return scalars.contains(name); } +bool Context::hasComputedScalar(const String & name) const +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + auto it = scalars.find(name); + return it != scalars.end() && !it->second.from_client; +} + void Context::addQueryAccessInfo( const StorageID & table_id, const Names & column_names) @@ -3201,6 +3234,13 @@ void Context::clampToSettingsConstraintsWithLock(SettingsChanges & changes, Sett doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); } +void Context::clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source) +{ + getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.clampRejectingInvalidChanges(*settings, changes, source); + if (getApplicationType() == ApplicationType::LOCAL || getApplicationType() == ApplicationType::SERVER) + doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); +} + void Context::checkMergeTreeSettingsConstraintsWithLock(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.check(merge_tree_settings, changes); @@ -3284,6 +3324,21 @@ void Context::clampToSettingsConstraints(SettingsChanges & changes, SettingSourc clampToSettingsConstraintsWithLock(changes, source); } +void Context::clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source) +{ + if (std::ranges::any_of(changes, isProfileChange)) + { + changes = enforceConstraintsAlongProfileChanges(shared_from_this(), changes, [source](Context & context, SettingsChanges & segment) + { + context.clampToSettingsConstraintsRejectingInvalidChanges(segment, source); + }); + return; + } + + SharedLockGuard lock(mutex); + clampToSettingsConstraintsRejectingInvalidChangesWithLock(changes, source); +} + void Context::checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { SharedLockGuard lock(mutex); @@ -6999,6 +7054,12 @@ void Context::setInitialUserName(const String & initial_user_name) need_recalculate_access = true; } +void Context::setAuthenticatedUserName(const String & authenticated_user_name) +{ + client_info.authenticated_user = authenticated_user_name; + need_recalculate_access = true; +} + void Context::setInitialAddress(const Poco::Net::SocketAddress & initial_address) { client_info.initial_address = std::make_shared(initial_address); diff --git a/src/Interpreters/Context.h b/src/Interpreters/Context.h index e2fcb1224695..d732882f83e9 100644 --- a/src/Interpreters/Context.h +++ b/src/Interpreters/Context.h @@ -164,6 +164,10 @@ class DDLWorker; class ITableFunction; using TableFunctionPtr = std::shared_ptr; class Block; +/// An entry of the query scalar map: the scalar block plus whether it came from the client. +/// Defined in Context.cpp, where `Block` is complete; here `std::map` only needs the forward +/// declaration, the same way `Scalars` is a `std::map` over the forward-declared `Block`. +struct ScalarEntry; class ActionLocksManager; using ActionLocksManagerPtr = std::shared_ptr; class ShellCommand; @@ -395,8 +399,13 @@ class ContextData String insert_format; /// Format, used in insert query. TemporaryTablesMapping external_tables_mapping; - /// Query scalars - Scalars scalars; + /// Query scalars. Each entry carries whether it was supplied by the client over the wire (the + /// `Scalar` packet, i.e. the `clickhouse-client --external ... --scalar` feature or an initiator + /// shipping scalars to a shard) rather than computed by the server itself. The origin travels with + /// the block so that the analyzer's scalar-subquery cache (which keys on the query-tree hash) never + /// mistakes a client-supplied block for an already-computed subquery result; without this a client + /// could forge the result of a scalar subquery used in a row policy and bypass the policy. + std::map scalars; /// Used to store constant values which are different on each instance during distributed plan, such as _shard_num. Scalars special_scalars; @@ -942,6 +951,7 @@ class Context: public ContextData, public std::enable_shared_from_this void setCurrentUserName(const String & current_user_name); void setCurrentAddress(const Poco::Net::SocketAddress & current_address); void setInitialUserName(const String & initial_user_name); + void setAuthenticatedUserName(const String & authenticated_user_name); void setInitialAddress(const Poco::Net::SocketAddress & initial_address); void setInitialQueryId(const String & initial_query_id); void setInitialQueryStartTime(std::chrono::time_point initial_query_start_time); @@ -981,6 +991,16 @@ class Context: public ContextData, public std::enable_shared_from_this void addScalar(const String & name, const Block & block); bool hasScalar(const String & name) const; + /// Add a scalar received from the client over the wire (the `Scalar` packet). Unlike `addScalar`, + /// the entry is marked as client-supplied so that `hasComputedScalar` will not report it as a + /// server-computed subquery result. Explicit readers (`__getScalar`, `_shard_num`, forwarding to + /// shards) still see it through `getScalar` / `hasScalar` / `getScalars`. + void addClientScalar(const String & name, const Block & block); + /// Like `hasScalar`, but returns true only for scalars the server computed itself, never for + /// client-supplied ones. The analyzer's scalar-subquery cache must use this so that a forged + /// client scalar cannot stand in for the result of a (e.g. row-policy) scalar subquery. + bool hasComputedScalar(const String & name) const; + std::optional tryGetSpecialScalar(const String & name) const; void addSpecialScalar(const String & name, const Block & block); @@ -1117,6 +1137,7 @@ class Context: public ContextData, public std::enable_shared_from_this /// For the resets of a statement that also changes `profile`: `changes_applied_first` decides their constraints. void checkSettingsConstraintsForSettingsReset(const std::vector & names, const SettingsChanges & changes_applied_first, SettingSource source); void clampToSettingsConstraints(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source); void checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const; /// Reset settings to default value @@ -1810,6 +1831,7 @@ class Context: public ContextData, public std::enable_shared_from_this void checkSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source); void checkSettingsConstraintsWithLock(const AlterSettingsProfileElements & profile_elements, SettingSource source) const; void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source) const; diff --git a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp index dc247f5119e3..bd217badfadf 100644 --- a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp +++ b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp @@ -156,7 +156,7 @@ void ExecuteScalarSubqueriesMatcher::visit(const ASTSubquery & subquery, ASTPtr } else { - if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasScalar(scalar_query_hash_str)) + if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasComputedScalar(scalar_query_hash_str)) { if (!data.getContext()->getViewSource()) { diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index 2ad408df7443..9976d55c6111 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -24,12 +25,17 @@ #include #include #include +#include #include #include +#include #include #include +#include #include +#include #include +#include #include #include #include @@ -62,6 +68,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int LOGICAL_ERROR; extern const int INCORRECT_QUERY; extern const int NOT_IMPLEMENTED; @@ -73,6 +80,83 @@ namespace ErrorCodes extern const int SUPPORT_IS_DISABLED; } +namespace +{ + +/// A setting that sends the table's data elsewhere copies the data as it is stored, so nothing can filter the rows +/// that a row policy hides. It reads only the query and the access entities, +/// not the table, so it runs on the initiator. The database is resolved only for such a setting, so that other queries +/// do not need a current database. +void checkNoRowPolicyForExport(const ASTAlterQuery & alter, const ContextPtr & context) +{ + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::MODIFY_SETTING || !command.settings_changes) + continue; + + const auto & changes = command.settings_changes->as().changes; + if (StorageFactory::instance().getExportAccessOfAnyEngine(changes).empty()) + continue; + + const String database = context->resolveDatabase(alter.getDatabase()); + auto row_policy_filter = context->getRowPolicyFilter(database, alter.getTable(), RowPolicyFilterType::SELECT_FILTER); + if (row_policy_filter && !row_policy_filter->isAlwaysTrue()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "Cannot change the settings of table {}.{} that send its data elsewhere because a row policy applies to it. " + "The data is copied as it is stored, so its rows cannot be filtered", + backQuoteIfNeed(database), backQuoteIfNeed(alter.getTable())); + } +} + +/// A `Replicated`-database host applies the statement without the submitting user. `ON CLUSTER` does +/// not reach this: it is refused unless its hosts run as the initiating user. +void checkAddedIndexPermissions(const ASTAlterQuery & alter, const StoragePtr & table, const ContextPtr & context) +{ + if (!table) + return; + + bool adds_transform = false; + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + + if (const auto * declaration = command.index_decl->as()) + if (hasTextIndexPreOrPostProcessor(*declaration)) + adds_transform = true; + } + + /// Against the schema the whole statement produces: a command of the same statement can change what + /// an alias in a transform expands to. Transforms only, so other statements get no extra analysis. + if (!adds_transform) + return; + + AlterCommands commands; + for (const auto & child : alter.command_list->children) + { + const auto * command_ast = child->as(); + if (command_ast->type == ASTAlterCommand::EXECUTE_COMMAND) + continue; + if (auto command = AlterCommand::parse(command_ast)) + commands.emplace_back(std::move(*command)); + } + + /// The same sequence as `executeToTable`: `apply` relies on the checks before it, and it authorizes + /// the added indices as the user. + StorageInMemoryMetadata metadata = table->getInMemoryMetadata(); + commands.validate(table, context); + commands.prepare(metadata); + table->checkAlterIsPossible(commands, context); + /// As the storages do before `apply`: an explicit `ADD STATISTICS` replaces an implicit one. + removeImplicitStatistics(metadata.columns); + commands.apply(metadata, context); +} + +} + InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, ContextMutablePtr context_) : WithMutableContext(context_), query_ptr(query_ptr_) { } @@ -130,15 +214,37 @@ BlockIO InterpreterAlterQuery::executeToTable(const ASTAlterQuery & alter) DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_alter = captured_query_ptr->as(); + for (const auto & child : captured_alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + if (const auto * declaration = command.index_decl->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + } + }; + /// The hosts run the entry without the user, so the row policy is checked here before the entry is enqueued. + checkNoRowPolicyForExport(alter, getContext()); return executeDDLQueryOnCluster(query_ptr, getContext(), params); } getContext()->checkAccess(getRequiredAccess()); + checkNoRowPolicyForExport(alter, getContext()); if (!table_id) throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(alter.getDatabase())); DatabasePtr database = DatabaseCatalog::instance().getDatabase(table_id.database_name); + + checkAddedIndexPermissions(alter, table, getContext()); + if (database->shouldReplicateQuery(getContext(), query_ptr)) { auto guard = DatabaseCatalog::instance().getDDLGuard(table_id.database_name, table_id.table_name, database.get()); @@ -624,6 +730,20 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand(const AS case ASTAlterCommand::MODIFY_SETTING: { required_access.emplace_back(AccessType::ALTER_SETTINGS, database, table); + + /// A setting that sends the table's data elsewhere, e.g. the move destination of a queue, is the same data flow as + /// `INSERT INTO FUNCTION s3(...) SELECT * FROM
`. The creator of the table supplied its source and credentials, + /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator + /// of `ON CLUSTER` can check them without the table. + if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) + { + auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + if (!export_access.empty()) + { + required_access.append_range(std::move(export_access)); + required_access.emplace_back(AccessType::SELECT, database, table); + } + } break; } case ASTAlterCommand::ATTACH_PARTITION: diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index 715a96ebc0b7..d0a1ce770c76 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -34,10 +34,12 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -146,6 +148,7 @@ namespace Setting namespace ServerSetting { + extern const ServerSettingsBool distributed_ddl_use_initial_user_and_roles; extern const ServerSettingsBool ignore_empty_sql_security_in_create_view_query; extern const ServerSettingsUInt64 max_database_num_to_throw; extern const ServerSettingsUInt64 max_dictionary_num_to_throw; @@ -988,6 +991,14 @@ InterpreterCreateQuery::TableProperties InterpreterCreateQuery::getTableProperti if (!create.columns_list) create.set(create.columns_list, make_intrusive()); + /// Authorize the text index transforms of every definition the user supplies now. A replay of stored + /// metadata is not checked, so such a table still attaches. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + { + for (const auto & index : properties.indices) + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + ASTPtr new_columns = formatColumns(properties.columns); ASTPtr new_indices = formatIndices(properties.indices); ASTPtr new_constraints = formatConstraints(properties.constraints); @@ -1714,6 +1725,11 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) /// Set and retrieve list of columns, indices and constraints. Set table engine if needed. Rewrite query in canonical way. TableProperties properties = getTablePropertiesAndNormalizeCreateQuery(create, mode); + /// Only here is an engine inherited through `AS` known, and nothing is enqueued or created yet. + /// A replay of a stored definition was checked when it was created. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + checkExportAccess(create); + DatabasePtr database; bool need_add_to_database = !create.isTemporary(); // In case of an ON CLUSTER query, the database may not be present on the initiator node @@ -2500,6 +2516,20 @@ BlockIO InterpreterCreateQuery::executeQueryOnCluster(ASTCreateQuery & create) prepareOnClusterQuery(create, getContext(), create.cluster); DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_create = captured_query_ptr->as(); + if (!captured_create.columns_list || !captured_create.columns_list->indices) + return; + + for (const auto & index : captured_create.columns_list->indices->children) + if (const auto * declaration = index->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + }; return executeDDLQueryOnCluster(query_ptr, getContext(), params); } @@ -2539,6 +2569,46 @@ BlockIO InterpreterCreateQuery::execute() if (inherited.storage && inherited.storage->engine) getContext()->checkAccess(AccessType::TABLE_ENGINE, inherited.storage->engine->name); + + /// setEngine copies only the outer engine of a `TimeSeries` source, and the worker copies + /// its inner engines while normalizing, so add the ones this query does not give itself + if (inherited.is_time_series_table) + { + auto as_create_ptr = DatabaseCatalog::instance().getDatabase(inherited.as_database)->getCreateTableQuery(inherited.as_table, getContext()); + const auto & as_create = as_create_ptr->as(); + if (as_create.targets) + for (const auto & target : as_create.targets->targets) + if (target.inner_engine && !inherited.getTargetInnerEngine(target.kind)) + inherited.setTargetInnerEngine(target.kind, target.inner_engine->clone()); + } + + /// the worker inherits the move destination of the source too, and runs with no user + checkExportAccess(inherited); + + /// A worker copies the source's indices with no user, so declare their transforms here. + if (inherited.storage && inherited.storage->engine && endsWith(inherited.storage->engine->name, "MergeTree")) + { + /// Before resolving it: an error below would otherwise disclose a source the user + /// cannot see. + getContext()->checkAccess(AccessType::SHOW_COLUMNS, create.as_database, create.as_table); + StoragePtr as_storage = resolveStorageProxyLoading( + DatabaseCatalog::instance().getTable({create.as_database, create.as_table}, getContext())); + /// The query dispatches `AS src`, so each host materializes its own source, which + /// may define the transform differently from the one authorized here. + const bool workers_use_initiator_user + = getContext()->getServerSettings()[ServerSetting::distributed_ddl_use_initial_user_and_roles] + && on_cluster_version >= DDLLogEntry::INITIATOR_USER_VERSION; + + auto as_storage_metadata = as_storage->getInMemoryMetadataPtr(); + for (const auto & index : as_storage_metadata->getSecondaryIndices()) + { + if (index.isImplicitlyCreated()) + continue; + if (!workers_use_initiator_user) + rejectTextIndexTransformWithoutInitiatorUser(index); + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + } } return executeQueryOnCluster(create); @@ -2623,9 +2693,28 @@ AccessRightsElements InterpreterCreateQuery::getRequiredAccess() const if (create.storage && create.storage->engine) required_access.emplace_back(AccessType::TABLE_ENGINE, create.storage->engine->name); + /// `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the table data and then moves it to the + /// data path of the new table. Reading it needs `READ` on the FILE source like the `file` function does, and + /// taking it away from `user_files` needs `WRITE`, like renaming files after processing does. Without this, + /// `CREATE TABLE` on a table of their own would let a user read or consume any data staged in `user_files`. + if (create.has_attach_from_path) + required_access.emplace_back(AccessType::READ | AccessType::WRITE, toStringSource(AccessTypeObjects::Source::FILE)); + + /// Settings that send the table's data elsewhere, e.g. the move destination of a queue, need the grants of that place. + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + return required_access; } +void InterpreterCreateQuery::checkExportAccess(const ASTCreateQuery & create) const +{ + /// Internal queries (initiated by the server itself) always have access to everything. + if (internal) + return; + + getContext()->checkAccess(StorageFactory::instance().getExportAccess(create)); +} + void InterpreterCreateQuery::extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr &, ContextPtr) const { if (!as_table_saved.empty()) diff --git a/src/Interpreters/InterpreterCreateQuery.h b/src/Interpreters/InterpreterCreateQuery.h index 9692dcdedbb6..674965cc7e00 100644 --- a/src/Interpreters/InterpreterCreateQuery.h +++ b/src/Interpreters/InterpreterCreateQuery.h @@ -112,6 +112,10 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext void setEngine(ASTCreateQuery & create) const; AccessRightsElements getRequiredAccess() const; + /// The part of `getRequiredAccess` for settings that send the table's data elsewhere, checked again once + /// `setEngine` has resolved an engine inherited through `AS`, which `getRequiredAccess` cannot see. + void checkExportAccess(const ASTCreateQuery & create) const; + /// Create IStorage and add it to database. If table already exists and IF NOT EXISTS specified, do nothing and return false. bool doCreateTable(ASTCreateQuery & create, const TableProperties & properties, DDLGuardPtr & ddl_guard, LoadingStrictnessLevel mode); BlockIO doCreateOrReplaceTable(ASTCreateQuery & create, const InterpreterCreateQuery::TableProperties & properties, LoadingStrictnessLevel mode); diff --git a/src/Interpreters/JIT/CHJIT.cpp b/src/Interpreters/JIT/CHJIT.cpp index 67c3068d0e0c..85609a0f5f07 100644 --- a/src/Interpreters/JIT/CHJIT.cpp +++ b/src/Interpreters/JIT/CHJIT.cpp @@ -427,7 +427,12 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function { std::lock_guard lock(jit_lock); - auto module = createModuleForCompilation(); + /// A fresh context per compile: `LLVMContext` never frees the constants it interns, and the optimizer + /// creates new ones for every distinct literal, so a long-lived context grows without bound. + /// Declared before `module`, which must be destroyed first. + auto context = std::make_unique(); + + auto module = createModuleForCompilation(*context); compile_function(*module); auto module_info = compileModule(std::move(module)); @@ -435,7 +440,7 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function return module_info; } -std::unique_ptr CHJIT::createModuleForCompilation() +std::unique_ptr CHJIT::createModuleForCompilation(llvm::LLVMContext & context) { std::unique_ptr module = std::make_unique("jit" + std::to_string(current_module_key), context); module->setDataLayout(layout); diff --git a/src/Interpreters/JIT/CHJIT.h b/src/Interpreters/JIT/CHJIT.h index 89d446fd3b34..04788222136e 100644 --- a/src/Interpreters/JIT/CHJIT.h +++ b/src/Interpreters/JIT/CHJIT.h @@ -89,7 +89,7 @@ class CHJIT private: - std::unique_ptr createModuleForCompilation(); + std::unique_ptr createModuleForCompilation(llvm::LLVMContext & context); CompiledModule compileModule(std::unique_ptr module); @@ -99,7 +99,6 @@ class CHJIT static std::unique_ptr getTargetMachine(); - llvm::LLVMContext context; std::unique_ptr machine; llvm::DataLayout layout; std::unique_ptr compiler; diff --git a/src/Interpreters/executeDDLQueryOnCluster.cpp b/src/Interpreters/executeDDLQueryOnCluster.cpp index 514f390e93ff..b2e6a3880daf 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.cpp +++ b/src/Interpreters/executeDDLQueryOnCluster.cpp @@ -194,6 +194,12 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, ContextPtr context, entry.initiator_user = context->getUserName(); entry.initiator_user_roles = context->getAccessControl().tryReadNames(context->getCurrentRoles()); } + + /// The workers run the query as the initiator's user and roles only if the entry carries them. + const bool workers_use_initiator_user = !entry.initiator_user.empty() && entry.version >= DDLLogEntry::INITIATOR_USER_VERSION; + if (params.additional_access_check) + params.additional_access_check(/* throw_if_unresolved = */ !workers_use_initiator_user); + ddl_worker.updateHostIDs(entry.hosts); String node_path = ddl_worker.enqueueQuery(entry, params.retries_info); diff --git a/src/Interpreters/executeDDLQueryOnCluster.h b/src/Interpreters/executeDDLQueryOnCluster.h index 69e0c38834e6..f98f9bb4aafc 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.h +++ b/src/Interpreters/executeDDLQueryOnCluster.h @@ -7,6 +7,8 @@ #include #include +#include + namespace zkutil { @@ -38,6 +40,12 @@ struct DDLQueryOnClusterParams /// Privileges which the current user should have to execute a query. AccessRightsElements access_to_check; + /// An authorization check which must run after the standard cluster and query checks but before enqueueing. + /// It receives whether the workers run the query without the initiator's user: they run it as that user and + /// roles only when `distributed_ddl_use_initial_user_and_roles` is enabled and `distributed_ddl_entry_format_version` + /// carries the initiator's user. + std::function additional_access_check; + /// Use retries when creating nodes "query-0000000000", "query-0000000001", "query-0000000002" in ZooKeeper. ZooKeeperRetriesInfo retries_info; }; diff --git a/src/Interpreters/tests/gtest_async_insert_key.cpp b/src/Interpreters/tests/gtest_async_insert_key.cpp index 0f4095a05bee..327525b4db5c 100644 --- a/src/Interpreters/tests/gtest_async_insert_key.cpp +++ b/src/Interpreters/tests/gtest_async_insert_key.cpp @@ -37,13 +37,59 @@ TEST(AsyncInsertKey, SettingsChanges) auto kind = AsynchronousInsertQueueDataKind::Parsed; - AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, settings1, kind); - AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, settings2, kind); - AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, settings3, kind); - AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, settings4, kind); + AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, {}, {}, {}, settings1, kind); + AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, {}, {}, {}, settings2, kind); + AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, {}, {}, {}, settings3, kind); + AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, {}, {}, {}, settings4, kind); EXPECT_EQ(key1, key2); EXPECT_NE(key1, key3); EXPECT_NE(key2, key3); EXPECT_NE(key3, key4); } + +TEST(AsyncInsertKey, IdentityHashIsNotAmbiguous) +{ + String query_str = "INSERT INTO test (a, b, c) VALUES (1, 2, 3)"; + ParserInsertQuery parser(query_str.data() + query_str.size(), false); + ASTPtr query = parseQuery(parser, query_str, DBMS_DEFAULT_MAX_QUERY_SIZE, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + Settings settings; + settings.set("async_insert", 1); + + auto kind = AsynchronousInsertQueueDataKind::Parsed; + + auto make_key = [&](const String & current_user, const String & initial_user, const String & authenticated_user) + { + return AsynchronousInsertQueue::InsertQuery( + query, {}, {}, current_user, initial_user, authenticated_user, settings, kind); + }; + + /// The three identity fields are variable-length strings folded into the queue key hash, + /// and the queue is indexed by hash alone. Without a length delimiter "a"/"a"/"aaa" and + /// "aa"/"aa"/"a" stream the same bytes ("aaaaa") and collide, which would route a second + /// user's insert into the first user's pending batch and flush it under the wrong + /// ClientInfo. The keys must differ both by hash and by equality. + auto key_a = make_key("a", "a", "aaa"); + auto key_b = make_key("aa", "aa", "a"); + EXPECT_NE(key_a.hash, key_b.hash); + EXPECT_NE(key_a, key_b); + + /// A field boundary shift across the current/initial split must also be distinguished. + auto key_c = make_key("a", "b", ""); + auto key_d = make_key("a", "", "b"); + EXPECT_NE(key_c.hash, key_d.hash); + EXPECT_NE(key_c, key_d); + + /// Same identity still hashes the same and compares equal (batching preserved). + auto key_e = make_key("alice", "alice", "alice"); + auto key_f = make_key("alice", "alice", "alice"); + EXPECT_EQ(key_e.hash, key_f.hash); + EXPECT_EQ(key_e, key_f); + + /// Distinct identities never coalesce. + auto key_g = make_key("alice", "alice", "alice"); + auto key_h = make_key("bob", "bob", "bob"); + EXPECT_NE(key_g.hash, key_h.hash); + EXPECT_NE(key_g, key_h); +} diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index 8509d3903c38..e2698652f3fc 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -72,6 +73,16 @@ namespace return AzureConnectionValue::PlainStorageAccountURL; } + /// The keys an Azure named collection accepts (`StorageAzureConfiguration`). An override with any + /// other key, which can name any credential, is rejected only after the statement is logged. + bool isAzureCollectionKey(std::string_view key) + { + static const std::unordered_set keys = {"blob_path", "container", "format", "compression", "structure", + "compression_method", "account_name", "account_key", "connection_string", "storage_account_url", "partition_strategy", + "partition_columns_in_data_file", "client_id", "tenant_id"}; + return keys.contains(key); + } + /// The backup engines whose locator names a destination with no credential in it, each with the /// argument count it accepts. `BackupFactory` registers exactly these plus `S3` and `AzureBlobStorage`. std::optional credentialFreeBackupEngineArity(const String & engine_name) @@ -607,43 +618,147 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageFunctionSecretArguments( /// azureBlobStorageCluster('cluster_name', 'conn_string/storage_account_url', ...) has 'conn_string/storage_account_url' as its second argument. size_t url_arg_idx = is_cluster_function ? 1 : 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + + /// The other values are hidden before a connection string is: hiding that replaces its whole argument. if (!is_cluster_function && isNamedCollectionName(0)) { /// azureBlobStorage(named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(1); + maskUnreadAzureCollectionOverrides(1); + findSecretNamedArgument("account_key", 1); if (maskAzureConnectionString(-1, true, 1)) return; - findSecretNamedArgument("account_key", 1); + maskUnshowableAzureConnectionOverrides(1); return; } if (is_cluster_function && isNamedCollectionName(1)) { /// azureBlobStorageCluster(cluster, named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(2); + maskUnreadAzureCollectionOverrides(2); + findSecretNamedArgument("account_key", 2); if (maskAzureConnectionString(-1, true, 2)) return; - findSecretNamedArgument("account_key", 2); + maskUnshowableAzureConnectionOverrides(2); return; } - if (maskAzureConnectionString(url_arg_idx)) + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + + if (const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx)) + markSecretArgument(*credential_arg_idx); + + if (maskAzureConnectionString(arg(url_arg_idx))) return; - /// We should check other arguments first because we don't need to do any replacement in case of - /// azureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - /// azureBlobStorageCluster(cluster, connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) + if (arg(url_arg_idx) < function->arguments->size()) + maskUnshowableAzureConnectionValue(arg(url_arg_idx), *function->arguments->at(arg(url_arg_idx)), /* argument_is_named= */ false); +} + +void FunctionSecretArgumentsFinder::maskAzureExtraCredentials() +{ + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + if (const auto f = function->arguments->at(i)->getFunction(); f && f->name() == "extra_credentials") + markSecretArgument(i); + } +} + +std::optional FunctionSecretArgumentsFinder::tryGetAzureKey(const AbstractFunction & equals) +{ + String key; + if (equals.arguments && equals.arguments->size() == 2 && tryGetStringFromArgument(*equals.arguments->at(0), &key) + && isAzureCollectionKey(key)) + return key; + return {}; +} + +void FunctionSecretArgumentsFinder::maskUnreadAzureCollectionOverrides(size_t start) +{ + std::vector connection_overrides; + for (size_t i = start, size = function->arguments->size(); i < size; ++i) { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) + const auto f = function->arguments->at(i)->getFunction(); + if (!f || f->name() != "equals") + continue; + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if (!(tryGetStringFromArgument(*f->arguments->at(1), nullptr) || f->arguments->at(1)->tryGetLiteralText(nullptr))) + markSecretArgument(i, /* argument_is_named= */ true); + if (key == "connection_string" || key == "storage_account_url") + connection_overrides.push_back(i); + } + + if (connection_overrides.size() > 1) + for (const size_t i : connection_overrides) + markSecretArgument(i, /* argument_is_named= */ true); +} + +std::vector FunctionSecretArgumentsFinder::azureSlotArguments(size_t start) +{ + std::vector slots; + size_t extra_credentials = 0; + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + const auto argument = function->arguments->at(i); + if (argument->isSettings()) + continue; + const auto f = i < start ? nullptr : argument->getFunction(); + if (f && f->name() == "extra_credentials") { - if (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg)) - return; + ++extra_credentials; + continue; + } + if (f && f->name() == "equals" && f->arguments && f->arguments->size() == 2) + { + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if ((key != "partition_strategy" && key != "partition_columns_in_data_file") || !f->arguments->at(1)->tryGetLiteralText(nullptr)) + markSecretArgument(i, /* argument_is_named= */ true); + continue; } + slots.push_back(i); } - /// We're going to replace 'account_key' with '[HIDDEN]' if account_key is used in the signature - if (url_arg_idx + 4 < count) - markSecretArgument(url_arg_idx + 4); + if (extra_credentials > 1) + { + maskEveryArgument(); + return {}; + } + return slots; +} + +std::optional FunctionSecretArgumentsFinder::azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const +{ + const size_t count = slot_arguments.size(); + if (count == url_arg_idx + 2) + return slot_arguments[url_arg_idx + 1]; + if (count <= url_arg_idx + 4) + return {}; + String fourth_arg; + if (count <= url_arg_idx + 7 && tryGetStringFromArgument(slot_arguments[url_arg_idx + 3], &fourth_arg) + && (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg))) + return {}; + return slot_arguments[url_arg_idx + 4]; +} + +void FunctionSecretArgumentsFinder::maskPositionalsAfterAzureCollection(size_t start) +{ + for (size_t i = start, size = function->arguments->size(); i < size; ++i) + { + const auto f = function->arguments->at(i)->getFunction(); + if (!f || (f->name() != "equals" && f->name() != "extra_credentials")) + markSecretArgument(i); + } } bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named, size_t start) @@ -663,32 +778,38 @@ bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_id return false; } - if (!url_arg.starts_with("http")) + if (!url_arg.starts_with("http") && maskAzureConnectionStringSecrets(url_arg)) { - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - if (RE2::Replace(&url_arg, account_key_pattern, "AccountKey=[HIDDEN]\\1")) - { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; - } + chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments + result.start = url_arg_idx; + result.are_named = argument_is_named; + result.count = 1; + result.replacement = url_arg; + return true; + } - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - if (RE2::Replace(&url_arg, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1")) + return false; +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionValue( + size_t index, const AbstractFunction::Argument & value, bool argument_is_named) +{ + String text; + if (!value.tryGetString(&text, /* allow_identifier= */ false) || classifyAzureConnectionValue(text) == AzureConnectionValue::Unmaskable) + markSecretArgument(index, argument_is_named); +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionOverrides(size_t start) +{ + for (const auto * key : {"connection_string", "storage_account_url"}) + { + for (ssize_t i = findNamedArgument(nullptr, key, start); i >= 0; i = findNamedArgument(nullptr, key, static_cast(i) + 1)) { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; + const auto index = static_cast(i); + /// `findNamedArgument` returns only an `equals` function with two arguments. + maskUnshowableAzureConnectionValue(index, *function->arguments->at(index)->getFunction()->arguments->at(1), /* argument_is_named= */ true); } } - - return false; } bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit) @@ -701,8 +822,10 @@ bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t s { /// A key this rule cannot read hides which credential the override carries; a value that is /// no plain literal or identifier can nest one (`headers('Authorization' = '...')`). + String key; if (argument_function->arguments && argument_function->arguments->size() == 2 - && tryGetStringFromArgument(*argument_function->arguments->at(0), nullptr) + && tryGetStringFromArgument(*argument_function->arguments->at(0), &key) + && isAzureCollectionKey(key) && (tryGetStringFromArgument(*argument_function->arguments->at(1), nullptr) || argument_function->arguments->at(1)->tryGetLiteralText(nullptr))) continue; @@ -1043,6 +1166,12 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format, [account_name, account_key, ...]) size_t url_arg_idx = 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + if (isNamedCollectionName(url_arg_idx)) { /// AzureBlobStorage(named_collection, ..., account_key = 'account_key', ...) @@ -1057,28 +1186,15 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - /// We should check other arguments first because we don't need to do any replacement in case of - /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - bool fourth_argument_is_format = false; - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) - { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) - fourth_argument_is_format = fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg); - } - /// Which argument holds a credential: the two-argument shape takes a shared access signature beside - /// the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. - std::optional credential_arg_idx; - if (count == url_arg_idx + 2) - credential_arg_idx = url_arg_idx + 1; - else if (!fourth_argument_is_format && (url_arg_idx + 4 < count)) - credential_arg_idx = url_arg_idx + 4; + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx); /// The engine reads this argument as a connection string or as a plain account url; a value of /// another shape is read by neither rule below, and a hidden connection string replaces it whole. String connection_value; - const auto shape = tryGetStringFromArgument(url_arg_idx, &connection_value) + const auto shape = tryGetStringFromArgument(arg(url_arg_idx), &connection_value) ? classifyAzureConnectionValue(connection_value) : AzureConnectionValue::Unmaskable; if (shape == AzureConnectionValue::Unmaskable || (shape == AzureConnectionValue::ConnectionString && credential_arg_idx)) @@ -1087,7 +1203,7 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - if (maskAzureConnectionString(url_arg_idx)) + if (maskAzureConnectionString(arg(url_arg_idx))) return; if (credential_arg_idx) diff --git a/src/Parsers/FunctionSecretArgumentsFinder.h b/src/Parsers/FunctionSecretArgumentsFinder.h index b2c0f511ebbd..161a9754aa52 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.h +++ b/src/Parsers/FunctionSecretArgumentsFinder.h @@ -28,6 +28,9 @@ class AbstractFunction /// The exact literal text of any scalar literal (`1`, `true`, `1.5`), with strings quoted. /// Lets a reconstructor keep non-string values like `use_environment_credentials = 1` visible. virtual bool tryGetLiteralText(String * res) const = 0; + /// A `SETTINGS` clause among the arguments (`remote(..., SETTINGS ...)`): not a positional + /// argument, and it hides its own secret values when formatted. + virtual bool isSettings() const { return false; } }; class Arguments { @@ -164,12 +167,37 @@ class FunctionSecretArgumentsFinder void findS3FunctionSecretArguments(bool is_cluster_function); void findAzureBlobStorageFunctionSecretArguments(bool is_cluster_function); + /// Hides every `extra_credentials(...)` whole, its keys included: a key can be written as anything, a credential too. + void maskAzureExtraCredentials(); + /// The key of a `key = value` argument if it is one of the keys an Azure named collection accepts. Any other left + /// operand can be the credential itself (`'sp=r&sig=...' = 'x'`), so its argument is hidden whole. + static std::optional tryGetAzureKey(const AbstractFunction & equals); + /// Hides every override from `start` on that this rule cannot read: one whose key an Azure named collection does not + /// accept or whose value is no plain literal (it can nest a credential), and every connection override when there are + /// several: only one is read, and only one can be partly shown. + void maskUnreadAzureCollectionOverrides(size_t start); + /// The raw indexes of the arguments the Azure parser assigns slots to, the ones before `start` (the cluster name) as + /// written: it strips the `SETTINGS` clause and the first `extra_credentials(...)`, and a `key = value` takes no slot. + /// Also hides the value of a key the explicit form does not read (all of an argument whose key is no Azure key), and + /// every argument when a second `extra_credentials(...)` shifts the slots. + std::vector azureSlotArguments(size_t start); + /// The raw index of the argument holding a credential, if any: the two-argument shape takes a shared access signature + /// beside the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. + std::optional azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const; + /// After the collection name every argument must be an override or `extra_credentials(...)`; a positional one is + /// invalid but logged before validation rejects it, and can be a credential. + void maskPositionalsAfterAzureCollection(size_t start); bool maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named = false, size_t start = 0); /// Whether the arguments an `AzureBlobStorage(named_collection, ...)` destination or table takes /// from `start` can be shown: only an argument written here can carry a credential, and each has /// to be readable enough to tell that it does not. `positional_limit` bounds the plain literals /// read beside the overrides: one filename for a backup locator, none for a table engine. bool azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit); + /// Hides a connection value that no rule here can show: a URL carrying a credential of its own + /// (`user:key@`, a SAS `?sig=...`), or a value that is not a plain string literal. + void maskUnshowableAzureConnectionValue(size_t index, const AbstractFunction::Argument & value, bool argument_is_named); + /// The same, for the `connection_string` and `storage_account_url` overrides of a named collection from `start` on. + void maskUnshowableAzureConnectionOverrides(size_t start); /// Masks the secrets of every URL form (`url`/`urlCluster` table functions, the `URL` table /// engine, and their named-collection variants): the userinfo password of the url positional or a /// named `url = ...` override, and the `headers(...)` values at any position. `url` is at diff --git a/src/Parsers/FunctionSecretArgumentsFinderAST.h b/src/Parsers/FunctionSecretArgumentsFinderAST.h index 754411535c8d..6d0c5c050342 100644 --- a/src/Parsers/FunctionSecretArgumentsFinderAST.h +++ b/src/Parsers/FunctionSecretArgumentsFinderAST.h @@ -5,6 +5,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,7 @@ class FunctionAST : public AbstractFunction return nullptr; } bool isIdentifier() const override { return argument->as(); } + bool isSettings() const override { return argument->as(); } bool tryGetString(String * res, bool allow_identifier) const override { if (const auto * literal = argument->as()) diff --git a/src/Parsers/Lexer.cpp b/src/Parsers/Lexer.cpp index 8806ed24492c..abb35a149bc5 100644 --- a/src/Parsers/Lexer.cpp +++ b/src/Parsers/Lexer.cpp @@ -116,7 +116,7 @@ Token quotedHexOrBinString(const char *& pos, const char * const token_begin, co Token Lexer::nextToken() { Token res = nextTokenImpl(); - if (max_query_size && res.end > begin + max_query_size) + if (begin && max_query_size && res.end > begin + max_query_size) res.type = TokenType::ErrorMaxQuerySizeExceeded; if (res.isSignificant()) prev_significant_token_type = res.type; diff --git a/src/Parsers/tests/gtest_Parser.cpp b/src/Parsers/tests/gtest_Parser.cpp index 22f73a45a039..429e65d8d125 100644 --- a/src/Parsers/tests/gtest_Parser.cpp +++ b/src/Parsers/tests/gtest_Parser.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -38,6 +39,13 @@ std::ostream & operator<<(std::ostream & ostr, const ParserTestCase & test_case) return ostr << "ParserTestCase input: " << input_text; } +TEST(Lexer, NullInputWithMaxQuerySize) +{ + Lexer lexer(nullptr, nullptr, 262144); + Token token = lexer.nextToken(); + EXPECT_EQ(TokenType::EndOfStream, token.type); +} + TEST_P(ParserTest, parseQuery) { const auto & parser = std::get<0>(GetParam()); diff --git a/src/Processors/Chunk.cpp b/src/Processors/Chunk.cpp index 0564131c8768..aef99bd3dee0 100644 --- a/src/Processors/Chunk.cpp +++ b/src/Processors/Chunk.cpp @@ -69,13 +69,11 @@ void Chunk::checkNumRowsIsConsistent() MutableColumns Chunk::mutateColumns() { - size_t num_columns = columns.size(); - MutableColumns mutable_columns(num_columns); - for (size_t i = 0; i < num_columns; ++i) - mutable_columns[i] = IColumn::mutate(std::move(columns[i])); - - columns.clear(); - num_rows = 0; + MutableColumns mutable_columns(columns.size()); + /// Detach first: `IColumn::mutate` consumes the column even when it throws, and a chunk never holds a null column. + Columns detached_columns = detachColumns(); + for (size_t i = 0; i < detached_columns.size(); ++i) + mutable_columns[i] = IColumn::mutate(std::move(detached_columns[i])); return mutable_columns; } diff --git a/src/Processors/Formats/IInputFormat.h b/src/Processors/Formats/IInputFormat.h index 2b1eb5a447e8..a2e2f693ef54 100644 --- a/src/Processors/Formats/IInputFormat.h +++ b/src/Processors/Formats/IInputFormat.h @@ -130,6 +130,8 @@ class IInputFormat : public ISource void needOnlyCount() { need_only_count = true; } + virtual void prefetch() {} + protected: ReadBuffer & getReadBuffer() const { chassert(in); return *in; } diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp new file mode 100644 index 000000000000..8f76772b9ef6 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp @@ -0,0 +1,319 @@ +#include + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace DB +{ + +namespace +{ + +/// The largest `n <= end - begin` for which the non-decreasing `offsets` grow by at most `limit` over +/// rows [begin, begin + n). +size_t maxRowsByOffsets(const IColumn::Offsets & offsets, size_t begin, size_t end, UInt64 limit) +{ + const UInt64 base = offsets[static_cast(begin) - 1]; + const auto * first = offsets.data() + begin; + const auto * it = std::upper_bound(first, offsets.data() + end, base + limit); + return static_cast(it - first); +} + +/// A writer either materializes the column or dictionary-encodes it; measuring it as materialized bounds +/// both, since a batch's dictionary holds at most the distinct values of its rows. `canBeInsideLowCardinality` +/// allows only fixed-width types, `String` and `FixedString`, and of those only the two string types reach +/// a 32-bit-offset buffer. +size_t maxRowsForLowCardinality( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const DataTypePtr values_type = removeNullable(removeLowCardinality(type)); + const auto & low_cardinality = assert_cast(column); + const IColumn & values_column = *low_cardinality.getDictionary().getNestedNotNullableColumn(); + + if (isFixedString(values_type)) + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(values_column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + + if (!isString(values_type)) + return num_rows; + + const auto & values = assert_cast(values_column); + const auto & value_offsets = values.getOffsets(); + + /// Scanning the indexes is only needed when the whole dictionary repeated on every row could overflow: + /// no single value is larger than all of them together. This is O(1), unlike finding the largest value, + /// so it does not add work proportional to the dictionary for every batch of a split chunk. + const UInt64 dictionary_bytes = values.empty() ? 0 : value_offsets.back(); + if (dictionary_bytes == 0 || num_rows <= max_batch_bytes / dictionary_bytes) + return num_rows; + + const auto & indexes = low_cardinality.getIndexes(); + UInt64 total = 0; + for (size_t row = begin; row != end; ++row) + { + const auto index = static_cast(indexes.getUInt(row)); + total += value_offsets[index] - value_offsets[index - 1]; + if (total > max_batch_bytes) + return row - begin; + } + return num_rows; +} + +/// A `Variant` becomes an Arrow dense union, whose own buffers are bounded by the row count; only its +/// children, holding one alternative's rows each, can overflow. +size_t maxRowsForVariant( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const auto & variant_column = assert_cast(column); + const auto & variant_type = assert_cast(*type); + const size_t num_variants = variant_column.getNumVariants(); + const auto & local_discriminators = variant_column.getLocalDiscriminators(); + const auto & variant_offsets = variant_column.getOffsets(); + + /// Within a contiguous row range the offsets of each alternative are contiguous too (see + /// `ColumnVariant::updateHashWithValueRange`), so [begin, end) maps to the range + /// [nested_begin, nested_begin + nested_rows) of every alternative. + std::vector nested_begin(num_variants, 0); + std::vector nested_rows(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows[local_discr] == 0) + nested_begin[local_discr] = variant_offsets[row]; + ++nested_rows[local_discr]; + } + + std::vector nested_rows_that_fit(num_variants); + bool all_fit = true; + for (size_t local_discr = 0; local_discr != num_variants; ++local_discr) + { + const auto global_discr + = variant_column.globalDiscriminatorByLocal(static_cast(local_discr)); + nested_rows_that_fit[local_discr] = maxRowsFittingOneArrowBatch( + variant_column.getVariantByLocalDiscriminator(local_discr), + variant_type.getVariant(global_discr), + nested_begin[local_discr], + nested_begin[local_discr] + nested_rows[local_discr], + fixed_string_as_fixed_byte_array, max_batch_bytes); + all_fit &= nested_rows_that_fit[local_discr] == nested_rows[local_discr]; + } + if (all_fit) + return num_rows; + + /// Some alternative cannot take all of its rows: cut at the row where it runs out. + std::vector nested_rows_taken(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows_taken[local_discr] == nested_rows_that_fit[local_discr]) + return row - begin; + ++nested_rows_taken[local_discr]; + } + return num_rows; +} + +} + +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Arrow cannot address more than this however the caller was configured. + max_batch_bytes = std::min(max_batch_bytes, MAX_ARROW_BUFFER_SIZE); + + if (type->lowCardinality()) + return maxRowsForLowCardinality(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + if (isVariant(type)) + return maxRowsForVariant(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + /// A null row is written as a zero-length slot, so measuring the nested column only overestimates. + if (type->isNullable()) + { + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + removeNullable(type), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + + switch (WhichDataType(type).idx) + { + case TypeIndex::String: + { + return maxRowsByOffsets(assert_cast(column).getOffsets(), begin, end, max_batch_bytes); + } + case TypeIndex::FixedString: + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + case TypeIndex::Array: + { + const auto & array = assert_cast(column); + const auto & offsets = array.getOffsets(); + const size_t nested_begin = offsets[static_cast(begin) - 1]; + const size_t nested_rows = maxRowsFittingOneArrowBatch( + array.getData(), + assert_cast(*type).getNestedType(), + nested_begin, + offsets[end - 1], + fixed_string_as_fixed_byte_array, max_batch_bytes); + return maxRowsByOffsets(offsets, begin, end, std::min(nested_rows, max_batch_bytes)); + } + case TypeIndex::Map: + { + /// Both writers encode a Map exactly as its nested `Array(Tuple(key, value))`. + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + assert_cast(*type).getNestedType(), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + case TypeIndex::Tuple: + { + const auto & tuple = assert_cast(column); + const auto & elements = assert_cast(*type).getElements(); + size_t rows = num_rows; + for (size_t i = 0; i != elements.size(); ++i) + { + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + tuple.getColumn(i), elements[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + } + return rows; + } + /// Fixed-width Arrow types: a single values buffer, no offsets, nothing to exceed. + case TypeIndex::UInt8: + case TypeIndex::UInt16: + case TypeIndex::UInt32: + case TypeIndex::UInt64: + case TypeIndex::UInt128: + case TypeIndex::UInt256: + case TypeIndex::Int8: + case TypeIndex::Int16: + case TypeIndex::Int32: + case TypeIndex::Int64: + case TypeIndex::Int128: + case TypeIndex::Int256: + case TypeIndex::Float32: + case TypeIndex::Float64: + case TypeIndex::Enum8: + case TypeIndex::Enum16: + case TypeIndex::Date: + case TypeIndex::Date32: + case TypeIndex::DateTime: + case TypeIndex::DateTime64: + case TypeIndex::Time: + case TypeIndex::Time64: + case TypeIndex::Decimal32: + case TypeIndex::Decimal64: + case TypeIndex::Decimal128: + case TypeIndex::Decimal256: + case TypeIndex::IPv4: + case TypeIndex::IPv6: + case TypeIndex::UUID: + case TypeIndex::Interval: + { + return num_rows; + } + default: + { + /// A type with no Arrow equivalent is written by serializing each value, so bounding its + /// encoded size would mean serializing twice. The encoder rejects a batch that overflows. + return num_rows; + } + } +} + +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + chassert(columns.size() == types.size()); + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Some limits (`Variant`, `LowCardinality`) take time linear in the rows they are given, so measuring + /// the whole remainder of a chunk for each of its batches would be quadratic. The window grows instead: + /// the limit of a prefix is the limit of the whole range capped at the prefix's length, so the first + /// window that does not fit entirely gives the answer, and the work stays proportional to the rows + /// emitted, plus the initial window. + static constexpr size_t initial_window = 8192; + size_t window = std::min(num_rows, initial_window); + while (true) + { + /// Two columns never share an Arrow buffer, so the smallest per-column limit applies. + size_t rows = window; + for (size_t i = 0; i < columns.size() && rows != 0; ++i) + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + *columns[i], types[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + + if (rows < window || window == num_rows) + return rows; + window = std::min(num_rows, window * 2); + } +} + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.h b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h new file mode 100644 index 000000000000..c532138a8da0 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h @@ -0,0 +1,47 @@ +#pragma once + +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include + +namespace DB +{ + +/// The largest `n` such that rows [begin, begin + n) of `column` stay within `max_batch_bytes`; writers +/// split an oversized chunk accordingly. Returns 0 only when the first row does not fit on its own, which +/// the writer then lets Arrow reject. `ColumnConst` and the sparse/replicated representations are not +/// handled; callers materialize first. +/// +/// `LowCardinality` is measured as materialized, which only over-splits when it is written as an Arrow +/// dictionary. A dictionary larger than one buffer is not covered at all: its bytes do not depend on the +/// row count, because `ColumnLowCardinality::insertRangeFrom` keeps a shared source dictionary whole, so +/// every slice re-emits it. Arrow rejects such a chunk. +/// +/// A type with no Arrow equivalent is not covered either, since only serializing its values reveals their +/// encoded size. Both uncovered shapes are rejected by the writer instead of being split. +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes = MAX_ARROW_BUFFER_SIZE); + +/// The largest `n` such that rows [begin, begin + n) of every column stay within `max_batch_bytes`: the +/// number of rows of the next record batch of a chunk. The work is proportional to the returned number of +/// rows rather than to `end - begin`, so splitting a chunk into many batches stays linear. +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes); + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp index 1a71a4a32447..7c0dfb0044ae 100644 --- a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp @@ -64,6 +64,7 @@ void ArrowBlockOutputFormat::consume(Chunk chunk) .use_signed_indexes_for_dictionary = format_settings.arrow.use_signed_indexes_for_dictionary, .use_64_bit_indexes_for_dictionary = format_settings.arrow.use_64_bit_indexes_for_dictionary, .output_date_as_uint16 = format_settings.arrow.output_date_as_uint16, + .output_max_record_batch_bytes = format_settings.arrow.output_max_record_batch_bytes, }); } diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp index 4699b1b2fdf0..7c2d5b54eed9 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp @@ -1,7 +1,7 @@ #pragma clang diagnostic ignored "-Wreserved-identifier" #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include #include diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.h b/src/Processors/Formats/Impl/ArrowBufferedStreams.h index ecb6ef8cb6fe..510e3ee4c26e 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.h +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.h @@ -3,7 +3,7 @@ #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp index ffac42b86605..a9b508893a8f 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp @@ -1,7 +1,7 @@ #include #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h index e06cce04579d..bf0e3ecf828a 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h @@ -5,7 +5,7 @@ #include "config.h" -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp index 60f89e76aeef..f4e991cc1643 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp @@ -21,9 +21,12 @@ #include #include #include +#include #include #include +#include + #include #include #include @@ -66,6 +69,7 @@ namespace DB extern const int LOGICAL_ERROR; extern const int DECIMAL_OVERFLOW; extern const int ILLEGAL_COLUMN; + extern const int TOO_LARGE_ARRAY_SIZE; } static const std::initializer_list>> internal_type_to_arrow_type = @@ -517,6 +521,18 @@ namespace DB throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot fill arrow array {} with {} data", value_type->name(), column_type->getName()); } + /// Arrow's `Utf8`/`Binary` builders take an int32 length and their `Append` skips the copy when it is + /// negative, so a narrowed size would store an empty value instead of failing. + static void checkStringSizeFitsArrowOffsets(size_t size, const String & column_name, const String & format_name) + { + if (size > MAX_ARROW_BUFFER_SIZE) + throw Exception( + ErrorCodes::TOO_LARGE_ARRAY_SIZE, + "Cannot write a value of {} bytes of column {} to {}: `Utf8`/`Binary` offsets are 32-bit, so a single " + "value cannot be larger than {} bytes", + size, column_name, format_name, MAX_ARROW_BUFFER_SIZE); + } + template static void fillArrowArrayWithStringColumnData( ColumnPtr write_column, @@ -541,6 +557,7 @@ namespace DB else { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); } checkStatus(status, write_column->getName(), format_name); @@ -551,6 +568,7 @@ namespace DB for (size_t string_i = start; string_i < end; ++string_i) { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); checkStatus(status, write_column->getName(), format_name); } @@ -1200,37 +1218,72 @@ namespace DB for (const auto & chunk : chunks) { - /// For arrow::Table creation + /// Normalize once per chunk, so that it is not repeated for each row range below. + Columns columns(columns_num); + DataTypes column_types(columns_num); for (size_t column_i = 0; column_i < columns_num; ++column_i) { - const ColumnWithTypeAndName & header_column = header_columns[column_i]; - auto column = chunk.getColumns()[column_i]; - + auto column = chunk.getColumns()[column_i]->convertToFullColumnIfConst()->convertToFullColumnIfReplicated(); + auto column_type = header_columns[column_i].type; if (!settings.low_cardinality_as_dictionary) column = recursiveRemoveLowCardinality(column); - - std::unique_ptr array_builder; - arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); - checkStatus(status, column->getName(), format_name); - - fillArrowArray( - header_column.name, - column, - header_column.type, - nullptr, - array_builder.get(), - format_name, - 0, - column->size(), - settings, - dictionary_values); - - std::shared_ptr arrow_array; - status = array_builder->Finish(&arrow_array); - checkStatus(status, column->getName(), format_name); - - table_data.at(column_i).emplace_back(std::move(arrow_array)); + columns[column_i] = std::move(column); + column_types[column_i] = std::move(column_type); } + + /// The row limit is measured on types matching the columns: without dictionary output the + /// `LowCardinality` columns were materialized above. + DataTypes measured_types = column_types; + if (!settings.low_cardinality_as_dictionary) + for (auto & type : measured_types) + type = recursiveRemoveLowCardinality(type); + + /// A chunk that exceeds the 32-bit Arrow offsets becomes several arrays of the ChunkedArray. + const size_t num_rows = chunk.getNumRows(); + size_t offset = 0; + do + { + size_t rows = maxRowsFittingOneArrowBatch( + columns, + measured_types, + offset, + num_rows, + settings.output_fixed_string_as_fixed_byte_array, + settings.output_max_record_batch_bytes); + /// A row that does not fit on its own cannot be represented at all; the leaf encoders reject it. + rows = std::min(std::max(rows, 1), num_rows - offset); + + /// For arrow::Table creation + for (size_t column_i = 0; column_i < columns_num; ++column_i) + { + const ColumnWithTypeAndName & header_column = header_columns[column_i]; + ColumnPtr column = columns[column_i]; + + std::unique_ptr array_builder; + arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); + checkStatus(status, column->getName(), format_name); + + fillArrowArray( + header_column.name, + column, + column_types[column_i], + nullptr, + array_builder.get(), + format_name, + offset, + offset + rows, + settings, + dictionary_values); + + std::shared_ptr arrow_array; + status = array_builder->Finish(&arrow_array); + checkStatus(status, column->getName(), format_name); + + table_data.at(column_i).emplace_back(std::move(arrow_array)); + } + + offset += rows; + } while (offset < num_rows); } std::vector> columns; diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h index 2544faf9ed1d..160a78ed1c9f 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h @@ -4,6 +4,7 @@ #if USE_ARROW || USE_PARQUET #include +#include #include #include @@ -33,6 +34,8 @@ class CHColumnToArrowColumn bool use_64_bit_indexes_for_dictionary = false; /// Output Date as UInt16 instead of Arrow DATE32 for backward compatibility. bool output_date_as_uint16 = false; + /// Upper bound on one record batch; a chunk holding more is written as several. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; }; CHColumnToArrowColumn(const Block & header, const std::string & format_name_, const Settings & settings_); diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp index 58e797b4d591..a6e69f02d3a8 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp @@ -59,7 +59,7 @@ MsgPackRowInputFormat::MsgPackRowInputFormat(SharedHeader header_, std::unique_p void MsgPackRowInputFormat::resetParser() { IRowInputFormat::resetParser(); - visitor.reset(); + parser.init(); } void MsgPackRowInputFormat::setReadBuffer(ReadBuffer & in_) @@ -83,7 +83,7 @@ void MsgPackVisitor::set_info(IColumn & column, DataTypePtr type, UInt8 & read) info_stack.push(Info{column, type, false, std::nullopt, &read}); } -void MsgPackVisitor::reset() +void MsgPackVisitor::init() { info_stack = {}; } @@ -667,10 +667,10 @@ DataTypePtr MsgPackSchemaReader::getDataType(const msgpack::object & object, siz msgpack::object_map object_map = object.via.map; if (object_map.size) { - auto key_type = removeNullable(getDataType(object_map.ptr[0].key, depth + 1)); + auto key_type = getDataType(object_map.ptr[0].key, depth + 1); auto value_type = getDataType(object_map.ptr[0].val, depth + 1); if (key_type && value_type) - return std::make_shared(key_type, value_type); + return std::make_shared(removeNullable(key_type), value_type); } return nullptr; } diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h index be9dd30d6e8f..323df67d9707 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h @@ -52,7 +52,8 @@ class MsgPackVisitor : public msgpack::null_visitor /// Update info_stack void set_info(IColumn & column, DataTypePtr type, UInt8 & read); - void reset(); + /// Called by msgpack's parse_helper::init. + void init(); private: /// Stack is needed to process arrays and maps diff --git a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp index 96bb9b23ef3c..a39c4d82ec12 100644 --- a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp @@ -377,8 +377,12 @@ static bool tryToExtractStructureFromCreateQuery(ReadBuffer & in, NamesAndTypesL if (!create_query) return false; + /// `CREATE TABLE ... LIKE` has no column list, and a column list with only indexes or constraints has no columns. + if (!create_query->columns_list) + return false; + const auto * create_defines = create_query->columns_list->as(); - if (!create_defines) + if (!create_defines || !create_defines->columns) return false; structure = getColumnsList(create_defines->columns); @@ -431,9 +435,10 @@ static void readFirstCreateAndInsertQueries(ReadBuffer & in, String & table_name if (type == MySQLQueryType::CREATE) { /// If we have CREATE query, we can extract columns names and types from it. + /// `tryToExtractStructureFromCreateQuery` reads the CREATE query up to and including its `;`, + /// so the next query must not be skipped: it can be the first INSERT query. if (tryToExtractStructureFromCreateQuery(in, structure_from_create)) column_names = structure_from_create.getNames(); - skipQuery(in); insert_query_present = skipToInsertQuery(table_name, in); } diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp index 0e999852c352..b0621dbd7d06 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp @@ -3,6 +3,7 @@ #if USE_ORC #include +#include #include #include #include @@ -10,8 +11,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include @@ -25,20 +29,26 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include +#include +#include #include #include #include -#include #include #include #include @@ -47,10 +57,11 @@ #include #include -#include #include +#include + namespace DB { namespace ErrorCodes @@ -66,9 +77,12 @@ extern const int TOO_DEEP_RECURSION; ORCInputStream::ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch) - : in(in_), file_size(file_size_), supports_read_at(use_prefetch && in_.supportsReadAt()) + : in(in_) + , file_size(file_size_) + , use_offset_based_read(in_.supportsReadAt()) + , use_async_prefetch(use_prefetch && use_offset_based_read) { - if (supports_read_at) + if (use_async_prefetch) async_runner = threadPoolCallbackRunnerUnsafe(getIOThreadPool().get(), ThreadName::ORC_FILE); } @@ -77,20 +91,23 @@ UInt64 ORCInputStream::getLength() const return file_size; } -UInt64 ORCInputStream::getNaturalReadSize() const -{ - return 128 * 1024; -} - void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) { - if (supports_read_at) + if (use_offset_based_read) { size_t bytes_read = 0; while (bytes_read < length) { size_t bytes_to_read = length - bytes_read; size_t n = in.readBigAt(reinterpret_cast(buf) + bytes_read, bytes_to_read, offset + bytes_read, nullptr); + if (n == 0) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Truncated or corrupted ORC input: readBigAt returned 0 bytes at offset {} ({} bytes remaining of {} requested from base offset {})", + offset + bytes_read, + bytes_to_read, + length, + offset); bytes_read += n; } } @@ -104,7 +121,7 @@ void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_t offset) { - if (supports_read_at) + if (use_async_prefetch) { return async_runner( [this, buf, length, offset] @@ -129,7 +146,7 @@ std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_ } } -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled) { bool has_file_size = isBufferWithFileSize(in); @@ -142,14 +159,15 @@ asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_pref return asORCInputStreamLoadIntoMemory(in, is_cancelled); } -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) { - size_t magic_size = strlen(ORC_MAGIC_BYTES); + static constexpr std::string_view orc_magic_bytes = "ORC"; + size_t magic_size = orc_magic_bytes.size(); std::string file_data(magic_size, '\0'); /// Avoid loading the whole file if it doesn't seem to even be in the correct format. size_t bytes_read = in.read(file_data.data(), magic_size); - if (bytes_read < magic_size || file_data != ORC_MAGIC_BYTES) + if (bytes_read < magic_size || file_data != orc_magic_bytes) throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file"); { @@ -161,53 +179,157 @@ std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in return std::make_unique(std::move(file_data), file_size); } -/// The default ORC memory pool allocates with `std::malloc`, which returns a null pointer when it -/// fails - and the library dereferences it - and which is invisible to the memory tracker. A -/// malformed file can ask for an arbitrarily large buffer, so allocate through `operator new` -/// instead: it is accounted for and it throws instead of returning null. -class ORCMemoryPool : public orc::MemoryPool +/// Defined below, next to the read path that also uses it. The sargs path resolves predicate column +/// names through the same recursive walk, so pruning and reading always agree on the column. +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case); + +struct ORCPredicateColumnTypes +{ + DataTypePtr result_type; + DataTypePtr declared_type; +}; + +struct ORCSubcolumnInfo { -public: - char * malloc(uint64_t size) override { return new char[size]; } - void free(char * p) override { delete[] p; } + ISerialization::SubstreamData data; + ISerialization::SubstreamPath substreams_path; }; -orc::MemoryPool & getORCMemoryPool() +/// Finds a subcolumn of `type` together with the substreams path that leads to it. +static std::optional tryGetORCSubcolumnInfo(const IDataType & type, std::string_view subcolumn_name) { - static ORCMemoryPool pool; - return pool; + std::optional result; + auto data = ISerialization::SubstreamData(type.getDefaultSerialization()).withType(type.getPtr()); + IDataType::forEachSubcolumn( + [&](const ISerialization::SubstreamPath & path, const String & name, const ISerialization::SubstreamData & subcolumn_data) + { + if (!result && name == subcolumn_name) + result = ORCSubcolumnInfo{subcolumn_data, path}; + }, + data); + return result; } -static const orc::Type * getORCTypeByName(const orc::Type & schema, const String & name, bool ignore_case) +/// True when `path` is a named tuple element at every level, so it is a file leaf with its own +/// statistics. Nullable, LowCardinality and Array are transparent; anything else is refused, +/// which is what rejects Map/Variant/JSON/Dynamic and `.null`, `.size0`, `.keys`, `.values`. +static bool isNamedTupleElementPath(const IDataType & type, std::string_view path, bool ignore_case) { - for (UInt64 i = 0; i != schema.getSubtypeCount(); ++i) - if (boost::equals(schema.getFieldName(i), name) || (ignore_case && boost::iequals(schema.getFieldName(i), name))) - return schema.getSubtype(i); - return nullptr; + const IDataType * current = &type; + while (true) + { + if (const auto * nullable = typeid_cast(current)) + current = nullable->getNestedType().get(); + else if (const auto * low_cardinality = typeid_cast(current)) + current = low_cardinality->getDictionaryType().get(); + else if (const auto * array = typeid_cast(current)) + current = array->getNestedType().get(); + else + break; + } + + const auto * tuple = typeid_cast(current); + if (!tuple || !tuple->hasExplicitNames()) + return false; + + if (tuple->tryGetPositionByName(path, ignore_case)) + return true; + + /// An element name may itself contain dots, so every split has to be considered. + for (size_t dot = path.find('.'); dot != std::string_view::npos; dot = path.find('.', dot + 1)) + { + auto head = path.substr(0, dot); + auto tail = path.substr(dot + 1); + if (head.empty() || tail.empty()) + continue; + if (auto position = tuple->tryGetPositionByName(head, ignore_case)) + if (isNamedTupleElementPath(*tuple->getElement(*position), tail, ignore_case)) + return true; + } + return false; } -static bool isDictionaryEncoded(const orc::StripeInformation * stripe_info, const orc::Type * orc_type) +/// Resolves a named tuple element and retains its declared type before ancestor wrappers are applied. +static std::optional findTupleElementKeyTypes( + const Block & header, const String & name, bool ignore_case) { - if (!stripe_info) + for (auto [column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(name)) + { + const auto * column = header.findByName(String(column_name), ignore_case); + if (!column || !isNamedTupleElementPath(*column->type, subcolumn_name, ignore_case)) + continue; + if (auto subcolumn = tryGetORCSubcolumnInfo(*column->type, subcolumn_name)) + { + const auto & path = subcolumn->substreams_path; + chassert(!path.empty() && path.back().data.type); + /// A dotted field name can also resolve to a virtual subcolumn of another element. + if (path.back().type != ISerialization::Substream::TupleElement) + continue; + return ORCPredicateColumnTypes{subcolumn->data.type, path.back().data.type}; + } + } + return {}; +} + +/// Resolves predicate types from the reader header, which can contain only the parent tuple column. +static std::optional findHeaderTypesByPath( + const Block & header, const String & name, bool ignore_case) +{ + if (const auto * column = header.findByName(name, ignore_case)) + return ORCPredicateColumnTypes{column->type, column->type}; + return findTupleElementKeyTypes(header, name, ignore_case); +} + +/// KeyCondition derives its key names from this block, and the ORC header carries only the parent +/// column, so a tuple element predicate would degrade to `unknown`. Only the local copy grows; +/// the reader header stays as it is, so the read path is unaffected. +static Block buildORCKeyConditionBlock(const Block & header, const ActionsDAG * filter_dag, bool ignore_case) +{ + if (!filter_dag) + return header; + + Block keys = header; + for (const auto & required : filter_dag->getRequiredColumns()) + { + if (keys.has(required.name)) + continue; + if (auto types = findTupleElementKeyTypes(header, required.name, ignore_case)) + keys.insert({types->result_type->createColumn(), types->result_type, required.name}); + } + return keys; +} + +static bool isDictionaryEncoded(const ORC::Proto::StripeFooter * stripe_footer, const ORC::Type * orc_type) +{ + if (!stripe_footer) return false; - auto encoding = stripe_info->getColumnEncoding(orc_type->getColumnId()); - return encoding == orc::ColumnEncodingKind_DICTIONARY || encoding == orc::ColumnEncodingKind_DICTIONARY_V2; + UInt64 column_id = orc_type->getColumnId(); + if (column_id >= stripe_footer->columns.size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Failed to read ORC schema: the first stripe has no encoding for column {}, it has {} column encodings", + column_id, + stripe_footer->columns.size()); + + auto encoding = stripe_footer->columns[column_id].kind; + return encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY || encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY_V2; } static DataTypePtr parseORCType( - const orc::Type * orc_type, + const ORC::Type * orc_type, bool skip_columns_with_unsupported_types, bool dictionary_as_low_cardinality, - const orc::StripeInformation * stripe_info, + const ORC::Proto::StripeFooter * stripe_info, bool & skipped, size_t max_depth = DBMS_DEFAULT_MAX_PARSER_DEPTH, size_t depth = 0) { - assert(orc_type != nullptr); + chassert(orc_type != nullptr); - /// ORC LIST/MAP/STRUCT types can be nested arbitrarily deep and the ORC library does not bound - /// the nesting, so reject deep nesting early (before building the type) with an explicit limit. + /// ORC LIST/MAP/STRUCT types can be nested deep (the ORC reader allows up to 2000 levels) + /// so reject deep nesting early (before building the type) with an explicit limit. /// This keeps schema inference cheap and interruptible instead of recursing over (and later /// walking) a pathologically deep type. checkStackSize is a last-resort backstop. /// max_depth == 0 means unlimited (matching the SQL parser), leaving only checkStackSize. @@ -220,34 +342,111 @@ static DataTypePtr parseORCType( checkStackSize(); const int subtype_count = static_cast(orc_type->getSubtypeCount()); + + /// ORC union maps to the ClickHouse Variant type. It is handled before the switch below so the + /// switch stays non-exhaustive (its default handles unsupported types). Variant sorts and + /// de-duplicates its nested types, but ORC keeps a separate physical stream per branch, so two + /// branches with identical types cannot be represented as a Variant; reject them explicitly + /// instead of silently squashing them. A branch that is itself a union is rejected too: it + /// would map to a Variant, which Variant does not allow to nest. + if (orc_type->getKind() == ORC::TypeKind::UNION) + { + /// A union with more branches than Variant can hold (ColumnVariant::MAX_NESTED_COLUMNS) + /// is valid ORC but not representable; reject it through the normal unsupported-type / + /// skip path before any branch is parsed - otherwise the DataTypeVariant constructor + /// throws a generic BAD_ARGUMENTS and the skip setting is never consulted. + if (static_cast(subtype_count) > ColumnVariant::MAX_NESTED_COLUMNS) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported: Variant supports at most {} nested types", + subtype_count, ColumnVariant::MAX_NESTED_COLUMNS); + } + + DataTypes nested_types; + std::unordered_set seen_type_names; + nested_types.reserve(subtype_count); + for (int i = 0; i < subtype_count; ++i) + { + const auto * subtype = orc_type->getSubtype(i); + + /// A union branch that is itself a union would map to a Variant, and Variant does not + /// allow a nested Variant. Reject it through the normal unsupported-type / skip path + /// here, before the outer DataTypeVariant is constructed - otherwise its constructor + /// throws a confusing BAD_ARGUMENTS ("Nested Variant types are not allowed") and the + /// skip setting is never consulted because the inner union has already been parsed. + if (subtype->getKind() == ORC::TypeKind::UNION) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported", + orc_type->toString()); + } + + auto parsed_type = parseORCType( + subtype, skip_columns_with_unsupported_types, dictionary_as_low_cardinality, stripe_info, skipped, max_depth, depth + 1); + if (skipped) + return {}; + + /// Branch identity must not depend on the stripe's physical encoding: a + /// dictionary-encoded branch parses as LowCardinality(...), which would let e.g. + /// uniontype with one dictionary-encoded branch slip past this check + /// (and the read would then fail on any stripe where the encodings agree). + if (!seen_type_names.insert(recursiveRemoveLowCardinality(parsed_type)->getName()).second) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported", + orc_type->toString()); + } + nested_types.push_back(parsed_type); + } + return std::make_shared(nested_types); + } + switch (orc_type->getKind()) { - case orc::TypeKind::BOOLEAN: + case ORC::TypeKind::BOOLEAN: return DataTypeFactory::instance().get("Bool"); - case orc::TypeKind::BYTE: + case ORC::TypeKind::BYTE: return std::make_shared(); - case orc::TypeKind::SHORT: + case ORC::TypeKind::SHORT: return std::make_shared(); - case orc::TypeKind::INT: + case ORC::TypeKind::INT: return std::make_shared(); - case orc::TypeKind::LONG: + case ORC::TypeKind::LONG: return std::make_shared(); - case orc::TypeKind::FLOAT: + case ORC::TypeKind::FLOAT: return std::make_shared(); - case orc::TypeKind::DOUBLE: + case ORC::TypeKind::DOUBLE: return std::make_shared(); - case orc::TypeKind::DATE: + case ORC::TypeKind::DATE: return std::make_shared(); - case orc::TypeKind::TIMESTAMP: + case ORC::TypeKind::TIMESTAMP: return std::make_shared(9); - case orc::TypeKind::TIMESTAMP_INSTANT: + case ORC::TypeKind::TIMESTAMP_INSTANT: return std::make_shared(9, "UTC"); - case orc::TypeKind::CHAR: - case orc::TypeKind::VARCHAR: - case orc::TypeKind::BINARY: - case orc::TypeKind::STRING: { + case ORC::TypeKind::CHAR: + case ORC::TypeKind::VARCHAR: + case ORC::TypeKind::BINARY: + case ORC::TypeKind::STRING: { DataTypePtr type; - if (orc_type->getKind() == orc::TypeKind::CHAR) + if (orc_type->getKind() == ORC::TypeKind::CHAR) type = std::make_shared(orc_type->getMaximumLength()); else type = std::make_shared(); @@ -258,7 +457,7 @@ static DataTypePtr parseORCType( return type; } - case orc::TypeKind::DECIMAL: { + case ORC::TypeKind::DECIMAL: { UInt64 precision = orc_type->getPrecision(); UInt64 scale = orc_type->getScale(); if (precision == 0) @@ -268,7 +467,7 @@ static DataTypePtr parseORCType( } return createDecimal(precision, scale); } - case orc::TypeKind::LIST: { + case ORC::TypeKind::LIST: { if (subtype_count != 1) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc List type {}", orc_type->toString()); @@ -279,7 +478,7 @@ static DataTypePtr parseORCType( return std::make_shared(nested_type); } - case orc::TypeKind::MAP: { + case ORC::TypeKind::MAP: { if (subtype_count != 2) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc Map type {}", orc_type->toString()); @@ -295,7 +494,7 @@ static DataTypePtr parseORCType( return std::make_shared(key_type, value_type); } - case orc::TypeKind::STRUCT: { + case ORC::TypeKind::STRUCT: { DataTypes nested_types; Strings nested_names; nested_types.reserve(subtype_count); @@ -322,7 +521,7 @@ static DataTypePtr parseORCType( throw Exception( ErrorCodes::UNKNOWN_TYPE, - "Unsupported ORC type '{}'." + "Unsupported ORC type '{}'. " "If you want to skip columns with unsupported types, " "you can enable setting input_format_orc_skip_columns_with_unsupported_types_in_schema_inference", orc_type->toString()); @@ -330,30 +529,30 @@ static DataTypePtr parseORCType( } } -static std::optional convertORCTypeToPredicateType(const orc::Type & orc_type) +static std::optional convertORCTypeToPredicateType(const ORC::Type & orc_type) { switch (orc_type.getKind()) { - case orc::BOOLEAN: - return orc::PredicateDataType::BOOLEAN; - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: - return orc::PredicateDataType::LONG; - case orc::FLOAT: - case orc::DOUBLE: - return orc::PredicateDataType::FLOAT; - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: - return orc::PredicateDataType::STRING; - case orc::DATE: - return orc::PredicateDataType::DATE; - case orc::TIMESTAMP: - return orc::PredicateDataType::TIMESTAMP; - case orc::DECIMAL: - return orc::PredicateDataType::DECIMAL; + case ORC::BOOLEAN: + return ORC::PredicateDataType::BOOLEAN; + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: + return ORC::PredicateDataType::LONG; + case ORC::FLOAT: + case ORC::DOUBLE: + return ORC::PredicateDataType::FLOAT; + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: + return ORC::PredicateDataType::STRING; + case ORC::DATE: + return ORC::PredicateDataType::DATE; + case ORC::TIMESTAMP: + return ORC::PredicateDataType::TIMESTAMP; + case ORC::DECIMAL: + return ORC::PredicateDataType::DECIMAL; default: return {}; } @@ -370,23 +569,23 @@ static String getColumnNameFromKeyCondition(const KeyCondition & key_condition, throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't get column from KeyCondition with indice {}", indice); } -static std::optional -convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) +static std::optional +convertFieldToORCLiteral(const ORC::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) { try { /// We always fallback to return null if possible CH type hint not consistent with ORC type switch (orc_type.getKind()) { - case orc::BOOLEAN: { + case ORC::BOOLEAN: { /// May throw exception auto val = field.safeGet(); - return orc::Literal(val != 0); + return ORC::Literal(val != 0); } - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: { + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: { /// May throw exception. /// /// In particular, it'll throw if we request the column as unsigned, like this: @@ -394,30 +593,30 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy /// We have to reject this, otherwise it would miss values > 127 (because /// they're treated as negative by ORC). auto val = field.safeGet(); - return orc::Literal(val); + return ORC::Literal(val); } - case orc::FLOAT: - case orc::DOUBLE: { - Float64 val; + case ORC::FLOAT: + case ORC::DOUBLE: { + Float64 val = 0; if (field.tryGet(val)) - return orc::Literal(val); + return ORC::Literal(val); break; } - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: { + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: { String str; if (field.tryGet(str)) - return orc::Literal(str.data(), str.size()); + return ORC::Literal(str.data(), str.size()); break; } - case orc::DATE: { - Int64 val; + case ORC::DATE: { + Int64 val = 0; if (field.tryGet(val)) - return orc::Literal(orc::PredicateDataType::DATE, val); + return ORC::Literal(ORC::PredicateDataType::DATE, val); break; } - case orc::TIMESTAMP: { + case ORC::TIMESTAMP: { if (type_hint && isDateTime64(type_hint)) { const auto * datetime64_type = typeid_cast(type_hint.get()); @@ -426,15 +625,23 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy } DecimalField ts; - if (field.tryGet(ts)) + if (field.tryGet(ts) && ts.getScale() <= 9) { - Int64 secs = (ts.getValue() / ts.getScaleMultiplier()).convertTo(); - Int32 nanos = (ts.getValue() - (ts.getValue() / ts.getScaleMultiplier()) * ts.getScaleMultiplier()).convertTo(); - return orc::Literal(secs, nanos); + /// The nanoseconds are not negative, as in the reference implementation and in the statistics. + const Int64 value = ts.getValue().value; + const Int64 multiplier = ts.getScaleMultiplier().value; + Int64 secs = value / multiplier; + Int64 rest = value % multiplier; + if (rest < 0) + { + rest += multiplier; + --secs; + } + return ORC::Literal(secs, static_cast(rest * (1'000'000'000 / multiplier))); } break; } - case orc::DECIMAL: { + case ORC::DECIMAL: { auto precision = orc_type.getPrecision(); if (precision == 0) precision = 38; @@ -445,8 +652,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -455,8 +662,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -464,10 +671,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy DecimalField val; if (field.tryGet(val)) { - Int64 high = val.getValue().value.items[1]; - UInt64 low = static_cast(val.getValue().value.items[0]); - return orc::Literal( - orc::Int128(high, low), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + val.getValue().value, static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } break; @@ -538,9 +743,9 @@ static bool evaluateRPNElement(const Field & field, const KeyCondition::RPNEleme static void buildORCSearchArgumentImpl( const KeyCondition & key_condition, const Block & header, - const orc::Type & schema, + const ORC::Type & schema, KeyCondition::RPN & rpn_stack, - orc::SearchArgumentBuilder & builder, + ORC::SearchArgumentBuilder & builder, const FormatSettings & format_settings) { if (rpn_stack.empty()) @@ -572,7 +777,7 @@ static void buildORCSearchArgumentImpl( /// Key filter expressions like "func(col) > 100" are not supported for ORC filter push down if (!curr.monotonic_functions_chain.empty()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -583,16 +788,32 @@ static void buildORCSearchArgumentImpl( { if (!set_index || set_index->getOrderedSet().size() != 1 || set_index->hasMonotonicFunctionsChain()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } String column_name = getColumnNameFromKeyCondition(key_condition, curr.getKeyColumn()); - const auto * orc_type = getORCTypeByName(schema, column_name, format_settings.orc.case_insensitive_column_matching); + const bool ignore_case = format_settings.orc.case_insensitive_column_matching; + + /// The predicate column may be a tuple element (`t.x`), which the ORC header does not + /// carry as a flat entry, so resolve it through the type as well as through the schema. + auto column_types = findHeaderTypesByPath(header, column_name, ignore_case); + if (!column_types) + { + builder.literal(ORC::TruthValue::YES_NO_NULL); + break; + } + + /// The resolver rewrites the type it is given when it descends a LIST (a flattened + /// Nested column), so give it a scratch copy: the guards below must judge the key's + /// own type, which is what KeyCondition's RPN holds. + const auto & column_type = column_types->result_type; + auto resolved_type = column_type; + const auto * orc_type = traverseDownORCTypeByName(column_name, &schema, resolved_type, ignore_case); if (!orc_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -607,30 +828,34 @@ static void buildORCSearchArgumentImpl( /// down filters would result in different outputs. bool skipped = false; auto expect_type = makeNullableRecursively(parseORCType(orc_type, true, false, nullptr, skipped, format_settings.max_parser_depth), format_settings); - const ColumnWithTypeAndName * column = header.findByName(column_name, format_settings.orc.case_insensitive_column_matching); - if (!expect_type || !column) + if (!expect_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - auto nested_type = removeNullable(recursiveRemoveLowCardinality(column->type)); + auto nested_type = removeNullable(recursiveRemoveLowCardinality(column_type)); auto expect_nested_type = removeNullable(expect_type); if (!nested_type->equals(*expect_nested_type)) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - /// If null_as_default is true, the only difference is nullable, and the evaluations of current RPNElement based on default and null field - /// have the same result, we still should push down current filter. - if (format_settings.null_as_default && !column->type->isNullable() && !column->type->isLowCardinalityNullable()) + /// A non-nullable element converts NULL to its default even when a nullable ancestor makes + /// its extracted type nullable. Pruning must agree with the values produced by the reader. + const auto & declared_type = column_types->declared_type; + if (format_settings.null_as_default && !isNullableOrLowCardinalityNullable(declared_type)) { - bool match_if_null = evaluateRPNElement({}, curr); - bool match_if_default = evaluateRPNElement(column->type->getDefault(), curr); + /// Use the column default inserted by `insertNullAsDefaultIfNeeded`. It differs from + /// the type default for `Date32`. + auto default_column = declared_type->createColumn(); + default_column->insertDefault(); + const bool match_if_null = evaluateRPNElement({}, curr); + const bool match_if_default = evaluateRPNElement((*default_column)[0], curr); if (match_if_default != match_if_null) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } @@ -638,13 +863,21 @@ static void buildORCSearchArgumentImpl( auto predicate_type = convertORCTypeToPredicateType(*orc_type); if (!predicate_type.has_value()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } if (need_wrap_not) builder.startNot(); + /// A relaxed atom can be false even when its approximation is true. Preserve that + /// possibility before negation, as `KeyCondition` does with `can_be_false`. + if (curr.relaxed) + { + builder.startAnd(); + builder.literal(ORC::TruthValue::YES_NO); + } + if (contains_is_null) { builder.isNull(orc_type->getColumnId(), *predicate_type); @@ -656,8 +889,8 @@ static void buildORCSearchArgumentImpl( bool has_right_bound = !range.right.isPositiveInfinity(); if (!has_left_bound && !has_right_bound) { - /// Transform whole range orc::TruthValue::YES_NULL - builder.literal(orc::TruthValue::YES_NULL); + /// Transform whole range ORC::TruthValue::YES_NULL + builder.literal(ORC::TruthValue::YES_NULL); } else if (has_left_bound && has_right_bound && range.left_included && range.right_included && range.left == range.right) { @@ -666,15 +899,15 @@ static void buildORCSearchArgumentImpl( if (literal.has_value()) builder.equals(orc_type->getColumnId(), *predicate_type, *literal); else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } else { - std::optional left_literal; + std::optional left_literal; if (has_left_bound) left_literal = convertFieldToORCLiteral(*orc_type, range.left); - std::optional right_literal; + std::optional right_literal; if (has_right_bound) right_literal = convertFieldToORCLiteral(*orc_type, range.right); @@ -694,7 +927,7 @@ static void buildORCSearchArgumentImpl( builder.end(); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_right_bound) @@ -707,7 +940,7 @@ static void buildORCSearchArgumentImpl( builder.lessThan(orc_type->getColumnId(), *predicate_type, *right_literal); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_left_bound && has_right_bound) @@ -721,7 +954,7 @@ static void buildORCSearchArgumentImpl( const auto & set_column = ordered_set[0]; bool fail = false; - std::vector literals; + std::vector literals; literals.reserve(set_column->size()); for (size_t i = 0; i < set_column->size(); ++i) { @@ -735,15 +968,28 @@ static void buildORCSearchArgumentImpl( literals.emplace_back(*literal); } - /// set has zero element - if (literals.empty()) - builder.literal(orc::TruthValue::YES); - else if (fail) - builder.literal(orc::TruthValue::YES_NO_NULL); + if (fail) + builder.literal(ORC::TruthValue::YES_NO_NULL); + else if (literals.empty()) + builder.literal(ORC::TruthValue::NO); else + { + /// A set without NULL has no NULL matches. ORC evaluates `IN` as NULL for a + /// NULL key, so exclude NULL explicitly before applying any outer negation. + /// This preserves `nullIn` and `notNullIn` semantics. For regular nullable + /// `IN`, it can only retain extra rows, which the query filter removes. + builder.startAnd(); + builder.startNot(); + builder.isNull(orc_type->getColumnId(), *predicate_type); + builder.end(); builder.in(orc_type->getColumnId(), *predicate_type, literals); + builder.end(); + } } + if (curr.relaxed) + builder.end(); + if (need_wrap_not) builder.end(); @@ -755,7 +1001,7 @@ static void buildORCSearchArgumentImpl( case KeyCondition::RPNElement::FUNCTION_POINT_IN_POLYGON: case KeyCondition::RPNElement::FUNCTION_UNKNOWN: { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); rpn_stack.pop_back(); break; } @@ -787,34 +1033,45 @@ static void buildORCSearchArgumentImpl( } case KeyCondition::RPNElement::ALWAYS_FALSE: { - builder.literal(orc::TruthValue::NO); + builder.literal(ORC::TruthValue::NO); rpn_stack.pop_back(); break; } case KeyCondition::RPNElement::ALWAYS_TRUE: { - builder.literal(orc::TruthValue::YES); + builder.literal(ORC::TruthValue::YES); rpn_stack.pop_back(); break; } } } -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings) +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings) { auto rpn_stack = key_condition.getRPN(); if (rpn_stack.empty()) return nullptr; - auto builder = orc::SearchArgumentFactory::newBuilder(); + auto builder = std::make_unique(); buildORCSearchArgumentImpl(key_condition, header, schema, rpn_stack, *builder, format_settings); return builder->build(); } +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options) +{ + auto reader = std::make_unique(std::move(stream), options); + if (reader->getType().getKind() != ORC::STRUCT) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC files whose root type is not a struct are not supported, the file has root type {}", + reader->getType().toString()); + return reader; +} + static void getFileReader( ReadBuffer & in, - std::unique_ptr & file_reader, + std::unique_ptr & file_reader, const FormatSettings & format_settings, bool use_prefetch, size_t min_bytes_for_seek, @@ -823,16 +1080,18 @@ static void getFileReader( if (is_stopped) return; - orc::ReaderOptions options; - options.setMemoryPool(getORCMemoryPool()); - options.setCacheOptions(orc::CacheOptions{.holeSizeLimit = min_bytes_for_seek, .rangeSizeLimit = 10 * 1024 * 1024UL}); + /// The ranges with the gaps up to `min_bytes_for_seek` are read with one request. + static constexpr UInt64 default_range_size_limit = 10 * 1024 * 1024UL; + ORC::ReaderOptions options; + options.hole_size_limit = min_bytes_for_seek; + options.range_size_limit = std::max(default_range_size_limit, min_bytes_for_seek); auto input_stream = asORCInputStream(in, format_settings, use_prefetch, is_stopped); - file_reader = orc::createReader(std::move(input_stream), options); + file_reader = createORCReader(std::move(input_stream), options); } -static const orc::Type * -traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type, DataTypePtr & type, bool ignore_case) +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case) { /// Recurses the file-controlled ORC type tree. The matching CH type (and the requested column /// name) bound the depth in practice, but keep a stack backstop here too, since this runs in @@ -842,39 +1101,50 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type if (target.empty()) return orc_type; - auto search_struct_field = [&](const std::string & target_, const orc::Type * type_) -> std::pair + auto search_struct_field = [&](const std::string & target_, const ORC::Type * type_) -> std::pair { - auto target_copy = target_; - if (ignore_case) - boost::to_lower(target_copy); - - for (size_t i = 0; i < type_->getSubtypeCount(); ++i) + auto search_pass = [&](bool fold) -> std::pair { - auto field_name = type_->getFieldName(i); - if (ignore_case) - boost::to_lower(field_name); + auto target_copy = target_; + if (fold) + boost::to_lower(target_copy); - if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + for (size_t i = 0; i < type_->getSubtypeCount(); ++i) { - return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + auto field_name = type_->getFieldName(i); + if (fold) + boost::to_lower(field_name); + + if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + { + return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + } } - } - return {"", nullptr}; + return {"", nullptr}; + }; + + /// A field spelled exactly like the request always wins: a struct may hold several fields + /// whose names differ only by case, and case-folding first binds the request to whichever + /// of them the file lists first. + auto exact_match = search_pass(/*fold=*/false); + if (exact_match.second || !ignore_case) + return exact_match; + return search_pass(/*fold=*/true); }; - if (orc::STRUCT == orc_type->getKind()) + if (ORC::STRUCT == orc_type->getKind()) { const auto [next_target, next_orc_type] = search_struct_field(target, orc_type); return next_orc_type ? traverseDownORCTypeByName(next_target, next_orc_type, type, ignore_case) : nullptr; } - if (orc::LIST == orc_type->getKind()) + if (ORC::LIST == orc_type->getKind()) { /// For cases in which header contains subcolumns flattened from nested columns. /// For example, "a Nested(x String, y Int64)" is flattened to "a.x Array(String), a.y Array(Int64)", and ORC file schema is still "a array>". /// In this case, we should skip possible array type and traverse down to its nested struct type. const auto * array_type = typeid_cast(removeNullable(type).get()); const auto * orc_nested_type = orc_type->getSubtype(0); - if (array_type && orc::STRUCT == orc_nested_type->getKind()) + if (array_type && ORC::STRUCT == orc_nested_type->getKind()) { auto next_type_and_target = search_struct_field(target, orc_nested_type); const auto & next_target = next_type_and_target.first; @@ -890,8 +1160,32 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type return nullptr; } +/// Forward declarations: updateIncludeTypeIds needs the union branch-hint machinery (defined +/// below, near readColumnFromORCColumn, which is where it is also used) to prune struct-branch +/// fields the same way the read path does. See computeOrcUnionBranchHints. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive); +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type); +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching); + +/// Binds a name to a field of an ORC struct type. A field spelled exactly like the name always +/// wins over one that only matches case-folded, so a struct holding several fields whose names +/// differ only by case resolves the name to the same field everywhere. +static std::optional findORCStructFieldByName(const ORC::Type * orc_type, const String & name, bool ignore_case) +{ + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (name == orc_type->getFieldName(i)) + return i; + + if (ignore_case) + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (boost::iequals(name, orc_type->getFieldName(i))) + return i; + + return std::nullopt; +} + static void -updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_case, std::unordered_set & include_typeids) +updateIncludeTypeIds(DataTypePtr type, const ORC::Type * orc_type, bool ignore_case, std::unordered_set & include_typeids) { /// Recurses the file-controlled ORC type tree in lockstep with the (parser-bounded) CH type. /// Keep a stack backstop here too: this runs in prepareFileReader, before the @@ -908,24 +1202,26 @@ updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_c auto non_nullable_type = removeNullable(type); switch (orc_type->getKind()) { - case orc::LIST: { + case ORC::LIST: { const auto * array_type = typeid_cast(non_nullable_type.get()); if (array_type) { updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids); + return; } - return; + break; } - case orc::MAP: { + case ORC::MAP: { const auto * map_type = typeid_cast(non_nullable_type.get()); if (map_type) { updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids); updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids); + return; } - return; + break; } - case orc::STRUCT: { + case ORC::STRUCT: { /// To make sure tuple field pruning work fine, we should include only the fields of ORC struct type which are also contained in CH tuple types, instead of all fields of ORC struct type. /// For example, CH tupe type in header is "x Tuple(a String)", ORC struct type is "x struct", then only type id of field "x.a" should be included. /// For tuple field pruning purpose, we should never include "x.b" for it is not required in format header. @@ -934,32 +1230,12 @@ updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_c { if (tuple_type->hasExplicitNames()) { - std::unordered_map orc_field_name_to_index; - orc_field_name_to_index.reserve(orc_type->getSubtypeCount()); - for (size_t struct_i = 0; struct_i < orc_type->getSubtypeCount(); ++struct_i) - { - String field_name = orc_type->getFieldName(struct_i); - if (ignore_case) - boost::to_lower(field_name); - - orc_field_name_to_index[field_name] = struct_i; - } - const auto & element_names = tuple_type->getElementNames(); for (size_t tuple_i = 0; tuple_i < element_names.size(); ++tuple_i) { - String element_name = element_names[tuple_i]; - if (ignore_case) - boost::to_lower(element_name); - - if (orc_field_name_to_index.contains(element_name)) - { + if (auto field_i = findORCStructFieldByName(orc_type, element_names[tuple_i], ignore_case)) updateIncludeTypeIds( - tuple_type->getElement(tuple_i), - orc_type->getSubtype(orc_field_name_to_index[element_name]), - ignore_case, - include_typeids); - } + tuple_type->getElement(tuple_i), orc_type->getSubtype(*field_i), ignore_case, include_typeids); } } else @@ -967,12 +1243,38 @@ updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_c for (size_t i = 0; i < tuple_type->getElements().size() && i < orc_type->getSubtypeCount(); ++i) updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids); } + return; + } + break; + } + case ORC::UNION: { + /// ORC union maps to the ClickHouse Variant type. A branch that gets a forced type hint + /// (the same way readColumnFromORCColumn computes it - see computeOrcUnionBranchHints) + /// is selected by recursing into the hint, so a STRUCT branch keeps the named-tuple + /// field pruning above: a field the hint's tuple does not reference (e.g. an + /// unsupported or corrupt one) is never added to include_typeids. A branch without a + /// forced hint is read in full, matching readColumnFromORCColumn's "no guess is ever + /// made" policy, so its entire subtree is selected. Every branch always contributes at + /// least one id, so ORC's ColumnSelector::selectParents never falls back to its "fully + /// select every branch or none" override for partial branch selection, and the union's + /// own tag stream is selected as the automatic parent of the selected branches. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, non_nullable_type, ignore_case); + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + { + const auto * branch_orc_type = orc_type->getSubtype(i); + if (branch_hints[i]) + updateIncludeTypeIds(branch_hints[i], branch_orc_type, ignore_case, include_typeids); + else + include_typeids.insert(branch_orc_type->getColumnId()); } return; } default: return; } + + /// A requested type of another kind reads the whole node, and the cast to the requested type converts it or throws. + include_typeids.insert(orc_type->getColumnId()); } NativeORCBlockInputFormat::NativeORCBlockInputFormat( @@ -999,18 +1301,18 @@ void NativeORCBlockInputFormat::prepareFileReader() return; if (format_filter_info) - format_filter_info->initKeyConditionOnce(getPort().getHeader()); - - std::unique_ptr stripe_info; - if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); + format_filter_info->initKeyConditionOnce(buildORCKeyConditionBlock( + getPort().getHeader(), + format_filter_info->filter_actions_dag.get(), + format_settings.orc.case_insensitive_column_matching)); orc_column_to_ch_column = std::make_unique( getPort().getHeader(), format_settings.orc.allow_missing_columns, format_settings.null_as_default, format_settings.orc.case_insensitive_column_matching, - format_settings.orc.dictionary_as_low_cardinality); + format_settings.orc.dictionary_as_low_cardinality, + format_settings.date_time_overflow_behavior); const bool ignore_case = format_settings.orc.case_insensitive_column_matching; const auto & header = getPort().getHeader(); @@ -1026,7 +1328,7 @@ void NativeORCBlockInputFormat::prepareFileReader() include_indices.assign(include_typeids.begin(), include_typeids.end()); if (format_settings.orc.filter_push_down && format_filter_info && format_filter_info->key_condition && !sargs) - sargs = buildORCSearchArgument(*format_filter_info->key_condition, getPort().getHeader(), file_reader->getType(), format_settings); + sargs = buildORCSearchArgument(*format_filter_info->key_condition, header, file_schema, format_settings); selected_stripes = calculateSelectedStripes(static_cast(file_reader->getNumberOfStripes()), skip_stripes); read_iterator = 0; @@ -1048,7 +1350,7 @@ void NativeORCBlockInputFormat::prefetchStripes() int stripe = selected_stripes[prefetch_iterator]; stripes.push_back(stripe); - total_stripe_size += file_reader->getStripe(stripe)->getLength(); + total_stripe_size += ORC::Reader::getStripeLength(file_reader->getStripe(stripe)); ++prefetch_iterator; } @@ -1079,32 +1381,31 @@ std::vector NativeORCBlockInputFormat::calculateSelectedStripes(int num_str bool NativeORCBlockInputFormat::prepareStripeReader() { - assert(file_reader); + chassert(file_reader); if (read_iterator >= selected_stripes.size()) return false; int current_stripe = selected_stripes[read_iterator]; - current_stripe_info = file_reader->getStripe(current_stripe); - if (!current_stripe_info->getNumberOfRows()) + current_stripe_info = &file_reader->getStripe(current_stripe); + if (!current_stripe_info->number_of_rows) throw Exception(ErrorCodes::INCORRECT_DATA, "ORC stripe {} has no rows", current_stripe); - orc::RowReaderOptions row_reader_options; - row_reader_options.setEnableLazyDecoding(format_settings.orc.dictionary_as_low_cardinality); - row_reader_options.includeTypes(include_indices); - row_reader_options.setTimezoneName(format_settings.orc.reader_time_zone_name); - row_reader_options.range(current_stripe_info->getOffset(), current_stripe_info->getLength()); + ORC::RowReaderOptions row_reader_options; + row_reader_options.enable_lazy_decoding = format_settings.orc.dictionary_as_low_cardinality; + row_reader_options.include_types = include_indices; + row_reader_options.timezone_name = format_settings.orc.reader_time_zone_name; + row_reader_options.range_offset = current_stripe_info->offset; + row_reader_options.range_length = ORC::Reader::getStripeLength(*current_stripe_info); if (format_settings.orc.filter_push_down && sargs) - { - row_reader_options.searchArgument(sargs); - } + row_reader_options.search_argument = sargs; stripe_reader = file_reader->createRowReader(row_reader_options); ++read_iterator; if (use_prefetch) { /// Release outdated buffer before boundary to avoid OOM - file_reader->releaseBuffer(current_stripe_info->getOffset()); + file_reader->releaseBuffer(current_stripe_info->offset); /// Prefetch next selected stripe prefetchStripes(); @@ -1127,7 +1428,7 @@ Chunk NativeORCBlockInputFormat::read() int current_stripe = selected_stripes[read_iterator]; ++read_iterator; - return getChunkForCount(file_reader->getStripe(current_stripe)->getNumberOfRows()); + return getChunkForCount(file_reader->getStripe(current_stripe).number_of_rows); } if (!stripe_reader) @@ -1139,14 +1440,12 @@ Chunk NativeORCBlockInputFormat::read() if (is_stopped) return {}; - /// TODO: figure out why reuse batch would cause asan fatals in https://s3.amazonaws.com/clickhouse-test-reports/55330/be39d23af2d7e27f5ec7f168947cf75aeaabf674/stateless_tests__asan__[4_4].html - /// Not sure if it is a false positive case. Notice that reusing batch will speed up reading ORC by 1.15x. + /// The values are decoded directly into the columns of the batch, which are then handed over to the chunk. Stopwatch time; - auto batch = stripe_reader->createRowBatch(format_settings.orc.row_batch_size); + auto batch = stripe_reader->createRowBatch(); while (true) { - bool ok = stripe_reader->next(*batch); - if (ok) + if (stripe_reader->next(*batch, static_cast(format_settings.orc.row_batch_size))) break; /// No more rows to read in current stripe, continue to prepare reading next stripe @@ -1163,7 +1462,7 @@ Chunk NativeORCBlockInputFormat::read() orc_column_to_ch_column->orcTableToCHChunk(res, &schema, batch.get(), num_rows, &block_missing_values); LOG_TEST(getLogger("NativeORCBlockInputFormat"), "Convert {} rows take {} ms", num_rows, time.elapsedMilliseconds()); - approx_bytes_read_for_chunk = num_rows * current_stripe_info->getLength() / current_stripe_info->getNumberOfRows(); + approx_bytes_read_for_chunk = num_rows * ORC::Reader::getStripeLength(*current_stripe_info) / current_stripe_info->number_of_rows; return res; } @@ -1188,33 +1487,41 @@ NativeORCSchemaReader::NativeORCSchemaReader(ReadBuffer & in_, const FormatSetti { } -NamesAndTypesList NativeORCSchemaReader::readSchema() +void NativeORCSchemaReader::initializeIfNeeded() { - std::unique_ptr file_reader; - std::atomic is_stopped = 0; + if (initialized) + return; getFileReader(in, file_reader, format_settings, false, 0, is_stopped); + initialized = true; +} + +NamesAndTypesList NativeORCSchemaReader::readSchema() +{ + initializeIfNeeded(); const auto & schema = file_reader->getType(); Block header; - std::unique_ptr stripe_info; + std::optional first_stripe_footer; if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); + first_stripe_footer = file_reader->readStripeFooter(0); - for (size_t i = 0; i < schema.getSubtypeCount(); ++i) { - const std::string & name = schema.getFieldName(i); - const orc::Type * orc_type = schema.getSubtype(i); - - bool skipped = false; - DataTypePtr type = parseORCType( - orc_type, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.orc.dictionary_as_low_cardinality, - stripe_info.get(), - skipped, - format_settings.max_parser_depth); - if (!skipped) - header.insert(ColumnWithTypeAndName{type, name}); + for (size_t i = 0; i < schema.getSubtypeCount(); ++i) + { + const std::string & name = schema.getFieldName(i); + const ORC::Type * orc_type = schema.getSubtype(i); + + bool skipped = false; + DataTypePtr type = parseORCType( + orc_type, + format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + format_settings.orc.dictionary_as_low_cardinality, + first_stripe_footer ? &*first_stripe_footer : nullptr, + skipped, + format_settings.max_parser_depth); + if (!skipped) + header.insert(ColumnWithTypeAndName{type, name}); + } } /// ORC doesn't have non-nullable data types. @@ -1223,26 +1530,34 @@ NamesAndTypesList NativeORCSchemaReader::readSchema() return header.getNamesAndTypesList(); } +std::optional NativeORCSchemaReader::readNumberOrRows() +{ + initializeIfNeeded(); + return file_reader->getNumberOfRows(); +} + ORCColumnToCHColumn::ORCColumnToCHColumn( const Block & header_, bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_, - bool dictionary_as_low_cardinality_) + bool dictionary_as_low_cardinality_, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_) : header(header_) , allow_missing_columns(allow_missing_columns_) , null_as_default(null_as_default_) , case_insensitive_matching(case_insensitive_matching_) , dictionary_as_low_cardinality(dictionary_as_low_cardinality_) + , date_time_overflow_behavior(date_time_overflow_behavior_) { } void ORCColumnToCHColumn::orcTableToCHChunk( - Chunk & res, const orc::Type * schema, const orc::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, const ORC::Type * schema, const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) { - const auto * struct_batch = dynamic_cast(table); + const auto * struct_batch = dynamic_cast(table); if (!struct_batch) - throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", struct_batch->toString()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", demangle(typeid(*table).name())); if (schema->getSubtypeCount() != struct_batch->fields.size()) throw Exception( @@ -1250,24 +1565,26 @@ void ORCColumnToCHColumn::orcTableToCHChunk( size_t field_num = struct_batch->fields.size(); NameToColumnPtr name_to_column_ptr; + /// The file's own spellings, in file order: the keys above are what a request is matched + /// against, and a case-folded match has to pick among them in a fixed order. + Names orc_field_names; + orc_field_names.reserve(field_num); for (size_t i = 0; i < field_num; ++i) { - auto name = schema->getFieldName(i); + const auto & name = schema->getFieldName(i); const auto * field = struct_batch->fields[i]; if (!field) throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table field {} is null", name); - if (case_insensitive_matching) - boost::to_lower(name); - - name_to_column_ptr[std::move(name)] = {field, schema->getSubtype(i)}; + name_to_column_ptr[name] = {field, schema->getSubtype(i)}; + orc_field_names.push_back(name); } - orcColumnsToCHChunk(res, name_to_column_ptr, num_rows, block_missing_values); + orcColumnsToCHChunk(res, name_to_column_ptr, orc_field_names, num_rows, block_missing_values); } /// Creates a null bytemap from ORC's not-null bytemap -static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_column) +static ColumnPtr readByteMapFromORCColumn(const ORC::ColumnVectorBatch * orc_column) { if (!orc_column->hasNulls) return ColumnUInt8::create(orc_column->numElements, static_cast(0)); @@ -1282,70 +1599,67 @@ static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_col } -static const orc::ColumnVectorBatch * getNestedORCColumn(const orc::ListVectorBatch * orc_column) +/// A branch of an ORC union can be non-null at the union level yet select a null payload; ORC +/// leaves a placeholder (a default value) at such positions. When the branch is later cast to an +/// explicit Variant alternative, a value-checking cast (e.g. Int8 -> Enum8, or the same inside a +/// Tuple field) would reject those placeholders even though the rows are never read (they become +/// the Variant NULL discriminator). Overwrite every null-payload row with a copy of a non-null row +/// before casting; the copied values are discarded downstream. If every row is a null payload there +/// is nothing to read, so a null is returned and the caller uses a default-valued column instead. +static ColumnPtr replaceNullPayloadRowsWithValidRow(const ColumnPtr & column, const NullMap & null_map) +{ + size_t valid_row = column->size(); + for (size_t row = 0; row < column->size(); ++row) + if (!null_map[row]) + { + valid_row = row; + break; + } + + if (valid_row == column->size()) + return nullptr; + + auto result = column->cloneEmpty(); + result->reserve(column->size()); + for (size_t row = 0; row < column->size(); ++row) + result->insertFrom(*column, null_map[row] ? valid_row : row); + return result; +} + + +static const ORC::ColumnVectorBatch * getNestedORCColumn(const ORC::ListVectorBatch * orc_column) { return orc_column->elements.get(); } +/// The reader decodes the lengths directly into the end offsets, as in `ColumnArray`. template static ColumnPtr readOffsetsFromORCListColumn(const BatchType * orc_column) { - auto offsets_column = ColumnUInt64::create(); - ColumnArray::Offsets & offsets_data = assert_cast &>(*offsets_column).getData(); - offsets_data.reserve(orc_column->numElements); - - for (size_t i = 0; i < orc_column->numElements; ++i) - offsets_data.push_back(orc_column->offsets[i + 1]); - - return offsets_column; + return orc_column->offsets; } +/// The values of the primitive types are decoded directly into the columns (with zeros for the nulls). static ColumnWithTypeAndName -readColumnWithBooleanData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithBooleanData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_bool_column = dynamic_cast(orc_column); - auto internal_type = DataTypeFactory::instance().get("Bool"); - auto internal_column = internal_type->createColumn(); - auto & column_data = assert_cast &>(*internal_column).getData(); - - column_data.reserve(orc_bool_column->numElements); - for (size_t i = 0; i < orc_bool_column->numElements; ++i) - { - if (!orc_bool_column->hasNulls || orc_bool_column->notNull[i]) - column_data.push_back(static_cast(orc_bool_column->data[i])); - else - column_data.push_back(static_cast(0)); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_bool_column = typeid_cast(*orc_column); + return {orc_bool_column.column, DataTypeFactory::instance().get("Bool"), column_name}; } -template +template static ColumnWithTypeAndName -readColumnWithNumericData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithNumericData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - auto internal_type = std::make_shared>(); - auto internal_column = internal_type->createColumn(); - auto & column_data = static_cast &>(*internal_column).getData(); - const auto * orc_int_column = dynamic_cast(orc_column); - - column_data.reserve(orc_int_column->numElements); - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(NumericType(orc_int_column->data[i])); - else - column_data.push_back(NumericType{}); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_numeric_column = typeid_cast &>(*orc_column); + return {orc_numeric_column.column, std::make_shared>(), column_name}; } template static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( - const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name, bool nullable) + const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name, bool nullable) { /// Fill CH holder_column with ORC dictionary /// Note that holder_column is always a ColumnString or ColumnFixedstring whether nullable is true or false, because ORC dictionary doesn't contain null values. @@ -1358,60 +1672,45 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( DataTypePtr nested_type = nullable ? std::make_shared(holder_type) : holder_type; auto internal_type = std::make_shared(std::move(nested_type)); - const auto & orc_str_column = dynamic_cast(*orc_column); + const auto & orc_str_column = dynamic_cast(*orc_column); size_t rows = orc_str_column.numElements; - const auto & orc_dict = *orc_str_column.dictionary; - if (orc_dict.dictionaryOffset.size() <= 1) + const auto & orc_dict = assert_cast(*orc_str_column.dictionary->column); + size_t dict_size = orc_dict.size(); + if (dict_size == 0) { + /// Only nulls can be encoded with an empty dictionary. + for (size_t i = 0; i < rows; ++i) + { + if (!orc_str_column.hasNulls || orc_str_column.notNull[i]) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC dictionary index {} at row {} is out of range [0, 0)", + orc_str_column.index[i], i); + } auto result_column = internal_type->createColumn(); result_column->insertManyDefaults(rows); return {std::move(result_column), internal_type, column_name}; } - size_t dict_size = orc_dict.dictionaryOffset.size() - 1; - auto holder_column = holder_type->createColumn(); + /// The dictionary of ORC is already a `ColumnString`, which is the holder for `String`. + ColumnPtr holder_column = orc_str_column.dictionary->column; if constexpr (fixed_string) { const size_t n = orc_type->getMaximumLength(); - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - size_t reserve_size = dict_size * n; - column_chars.resize_exact(reserve_size); - size_t curr_offset = 0; + auto fixed_holder_column = ColumnFixedString::create(n); + PaddedPODArray & column_chars = fixed_holder_column->getChars(); + column_chars.resize_fill(dict_size * n); for (size_t i = 0; i < dict_size; ++i) { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - if (buf_size > n) + auto value = orc_dict.getDataAt(i); + if (value.size() > n) throw Exception( ErrorCodes::INCORRECT_DATA, "ORC dictionary entry {} has size {} that exceeds the declared FixedString length {}", - i, buf_size, n); - memcpy(&column_chars[curr_offset], buf, buf_size); - /// resize_exact does not zero-initialize, so pad shorter entries to keep FixedString values - /// deterministic and to avoid leaking uninitialized heap memory. - if (buf_size < n) - memset(&column_chars[curr_offset + buf_size], 0, n - buf_size); - curr_offset += n; - } - } - else - { - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - PaddedPODArray & column_offsets = concrete_holder_column.getOffsets(); - - column_chars.resize_exact(orc_dict.dictionaryBlob.size()); - column_offsets.resize_exact(dict_size); - size_t curr_offset = 0; - for (size_t i = 0; i < dict_size; ++i) - { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; + i, value.size(), n); + memcpy(&column_chars[i * n], value.data(), value.size()); } + holder_column = std::move(fixed_holder_column); } /// Insert CH dictionary_column from holder_column @@ -1475,57 +1774,22 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithStringData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static const ColumnString & getStringColumnFromBatch(const ORC::ColumnVectorBatch * orc_column, ColumnPtr & holder) { - auto internal_type = std::make_shared(); - auto internal_column = internal_type->createColumn(); - PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); - PaddedPODArray & column_offsets = assert_cast(*internal_column).getOffsets(); - - const auto * orc_str_column = dynamic_cast(orc_column); - size_t reserve_size = 0; - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - reserve_size += orc_str_column->length[i]; - } - - column_chars.resize_exact(reserve_size); - column_offsets.resize_exact(orc_str_column->numElements); - - size_t curr_offset = 0; - if (!orc_str_column->hasNulls) - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; - } - } - else - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (orc_str_column->notNull[i]) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - } + holder = ORC::getStringColumn(dynamic_cast(*orc_column)); + return assert_cast(*holder); +} - column_offsets[i] = curr_offset; - } - } - return {std::move(internal_column), internal_type, column_name}; +static ColumnWithTypeAndName +readColumnWithStringData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) +{ + ColumnPtr column; + getStringColumnFromBatch(orc_column, column); + return {column, std::make_shared(), column_name}; } static ColumnWithTypeAndName -readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name) +readColumnWithFixedStringData(const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name) { size_t fixed_len = orc_type->getMaximumLength(); auto internal_type = std::make_shared(fixed_len); @@ -1533,25 +1797,22 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); column_chars.reserve(orc_column->numElements * fixed_len); - const auto * orc_str_column = dynamic_cast(orc_column); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - { - const Int64 length = orc_str_column->length[i]; - if (length < 0 || static_cast(length) > fixed_len) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "ORC string value at row {} has size {} that doesn't fit into FixedString({})", - i, length, fixed_len); + /// The null values are empty strings. + auto value = strings.getDataAt(i); + if (value.size() > fixed_len) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC string value at row {} has size {} that doesn't fit into FixedString({})", + i, value.size(), fixed_len); - column_chars.insert_assume_reserved(orc_str_column->data[i], orc_str_column->data[i] + length); - /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. - if (static_cast(length) < fixed_len) - column_chars.resize_fill(column_chars.size() + (fixed_len - static_cast(length))); - } - else - column_chars.resize_fill(column_chars.size() + fixed_len); + column_chars.insert_assume_reserved(value.data(), value.data() + value.size()); + /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. + if (value.size() < fixed_len) + column_chars.resize_fill(column_chars.size() + (fixed_len - value.size())); } return {std::move(internal_column), internal_type, column_name}; @@ -1560,10 +1821,10 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o template static ColumnWithTypeAndName readColumnWithDecimalDataCast( - const orc::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) { using NativeType = typename DecimalType::NativeType; - static_assert(std::is_same_v || std::is_same_v); + static_assert(std::is_same_v || std::is_same_v); auto internal_column = internal_type->createColumn(); auto & column_data = static_cast &>(*internal_column).getData(); @@ -1574,13 +1835,10 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( { if (!orc_decimal_column->hasNulls || orc_decimal_column->notNull[i]) { - DecimalType decimal_value; - if constexpr (std::is_same_v) + DecimalType decimal_value{}; + if constexpr (std::is_same_v) { - Int128 int128_value; - int128_value.items[0] = orc_decimal_column->values[i].getLowBits(); - int128_value.items[1] = orc_decimal_column->values[i].getHighBits(); - decimal_value.value = static_cast(int128_value); + decimal_value.value = static_cast(orc_decimal_column->values[i]); } else decimal_value.value = static_cast(orc_decimal_column->values[i]); @@ -1595,26 +1853,30 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( } static ColumnWithTypeAndName -readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv6ColumnFromBinaryData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { /// If at least one value size is not 16 bytes, fallback to reading String column and further cast to IPv6. - if ((!orc_str_column->hasNulls || orc_str_column->notNull[i]) && orc_str_column->length[i] != sizeof(IPv6)) - return readColumnWithStringData(orc_column, column_name); + if ((!orc_column->hasNulls || orc_column->notNull[i]) && strings.getDataAt(i).size() != sizeof(IPv6)) + return {holder, std::make_shared(), column_name}; } auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & ipv6_column = assert_cast(*internal_column); - ipv6_column.reserve(orc_str_column->numElements); + ipv6_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - ipv6_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + if (!orc_column->hasNulls || orc_column->notNull[i]) + { + auto value = strings.getDataAt(i); + ipv6_column.insertData(value.data(), value.size()); + } else ipv6_column.insertDefault(); } @@ -1623,49 +1885,46 @@ readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const St } static ColumnWithTypeAndName -readIPv4ColumnWithInt32Data(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv4ColumnWithInt32Data(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_int_column = dynamic_cast(orc_column); + const auto & data = typeid_cast(*orc_column).getData(); auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); - column_data.reserve(orc_int_column->numElements); - - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(static_cast(orc_int_column->data[i])); - else - column_data.push_back(0); - } + column_data.resize(data.size()); + /// The null values are zeros. + for (size_t i = 0; i < data.size(); ++i) + column_data[i] = static_cast(data[i]); return {std::move(internal_column), internal_type, column_name}; } template static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); auto internal_column = column_type->createColumn(); auto & integer_column = assert_cast(*internal_column); - integer_column.reserve(orc_str_column->numElements); + integer_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) + if (!orc_column->hasNulls || orc_column->notNull[i]) { - if (sizeof(typename ColumnType::ValueType) != orc_str_column->length[i]) + auto value = strings.getDataAt(i); + if (sizeof(typename ColumnType::ValueType) != value.size()) throw Exception( ErrorCodes::INCORRECT_DATA, "ValueType size {} of column {} is not equal to size of binary data {}", sizeof(typename ColumnType::ValueType), integer_column.getName(), - orc_str_column->length[i]); + value.size()); - integer_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + integer_column.insertData(value.data(), value.size()); } else { @@ -1676,11 +1935,21 @@ static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( } static ColumnWithTypeAndName readColumnWithDateData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & type_hint) + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & raw_type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { + /// The hint is the raw header type: `readColumnFromORCColumn` strips an outer Nullable but not + /// LowCardinality, so e.g. a LowCardinality(DateTime('UTC')) target would fall through to the + /// raw Int32 branch below and the later context-less cast would read the day count as unix + /// seconds. Strip the wrappers so such targets take the same branches as the plain types. + const DataTypePtr type_hint = raw_type_hint ? removeNullable(recursiveRemoveLowCardinality(raw_type_hint)) : nullptr; + DataTypePtr internal_type; bool check_date32_range = false; bool check_date_range = false; + bool check_datetime_range = false; /// Make result type Date32 when requested type is actually Date32 or when we use schema inference if (!type_hint || isDate32(*type_hint)) @@ -1696,12 +1965,23 @@ static ColumnWithTypeAndName readColumnWithDateData( internal_type = std::make_shared(); check_date_range = true; } + else if (isDateTime(*type_hint)) + { + /// Keep the intermediate as Date32, so the later cast converts the day count to midnight + /// of that day instead of reading it as unix seconds. The cast is context-less, so + /// `date_time_overflow_behavior` does not reach it and a day number whose midnight does + /// not fit into DateTime would wrap to an unrelated timestamp. Validate the range here + /// against the same [0, MAX_DATETIME_DAY_NUM] window that `ToDateTimeImpl` uses. + internal_type = std::make_shared(); + check_datetime_range = true; + } else { internal_type = std::make_shared(); } - const auto * orc_int_column = dynamic_cast(orc_column); + const auto * orc_int_column = dynamic_cast(orc_column); + const auto & orc_int_data = orc_int_column->getData(); auto internal_column = internal_type->createColumn(); PaddedPODArray & column_data = assert_cast &>(*internal_column).getData(); column_data.reserve(orc_int_column->numElements); @@ -1710,25 +1990,50 @@ static ColumnWithTypeAndName readColumnWithDateData( { if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) { - Int32 days_num = static_cast(orc_int_column->data[i]); - if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < -DAYNUM_OFFSET_EPOCH)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", - days_num, - column_name, - -DAYNUM_OFFSET_EPOCH, - DATE_LUT_MAX_EXTEND_DAY_NUM); + /// Range-check the original Int64 day count before narrowing to Int32, + /// otherwise a malformed value could wrap into an apparently valid date. + Int64 days_num = orc_int_data[i]; + if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < (-DAYNUM_OFFSET_EPOCH))) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < (-DAYNUM_OFFSET_EPOCH)) ? (-DAYNUM_OFFSET_EPOCH) : DATE_LUT_MAX_EXTEND_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", + days_num, + column_name, + (-DAYNUM_OFFSET_EPOCH), + DATE_LUT_MAX_EXTEND_DAY_NUM); + } if (check_date_range && (days_num > DATE_LUT_MAX_DAY_NUM || days_num < 0)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", - days_num, - column_name, - DATE_LUT_MAX_DAY_NUM); + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : DATE_LUT_MAX_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", + days_num, + column_name, + DATE_LUT_MAX_DAY_NUM); + } - column_data.push_back(days_num); + if (check_datetime_range && (days_num > MAX_DATETIME_DAY_NUM || days_num < 0)) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : MAX_DATETIME_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the day range of type DateTime, which is [0, {}]", + days_num, + column_name, + MAX_DATETIME_DAY_NUM); + } + + column_data.push_back(static_cast(days_num)); } else { @@ -1739,40 +2044,65 @@ static ColumnWithTypeAndName readColumnWithDateData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static ColumnWithTypeAndName readColumnWithTimestampData( + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { - const auto * orc_ts_column = dynamic_cast(orc_column); + const auto * orc_ts_column = dynamic_cast(orc_column); + + /// ORC stores timestamps as (seconds, nanoseconds). ClickHouse used to convert them through a fixed + /// DateTime64(9) intermediate (seconds * 1e9 + nanoseconds), which overflows Int64 for timestamps beyond + /// ~year 2262 even when the requested DateTime64 scale can represent the value (e.g. Iceberg's DateTime64(6)). + /// Read directly at the requested scale so such values round-trip like Parquet, and only handle overflow when + /// even the target scale does not fit Int64. + UInt32 scale = 9; + if (type_hint) + { + const auto * dt64_hint = typeid_cast(removeNullable(recursiveRemoveLowCardinality(type_hint)).get()); + if (dt64_hint) + scale = dt64_hint->getScale(); + } - auto internal_type = std::make_shared(9); + auto internal_type = std::make_shared(scale); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); column_data.reserve(orc_ts_column->numElements); - constexpr Int64 multiplier = 1e9L; + /// Factor to go from nanoseconds down to the target scale (scale is in [0, 9]). + const Int128 divisor = DecimalUtils::scaleMultiplier(9 - scale); + const Int128 int64_min = std::numeric_limits::min(); + const Int128 int64_max = std::numeric_limits::max(); + for (size_t i = 0; i < orc_ts_column->numElements; ++i) { if (!orc_ts_column->hasNulls || orc_ts_column->notNull[i]) { - Int64 timestamp_value; - Int64 seconds = orc_ts_column->data[i]; - Int64 nanoseconds = orc_ts_column->nanoseconds[i]; + const Int64 seconds = orc_ts_column->data[i]; + const Int64 nanoseconds = orc_ts_column->nanoseconds[i]; - /// Check for overflow when converting timestamp to DateTime64(9) - bool overflow = common::mulOverflow(seconds, multiplier, timestamp_value); - overflow |= common::addOverflow(timestamp_value, nanoseconds, timestamp_value); + /// seconds * 1e9 + nanoseconds cannot overflow Int128 (|seconds| < 2^63, product < ~9.2e27 << Int128 max). + const Int128 nanos_total = static_cast(seconds) * 1'000'000'000 + nanoseconds; + /// Integer division truncates toward zero, matching the DateTime64(9) -> DateTime64(scale) cast that ran afterwards. + Int128 value = nanos_total / divisor; - if (overflow) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Timestamp value in column \"{}\" is out of range for DateTime64: seconds={}, nanoseconds={}", - column_name, - seconds, - nanoseconds); - - Decimal64 decimal64; - decimal64.value = timestamp_value; - column_data.emplace_back(std::move(decimal64)); + if (value < int64_min || value > int64_max) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + value = value < int64_min ? int64_min : int64_max; + else + /// Throw for both `throw` and `ignore` (the default): keep the historical behavior and never silently corrupt data. + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp value in column \"{}\" is out of range for DateTime64({}): seconds={}, nanoseconds={}", + column_name, + scale, + seconds, + nanoseconds); + } + + column_data.push_back(DateTime64(static_cast(value))); } else column_data.push_back(0); @@ -1780,9 +2110,393 @@ readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const Str return {std::move(internal_column), internal_type, column_name}; } +/// Whether a DateTime/DateTime64 target carries an explicit timezone - schema inference produces one +/// (UTC) for the ORC `TIMESTAMP_INSTANT` ("timestamp with local timezone") kind, but an explicit +/// schema may name any timezone. Used to tell the two ORC timestamp kinds apart when matching union +/// branches (see `orcUnionBranchMatchesType`). +static bool orcTimestampTargetHasExplicitTimeZone(const DataTypePtr & type) +{ + const auto * timezone = dynamic_cast(type.get()); + return timezone && timezone->hasExplicitTimeZone(); +} + +/// Whether a ClickHouse numeric type is a widening of an ORC integer branch whose values occupy +/// `orc_size` bytes: a strictly wider integer, or a float that represents every value of that width +/// exactly. The ordinary (non-union) ORC column path gets these conversions for free from the final +/// cast in `orcColumnsToCHChunk`; a union branch has to request them as a per-branch hint, because +/// the final cast of a union column is a `Variant` -> `Variant` cast, which only extends the set of +/// alternatives by exact type name and cannot widen an alternative. Equal-width targets are listed +/// explicitly by the caller (they include the writer's own mappings, such as the unsigned and `Enum` +/// types), so only strictly wider integers are accepted here. +static bool orcIntegerBranchWidensTo(const DataTypePtr & type, size_t orc_size) +{ + const WhichDataType which(type); + if (which.isFloat32()) + return orc_size <= 2; + if (which.isFloat64()) + return orc_size <= 4; + return which.isInteger() && type->getSizeOfValueInMemory() > orc_size; +} + +/// Whether a ClickHouse type can serve as the per-branch type hint for an ORC union branch of the +/// given ORC type. The correspondence is structural (up to Nullable and LowCardinality wrappers), +/// extended with the explicit-schema conversions the reader supports: the integer targets the +/// ordinary column path accepts through the final cast (the unsigned and Enum types of the +/// matching width - they are what the ORC writer maps to these ORC types - int -> IPv4, and the +/// widenings of `orcIntegerBranchWidensTo`, e.g. `Variant(Int64, String)` over +/// `uniontype`) and +/// the special binary readers (binary -> IPv6/Int128/UInt128/Int256/UInt256/Decimal256, +/// char -> big integers and Decimal256). Custom type names matter here: `Bool` is a custom-named +/// `UInt8`, but the writer maps it to BOOLEAN while a plain `UInt8` goes to BYTE, so only BOOLEAN +/// accepts `Bool` - otherwise `Variant(Bool, UInt8)` over `uniontype` would leave +/// both branches ambiguous. The two ORC timestamp kinds need the same care: both read back as plain +/// `DateTime64(9)`, but `TIMESTAMP` is inferred as `DateTime64(9)` and `TIMESTAMP_INSTANT` as +/// `DateTime64(9, 'UTC')`, so `TIMESTAMP_INSTANT` matches only an explicitly time-zoned target while +/// `TIMESTAMP` stays permissive - otherwise `uniontype`, +/// inferred as `Variant(DateTime64(9), DateTime64(9, 'UTC'))`, would leave both branches ambiguous, +/// collapse them to identical `DateTime64(9)`, and be rejected by the duplicate-branch check. Any +/// explicit timezone is accepted (not only `UTC`) so that an explicit schema like +/// `Variant(DateTime64(9), DateTime64(9, 'Europe/Berlin'))` is not rejected; the singles-elimination +/// step decides whether the assignment is forced, and the repair cast relabels the branch to the +/// target timezone (value-preserving for `DateTime64`). Variant sorts its nested types, so the +/// positional correspondence between ORC union branches and Variant alternatives is lost; this +/// predicate is used to reconstruct it. +/// +/// STRUCT branches follow the same named-tuple rules as the non-union ORC struct path: a target +/// tuple with explicit names matches by field name and may project and reorder the ORC struct's +/// fields (the per-branch repair cast then projects/reorders the read tuple to exactly the target), +/// while an unnamed target tuple is matched positionally with the same arity. `case_insensitive` +/// mirrors `input_format_orc_case_insensitive_column_matching` for that name-based matching. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive) +{ + checkStackSize(); + + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + /// A boolean holds only 0 and 1, so every integer type is a widening of it. + return which.isUInt8() || which.isEnum8() || orcIntegerBranchWidensTo(type, 0); + case ORC::TypeKind::BYTE: + return which.isInt8() || (which.isUInt8() && !isBool(type)) || which.isEnum8() || orcIntegerBranchWidensTo(type, 1); + case ORC::TypeKind::SHORT: + return which.isInt16() || which.isUInt16() || which.isEnum16() || orcIntegerBranchWidensTo(type, 2); + case ORC::TypeKind::INT: + return which.isInt32() || which.isUInt32() || which.isIPv4() || orcIntegerBranchWidensTo(type, 4); + case ORC::TypeKind::LONG: + return which.isInt64() || which.isUInt64() || orcIntegerBranchWidensTo(type, 8); + case ORC::TypeKind::FLOAT: + return which.isFloat32() || which.isFloat64(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::DATE: + return which.isDate32() || which.isDate(); + case ORC::TypeKind::TIMESTAMP: + /// Permissive: matches any DateTime/DateTime64 alternative. The repair cast relabels the + /// branch to the alternative's timezone, which is value-preserving for DateTime64. + return which.isDateTime64() || which.isDateTime(); + case ORC::TypeKind::TIMESTAMP_INSTANT: + /// Matches only an explicitly time-zoned target so it stays distinct from a TIMESTAMP + /// branch in the same union (both read back as DateTime64(9)); see the comment above the + /// function. + return (which.isDateTime64() || which.isDateTime()) && orcTimestampTargetHasExplicitTimeZone(type); + case ORC::TypeKind::DECIMAL: + return which.isDecimal(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isStringOrFixedString(); + case ORC::TypeKind::BINARY: + return which.isStringOrFixedString() || which.isIPv6() || which.isInt128() || which.isUInt128() || which.isInt256() + || which.isUInt256() || which.isDecimal256(); + case ORC::TypeKind::CHAR: + return which.isStringOrFixedString() || which.isInt128() || which.isUInt128() || which.isInt256() || which.isUInt256() + || which.isDecimal256(); + case ORC::TypeKind::LIST: + return which.isArray() && orc_branch_type->getSubtypeCount() == 1 + && orcUnionBranchMatchesType( + orc_branch_type->getSubtype(0), assert_cast(*type).getNestedType(), case_insensitive); + case ORC::TypeKind::MAP: + { + if (!which.isMap() || orc_branch_type->getSubtypeCount() != 2) + return false; + const auto & map_type = assert_cast(*type); + return orcUnionBranchMatchesType(orc_branch_type->getSubtype(0), map_type.getKeyType(), case_insensitive) + && orcUnionBranchMatchesType(orc_branch_type->getSubtype(1), map_type.getValueType(), case_insensitive); + } + case ORC::TypeKind::STRUCT: + { + if (!which.isTuple()) + return false; + const auto & tuple_type = assert_cast(*type); + const auto & elements = tuple_type.getElements(); + if (tuple_type.hasExplicitNames()) + { + /// Match by field name, like the non-union ORC struct path: the target tuple may be + /// a subset of the ORC struct's fields, in any order. Each target field must map to + /// an ORC field with a recursively matching type; extra ORC fields are projected out + /// by the repair cast. Build a name -> ORC subtype map for the lookup. + std::unordered_map orc_field_by_name; + orc_field_by_name.reserve(orc_branch_type->getSubtypeCount()); + for (size_t i = 0; i < orc_branch_type->getSubtypeCount(); ++i) + { + String field_name = orc_branch_type->getFieldName(i); + if (case_insensitive) + boost::to_lower(field_name); + orc_field_by_name.emplace(std::move(field_name), orc_branch_type->getSubtype(i)); + } + + const auto & element_names = tuple_type.getElementNames(); + for (size_t i = 0; i < elements.size(); ++i) + { + String element_name = element_names[i]; + if (case_insensitive) + boost::to_lower(element_name); + auto it = orc_field_by_name.find(element_name); + if (it == orc_field_by_name.end() || !orcUnionBranchMatchesType(it->second, elements[i], case_insensitive)) + return false; + } + return true; + } + + /// Unnamed tuple: positional, same arity (no ORC field is silently dropped). + if (elements.size() != orc_branch_type->getSubtypeCount()) + return false; + for (size_t i = 0; i < elements.size(); ++i) + if (!orcUnionBranchMatchesType(orc_branch_type->getSubtype(i), elements[i], case_insensitive)) + return false; + return true; + } + case ORC::TypeKind::UNION: + return which.isVariant(); + case ORC::TypeKind::GEOMETRY: + case ORC::TypeKind::GEOGRAPHY: + /// Added in ORC 2.3. We do not read these, so no target type can match such a branch. + return false; + } + + return false; +} + +/// The natural inference pairing of the string-like ORC kinds, used to tie-break their union-branch +/// matching: CHAR is inferred as FixedString of the same length and STRING/VARCHAR as String, but +/// all of them can be *read* as either (see orcUnionBranchMatchesType), so e.g. +/// uniontype with the inferred Variant(FixedString(1), String) leaves both branches +/// with two candidates. Without a hint each branch would materialize per the current stripe's +/// physical encoding (a dictionary-encoded stripe comes back as LowCardinality), making a supported +/// schema fail depending on per-stripe encoding choices; preferring the natural pairing keeps the +/// assignment stable. The target is inspected with the LowCardinality/Nullable wrappers stripped, +/// so a LowCardinality-wrapped alternative (inferred from a dictionary-encoded stripe) pairs the +/// same way. BINARY deliberately has no preference: it is the conversion-rich kind (IPv6, big +/// integers, Decimal256), so a preference could steal a String alternative from a STRING branch. +/// +/// The numeric kinds are tie-broken the same way, for the same reason: they match their widenings +/// too (see `orcIntegerBranchWidensTo`), so e.g. `uniontype` with the explicit +/// schema `Variant(Int8, Int64)` leaves the `BYTE` branch with two candidates. Preferring the +/// natural pairing keeps the exact-width alternative with its own branch and lets the wider +/// alternative go to the branch that needs it. +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type) +{ + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + return isBool(type); + case ORC::TypeKind::BYTE: + return which.isInt8(); + case ORC::TypeKind::SHORT: + return which.isInt16(); + case ORC::TypeKind::INT: + return which.isInt32(); + case ORC::TypeKind::LONG: + return which.isInt64(); + case ORC::TypeKind::FLOAT: + return which.isFloat32(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::CHAR: + return which.isFixedString() + && assert_cast(*type).getN() == orc_branch_type->getMaximumLength(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isString(); + default: + return false; + } +} + +/// Variant sorts its nested types, so the positional correspondence between ORC union branches +/// and the alternatives of an explicit (or inferred) Variant type hint is lost. Reconstruct it +/// structurally: collect the alternatives each branch can be read as (orcUnionBranchMatchesType), +/// then keep only the forced assignments (a branch takes an alternative when it is its only +/// remaining candidate), tie-breaking the string-like branches by their natural inference pairing +/// (orcUnionBranchPrefersType). A branch whose correspondence stays ambiguous is left without a +/// hint (nullptr in the result), so no guess is ever made. Shared between +/// readColumnFromORCColumn (drives the branch conversions) and updateIncludeTypeIds (prunes a +/// hinted STRUCT branch's fields the same way the read path does), so the two stay in sync. +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching) +{ + const size_t num_children = orc_type->getSubtypeCount(); + DataTypes branch_hints(num_children); + const auto * variant_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; + if (!variant_hint) + return branch_hints; + + const auto & alternatives = variant_hint->getVariants(); + std::vector> candidates(num_children); + for (size_t i = 0; i < num_children; ++i) + for (size_t a = 0; a < alternatives.size(); ++a) + if (orcUnionBranchMatchesType(orc_type->getSubtype(i), alternatives[a], case_insensitive_matching)) + candidates[i].push_back(a); + + std::vector alternative_taken(alternatives.size(), false); + const auto preferred_candidates = [&](size_t i) + { + std::vector preferred; + for (const size_t a : candidates[i]) + if (orcUnionBranchPrefersType(orc_type->getSubtype(i), alternatives[a])) + preferred.push_back(a); + return preferred; + }; + bool changed = true; + while (changed) + { + changed = false; + for (size_t i = 0; i < num_children; ++i) + { + if (branch_hints[i] || candidates[i].size() != 1) + continue; + const size_t a = candidates[i].front(); + if (alternative_taken[a]) + { + /// Another branch already took this alternative; leave this branch without a hint. + candidates[i].clear(); + continue; + } + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + + if (changed) + continue; + + /// The forced assignments are exhausted. Tie-break the string-like branches by their + /// natural inference pairing (see orcUnionBranchPrefersType): a branch takes the single + /// alternative it prefers among its remaining candidates, unless another unassigned + /// branch uniquely prefers the same one - a contested preference is still ambiguous and no + /// guess is ever made. One assignment at a time, then back to the forced-assignment loop + /// to propagate it. + for (size_t i = 0; i < num_children && !changed; ++i) + { + if (branch_hints[i] || candidates[i].size() < 2) + continue; + const auto preferred = preferred_candidates(i); + if (preferred.size() != 1) + continue; + const size_t a = preferred.front(); + bool contested = false; + for (size_t j = 0; j < num_children && !contested; ++j) + { + if (j == i || branch_hints[j]) + continue; + const auto preferred_j = preferred_candidates(j); + contested = preferred_j.size() == 1 && preferred_j.front() == a; + } + if (contested) + continue; + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + } + + return branch_hints; +} + +/// Strips Nullable from a Nullable(Tuple) and propagates the struct null map into its elements. +static ColumnWithTypeAndName unwrapORCNullableTuple(const ColumnWithTypeAndName & column) +{ + const auto * type_nullable = typeid_cast(column.type.get()); + if (!type_nullable) + return column; + + const auto * tuple_type = typeid_cast(type_nullable->getNestedType().get()); + if (!tuple_type) + return column; + + const auto & col_nullable = assert_cast(*column.column); + + const auto & null_map_data = col_nullable.getNullMapData(); + bool has_nulls = !memoryIsZero(null_map_data.data(), 0, null_map_data.size()); + + if (!has_nulls) + { + /// No actual nulls — just strip the Nullable wrapper. + return {col_nullable.getNestedColumnPtr(), type_nullable->getNestedType(), column.name}; + } + + /// Propagate the struct null map to each Tuple element. + const auto & inner_tuple = assert_cast(col_nullable.getNestedColumn()); + const auto & null_map_ptr = col_nullable.getNullMapColumnPtr(); + Columns new_elements; + DataTypes new_types; + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + auto elem_col = inner_tuple.getColumnPtr(i); + auto elem_type = tuple_type->getElement(i); + if (elem_type->isNullable()) + { + /// Element already Nullable — merge null maps (struct null OR element null). + const auto & existing = assert_cast(*elem_col); + auto merged = ColumnUInt8::create(null_map_ptr->size()); + const auto & s = assert_cast(*null_map_ptr).getData(); + const auto & e = existing.getNullMapData(); + auto & m = merged->getData(); + for (size_t j = 0; j < s.size(); ++j) + m[j] = s[j] | e[j]; + new_elements.push_back(ColumnNullable::create(existing.getNestedColumnPtr(), std::move(merged))); + new_types.push_back(elem_type); + } + else if (elem_type->canBeInsideNullable()) + { + new_elements.push_back(ColumnNullable::create(elem_col, null_map_ptr)); + new_types.push_back(std::make_shared(elem_type)); + } + else + { + /// Array, Map, etc. — replace values at null positions with type defaults. + const auto & nm = col_nullable.getNullMapData(); + auto mutable_col = elem_col->cloneEmpty(); + for (size_t j = 0; j < elem_col->size(); ++j) + { + if (nm[j]) + mutable_col->insertDefault(); + else + mutable_col->insertFrom(*elem_col, j); + } + new_elements.push_back(std::move(mutable_col)); + new_types.push_back(elem_type); + } + } + + auto result_type = tuple_type->hasExplicitNames() ? std::make_shared(std::move(new_types), tuple_type->getElementNames()) + : std::make_shared(std::move(new_types)); + return {ColumnTuple::create(std::move(new_elements)), result_type, column.name}; +} + ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint) const @@ -1793,8 +2507,8 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( bool skipped = false; - if (!inside_nullable && (orc_column->hasNulls || (type_hint && type_hint->isNullable())) && !orc_column->isEncoded - && (orc_type->getKind() != orc::LIST && orc_type->getKind() != orc::MAP && orc_type->getKind() != orc::STRUCT)) + if (!inside_nullable && (orc_column->hasNulls || (type_hint && isNullableOrLowCardinalityNullable(type_hint))) && !orc_column->isEncoded + && (orc_type->getKind() != ORC::LIST && orc_type->getKind() != ORC::MAP && orc_type->getKind() != ORC::UNION)) { DataTypePtr nested_type_hint; if (type_hint) @@ -1808,11 +2522,209 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( return {nullable_column, nullable_type, column_name}; } + /// ORC union maps to the ClickHouse Variant type. Handled before the switch below so the switch + /// stays non-exhaustive (its default handles unsupported types). + if (orc_type->getKind() == ORC::UNION) + { + const auto * orc_union_column = dynamic_cast(orc_column); + if (!orc_union_column) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC column for union type must be a UnionVectorBatch"); + + const size_t num_children = orc_type->getSubtypeCount(); + const size_t num_rows = orc_union_column->numElements; + + /// Mirror of the schema-inference guard: a union with more branches than Variant can hold + /// (ColumnVariant::MAX_NESTED_COLUMNS) is rejected explicitly instead of letting the + /// DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an explicit + /// structure, since schema inference already rejects oversized unions. + if (num_children > ColumnVariant::MAX_NESTED_COLUMNS) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported (Variant supports at most {} nested types), while reading column {}", + num_children, ColumnVariant::MAX_NESTED_COLUMNS, column_name); + + /// The hints enable the explicit-schema conversions the scalar readers support (e.g. + /// binary -> IPv6) and keep the branch types aligned with the hinted Variant (e.g. + /// Array(Nullable(...)) produced by schema inference). See computeOrcUnionBranchHints for + /// how a branch's forced alternative is reconstructed; updateIncludeTypeIds calls the same + /// function so a hinted STRUCT branch's field pruning matches what is actually read here. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, type_hint, case_insensitive_matching); + + /// Read each ORC union branch into its own column. ORC keeps a separate physical batch per + /// branch. Variant branches are non-nullable, and an ORC union row can be non-null yet + /// select a branch whose payload is null - such a row is represented by the Variant NULL + /// discriminator (see the row loop below). The branch null map is taken directly from the + /// ORC batch rather than from a Nullable result column: complex (LIST/MAP) and + /// dictionary-encoded branches never come back as ColumnNullable, yet their payload can + /// still be null. inside_nullable is set because nulls are handled here rather than by + /// wrapping the branch value in Nullable. + DataTypes branch_types; + Columns branch_columns; + std::vector branch_null_map_columns(num_children); /// keeps the null maps alive + std::vector branch_null_maps(num_children, nullptr); + branch_types.reserve(num_children); + branch_columns.reserve(num_children); + for (size_t i = 0; i < num_children; ++i) + { + /// A union branch that is itself a union would map to a nested Variant, which Variant + /// forbids; reject it explicitly (matching the schema-inference path) instead of letting + /// the DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an + /// explicit structure, since schema inference already rejects nested unions. + if (orc_type->getSubtype(i)->getKind() == ORC::UNION) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto branch = readColumnFromORCColumn( + orc_union_column->children[i], orc_type->getSubtype(i), column_name, /*inside_nullable=*/true, branch_hints[i]); + + if (orc_union_column->children[i]->hasNulls) + { + branch_null_map_columns[i] = readByteMapFromORCColumn(orc_union_column->children[i]); + branch_null_maps[i] = &assert_cast(*branch_null_map_columns[i]).getData(); + } + + /// A dictionary-encoded branch read without a hint comes back as + /// LowCardinality(Nullable(...)); Variant alternatives cannot be nullable, so strip the + /// inner Nullable (the nulls are tracked by the branch null map above). + ColumnWithTypeAndName branch_non_nullable{ + removeNullableOrLowCardinalityNullable(branch.column), + removeNullableOrLowCardinalityNullable(branch.type), + branch.name}; + + /// With a per-branch hint the branch must end up as exactly that alternative, so that + /// the resulting Variant type equals the hinted one (e.g. a branch of a + /// non-dictionary-encoded file read for a LowCardinality(String) alternative comes + /// back as plain String). Compared by name, not equals: Variant identity is name-based + /// and e.g. equals cannot tell the custom-named Bool from a plain UInt8, which would + /// skip the Bool -> UInt8 repair cast for a boolean branch hinted as UInt8. + if (branch_hints[i] && branch_hints[i]->getName() != branch_non_nullable.type->getName()) + { + if (branch_null_map_columns[i]) + { + /// A value-checking cast (e.g. Int8 -> Enum8, or the same on a nested Tuple + /// field) must not inspect the placeholder values ORC leaves at null-payload + /// positions - those rows become the Variant NULL discriminator below and are + /// never read. Replace them with a valid, castable row before casting. + /// Wrapping the branch in Nullable is not enough: a Nullable(Tuple) cast would + /// still descend into and reject a null nested field. + if (auto safe = replaceNullPayloadRowsWithValidRow(branch_non_nullable.column, *branch_null_maps[i])) + branch_non_nullable.column + = castColumn({safe, branch_non_nullable.type, branch_non_nullable.name}, branch_hints[i]); + else + /// Every row is a null payload and none is read, so a default-valued column + /// of the target type with the same number of rows is enough. + branch_non_nullable.column + = branch_hints[i]->createColumn()->cloneResized(branch_non_nullable.column->size()); + } + else + { + branch_non_nullable.column = castColumn(branch_non_nullable, branch_hints[i]); + } + branch_non_nullable.type = branch_hints[i]; + } + + branch_types.push_back(branch_non_nullable.type); + branch_columns.push_back(std::move(branch_non_nullable.column)); + } + + /// ORC keeps one physical stream per branch, so branches with identical types cannot be + /// represented as a Variant (which de-duplicates types); reject them explicitly. The + /// identity is compared with LowCardinality stripped, so it does not depend on the current + /// stripe's physical encoding (a dictionary-encoded branch materializes as LowCardinality), + /// mirroring the schema-inference check in parseORCType. + std::unordered_set seen_type_names; + for (const auto & branch_type : branch_types) + if (!seen_type_names.insert(recursiveRemoveLowCardinality(branch_type)->getName()).second) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto variant_type = std::make_shared(branch_types); + const auto & global_variants = assert_cast(*variant_type).getVariants(); + + /// Variant stores its branches sorted by type name, so remap ORC tags to global (sorted) + /// discriminators. The Variant sub-columns are built compactly (each must contain exactly + /// the values referenced by its discriminator, in appended order), so they are cloned empty + /// from the ORC branch columns and filled row by row below rather than placed wholesale. + std::unordered_map type_name_to_global; + for (size_t g = 0; g < global_variants.size(); ++g) + type_name_to_global[global_variants[g]->getName()] = static_cast(g); + + MutableColumns variant_columns(global_variants.size()); + std::vector tag_to_global(num_children); + for (size_t i = 0; i < num_children; ++i) + { + auto global = type_name_to_global.at(branch_types[i]->getName()); + tag_to_global[i] = global; + variant_columns[global] = branch_columns[i]->cloneEmpty(); + } + + auto local_discriminators = ColumnVariant::ColumnDiscriminators::create(); + auto & discriminators_data = local_discriminators->getData(); + discriminators_data.resize_exact(num_rows); + + auto offsets = ColumnVariant::ColumnOffsets::create(); + auto & offsets_data = offsets->getData(); + offsets_data.resize_exact(num_rows); + + const UInt8 * tags = orc_union_column->tags.data(); + const uint64_t * orc_offsets = orc_union_column->offsets.data(); + const char * not_null = orc_union_column->hasNulls ? orc_union_column->notNull.data() : nullptr; + + for (size_t row = 0; row < num_rows; ++row) + { + if (not_null && !not_null[row]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const size_t tag = tags[row]; + if (tag >= num_children) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union tag {} for union with {} branches while reading column {}", + tag, num_children, column_name); + + const size_t offset = orc_offsets[row]; + /// A malformed file can point past the selected branch's values; reject it rather than + /// reading out of bounds (the branch column and its null map share this size). + if (offset >= branch_columns[tag]->size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union offset {} into branch {} of size {} while reading column {}", + offset, tag, branch_columns[tag]->size(), column_name); + + /// A non-null union row can still select a branch whose payload is null (ORC keeps the + /// union-level null count at 0 in that case). Variant branches are non-nullable, so + /// represent such a row as a Variant NULL rather than the branch's nested default value. + if (branch_null_maps[tag] && (*branch_null_maps[tag])[offset]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const auto global = tag_to_global[tag]; + auto & variant_column = *variant_columns[global]; + discriminators_data[row] = global; + offsets_data[row] = variant_column.size(); + variant_column.insertFrom(*branch_columns[tag], offset); + } + + auto variant_column = ColumnVariant::create(std::move(local_discriminators), std::move(offsets), std::move(variant_columns)); + return {std::move(variant_column), variant_type, column_name}; + } + switch (orc_type->getKind()) { - case orc::STRING: - case orc::BINARY: - case orc::VARCHAR: + case ORC::STRING: + case ORC::BINARY: + case ORC::VARCHAR: { if (type_hint) { @@ -1844,7 +2756,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithStringData(orc_column, column_name); } - case orc::CHAR: + case ORC::CHAR: { if (type_hint) { @@ -1870,32 +2782,32 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithFixedStringData(orc_column, orc_type, column_name); } - case orc::BOOLEAN: + case ORC::BOOLEAN: return readColumnWithBooleanData(orc_column, column_name); - case orc::BYTE: - return readColumnWithNumericData(orc_column, column_name); - case orc::SHORT: - return readColumnWithNumericData(orc_column, column_name); - case orc::INT: + case ORC::BYTE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::SHORT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::INT: { /// ORC format doesn't have unsigned integers and we output IPv4 as Int32. /// We should allow to read it back from Int32. if (type_hint && isIPv4(type_hint)) return readIPv4ColumnWithInt32Data(orc_column, column_name); - return readColumnWithNumericData(orc_column, column_name); + return readColumnWithNumericData(orc_column, column_name); } - case orc::LONG: - return readColumnWithNumericData(orc_column, column_name); - case orc::FLOAT: - return readColumnWithNumericData(orc_column, column_name); - case orc::DOUBLE: - return readColumnWithNumericData(orc_column, column_name); - case orc::DATE: - return readColumnWithDateData(orc_column, column_name, type_hint); - case orc::TIMESTAMP: [[fallthrough]]; - case orc::TIMESTAMP_INSTANT: - return readColumnWithTimestampData(orc_column, column_name); - case orc::DECIMAL: + case ORC::LONG: + return readColumnWithNumericData(orc_column, column_name); + case ORC::FLOAT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DOUBLE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DATE: + return readColumnWithDateData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::TIMESTAMP: [[fallthrough]]; + case ORC::TIMESTAMP_INSTANT: + return readColumnWithTimestampData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::DECIMAL: { auto interal_type = parseORCType(orc_type, false, false, nullptr, skipped); @@ -1904,15 +2816,15 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( precision = 38; if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); throw Exception( ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal precision {} in ORC type {} is out of bound", precision, orc_type->toString()); } - case orc::MAP: + case ORC::MAP: { DataTypePtr key_type_hint; DataTypePtr value_type_hint; @@ -1926,13 +2838,16 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } } - const auto * orc_map_column = dynamic_cast(orc_column); + const auto * orc_map_column = dynamic_cast(orc_column); const auto * orc_key_column = orc_map_column->keys.get(); const auto * orc_value_column = orc_map_column->elements.get(); const auto * orc_key_type = orc_type->getSubtype(0); const auto * orc_value_type = orc_type->getSubtype(1); auto key_column = readColumnFromORCColumn(orc_key_column, orc_key_type, "key", false, key_type_hint); + /// A map key cannot be Nullable. + if (!key_type_hint && !DataTypeMap::isValidKeyType(key_column.type)) + key_type_hint = removeNullableOrLowCardinalityNullable(key_column.type); if (key_type_hint && !key_type_hint->equals(*key_column.type)) { /// Cast key column to target type, because it can happen @@ -1950,7 +2865,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( auto map_type = std::make_shared(key_column.type, value_column.type); return {map_column, map_type, column_name}; } - case orc::LIST: + case ORC::LIST: { DataTypePtr nested_type_hint; if (type_hint) @@ -1960,35 +2875,43 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( nested_type_hint = array_type_hint->getNestedType(); } - const auto * orc_list_column = dynamic_cast(orc_column); + const auto * orc_list_column = dynamic_cast(orc_column); const auto * orc_nested_column = getNestedORCColumn(orc_list_column); const auto * orc_nested_type = orc_type->getSubtype(0); auto nested_column = readColumnFromORCColumn(orc_nested_column, orc_nested_type, column_name, false, nested_type_hint); auto offsets_column = readOffsetsFromORCListColumn(orc_list_column); - auto array_column = ColumnArray::create(nested_column.column, offsets_column); DataTypePtr array_type; - /// If type hint is Nested, we should return Nested type, - /// because we differentiate Nested and simple Array(Tuple) - if (type_hint && isNested(type_hint)) + ColumnPtr array_data_column = nested_column.column; + /// If type hint is Nested and the element is a named Tuple, return the Nested type + /// so that `Nested::flatten` can decompose it into separate arrays. + /// When the element is Nullable(Tuple(...)), unwrap it and propagate the struct null + /// map to each element via `unwrapNullableTuple`. + const auto * tuple_type = type_hint && isNested(type_hint) + ? typeid_cast(removeNullable(nested_column.type).get()) + : nullptr; + if (tuple_type) { - const auto & tuple_type = assert_cast(*nested_column.type); - array_type = createNested(tuple_type.getElements(), tuple_type.getElementNames()); + auto unwrapped = unwrapORCNullableTuple({array_data_column, nested_column.type, column_name}); + array_data_column = unwrapped.column; + const auto & result_tuple = assert_cast(*unwrapped.type); + array_type = createNested(result_tuple.getElements(), result_tuple.getElementNames()); } else { array_type = std::make_shared(nested_column.type); } + auto array_column = ColumnArray::create(array_data_column, offsets_column); return {array_column, array_type, column_name}; } - case orc::STRUCT: + case ORC::STRUCT: { Columns tuple_elements; DataTypes tuple_types; std::vector tuple_names; const auto * tuple_type_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; - const auto * orc_struct_column = dynamic_cast(orc_column); + const auto * orc_struct_column = dynamic_cast(orc_column); for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) { @@ -1999,7 +2922,12 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( { if (tuple_type_hint->hasExplicitNames()) { - auto pos = tuple_type_hint->tryGetPositionByName(field_name, case_insensitive_matching); + /// An element spelled exactly like the field wins over one that only matches + /// case-folded, so two fields whose names differ only by case cannot both + /// claim the same element and leave the other one unread. + auto pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/false); + if (!pos && case_insensitive_matching) + pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/true); if (pos) { nested_type_hint = tuple_type_hint->getElement(*pos); @@ -2034,8 +2962,27 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } void ORCColumnToCHColumn::orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values) { + /// A file field spelled exactly like the request wins over one that only matches case-folded, + /// so two fields whose names differ only by case are not both answered by the same one. Among + /// fields that only match folded, the first in file order answers. + auto find_orc_column = [&](const String & name) + { + auto it = name_to_column_ptr.find(name); + if (it == name_to_column_ptr.end() && case_insensitive_matching) + { + for (const auto & field_name : orc_field_names) + if (boost::iequals(field_name, name)) + return name_to_column_ptr.find(field_name); + } + return it; + }; + Columns columns_list; columns_list.reserve(header.columns()); std::unordered_map>> nested_tables; @@ -2043,23 +2990,20 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( { const ColumnWithTypeAndName & header_column = header.getByPosition(column_i); - auto search_column_name = header_column.name; - if (case_insensitive_matching) - boost::to_lower(search_column_name); - ColumnWithTypeAndName column; - if (!name_to_column_ptr.contains(search_column_name)) + auto orc_column_it = find_orc_column(header_column.name); + if (orc_column_it == name_to_column_ptr.end()) { bool read_from_nested = false; /// Check if it's a column from nested table. String nested_table_name = Nested::extractTableName(header_column.name); - String search_nested_table_name = nested_table_name; - if (case_insensitive_matching) - boost::to_lower(search_nested_table_name); - if (name_to_column_ptr.contains(search_nested_table_name)) + auto orc_nested_column_it = find_orc_column(nested_table_name); + if (orc_nested_column_it != name_to_column_ptr.end()) { - if (!nested_tables.contains(search_nested_table_name)) + /// Keyed by the file's spelling, so requests that differ only by case share one. + const String & resolved_nested_table_name = orc_nested_column_it->first; + if (!nested_tables.contains(resolved_nested_table_name)) { NamesAndTypesList nested_columns; for (const auto & name_and_type : header.getNamesAndTypesList()) @@ -2069,15 +3013,17 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } auto nested_table_type = Nested::collect(nested_columns).front().type; - auto orc_column_with_type = name_to_column_ptr[search_nested_table_name]; + const auto & orc_column_with_type = orc_nested_column_it->second; ColumnsWithTypeAndName cols = {readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, nested_table_name, false, nested_table_type)}; BlockPtr block_ptr = std::make_shared(cols); auto column_extractor = std::make_shared(*block_ptr, case_insensitive_matching); - nested_tables[search_nested_table_name] = {block_ptr, column_extractor}; + nested_tables[resolved_nested_table_name] = {block_ptr, column_extractor}; } - auto nested_column = nested_tables[search_nested_table_name].second->extractColumn(search_column_name); + /// The requested spelling, not the file's one: the helper matches names + /// case-insensitively itself, and an exact element name outranks a folded match. + auto nested_column = nested_tables[resolved_nested_table_name].second->extractColumn(header_column.name); if (nested_column) { column = *nested_column; @@ -2103,7 +3049,7 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } else { - auto orc_column_with_type = name_to_column_ptr[search_column_name]; + const auto & orc_column_with_type = orc_column_it->second; column = readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, header_column.name, false, header_column.type); } @@ -2118,6 +3064,72 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( res.setColumns(columns_list, num_rows); } +void registerInputFormatORC(FormatFactory & factory); +void registerInputFormatORC(FormatFactory & factory) +{ + factory.registerRandomAccessInputFormat( + "ORC", + [](ReadBuffer & buf, + const Block & sample, + const FormatSettings & settings, + const ReadSettings & read_settings, + bool is_remote_fs, + FormatParserSharedResourcesPtr, + FormatFilterInfoPtr format_filter_info) + { + const bool has_file_size = isBufferWithFileSize(buf); + auto * seekable_in = dynamic_cast(&buf); + const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in + && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; + const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; + return std::make_shared( + buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); + }); + factory.markFormatSupportsSubsetOfColumns("ORC"); +} + +void registerORCSchemaReader(FormatFactory & factory); +void registerORCSchemaReader(FormatFactory & factory) +{ + factory.registerSchemaReader( + "ORC", + [](ReadBuffer & buf, const FormatSettings & settings) + { + return std::make_shared(buf, settings); + } + ); + + factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) + { + return fmt::format( + "schema_inference_make_columns_nullable={};schema_inference_allow_nullable_tuple_type={};" + "dictionary_as_low_cardinality={};skip_columns_with_unsupported_types={};max_parser_depth={}", + settings.schema_inference_make_columns_nullable, + settings.schema_inference_allow_nullable_tuple_type, + settings.orc.dictionary_as_low_cardinality, + settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + settings.max_parser_depth); + }); +} + +} + +#else + +namespace DB +{ + class FormatFactory; + + void registerInputFormatORC(FormatFactory &); + void registerORCSchemaReader(FormatFactory &); + + void registerInputFormatORC(FormatFactory &) + { + } + + void registerORCSchemaReader(FormatFactory &) + { + } } #endif diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h index c58c59889a8c..c22c2be48be3 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h @@ -6,13 +6,12 @@ #include #include -#include #include #include #include #include #include -#include +#include #include namespace DB @@ -20,21 +19,23 @@ namespace DB class KeyCondition; -class ORCInputStream : public orc::InputStream +class ORCInputStream : public ORC::InputStream { public: ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch); - uint64_t getLength() const override; - uint64_t getNaturalReadSize() const override; - void read(void * buf, uint64_t length, uint64_t offset) override; - std::future readAsync(void * buf, uint64_t length, uint64_t offset) override; + UInt64 getLength() const override; + void read(void * buf, UInt64 length, UInt64 offset) override; + std::future readAsync(void * buf, UInt64 length, UInt64 offset) override; const std::string & getName() const override { return name; } protected: SeekableReadBuffer & in; size_t file_size; - bool supports_read_at; + /// Use offset-based reads (ReadBuffer::readBigAt) instead of seek+read; needed for ORC tail. + bool use_offset_based_read; + /// Async wrapper only when caller enabled prefetch and the buffer supports read-at. + bool use_async_prefetch; ThreadPoolCallbackRunnerUnsafe async_runner; std::string name = "ORCInputStream"; @@ -50,22 +51,20 @@ class ORCInputStreamFromString : public ReadBufferFromOwnString, public ORCInput } }; -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled); // Reads the whole file into a memory buffer, owned by the returned RandomAccessFile. -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); -/// The memory pool to set on the options of every ORC reader and writer we create: unlike the -/// default one of the library, it is accounted for by the memory tracker and it throws on failure -/// instead of returning a null pointer that the library dereferences. -orc::MemoryPool & getORCMemoryPool(); +/// Creates an ORC file reader; throws INCORRECT_DATA if the root type of the file is not a struct. +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options); -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings); +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings); class ORCColumnToCHColumn; -class NativeORCBlockInputFormat : public IInputFormat +class NativeORCBlockInputFormat final : public IInputFormat { public: NativeORCBlockInputFormat( @@ -96,14 +95,14 @@ class NativeORCBlockInputFormat : public IInputFormat bool prepareStripeReader(); void prefetchStripes(); - std::unique_ptr file_reader; - std::unique_ptr stripe_reader; + std::unique_ptr file_reader; + std::unique_ptr stripe_reader; std::unique_ptr orc_column_to_ch_column; - std::shared_ptr sargs; + std::shared_ptr sargs; // indices of columns to read from ORC file - std::list include_indices; + std::vector include_indices; BlockMissingValues block_missing_values; size_t approx_bytes_read_for_chunk = 0; @@ -115,30 +114,36 @@ class NativeORCBlockInputFormat : public IInputFormat FormatFilterInfoPtr format_filter_info; std::vector selected_stripes; - size_t read_iterator; - size_t prefetch_iterator; + size_t read_iterator{}; + size_t prefetch_iterator{}; - std::unique_ptr current_stripe_info; + const ORC::Proto::StripeInformation * current_stripe_info = nullptr; std::atomic is_stopped{0}; }; -class NativeORCSchemaReader : public ISchemaReader +class NativeORCSchemaReader final : public ISchemaReader { public: NativeORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); NamesAndTypesList readSchema() override; + std::optional readNumberOrRows() override; private: + void initializeIfNeeded(); + const FormatSettings format_settings; + std::unique_ptr file_reader; + std::atomic is_stopped{0}; + bool initialized = false; }; class ORCColumnToCHColumn { public: - using ORCColumnPtr = const orc::ColumnVectorBatch *; - using ORCTypePtr = const orc::Type *; + using ORCColumnPtr = const ORC::ColumnVectorBatch *; + using ORCTypePtr = const ORC::Type *; using ORCColumnWithType = std::pair; using NameToColumnPtr = std::unordered_map; @@ -147,22 +152,27 @@ class ORCColumnToCHColumn bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_ = false, - bool dictionary_as_low_cardinality_ = false); + bool dictionary_as_low_cardinality_ = false, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_ = FormatSettings::DateTimeOverflowBehavior::Ignore); void orcTableToCHChunk( Chunk & res, - const orc::Type * schema, - const orc::ColumnVectorBatch * table, + const ORC::Type * schema, + const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); void orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values = nullptr); private: ColumnWithTypeAndName readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint = nullptr) const; @@ -173,6 +183,7 @@ class ORCColumnToCHColumn bool null_as_default; bool case_insensitive_matching; bool dictionary_as_low_cardinality; + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior; }; } #endif diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.cpp b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp new file mode 100644 index 000000000000..f792e8d980ad --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp @@ -0,0 +1,1218 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +RleVersion getRleVersion(const Proto::ColumnEncoding & encoding) +{ + switch (encoding.kind) + { + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DICTIONARY: + return RleVersion::V1; + case Proto::ColumnEncodingKind::DIRECT_V2: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return RleVersion::V2; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding {}", static_cast(encoding.kind)); +} + +std::unique_ptr getRequiredStream(StripeStreams & stripe, UInt64 column_id, Proto::StreamKind kind, const char * stream_name, const char * column_kind) +{ + auto stream = stripe.getStream(column_id, kind); + if (!stream) + throw Exception(ErrorCodes::INCORRECT_DATA, "{} stream not found in ORC {} column {}", stream_name, column_kind, column_id); + return stream; +} + +/// Converts the bytes read into the beginning of a buffer of integers into the integers, in place. +/// BOOLEAN and BYTE: the values are decoded into the bytes of the column. +template +class ByteColumnReaderImpl final : public ColumnReader +{ +public: + ByteColumnReaderImpl(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", type.toString().c_str())) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle.skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle.next(reinterpret_cast(data.data()), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + } + +private: + Decoder rle; +}; + +using BooleanColumnReader = ByteColumnReaderImpl; +using ByteColumnReader = ByteColumnReaderImpl; + +/// SHORT, INT, LONG and DATE: the values are decoded into a column of the matching width. +template +class IntegerColumnReader final : public ColumnReader +{ +public: + IntegerColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "integer"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle->next(data.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + std::unique_ptr rle; +}; + +/// FLOAT and DOUBLE: the values are stored as is (little endian), so they are copied into the column. +template +class FloatingColumnReader final : public ColumnReader +{ +public: + FloatingColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , stream(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "floating point")) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + stream->skipBytes(num_values * sizeof(ItemType)); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & data = typeid_cast &>(batch).prepareColumn(num_values); + ItemType * out = data.data(); + + /// The stream has only the non-null values: read them at once to the beginning of the column. + size_t num_present = num_values; + if (not_null) + num_present = std::count_if(not_null, not_null + num_values, [](char c) { return c != 0; }); + + stream->readBytes(reinterpret_cast(out), num_present * sizeof(ItemType)); + if constexpr (std::endian::native == std::endian::big) + for (size_t i = 0; i < num_present; ++i) + out[i] = std::bit_cast(std::byteswap(std::bit_cast(out[i]))); + + if (!not_null) + return; + + /// Move the values to their rows from the back: the k-th value goes to a row i >= k, so it is not overwritten before it is moved. + size_t next_value = num_present; + for (size_t i = num_values; i-- > 0;) + out[i] = not_null[i] ? out[--next_value] : 0; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + stream->seek(positions.at(column_id)); + } + +private: + using Bits = std::conditional_t; + + std::unique_ptr stream; +}; + +/// Converts the lengths in `offsets` into the end offsets (as in `ColumnString` and `ColumnArray`), starting +/// from `total`, and returns the total length. The lengths of the null values are zeros. +UInt64 lengthsToEndOffsets(UInt64 * offsets, size_t num_values, UInt64 column_id, UInt64 total = 0) +{ + for (size_t i = 0; i < num_values; ++i) + { + /// The lengths are non-negative, a negative one is huge as unsigned. + if (offsets[i] > static_cast(std::numeric_limits::max()) || common::addOverflow(total, offsets[i], total) + || total > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid length {} in ORC column {}", static_cast(offsets[i]), column_id); + offsets[i] = total; + } + return total; +} + +/// Reads the strings with their lengths in a separate stream into a `ColumnString`. +ColumnString::MutablePtr readStrings( + IntRleDecoder & length_rle, InputByteStream & blob_stream, size_t num_values, const char * not_null, UInt64 column_id) +{ + /// The buffers grow as the data is decoded: a malformed count or length must not allocate memory + /// before the streams prove to contain the data. + static constexpr size_t MIN_STEP = 64 * 1024; + auto column = ColumnString::create(); + auto & offsets = column->getOffsets(); + UInt64 total = 0; + while (offsets.size() < num_values) + { + size_t done = offsets.size(); + size_t step = std::min(num_values - done, std::max(MIN_STEP, done)); + offsets.resize(done + step); + length_rle.next(offsets.data() + done, step, not_null ? not_null + done : nullptr); + total = lengthsToEndOffsets(offsets.data() + done, step, column_id, total); + } + auto & chars = column->getChars(); + while (chars.size() < total) + { + size_t done = chars.size(); + size_t step = std::min(total - done, std::max(MIN_STEP, done)); + chars.resize(done + step); + blob_stream.readBytes(reinterpret_cast(chars.data() + done), step); + } + return column; +} + +std::shared_ptr loadStringDictionary(UInt64 column_id, StripeStreams & stripe) +{ + const auto & encoding = stripe.getEncoding(column_id); + /// The dictionary is not bounded by the number of rows of the stripe: a column nested in a list or a map + /// can have more values than the stripe has rows. + UInt32 dictionary_size = encoding.dictionary_size; + + auto dictionary = std::make_shared(); + if (dictionary_size == 0) + { + dictionary->column = ColumnString::create(); + return dictionary; + } + + auto length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string dictionary"), false, getRleVersion(encoding)); + auto blob_stream = stripe.getStream(column_id, Proto::StreamKind::DICTIONARY_DATA); + if (!blob_stream) + { + /// All entries can be empty strings, then the stream is not needed. + blob_stream = std::make_unique(std::string_view{}, CompressionKind::NONE, 0, "empty dictionary"); + } + dictionary->column = readStrings(*length_rle, *blob_stream, dictionary_size, nullptr, column_id); + return dictionary; +} + +class StringDictionaryColumnReader final : public ColumnReader +{ +public: + StringDictionaryColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string dictionary"), + false, getRleVersion(stripe.getEncoding(column_id))); + dictionary = loadStringDictionary(column_id, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & string_batch = dynamic_cast(batch); + index.resize(num_values); + rle->next(index.data(), num_values, not_null); + string_batch.isEncoded = false; + string_batch.column = decodeDictionary(assert_cast(*dictionary->column), index.data(), not_null, num_values); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + readIndex(dynamic_cast(batch), num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + void readIndex(EncodedStringVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + batch.isEncoded = true; + batch.dictionary = dictionary; + batch.column = nullptr; + batch.index.resize(num_values); + rle->next(batch.index.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + std::shared_ptr dictionary; + std::unique_ptr rle; + PaddedPODArray index; +}; + +class StringDirectColumnReader final : public ColumnReader +{ +public: + StringDirectColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string"), + false, getRleVersion(stripe.getEncoding(column_id))); + blob_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string"); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + static constexpr size_t BUFFER_SIZE = 1024; + UInt64 buffer[BUFFER_SIZE]; + size_t done = 0; + size_t total_bytes = 0; + while (done < num_values) + { + size_t step = std::min(BUFFER_SIZE, num_values - done); + length_rle->next(buffer, step, nullptr); + total_bytes += lengthsToEndOffsets(buffer, step, column_id); + done += step; + } + blob_stream->skipBytes(total_bytes); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & string_batch = dynamic_cast(batch); + string_batch.isEncoded = false; + string_batch.column = readStrings(*length_rle, *blob_stream, num_values, batch.hasNulls ? batch.notNull.data() : nullptr, column_id); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + blob_stream->seek(provider); + length_rle->seek(provider); + } + +private: + std::unique_ptr length_rle; + std::unique_ptr blob_stream; +}; + +class TimestampColumnReader final : public ColumnReader +{ +public: + TimestampColumnReader(const Type & type, StripeStreams & stripe, bool is_instant) + : ColumnReader(type, stripe) + , writer_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getWriterTimezone()) + , reader_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getReaderTimezone()) + , same_timezone(&writer_timezone == &reader_timezone || writer_timezone.getTimeZone() == reader_timezone.getTimeZone()) + , writer_offset_of(writer_timezone) + , reader_offset_of(reader_timezone) + { + /// The base of the seconds is 2015-01-01 00:00:00 in the time zone of the writer. + static constexpr Int64 UTC_2015_01_01 = 1420070400; + epoch_offset = UTC_2015_01_01 - writer_timezone.timezoneOffset(UTC_2015_01_01); + + RleVersion version = getRleVersion(stripe.getEncoding(column_id)); + seconds_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "timestamp"), true, version); + nanos_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "timestamp"), false, version); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + seconds_rle->skip(num_values); + nanos_rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & timestamp_batch = typeid_cast(batch); + timestamp_batch.data.resize(num_values); + timestamp_batch.nanoseconds.resize(num_values); + Int64 * seconds = timestamp_batch.data.data(); + Int64 * nanos = timestamp_batch.nanoseconds.data(); + seconds_rle->next(seconds, num_values, not_null); + nanos_rle->next(nanos, num_values, not_null); + + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + + const Int64 encoded_nanos = nanos[i]; + /// The lowest 3 bits are the number of the trailing zeros (minus one) that are removed. + UInt64 zeros = nanos[i] & 0x7; + /// An arithmetic shift, as in the reference implementation: some writers (the Arrow + /// adapter) store negative nanoseconds for the timestamps before the epoch. + nanos[i] >>= 3; + if (zeros != 0 && common::mulOverflow(nanos[i], POWERS_OF_TEN_FOR_NANOS[zeros + 1], nanos[i])) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (nanos[i] < -999'999'999 || nanos[i] > 999'999'999) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + Int64 writer_time = 0; + if (common::addOverflow(seconds[i], epoch_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (writer_time < 0 && nanos[i] > 999999 && common::subOverflow(writer_time, Int64{1}, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + if (!same_timezone) + { + /// Keep the same wall clock time when the writer and the reader time zones differ. + Int64 writer_offset = writer_offset_of(writer_time); + Int64 reader_offset = reader_offset_of(writer_time); + if (writer_offset != reader_offset) + { + /// If the adjustment crosses a DST boundary, the offset has to be reevaluated. + Int64 adjusted_time = 0; + if (common::addOverflow(writer_time, writer_offset - reader_offset, adjusted_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + Int64 adjusted_reader_offset = reader_offset_of(adjusted_time); + if (common::addOverflow(writer_time, writer_offset - adjusted_reader_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + } + } + seconds[i] = writer_time; + } + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + seconds_rle->seek(provider); + nanos_rle->seek(provider); + } + +private: + static constexpr Int64 POWERS_OF_TEN_FOR_NANOS[9] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; + + [[noreturn]] void throwInvalidTimestamp(Int64 seconds, Int64 encoded_nanos) const + { + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid timestamp in ORC column {}: seconds={}, encoded nanoseconds={}", column_id, seconds, encoded_nanos); + } + + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + const bool same_timezone; + const TimezoneOffset writer_offset_of; + const TimezoneOffset reader_offset_of; + Int64 epoch_offset = 0; + std::unique_ptr seconds_rle; + std::unique_ptr nanos_rle; +}; + +constexpr UInt32 MAX_PRECISION_64 = 18; +constexpr UInt32 MAX_PRECISION_128 = 38; + +constexpr Int64 POWERS_OF_TEN[MAX_PRECISION_64 + 1] = { + 1LL, + 10LL, + 100LL, + 1000LL, + 10000LL, + 100000LL, + 1000000LL, + 10000000LL, + 100000000LL, + 1000000000LL, + 10000000000LL, + 100000000000LL, + 1000000000000LL, + 10000000000000LL, + 100000000000000LL, + 1000000000000000LL, + 10000000000000000LL, + 100000000000000000LL, + 1000000000000000000LL}; + +/// The DECIMAL columns: an unbounded signed varint per value in the DATA stream and the scale of +/// each value in the SECONDARY stream. The values are rescaled to the scale of the type. +class DecimalColumnReader : public ColumnReader +{ +public: + DecimalColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getPrecision() > MAX_PRECISION_128 || type.getScale() > MAX_PRECISION_128) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + value_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"); + scale_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "decimal"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + size_t skipped = 0; + while (skipped < num_values) + if (!(value_stream->readByte() & 0x80)) + ++skipped; + scale_decoder->skip(num_values); + return num_values; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + value_stream->seek(provider); + scale_decoder->seek(provider); + } + +protected: + /// Reads the zigzag-encoded varint of up to 128 bits. + Int128 readInt128() + { + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + if (shift < 128) + value |= static_cast(byte & 0x7F) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + return static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + } + + /// The scale of each value is read from the file. The valid scales are from 0 to 38, the bound + /// also keeps the differences of the scales and the rescaling work small. + Int32 getValueScale(Int64 value_scale) const + { + if (value_scale < -Int64(MAX_PRECISION_128) || value_scale > Int64(MAX_PRECISION_128)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", value_scale, column_id); + return static_cast(value_scale); + } + + static void scaleInt128(Int128 & value, Int32 target_scale, Int32 current_scale) + { + while (target_scale > current_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, target_scale - current_scale); + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[adjust])); + current_scale += adjust; + } + while (current_scale > target_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, current_scale - target_scale); + value /= POWERS_OF_TEN[adjust]; + current_scale -= adjust; + } + } + + const Int32 precision; + Int32 scale; + std::unique_ptr value_stream; + std::unique_ptr scale_decoder; + PaddedPODArray scales; +}; + +class Decimal64ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int64 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt64(getValueScale(scales[i])); + } + } + +private: + Int64 readInt64(Int32 current_scale) + { + UInt64 encoded = readVarint(*value_stream); + Int64 value = static_cast((encoded >> 1) ^ (~(encoded & 1) + 1)); + if (scale > current_scale && static_cast(scale - current_scale) <= MAX_PRECISION_64) + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[scale - current_scale])); + else if (scale < current_scale && static_cast(current_scale - scale) <= MAX_PRECISION_64) + value /= POWERS_OF_TEN[current_scale - scale]; + else if (scale != current_scale) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", current_scale, column_id); + return value; + } +}; + +class Decimal128ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt128(); + scaleInt128(values[i], scale, getValueScale(scales[i])); + } + } +}; + +/// The DECIMAL columns with the precision up to 18 in the files of the format version 1.9999 +/// (`UNSTABLE_PRE_2_0`): the unscaled values are signed RLEv2 integers in the DATA stream, +/// all with the scale of the type, and there is no SECONDARY stream. +class Decimal64V2ColumnReader final : public ColumnReader +{ +public: + Decimal64V2ColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getScale() > type.getPrecision()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + /// As in the reference implementation, RLEv2 is used regardless of the column encoding. + value_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"), true, RleVersion::V2); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + value_decoder->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & decimal_batch = typeid_cast(batch); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + value_decoder->next(decimal_batch.values.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + value_decoder->seek(positions.at(column_id)); + } + +private: + const Int32 precision; + const Int32 scale; + std::unique_ptr value_decoder; +}; + +/// The DECIMAL columns written by Hive 0.11, without the precision and the scale in the type. +/// As in the reference implementation, the values are read with the scale 6 and must have at most 38 digits. +class DecimalHive11ColumnReader final : public DecimalColumnReader +{ +public: + DecimalHive11ColumnReader(const Type & type, StripeStreams & stripe) + : DecimalColumnReader(type, stripe) + { + scale = 6; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + + static const Int128 max_value = Int128(10000000000000000000ULL) * Int128(10000000000000000000ULL) - 1; + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + bool overflow = false; + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + UInt32 bits = byte & 0x7F; + if (shift > 128 || (shift == 126 && bits > 3)) + overflow = true; + if (shift < 128) + value |= static_cast(bits) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + Int128 decoded = static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + if (!overflow) + { + scaleInt128(decoded, scale, getValueScale(scales[i])); + overflow = decoded > max_value || decoded < -max_value; + } + if (overflow) + throw Exception(ErrorCodes::INCORRECT_DATA, "Hive 0.11 decimal was more than 38 digits in ORC column {}", column_id); + values[i] = decoded; + } + } +}; + +class StructColumnReader final : public ColumnReader +{ +public: + StructColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + const auto & encoding = stripe.getEncoding(column_id); + if (encoding.kind != Proto::ColumnEncodingKind::DIRECT) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown encoding {} of ORC struct column {}", static_cast(encoding.kind), column_id); + const auto & selected = stripe.getSelectedColumns(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children.push_back(buildColumnReader(child, stripe)); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + for (auto & child : children) + child->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + for (auto & child : children) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & struct_batch = typeid_cast(batch); + for (size_t i = 0; i < children.size(); ++i) + { + if constexpr (encoded) + children[i]->nextEncoded(*struct_batch.fields[i], num_values, not_null); + else + children[i]->next(*struct_batch.fields[i], num_values, not_null); + } + } + + std::vector> children; +}; + +/// Reads the lengths of the lists or maps as the end offsets, returns the total number of the children. +UInt64 readListOffsets(IntRleDecoder & rle, ColumnPtr & result, size_t num_values, const char * not_null, UInt64 column_id) +{ + auto column = ColumnUInt64::create(num_values); + auto & offsets = column->getData(); + rle.next(offsets.data(), num_values, not_null); + UInt64 total = lengthsToEndOffsets(offsets.data(), num_values, column_id); + result = std::move(column); + return total; +} + +UInt64 sumLengths(IntRleDecoder & rle, size_t num_values, UInt64 column_id) +{ + static constexpr size_t BUFFER_SIZE = 1024; + Int64 buffer[BUFFER_SIZE]; + UInt64 total = 0; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + { + if (buffer[i] < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Negative length {} in ORC column {}", buffer[i], column_id); + total += static_cast(buffer[i]); + } + read += chunk; + } + return total; +} + +class ListColumnReader final : public ColumnReader +{ +public: + ListColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "list"), + false, getRleVersion(stripe.getEncoding(column_id))); + const Type & child_type = *type.getSubtype(0); + if (stripe.getSelectedColumns()[child_type.getColumnId()]) + child = buildColumnReader(child_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (child) + child->skip(sumLengths(*rle, num_values, column_id)); + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (child) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & list_batch = typeid_cast(batch); + const char * not_null = list_batch.hasNulls ? list_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, list_batch.offsets, num_values, not_null, column_id); + if (child) + { + if constexpr (encoded) + child->nextEncoded(*list_batch.elements, total, nullptr); + else + child->next(*list_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr child; +}; + +class MapColumnReader final : public ColumnReader +{ +public: + MapColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "map"), + false, getRleVersion(stripe.getEncoding(column_id))); + const auto & selected = stripe.getSelectedColumns(); + const Type & key_type = *type.getSubtype(0); + if (selected[key_type.getColumnId()]) + key_reader = buildColumnReader(key_type, stripe); + const Type & value_type = *type.getSubtype(1); + if (selected[value_type.getColumnId()]) + value_reader = buildColumnReader(value_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (key_reader || value_reader) + { + UInt64 total = sumLengths(*rle, num_values, column_id); + if (key_reader) + key_reader->skip(total); + if (value_reader) + value_reader->skip(total); + } + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (key_reader) + key_reader->seekToRowGroup(positions); + if (value_reader) + value_reader->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & map_batch = typeid_cast(batch); + const char * not_null = map_batch.hasNulls ? map_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, map_batch.offsets, num_values, not_null, column_id); + if (key_reader) + { + if constexpr (encoded) + key_reader->nextEncoded(*map_batch.keys, total, nullptr); + else + key_reader->next(*map_batch.keys, total, nullptr); + } + if (value_reader) + { + if constexpr (encoded) + value_reader->nextEncoded(*map_batch.elements, total, nullptr); + else + value_reader->next(*map_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr key_reader; + std::unique_ptr value_reader; +}; + +class UnionColumnReader final : public ColumnReader +{ +public: + UnionColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "union")) + , num_children(type.getSubtypeCount()) + { + children.resize(num_children); + counts.resize(num_children); + const auto & selected = stripe.getSelectedColumns(); + for (size_t i = 0; i < num_children; ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children[i] = buildColumnReader(child, stripe); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + std::fill(counts.begin(), counts.end(), 0); + static constexpr size_t BUFFER_SIZE = 1024; + char buffer[BUFFER_SIZE]; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + ++counts[checkedTag(static_cast(buffer[i]))]; + read += chunk; + } + for (size_t i = 0; i < num_children; ++i) + if (counts[i] && children[i]) + children[i]->skip(counts[i]); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + for (auto & child : children) + if (child) + child->seekToRowGroup(positions); + } + +private: + size_t checkedTag(UInt8 tag) const + { + if (tag >= num_children) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid union tag {} for union with {} children in ORC column {}", static_cast(tag), num_children, column_id); + return tag; + } + + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & union_batch = typeid_cast(batch); + const char * not_null = union_batch.hasNulls ? union_batch.notNull.data() : nullptr; + union_batch.tags.resize(num_values); + union_batch.offsets.resize(num_values); + UInt8 * tags = union_batch.tags.data(); + UInt64 * offsets = union_batch.offsets.data(); + memset(tags, 0, num_values); + rle.next(reinterpret_cast(tags), num_values, not_null); + std::fill(counts.begin(), counts.end(), 0); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + offsets[i] = counts[checkedTag(tags[i])]++; + } + for (size_t i = 0; i < num_children; ++i) + { + if (!children[i]) + continue; + if constexpr (encoded) + children[i]->nextEncoded(*union_batch.children[i], counts[i], nullptr); + else + children[i]->next(*union_batch.children[i], counts[i], nullptr); + } + } + + ByteRleDecoder rle; + const size_t num_children; + std::vector> children; + std::vector counts; +}; + +} + + +ColumnReader::ColumnReader(const Type & type, StripeStreams & stripe) + : column_id(type.getColumnId()) +{ + if (auto stream = stripe.getStream(column_id, Proto::StreamKind::PRESENT)) + not_null_decoder = std::make_unique(std::move(stream)); +} + +void ColumnReader::next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) +{ + batch.reset(num_values); + + if (not_null_decoder) + { + char * not_null = batch.notNull.data(); + not_null_decoder->next(not_null, num_values, incoming_mask); + batch.hasNulls = memchr(not_null, 0, num_values) != nullptr; + return; + } + if (incoming_mask) + { + batch.hasNulls = true; + memcpy(batch.notNull.data(), incoming_mask, num_values); + return; + } + batch.hasNulls = false; +} + +size_t ColumnReader::skip(size_t num_values) +{ + if (!not_null_decoder) + return num_values; + + static constexpr size_t BUFFER_SIZE = 32768; + char buffer[BUFFER_SIZE]; + size_t remaining = num_values; + while (remaining) + { + size_t chunk = std::min(remaining, BUFFER_SIZE); + not_null_decoder->next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + if (!buffer[i]) + --num_values; + remaining -= chunk; + } + return num_values; +} + +void ColumnReader::seekToRowGroup(std::unordered_map & positions) +{ + if (not_null_decoder) + { + auto it = positions.find(column_id); + if (it == positions.end()) + throw Exception(ErrorCodes::INCORRECT_DATA, "No row index for ORC column {}", column_id); + not_null_decoder->seek(it->second); + } +} + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, stripe); + case BYTE: + return std::make_unique(type, stripe); + case SHORT: + return std::make_unique>(type, stripe); + case INT: + return std::make_unique>(type, stripe); + case LONG: + case DATE: + return std::make_unique>(type, stripe); + case FLOAT: + return std::make_unique>(type, stripe); + case DOUBLE: + return std::make_unique>(type, stripe); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + switch (stripe.getEncoding(type.getColumnId()).kind) + { + case Proto::ColumnEncodingKind::DICTIONARY: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return std::make_unique(type, stripe); + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DIRECT_V2: + return std::make_unique(type, stripe); + } + break; + case TIMESTAMP: + return std::make_unique(type, stripe, false); + case TIMESTAMP_INSTANT: + return std::make_unique(type, stripe, true); + case DECIMAL: + if (type.getPrecision() == 0) + return std::make_unique(type, stripe); + if (type.getPrecision() <= MAX_PRECISION_64) + { + if (stripe.isDecimalAsLong()) + return std::make_unique(type, stripe); + return std::make_unique(type, stripe); + } + return std::make_unique(type, stripe); + case STRUCT: + return std::make_unique(type, stripe); + case LIST: + return std::make_unique(type, stripe); + case MAP: + return std::make_unique(type, stripe); + case UNION: + return std::make_unique(type, stripe); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Reading ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.h b/src/Processors/Formats/Impl/ORC/ColumnReader.h new file mode 100644 index 000000000000..1abaedb6fff5 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +/// Access to the streams of one stripe for the column readers. +class StripeStreams +{ +public: + virtual ~StripeStreams() = default; + + virtual const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const = 0; + /// Returns nullptr if the stripe does not have this stream. + virtual std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const = 0; + virtual const std::vector & getSelectedColumns() const = 0; + /// The time zones for TIMESTAMP (not TIMESTAMP_INSTANT) columns. + virtual const DateLUTImpl & getWriterTimezone() const = 0; + virtual const DateLUTImpl & getReaderTimezone() const = 0; + virtual UInt64 getNumberOfRows() const = 0; + /// Whether the file has the format version 1.9999 (`UNSTABLE_PRE_2_0` in the reference implementation), + /// where DECIMAL columns with the precision up to 18 are written as signed RLEv2 integers in the DATA stream + /// without the SECONDARY stream of scales. + virtual bool isDecimalAsLong() const = 0; +}; + +class ColumnReader +{ +public: + ColumnReader(const Type & type, StripeStreams & stripe); + virtual ~ColumnReader() = default; + + /// Reads the next `num_values` values into `batch`. `incoming_mask` is the mask of the + /// non-null values of the parent (or nullptr). + virtual void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask); + + /// Same, but the string columns with dictionary encoding fill `EncodedStringVectorBatch` + /// without decoding the dictionary. + virtual void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + next(batch, num_values, incoming_mask); + } + + /// Skips `num_values` values, returns the number of the skipped non-null values. + virtual size_t skip(size_t num_values); + + /// Moves to the beginning of a row group, by the positions from the row indexes of the columns. + virtual void seekToRowGroup(std::unordered_map & positions); + +protected: + const UInt64 column_id; + std::unique_ptr not_null_decoder; +}; + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe); + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.cpp b/src/Processors/Formats/Impl/ORC/Compression.cpp new file mode 100644 index 000000000000..cfacdc431ca8 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.cpp @@ -0,0 +1,437 @@ +#include + +#include + +#include +#include +#include +/// For `ZSTD_decompressBound`, which is not in the stable ABI of zstd. It is safe, as zstd is linked statically from contrib. +#define ZSTD_STATIC_LINKING_ONLY +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int CANNOT_COMPRESS; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +[[noreturn]] void throwMalformedLzo(size_t offset) +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed LZO-compressed data in ORC file at offset {}", offset); +} + +/// LZO1X decompressor, as written by the Hadoop codecs (and the ORC Java writer). A chunk can be a +/// concatenation of several LZO blocks, each terminated with the end-of-stream marker. +size_t decompressLzo(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + const UInt8 * input = reinterpret_cast(src); + const UInt8 * const input_begin = input; + const UInt8 * const input_end = input + src_size; + char * output = dst; + char * const output_end = dst + dst_capacity; + + auto offset = [&] { return static_cast(input - input_begin); }; + + auto read_byte = [&]() -> UInt32 + { + if (input >= input_end) + throwMalformedLzo(offset()); + return *input++; + }; + + /// A run of zero bytes extends a length by 255 each, then the next byte is added. + auto read_variable_length = [&](UInt32 base) -> size_t + { + size_t length = base; + UInt32 next = 0; + while ((next = read_byte()) == 0) + { + length += 0xFF; + if (length > dst_capacity) + throwMalformedLzo(offset()); + } + return length + next; + }; + + while (input < input_end) + { + bool first_command = true; + size_t last_literal_length = 0; + + while (true) + { + UInt32 command = read_byte(); + if (command == 0x11) + break; + + size_t match_length = 0; + size_t match_offset = 0; + size_t literal_length = 0; + + if ((command & 0xF0) == 0) + { + if (last_literal_length == 0) + { + /// A long run of literals. + literal_length = command & 0xF; + if (literal_length == 0) + literal_length = read_variable_length(0xF); + literal_length += 3; + } + else if (last_literal_length <= 3) + { + match_length = 3; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + match_offset |= 0x800; + literal_length = command & 0x3; + } + else + { + match_length = 2; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + literal_length = command & 0x3; + } + } + else if (first_command) + { + literal_length = command - 17; + } + else if ((command & 0xF0) == 0x10) + { + match_length = command & 0x7; + if (match_length == 0) + match_length = read_variable_length(0x7); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + match_offset |= (command & 0x8) ? 0x8000 : 0x4000; + --match_offset; + literal_length = trailer & 0x3; + } + else if ((command & 0xE0) == 0x20) + { + match_length = command & 0x1F; + if (match_length == 0) + match_length = read_variable_length(0x1F); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + literal_length = trailer & 0x3; + } + else if ((command & 0xC0) != 0) + { + match_length = ((command & 0xE0) >> 5) + 1; + match_offset = (command & 0x1C) >> 2; + match_offset |= read_byte() << 3; + literal_length = command & 0x3; + } + else + throwMalformedLzo(offset()); + + first_command = false; + + if (match_length != 0) + { + /// LZO encodes the match offset minus one. + ++match_offset; + if (match_offset > static_cast(output - dst) || match_length > static_cast(output_end - output)) + throwMalformedLzo(offset()); + const char * match = output - match_offset; + /// The source can overlap the destination, so copy byte by byte. + for (size_t i = 0; i < match_length; ++i) + output[i] = match[i]; + output += match_length; + } + + if (literal_length > static_cast(output_end - output) || literal_length > static_cast(input_end - input)) + throwMalformedLzo(offset()); + memcpy(output, input, literal_length); + output += literal_length; + input += literal_length; + last_literal_length = literal_length; + } + + /// The end-of-stream marker is 0x11 0x00 0x00. + if (input_end - input < 2 || input[0] != 0 || input[1] != 0) + throwMalformedLzo(offset()); + input += 2; + } + + return output - dst; +} + +size_t decompressZlib(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + z_stream stream{}; + if (inflateInit2(&stream, -15) != Z_OK) + throw Exception(ErrorCodes::INCORRECT_DATA, "Cannot initialize zlib decompression for ORC file"); + + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(dst); + stream.avail_out = static_cast(dst_capacity); + + int ret = inflate(&stream, Z_FINISH); + size_t result = dst_capacity - stream.avail_out; + inflateEnd(&stream); + + if (ret != Z_STREAM_END) + { + if (ret == Z_BUF_ERROR && stream.avail_out == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A zlib-compressed chunk of ORC file decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zlib-compressed data in ORC file (zlib error {})", ret); + } + return result; +} + +size_t decompressSnappy(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + if (uncompressed_size > dst_capacity) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A snappy-compressed chunk of ORC file decompresses to {} bytes, more than the {} bytes allowed for the chunk", + uncompressed_size, dst_capacity); + if (!snappy::RawUncompress(src, src_size, dst)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + return uncompressed_size; +} + +size_t decompressLz4(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + if (src_size > static_cast(std::numeric_limits::max()) || dst_capacity > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "LZ4-compressed chunk of ORC file is too large"); + int res = LZ4_decompress_safe(src, dst, static_cast(src_size), static_cast(dst_capacity)); + if (res < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed LZ4-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + return static_cast(res); +} + +size_t decompressZstd(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t res = ZSTD_decompress(dst, dst_capacity, src, src_size); + if (ZSTD_isError(res)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed zstd-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk: {}", + dst_capacity, ZSTD_getErrorName(res)); + return res; +} + + +class ZlibCompressor final : public Compressor +{ +public: + ZlibCompressor() + { + /// The level and the parameters are the same as in the C++ ORC library with its default + /// compression strategy, "speed". + if (deflateInit2(&stream, Z_BEST_SPEED + 1, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot initialize zlib compression for ORC"); + } + + ~ZlibCompressor() override { deflateEnd(&stream); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + if (deflateReset(&stream) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot reset zlib compression for ORC"); + + size_t old_size = out.size(); + /// Allow only the output smaller than the input. + out.resize(old_size + src_size); + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(out.data() + old_size); + stream.avail_out = static_cast(src_size); + + int ret = deflate(&stream, Z_FINISH); + if (ret == Z_STREAM_END && stream.avail_out > 0) + { + size_t compressed = src_size - stream.avail_out; + out.resize(old_size + compressed); + return compressed; + } + out.resize(old_size); + if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zlib compression failed with error {}", ret); + return 0; + } + +private: + z_stream stream{}; +}; + +class SnappyCompressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + out.resize(old_size + snappy::MaxCompressedLength(src_size)); + size_t compressed = 0; + snappy::RawCompress(src, src_size, out.data() + old_size, &compressed); + return finish(out, old_size, compressed, src_size); + } + + static size_t finish(std::string & out, size_t old_size, size_t compressed, size_t src_size) + { + if (compressed >= src_size) + { + out.resize(old_size); + return 0; + } + out.resize(old_size + compressed); + return compressed; + } +}; + +class Lz4Compressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + int bound = LZ4_compressBound(static_cast(src_size)); + out.resize(old_size + bound); + int compressed = LZ4_compress_default(src, out.data() + old_size, static_cast(src_size), bound); + if (compressed <= 0) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "LZ4 compression failed"); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } +}; + +class ZstdCompressor final : public Compressor +{ +public: + ZstdCompressor() : context(ZSTD_createCCtx()) + { + if (!context) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot create zstd compression context"); + } + + ~ZstdCompressor() override { ZSTD_freeCCtx(context); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + size_t bound = ZSTD_compressBound(src_size); + out.resize(old_size + bound); + /// Level 1, as in the C++ ORC library with its default compression strategy, "speed". + size_t compressed = ZSTD_compressCCtx(context, out.data() + old_size, bound, src, src_size, 1); + if (ZSTD_isError(compressed)) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zstd compression failed: {}", ZSTD_getErrorName(compressed)); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } + +private: + ZSTD_CCtx * context; +}; + +} + + +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size) +{ + /// The ratios are the theoretical maximums of the formats, rounded up, so that valid chunks are never rejected. + /// The sizes stored in the chunks are only trusted below these bounds. + static constexpr size_t SLACK = 1024; + switch (kind) + { + case CompressionKind::NONE: + return src_size; + case CompressionKind::SNAPPY: + { + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + /// A copy of 64 bytes takes at least 3 bytes. + return std::min(uncompressed_size, src_size * 22 + SLACK); + } + case CompressionKind::ZSTD: + { + /// Sums the content sizes of all frames, or 128 KiB per block when a frame omits its size, as in `ArrowIPC/BufferCompression.cpp`. + UInt64 bound = ZSTD_decompressBound(src, src_size); + if (bound == ZSTD_CONTENTSIZE_ERROR) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zstd-compressed data in ORC file"); + /// A block of at most 128 KiB takes at least 4 bytes (an RLE block). + return std::min(bound, src_size * 32768 + SLACK); + } + /// A deflate match of 258 bytes takes at least 2 bits. + case CompressionKind::ZLIB: + return src_size * 1032 + SLACK; + /// Every byte of a match length extension adds at most 255 bytes. + case CompressionKind::LZ4: + case CompressionKind::LZO: + return src_size * 256 + SLACK; + default: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + switch (kind) + { + case CompressionKind::ZLIB: return decompressZlib(src, src_size, dst, dst_capacity); + case CompressionKind::SNAPPY: return decompressSnappy(src, src_size, dst, dst_capacity); + case CompressionKind::LZO: return decompressLzo(src, src_size, dst, dst_capacity); + case CompressionKind::LZ4: return decompressLz4(src, src_size, dst, dst_capacity); + case CompressionKind::ZSTD: return decompressZstd(src, src_size, dst, dst_capacity); + case CompressionKind::NONE: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +std::unique_ptr createCompressor(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return nullptr; + case CompressionKind::ZLIB: return std::make_unique(); + case CompressionKind::SNAPPY: return std::make_unique(); + case CompressionKind::LZ4: return std::make_unique(); + case CompressionKind::ZSTD: return std::make_unique(); + case CompressionKind::LZO: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC with compression {} is not supported", compressionKindToString(kind)); +} + +String compressionKindToString(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return "NONE"; + case CompressionKind::ZLIB: return "ZLIB"; + case CompressionKind::SNAPPY: return "SNAPPY"; + case CompressionKind::LZO: return "LZO"; + case CompressionKind::LZ4: return "LZ4"; + case CompressionKind::ZSTD: return "ZSTD"; + case CompressionKind::BROTLI: return "BROTLI"; + } + return "UNKNOWN(" + std::to_string(static_cast(kind)) + ")"; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.h b/src/Processors/Formats/Impl/ORC/Compression.h new file mode 100644 index 000000000000..7e0ceddb72a7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include +#include + +namespace DB::ORC +{ + +using Proto::CompressionKind; + +/// Every compressed chunk of an ORC stream is prefixed with a 3-byte little-endian header: +/// `(chunk_length << 1) | is_original`, where `is_original` means the chunk is stored as is. +static constexpr size_t COMPRESSION_HEADER_SIZE = 3; + +/// Decompresses one chunk into `dst`, which has room for `dst_capacity` bytes (the compression block +/// size of the file). Returns the decompressed size. Throws `INCORRECT_DATA` on malformed input, +/// including a chunk that decompresses to more than `dst_capacity` bytes. +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity); + +/// An upper bound of the decompressed size of a chunk, from the maximum compression ratio of the codec +/// (and the size stored in the chunk), to avoid allocating the whole compression block for a small chunk. +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size); + +/// Compresses chunks of an ORC stream. +class Compressor +{ +public: + virtual ~Compressor() = default; + + /// Appends the compressed representation of `src` to `out` and returns its size, + /// or appends nothing and returns 0 if it would not be smaller than the input. + virtual size_t compress(const char * src, size_t src_size, std::string & out) = 0; +}; + +/// Returns nullptr for `NONE`. +std::unique_ptr createCompressor(CompressionKind kind); + +String compressionKindToString(CompressionKind kind); + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.cpp b/src/Processors/Formats/Impl/ORC/Proto.cpp new file mode 100644 index 000000000000..19e504dfd365 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.cpp @@ -0,0 +1,944 @@ +#include + +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC::Proto +{ + +void WireReader::check(size_t n) const +{ + if (static_cast(end - pos) < n) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated protobuf message in ORC metadata"); +} + +UInt64 WireReader::readVarint() +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + check(1); + UInt8 byte = static_cast(*pos++); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC metadata"); +} + +UInt64 WireReader::readFixed64() +{ + check(8); + UInt64 v = 0; + memcpy(&v, pos, 8); + pos += 8; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +UInt32 WireReader::readFixed32() +{ + check(4); + UInt32 v = 0; + memcpy(&v, pos, 4); + pos += 4; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +double WireReader::readDouble() +{ + return std::bit_cast(readFixed64()); +} + +std::string_view WireReader::readBytes() +{ + UInt64 size = readVarint(); + check(size); + std::string_view res(pos, size); + pos += size; + return res; +} + +bool WireReader::nextField(UInt32 & field_number, WireType & wire_type) +{ + if (pos == end) + return false; + UInt64 key = readVarint(); + field_number = static_cast(key >> 3); + wire_type = static_cast(key & 7); + if (field_number == 0 || (key >> 3) > std::numeric_limits::max()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed field key in ORC metadata"); + return true; +} + +void WireReader::skip(WireType wire_type) +{ + switch (wire_type) + { + case VARINT: readVarint(); return; + case FIXED64: check(8); pos += 8; return; + case LENGTH_DELIMITED: readBytes(); return; + case FIXED32: check(4); pos += 4; return; + case START_GROUP: + case END_GROUP: + break; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unsupported protobuf wire type {} in ORC metadata", static_cast(wire_type)); +} + +bool WireReader::readRepeatedVarint(WireType wire_type, std::vector & out) +{ + if (wire_type == LENGTH_DELIMITED) + { + WireReader packed(readBytes()); + while (packed.pos != packed.end) + out.push_back(packed.readVarint()); + return true; + } + if (wire_type == VARINT) + { + out.push_back(readVarint()); + return true; + } + return false; +} + + +void WireWriter::appendRawVarint(std::string & s, UInt64 value) +{ + while (value >= 0x80) + { + s.push_back(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + s.push_back(static_cast(value)); +} + +void WireWriter::writeVarint(UInt32 field, UInt64 value) +{ + writeKey(field, WireReader::VARINT); + appendRawVarint(out, value); +} + +void WireWriter::writeDouble(UInt32 field, double value) +{ + writeKey(field, WireReader::FIXED64); + UInt64 v = std::bit_cast(value); + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + out.append(reinterpret_cast(&v), 8); +} + +void WireWriter::writeBytes(UInt32 field, std::string_view value) +{ + writeKey(field, WireReader::LENGTH_DELIMITED); + appendRawVarint(out, value.size()); + out.append(value); +} + +void WireWriter::writePackedVarint(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + appendRawVarint(packed, v); + writeBytes(field, packed); +} + +void WireWriter::writePackedFixed64(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + { + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + packed.append(reinterpret_cast(&v), 8); + } + writeBytes(field, packed); +} + + +namespace +{ + +using WireType = WireReader::WireType; + +/// A field with an unexpected wire type is an unknown field, which the Protocol Buffers rules +/// require to skip. It is detected before anything is read, and handled in `parseMessage`. +struct WireTypeMismatch : std::exception +{ +}; + +void expectWireType(WireType actual, WireType expected) +{ + if (actual != expected) + throw WireTypeMismatch{}; +} + +UInt64 readVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readVarint(); +} + +Int64 readSignedVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readSignedVarint(); +} + +UInt32 readUInt32Field(WireReader & r, WireType t) +{ + /// Protobuf truncates the 64-bit varint for 32-bit fields. + return static_cast(readVarintField(r, t)); +} + +/// For `sint32` fields. +Int32 readSignedVarint32Field(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + UInt32 v = static_cast(r.readVarint()); + return static_cast((v >> 1) ^ (~(v & 1) + 1)); +} + +double readDoubleField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::FIXED64); + return r.readDouble(); +} + +std::string_view readBytesField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::LENGTH_DELIMITED); + return r.readBytes(); +} + +void checkCount(size_t count, size_t max_count, std::string_view what) +{ + if (count >= max_count) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many {} in ORC metadata, at most {} expected", what, max_count); +} + +template +void parseMessage(std::string_view data, F && handle_field) +{ + WireReader r(data); + UInt32 field = 0; + WireType type = WireReader::VARINT; + while (r.nextField(field, type)) + { + bool handled = false; + try + { + handled = handle_field(r, field, type); + } + catch (const WireTypeMismatch &) + { + handled = false; + } + if (!handled) + r.skip(type); + } +} + +IntegerStatistics parseIntegerStatistics(std::string_view data) +{ + IntegerStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +DoubleStatistics parseDoubleStatistics(std::string_view data) +{ + DoubleStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readDoubleField(r, type); return true; + case 2: res.maximum = readDoubleField(r, type); return true; + case 3: res.sum = readDoubleField(r, type); return true; + default: return false; + } + }); + return res; +} + +StringStatistics parseStringStatistics(std::string_view data) +{ + StringStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + case 4: res.lower_bound = std::string(readBytesField(r, type)); return true; + case 5: res.upper_bound = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +BucketStatistics parseBucketStatistics(std::string_view data) +{ + BucketStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + return r.readRepeatedVarint(type, res.count); + }); + return res; +} + +DecimalStatistics parseDecimalStatistics(std::string_view data) +{ + DecimalStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +DateStatistics parseDateStatistics(std::string_view data) +{ + DateStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarint32Field(r, type); return true; + case 2: res.maximum = readSignedVarint32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +TimestampStatistics parseTimestampStatistics(std::string_view data) +{ + TimestampStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.minimum_utc = readSignedVarintField(r, type); return true; + case 4: res.maximum_utc = readSignedVarintField(r, type); return true; + case 5: res.minimum_nanos = readVarintField(r, type); return true; + case 6: res.maximum_nanos = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +BinaryStatistics parseBinaryStatistics(std::string_view data) +{ + BinaryStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + res.sum = readSignedVarintField(r, type); + return true; + }); + return res; +} + +CollectionStatistics parseCollectionStatistics(std::string_view data) +{ + CollectionStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.min_children = readVarintField(r, type); return true; + case 2: res.max_children = readVarintField(r, type); return true; + case 3: res.total_children = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +Stream parseStream(std::string_view data) +{ + Stream res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: res.column = readUInt32Field(r, type); return true; + case 3: res.length = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +ColumnEncoding parseColumnEncoding(std::string_view data) +{ + ColumnEncoding res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: + { + UInt32 kind = readUInt32Field(r, type); + if (kind > static_cast(ColumnEncodingKind::DICTIONARY_V2)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding kind {}", kind); + res.kind = static_cast(kind); + return true; + } + case 2: res.dictionary_size = readUInt32Field(r, type); return true; + case 3: res.bloom_encoding = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +Type parseType(std::string_view data) +{ + Type res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: return r.readRepeatedVarint(type, res.subtypes); + case 3: res.field_names.emplace_back(readBytesField(r, type)); return true; + case 4: res.maximum_length = readUInt32Field(r, type); return true; + case 5: res.precision = readUInt32Field(r, type); return true; + case 6: res.scale = readUInt32Field(r, type); return true; + case 7: + { + StringPair pair; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: pair.key = std::string(readBytesField(rr, t)); return true; + case 2: pair.value = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + res.attributes.push_back(std::move(pair)); + return true; + } + case 8: res.crs = std::string(readBytesField(r, type)); return true; + case 9: res.algorithm = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +StripeInformation parseStripeInformation(std::string_view data) +{ + StripeInformation res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.offset = readVarintField(r, type); return true; + case 2: res.index_length = readVarintField(r, type); return true; + case 3: res.data_length = readVarintField(r, type); return true; + case 4: res.footer_length = readVarintField(r, type); return true; + case 5: res.number_of_rows = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +UserMetadataItem parseUserMetadataItem(std::string_view data) +{ + UserMetadataItem res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.name = std::string(readBytesField(r, type)); return true; + case 2: res.value = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +std::string serializeIntegerStatistics(const IntegerStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + return out; +} + +std::string serializeDoubleStatistics(const DoubleStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeDouble(1, *s.minimum); + if (s.maximum) w.writeDouble(2, *s.maximum); + if (s.sum) w.writeDouble(3, *s.sum); + return out; +} + +std::string serializeStringStatistics(const StringStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + if (s.lower_bound) w.writeBytes(4, *s.lower_bound); + if (s.upper_bound) w.writeBytes(5, *s.upper_bound); + return out; +} + +std::string serializeDecimalStatistics(const DecimalStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeBytes(3, *s.sum); + return out; +} + +std::string serializeDateStatistics(const DateStatistics & s) +{ + std::string out; + WireWriter w(out); + auto zigzag32 = [](Int32 v) { return static_cast((static_cast(v) << 1) ^ static_cast(v >> 31)); }; + if (s.minimum) w.writeVarint(1, zigzag32(*s.minimum)); + if (s.maximum) w.writeVarint(2, zigzag32(*s.maximum)); + return out; +} + +std::string serializeTimestampStatistics(const TimestampStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.minimum_utc) w.writeSignedVarint(3, *s.minimum_utc); + if (s.maximum_utc) w.writeSignedVarint(4, *s.maximum_utc); + /// `int32` fields: negative values are sign-extended to 64 bits. + if (s.minimum_nanos) w.writeVarint(5, *s.minimum_nanos); + if (s.maximum_nanos) w.writeVarint(6, *s.maximum_nanos); + return out; +} + +std::string serializeCollectionStatistics(const CollectionStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.min_children) w.writeVarint(1, *s.min_children); + if (s.max_children) w.writeVarint(2, *s.max_children); + if (s.total_children) w.writeVarint(3, *s.total_children); + return out; +} + +std::string serializeType(const Type & t) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, t.kind); + w.writePackedVarint(2, t.subtypes); + for (const auto & name : t.field_names) + w.writeBytes(3, name); + if (t.maximum_length) w.writeVarint(4, *t.maximum_length); + if (t.precision) w.writeVarint(5, *t.precision); + if (t.scale) w.writeVarint(6, *t.scale); + for (const auto & attr : t.attributes) + { + std::string pair; + WireWriter pw(pair); + pw.writeBytes(1, attr.key); + pw.writeBytes(2, attr.value); + w.writeBytes(7, pair); + } + if (t.crs) w.writeBytes(8, *t.crs); + if (t.algorithm) w.writeVarint(9, *t.algorithm); + return out; +} + +std::string serializeStripeInformation(const StripeInformation & s) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, s.offset); + w.writeVarint(2, s.index_length); + w.writeVarint(3, s.data_length); + w.writeVarint(4, s.footer_length); + w.writeVarint(5, s.number_of_rows); + return out; +} + +} + + +void PostScript::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: footer_length = readVarintField(r, type); return true; + case 2: + { + UInt64 kind = readVarintField(r, type); + if (kind > static_cast(CompressionKind::BROTLI)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC compression kind {}", kind); + compression = static_cast(kind); + return true; + } + case 3: compression_block_size = readVarintField(r, type); return true; + case 4: return r.readRepeatedVarint(type, version); + case 5: metadata_length = readVarintField(r, type); return true; + case 6: writer_version = readUInt32Field(r, type); return true; + case 8000: magic = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string PostScript::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, footer_length); + w.writeVarint(2, static_cast(compression)); + w.writeVarint(3, compression_block_size); + w.writePackedVarint(4, version); + w.writeVarint(5, metadata_length); + w.writeVarint(6, writer_version); + w.writeBytes(8000, magic); + return out; +} + +void ColumnStatistics::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: number_of_values = readVarintField(r, type); return true; + case 2: int_statistics = parseIntegerStatistics(readBytesField(r, type)); return true; + case 3: double_statistics = parseDoubleStatistics(readBytesField(r, type)); return true; + case 4: string_statistics = parseStringStatistics(readBytesField(r, type)); return true; + case 5: bucket_statistics = parseBucketStatistics(readBytesField(r, type)); return true; + case 6: decimal_statistics = parseDecimalStatistics(readBytesField(r, type)); return true; + case 7: date_statistics = parseDateStatistics(readBytesField(r, type)); return true; + case 8: binary_statistics = parseBinaryStatistics(readBytesField(r, type)); return true; + case 9: timestamp_statistics = parseTimestampStatistics(readBytesField(r, type)); return true; + case 10: has_null = readVarintField(r, type) != 0; return true; + case 11: bytes_on_disk = readVarintField(r, type); return true; + case 12: collection_statistics = parseCollectionStatistics(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string ColumnStatistics::serialize() const +{ + std::string out; + WireWriter w(out); + if (number_of_values) w.writeVarint(1, *number_of_values); + if (int_statistics) w.writeBytes(2, serializeIntegerStatistics(*int_statistics)); + if (double_statistics) w.writeBytes(3, serializeDoubleStatistics(*double_statistics)); + if (string_statistics) w.writeBytes(4, serializeStringStatistics(*string_statistics)); + if (bucket_statistics) + { + std::string bucket; + WireWriter(bucket).writePackedVarint(1, bucket_statistics->count); + w.writeBytes(5, bucket); + } + if (decimal_statistics) w.writeBytes(6, serializeDecimalStatistics(*decimal_statistics)); + if (date_statistics) w.writeBytes(7, serializeDateStatistics(*date_statistics)); + if (binary_statistics) + { + std::string binary; + if (binary_statistics->sum) + WireWriter(binary).writeSignedVarint(1, *binary_statistics->sum); + w.writeBytes(8, binary); + } + if (timestamp_statistics) w.writeBytes(9, serializeTimestampStatistics(*timestamp_statistics)); + if (has_null) w.writeVarint(10, *has_null); + if (bytes_on_disk) w.writeVarint(11, *bytes_on_disk); + if (collection_statistics) w.writeBytes(12, serializeCollectionStatistics(*collection_statistics)); + return out; +} + +void RowIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view entry_data = readBytesField(r, type); + checkCount(entry.size(), max_entries, "row index entries"); + auto & e = entry.emplace_back(); + parseMessage(entry_data, [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: return rr.readRepeatedVarint(t, e.positions); + case 2: e.statistics.emplace().parse(readBytesField(rr, t)); return true; + default: return false; + } + }); + return true; + }); +} + +std::string RowIndex::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & e : entry) + { + std::string entry_data; + WireWriter ew(entry_data); + ew.writePackedVarint(1, e.positions); + if (e.statistics) + ew.writeBytes(2, e.statistics->serialize()); + w.writeBytes(1, entry_data); + } + return out; +} + +void BloomFilterIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + checkCount(bloom_filter.size(), max_entries, "bloom filters"); + BloomFilter bf; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: bf.num_hash_functions = readUInt32Field(rr, t); return true; + case 2: + { + if (t == WireReader::LENGTH_DELIMITED) + { + /// Packed fixed64: a sequence of 8-byte little-endian values. + std::string_view bytes = rr.readBytes(); + if (bytes.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed bloom filter bitset in ORC file"); + WireReader packed(bytes); + for (size_t i = 0; i < bytes.size() / 8; ++i) + bf.bitset.push_back(packed.readFixed64()); + } + else + { + expectWireType(t, WireReader::FIXED64); + bf.bitset.push_back(rr.readFixed64()); + } + return true; + } + case 3: bf.utf8bitset = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + bloom_filter.push_back(std::move(bf)); + return true; + }); +} + +void StripeFooter::parse(std::string_view data, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: streams.push_back(parseStream(readBytesField(r, type))); return true; + case 2: + { + std::string_view encoding_data = readBytesField(r, type); + checkCount(columns.size(), max_columns, "column encodings"); + columns.push_back(parseColumnEncoding(encoding_data)); + return true; + } + case 3: writer_timezone = std::string(readBytesField(r, type)); return true; + case 4: readBytesField(r, type); ++encryption_variants; return true; + default: return false; + } + }); +} + +std::string StripeFooter::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & s : streams) + { + std::string stream; + WireWriter sw(stream); + if (s.kind) + sw.writeVarint(1, *s.kind); + sw.writeVarint(2, s.column); + sw.writeVarint(3, s.length); + w.writeBytes(1, stream); + } + for (const auto & c : columns) + { + std::string encoding; + WireWriter ew(encoding); + ew.writeVarint(1, static_cast(c.kind)); + if (c.kind == ColumnEncodingKind::DICTIONARY || c.kind == ColumnEncodingKind::DICTIONARY_V2) + ew.writeVarint(2, c.dictionary_size); + w.writeBytes(2, encoding); + } + if (writer_timezone) + w.writeBytes(3, *writer_timezone); + return out; +} + +void Metadata::parse(std::string_view data, size_t max_stripes, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view stripe_data = readBytesField(r, type); + checkCount(stripe_stats.size(), max_stripes, "stripe statistics"); + StripeStatistics stats; + parseMessage(stripe_data, [&](WireReader & rr, UInt32 f, WireType t) + { + if (f != 1) + return false; + std::string_view column_data = readBytesField(rr, t); + checkCount(stats.col_stats.size(), max_columns, "column statistics"); + stats.col_stats.emplace_back().parse(column_data); + return true; + }); + stripe_stats.push_back(std::move(stats)); + return true; + }); +} + +std::string Metadata::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & stats : stripe_stats) + { + std::string stripe; + WireWriter sw(stripe); + for (const auto & col : stats.col_stats) + sw.writeBytes(1, col.serialize()); + w.writeBytes(1, stripe); + } + return out; +} + +void Footer::parse(std::string_view data) +{ + /// The statistics are parsed after the types, to limit their number by the number of columns. + std::vector statistics_data; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: header_length = readVarintField(r, type); return true; + case 2: content_length = readVarintField(r, type); return true; + case 3: stripes.push_back(parseStripeInformation(readBytesField(r, type))); return true; + case 4: types.push_back(parseType(readBytesField(r, type))); return true; + case 5: metadata.push_back(parseUserMetadataItem(readBytesField(r, type))); return true; + case 6: number_of_rows = readVarintField(r, type); return true; + case 7: statistics_data.push_back(readBytesField(r, type)); return true; + case 8: row_index_stride = readUInt32Field(r, type); return true; + case 9: writer = readUInt32Field(r, type); return true; + case 10: readBytesField(r, type); has_encryption = true; return true; + case 12: software_version = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + if (statistics_data.size() > types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many column statistics in ORC footer: {}, the file has {} columns", + statistics_data.size(), types.size()); + statistics.resize(statistics_data.size()); + for (size_t i = 0; i < statistics_data.size(); ++i) + statistics[i].parse(statistics_data[i]); +} + +std::string Footer::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, header_length); + w.writeVarint(2, content_length); + for (const auto & s : stripes) + w.writeBytes(3, serializeStripeInformation(s)); + for (const auto & t : types) + w.writeBytes(4, serializeType(t)); + for (const auto & item : metadata) + { + std::string m; + WireWriter mw(m); + mw.writeBytes(1, item.name); + mw.writeBytes(2, item.value); + w.writeBytes(5, m); + } + w.writeVarint(6, number_of_rows); + for (const auto & s : statistics) + w.writeBytes(7, s.serialize()); + w.writeVarint(8, row_index_stride); + if (writer) + w.writeVarint(9, *writer); + if (software_version) + w.writeBytes(12, *software_version); + return out; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.h b/src/Processors/Formats/Impl/ORC/Proto.h new file mode 100644 index 000000000000..999839f6ab5d --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.h @@ -0,0 +1,343 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +/// Structures of the ORC file metadata, which is serialized with Protocol Buffers. +/// See `orc_proto.proto` in the ORC specification: https://orc.apache.org/specification/ORCv1/ +/// +/// Only the messages and the fields that are used by the reader and the writer are represented. +/// The parser skips the unknown fields, as required by the Protocol Buffers rules, so the files +/// written by newer writers can be read. + +namespace DB::ORC::Proto +{ + +/// Low-level reader of the Protocol Buffers wire format over a contiguous buffer. +/// Throws `INCORRECT_DATA` on a malformed or truncated message. +class WireReader +{ +public: + enum WireType : UInt8 + { + VARINT = 0, + FIXED64 = 1, + LENGTH_DELIMITED = 2, + START_GROUP = 3, + END_GROUP = 4, + FIXED32 = 5, + }; + + WireReader(const char * begin_, const char * end_) : pos(begin_), end(end_) {} + explicit WireReader(std::string_view data) : pos(data.data()), end(data.data() + data.size()) {} + + /// Reads the next field key. Returns false at the end of the message. + bool nextField(UInt32 & field_number, WireType & wire_type); + + UInt64 readVarint(); + Int64 readSignedVarint() { UInt64 v = readVarint(); return static_cast((v >> 1) ^ (~(v & 1) + 1)); } + UInt64 readFixed64(); + UInt32 readFixed32(); + double readDouble(); + std::string_view readBytes(); + + /// Skips a field of the given wire type. + void skip(WireType wire_type); + + /// Reads a scalar field that can be either packed or not packed. + /// Returns false (and reads nothing) if the wire type is not suitable. + [[nodiscard]] bool readRepeatedVarint(WireType wire_type, std::vector & out); + +private: + void check(size_t n) const; + + const char * pos; + const char * end; +}; + +/// Low-level writer of the Protocol Buffers wire format. +class WireWriter +{ +public: + explicit WireWriter(std::string & out_) : out(out_) {} + + void writeVarint(UInt32 field, UInt64 value); + void writeSignedVarint(UInt32 field, Int64 value) { writeVarint(field, (static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeDouble(UInt32 field, double value); + void writeBytes(UInt32 field, std::string_view value); + void writePackedVarint(UInt32 field, const std::vector & values); + void writePackedFixed64(UInt32 field, const std::vector & values); + + static void appendRawVarint(std::string & s, UInt64 value); + +private: + void writeKey(UInt32 field, UInt8 wire_type) { appendRawVarint(out, (static_cast(field) << 3) | wire_type); } + + std::string & out; +}; + + +enum class CompressionKind : UInt8 +{ + NONE = 0, + ZLIB = 1, + SNAPPY = 2, + LZO = 3, + LZ4 = 4, + ZSTD = 5, + BROTLI = 6, +}; + +struct PostScript +{ + UInt64 footer_length = 0; + CompressionKind compression = CompressionKind::NONE; + /// The default value in the specification. + UInt64 compression_block_size = 256 * 1024; + std::vector version; + UInt64 metadata_length = 0; + UInt32 writer_version = 0; + std::string magic; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct IntegerStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DoubleStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct StringStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; + std::optional lower_bound; + std::optional upper_bound; +}; + +struct BucketStatistics +{ + std::vector count; +}; + +struct DecimalStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DateStatistics +{ + std::optional minimum; + std::optional maximum; +}; + +struct TimestampStatistics +{ + /// In milliseconds, in the local time zone of the writer (deprecated). + std::optional minimum; + std::optional maximum; + /// In milliseconds since the epoch in UTC. + std::optional minimum_utc; + std::optional maximum_utc; + /// The sub-millisecond part of the nanoseconds plus one, if not zero. Unvalidated when read from a file. + std::optional minimum_nanos; + std::optional maximum_nanos; +}; + +struct BinaryStatistics +{ + std::optional sum; +}; + +struct CollectionStatistics +{ + std::optional min_children; + std::optional max_children; + std::optional total_children; +}; + +struct ColumnStatistics +{ + std::optional number_of_values; + std::optional int_statistics; + std::optional double_statistics; + std::optional string_statistics; + std::optional bucket_statistics; + std::optional decimal_statistics; + std::optional date_statistics; + std::optional binary_statistics; + std::optional timestamp_statistics; + std::optional has_null; + std::optional bytes_on_disk; + std::optional collection_statistics; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct RowIndexEntry +{ + std::vector positions; + std::optional statistics; +}; + +struct RowIndex +{ + std::vector entry; + + /// The limits of the number of the repeated objects keep a small malformed message from allocating much memory. + void parse(std::string_view data, size_t max_entries); + std::string serialize() const; +}; + +struct BloomFilter +{ + UInt32 num_hash_functions = 0; + std::vector bitset; + std::optional utf8bitset; +}; + +struct BloomFilterIndex +{ + std::vector bloom_filter; + + void parse(std::string_view data, size_t max_entries); +}; + +enum class StreamKind : UInt32 +{ + PRESENT = 0, + DATA = 1, + LENGTH = 2, + DICTIONARY_DATA = 3, + DICTIONARY_COUNT = 4, + SECONDARY = 5, + ROW_INDEX = 6, + BLOOM_FILTER = 7, + BLOOM_FILTER_UTF8 = 8, + ENCRYPTED_INDEX = 9, + ENCRYPTED_DATA = 10, + STRIPE_STATISTICS = 100, + FILE_STATISTICS = 101, +}; + +struct Stream +{ + std::optional kind; + UInt32 column = 0; + UInt64 length = 0; +}; + +enum class ColumnEncodingKind : UInt32 +{ + DIRECT = 0, + DICTIONARY = 1, + DIRECT_V2 = 2, + DICTIONARY_V2 = 3, +}; + +struct ColumnEncoding +{ + ColumnEncodingKind kind = ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; + /// 1 means the bloom filters use UTF-8 for the strings and UTC for the timestamps. + std::optional bloom_encoding; +}; + +struct StripeFooter +{ + std::vector streams; + std::vector columns; + std::optional writer_timezone; + /// Non-zero if the stripe has encrypted columns, which are not supported. + size_t encryption_variants = 0; + + void parse(std::string_view data, size_t max_columns); + std::string serialize() const; +}; + +struct StringPair +{ + std::string key; + std::string value; +}; + +struct Type +{ + UInt32 kind = 0; + std::vector subtypes; + std::vector field_names; + std::optional maximum_length; + std::optional precision; + std::optional scale; + std::vector attributes; + /// Only for GEOMETRY and GEOGRAPHY. + std::optional crs; + std::optional algorithm; +}; + +struct StripeInformation +{ + UInt64 offset = 0; + UInt64 index_length = 0; + UInt64 data_length = 0; + UInt64 footer_length = 0; + UInt64 number_of_rows = 0; +}; + +struct UserMetadataItem +{ + std::string name; + std::string value; +}; + +struct StripeStatistics +{ + std::vector col_stats; +}; + +struct Metadata +{ + std::vector stripe_stats; + + void parse(std::string_view data, size_t max_stripes, size_t max_columns); + std::string serialize() const; +}; + +struct Footer +{ + UInt64 header_length = 0; + UInt64 content_length = 0; + std::vector stripes; + std::vector types; + std::vector metadata; + UInt64 number_of_rows = 0; + std::vector statistics; + UInt32 row_index_stride = 0; + std::optional writer; + bool has_encryption = false; + std::optional software_version; + + void parse(std::string_view data); + std::string serialize() const; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.cpp b/src/Processors/Formats/Impl/ORC/RLE.cpp new file mode 100644 index 000000000000..7b9762e32de3 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.cpp @@ -0,0 +1,1129 @@ +#include + +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +namespace +{ + +inline Int64 unZigZag(UInt64 value) +{ + return static_cast((value >> 1) ^ (~(value & 1) + 1)); +} + +inline UInt64 zigZag(Int64 value) +{ + return (static_cast(value) << 1) ^ static_cast(value >> 63); +} + +/// The 5-bit codes of the bit widths in RLE v2. +constexpr UInt8 code_to_bit_width[32] = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 40, 48, 56, 64}; + +/// The smallest bit width representable in RLE v2 that fits the given number of bits. +constexpr UInt8 closest_fixed_bits[65] = { + 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 26, 26, 28, 28, 30, 30, 32, 32, 40, 40, 40, 40, 40, 40, 40, 40, 48, 48, 48, + 48, 48, 48, 48, 48, 56, 56, 56, 56, 56, 56, 56, 56, 64, 64, 64, 64, 64, 64, 64, 64}; + +inline UInt32 decodeBitWidth(UInt32 code) +{ + return code_to_bit_width[code & 0x1F]; +} + +inline UInt32 getClosestFixedBits(UInt32 n) +{ + return n <= 64 ? closest_fixed_bits[n] : 64; +} + +inline UInt32 encodeBitWidth(UInt32 width) +{ + width = getClosestFixedBits(width); + if (width <= 24) + return width - 1; + switch (width) + { + case 26: return 24; + case 28: return 25; + case 30: return 26; + case 32: return 27; + case 40: return 28; + case 48: return 29; + case 56: return 30; + default: return 31; + } +} + +/// The number of bits required to represent the value, rounded to a representable bit width. +/// Negative values require 64 bits. +inline UInt32 findClosestNumBits(Int64 value) +{ + if (value < 0) + return 64; + UInt32 count = 64 - static_cast(std::countl_zero(static_cast(value))); + return getClosestFixedBits(count); +} + +} + + +UInt64 readVarint(InputByteStream & stream) +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + UInt8 byte = stream.readByte(); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC stream {}", stream.getName()); +} + +Int64 readSignedVarint(InputByteStream & stream) +{ + return unZigZag(readVarint(stream)); +} + + +void ByteRleDecoder::readHeader() +{ + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + value = static_cast(stream->readByte()); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } +} + +void ByteRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + if (not_null) + memset(data, 0, num_values); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + if (repeating) + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = value; + ++consumed; + } + } + } + else + { + memset(data + position, value, count); + consumed = count; + } + } + else + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = static_cast(stream->readByte()); + ++consumed; + } + } + } + else + { + stream->readBytes(data + position, count); + consumed = count; + } + } + remaining_values -= consumed; + position += count; + } +} + +void ByteRleDecoder::skip(size_t num_values) +{ + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (!repeating) + stream->skipBytes(count); + } +} + +void ByteRleDecoder::seek(PositionProvider & positions) +{ + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); +} + + +void BooleanRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + { + /// The PRESENT stream of a child column is read with the mask of its parent, + /// and the masked positions must be null. + data[i] = 0; + continue; + } + if (remaining_bits == 0) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8; + } + --remaining_bits; + data[i] = (last_byte >> remaining_bits) & 1; + } +} + +void BooleanRleDecoder::skip(size_t num_values) +{ + if (num_values <= remaining_bits) + { + remaining_bits -= num_values; + return; + } + num_values -= remaining_bits; + byte_decoder.skip(num_values / 8); + if (num_values % 8) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - num_values % 8; + } + else + remaining_bits = 0; +} + +void BooleanRleDecoder::seek(PositionProvider & positions) +{ + byte_decoder.seek(positions); + UInt64 consumed = positions.next(); + remaining_bits = 0; + if (consumed > 8) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid seek position {} of a boolean stream in ORC file", consumed); + if (consumed) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - consumed; + } +} + + +namespace +{ + +class IntRleDecoderV1 final : public IntRleDecoder +{ +public: + IntRleDecoderV1(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + for (size_t i = 0; i < count; ++i) + { + if (not_null && !not_null[position + i]) + continue; + if (repeating) + { + data[position + i] = static_cast(value); + value = static_cast(static_cast(value) + static_cast(delta)); + } + else + data[position + i] = static_cast(readValue()); + ++consumed; + } + remaining_values -= consumed; + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (repeating) + value = static_cast(static_cast(value) + static_cast(delta) * count); + else + for (size_t i = 0; i < count; ++i) + readVarint(*stream); + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); + } + +private: + Int64 readValue() + { + return is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + } + + void readHeader() + { + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + delta = static_cast(stream->readByte()); + value = readValue(); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } + } + + std::unique_ptr stream; + const bool is_signed; + size_t remaining_values = 0; + bool repeating = false; + Int64 value = 0; + Int64 delta = 0; +}; + + +class IntRleDecoderV2 final : public IntRleDecoder +{ +public: + IntRleDecoderV2(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (run_read == run_length) + readRun(); + + size_t count = std::min(num_values - position, run_length - run_read); + if (not_null) + { + for (size_t i = position; i < position + count; ++i) + if (not_null[i]) + data[i] = static_cast(literals[run_read++]); + } + else if constexpr (sizeof(T) == sizeof(Int64)) + { + memcpy(static_cast(data + position), literals.data() + run_read, count * sizeof(Int64)); + run_read += count; + } + else + { + for (size_t i = 0; i < count; ++i) + data[position + i] = static_cast(literals[run_read + i]); + run_read += count; + } + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (run_read == run_length) + readRun(); + size_t count = std::min(num_values, run_length - run_read); + run_read += count; + num_values -= count; + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + run_read = run_length = 0; + skip(positions.next()); + } + +private: + enum EncodingType : UInt8 + { + SHORT_REPEAT = 0, + DIRECT = 1, + PATCHED_BASE = 2, + DELTA = 3, + }; + + Int64 readLongBE(size_t num_bytes) + { + UInt64 result = 0; + for (size_t i = 0; i < num_bytes; ++i) + result = (result << 8) | stream->readByte(); + return static_cast(result); + } + + template + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count) + { + for (size_t i = 0; i < count; ++i, in += num_bytes) + { + UInt64 value = 0; + for (size_t j = 0; j < num_bytes; ++j) + value = (value << 8) | in[j]; + out[i] = static_cast(value); + } + } + + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count, size_t num_bytes) + { + switch (num_bytes) + { + case 1: decodeBigEndian<1>(in, out, count); return; + case 2: decodeBigEndian<2>(in, out, count); return; + case 3: decodeBigEndian<3>(in, out, count); return; + case 4: decodeBigEndian<4>(in, out, count); return; + case 5: decodeBigEndian<5>(in, out, count); return; + case 6: decodeBigEndian<6>(in, out, count); return; + case 7: decodeBigEndian<7>(in, out, count); return; + default: decodeBigEndian<8>(in, out, count); return; + } + } + + /// The only bit widths that are not a multiple of 8 are at most 30. + template + static void decodeBitPacked(Int64 * out, size_t count, UInt32 bit_width, ReadByte && read_byte) + { + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + while (bits_in_buffer < bit_width) + { + buffer = (buffer << 8) | read_byte(); + bits_in_buffer += 8; + } + bits_in_buffer -= bit_width; + out[i] = static_cast((buffer >> bits_in_buffer) & mask); + } + } + + /// Reads `count` bit-packed values of `bit_width` bits, starting and ending at a byte boundary. + void readInts(Int64 * out, size_t count, UInt32 bit_width) + { + if (bit_width % 8 == 0) + { + const size_t num_bytes = bit_width / 8; + while (count) + { + /// Decode the values that are entirely in the current chunk directly from it. + size_t in_chunk = std::min(count, static_cast(stream->end - stream->pos) / num_bytes); + if (in_chunk == 0) + { + *out = readLongBE(num_bytes); + ++out; + --count; + continue; + } + decodeBigEndian(reinterpret_cast(stream->pos), out, in_chunk, num_bytes); + stream->pos += in_chunk * num_bytes; + out += in_chunk; + count -= in_chunk; + } + return; + } + + const size_t total_bytes = (count * bit_width + 7) / 8; + if (static_cast(stream->end - stream->pos) >= total_bytes) + { + const UInt8 * in = reinterpret_cast(stream->pos); + decodeBitPacked(out, count, bit_width, [&] { return *in++; }); + stream->pos += total_bytes; + } + else + { + decodeBitPacked(out, count, bit_width, [&] { return stream->readByte(); }); + } + } + + void readRun() + { + UInt8 first_byte = stream->readByte(); + auto encoding = static_cast(first_byte >> 6); + run_read = 0; + switch (encoding) + { + case SHORT_REPEAT: + { + size_t num_bytes = ((first_byte >> 3) & 0x07) + 1; + run_length = (first_byte & 0x07) + 3; + Int64 value = readLongBE(num_bytes); + if (is_signed) + value = unZigZag(static_cast(value)); + std::fill(literals.begin(), literals.begin() + run_length, value); + break; + } + case DIRECT: + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + readInts(literals.data(), run_length, bit_width); + if (is_signed) + for (size_t i = 0; i < run_length; ++i) + literals[i] = unZigZag(static_cast(literals[i])); + break; + } + case PATCHED_BASE: + readPatchedBase(first_byte); + break; + case DELTA: + readDelta(first_byte); + break; + } + } + + void readPatchedBase(UInt8 first_byte) + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + UInt8 third_byte = stream->readByte(); + size_t base_bytes = ((third_byte >> 5) & 0x07) + 1; + UInt32 patch_bit_width = decodeBitWidth(third_byte & 0x1F); + + UInt8 fourth_byte = stream->readByte(); + UInt32 patch_gap_width = ((fourth_byte >> 5) & 0x07) + 1; + size_t patch_list_length = fourth_byte & 0x1F; + if (patch_list_length == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (empty patch list)", stream->getName()); + + Int64 base = readLongBE(base_bytes); + Int64 sign_mask = static_cast(1ULL << (base_bytes * 8 - 1)); + if (base & sign_mask) + { + base &= ~sign_mask; + base = -base; + } + + readInts(literals.data(), run_length, bit_width); + + if (patch_bit_width + patch_gap_width > 64) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Corrupt PATCHED_BASE encoded data in ORC stream {} (patch width + patch gap width > 64)", stream->getName()); + + Int64 patches[32]; + readInts(patches, patch_list_length, getClosestFixedBits(patch_bit_width + patch_gap_width)); + + const Int64 patch_mask = patch_bit_width >= 64 ? -1 : static_cast((1ULL << patch_bit_width) - 1); + size_t patch_index = 0; + Int64 gap = 0; + Int64 patch = 0; + + auto adjust_gap_and_patch = [&] + { + UInt64 current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + Int64 actual_gap = 0; + /// A gap of 255 with a zero patch means that the gap continues in the next entry. + while (current_gap == 255 && patch == 0) + { + actual_gap += 255; + ++patch_index; + if (patch_index >= patch_list_length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (unterminated gap)", stream->getName()); + current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + } + gap = actual_gap + static_cast(current_gap); + }; + + adjust_gap_and_patch(); + for (size_t i = 0; i < run_length; ++i) + { + if (static_cast(i) != gap) + { + literals[i] = static_cast(static_cast(literals[i]) + static_cast(base)); + } + else + { + UInt64 patched = static_cast(literals[i]) | (bit_width < 64 ? static_cast(patch) << bit_width : 0); + literals[i] = static_cast(static_cast(base) + patched); + ++patch_index; + if (patch_index < patch_list_length) + { + adjust_gap_and_patch(); + /// The next gap is relative to the current position. + gap += static_cast(i); + } + } + } + } + + void readDelta(UInt8 first_byte) + { + UInt32 code = (first_byte >> 1) & 0x1F; + UInt32 bit_width = code ? decodeBitWidth(code) : 0; + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + Int64 first_value = is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + literals[0] = first_value; + Int64 delta_base = readSignedVarint(*stream); + + if (bit_width == 0) + { + /// Fixed delta. + for (size_t i = 1; i < run_length; ++i) + literals[i] = static_cast(static_cast(literals[i - 1]) + static_cast(delta_base)); + return; + } + + if (run_length < 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal run length {} for delta encoding in ORC stream {}", run_length, stream->getName()); + + Int64 previous = static_cast(static_cast(first_value) + static_cast(delta_base)); + literals[1] = previous; + readInts(literals.data() + 2, run_length - 2, bit_width); + for (size_t i = 2; i < run_length; ++i) + { + if (delta_base < 0) + previous = static_cast(static_cast(previous) - static_cast(literals[i])); + else + previous = static_cast(static_cast(previous) + static_cast(literals[i])); + literals[i] = previous; + } + } + + std::unique_ptr stream; + const bool is_signed; + std::array literals{}; + size_t run_length = 0; + size_t run_read = 0; +}; + +} + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version) +{ + if (version == RleVersion::V1) + return std::make_unique(std::move(stream), is_signed); + return std::make_unique(std::move(stream), is_signed); +} + + +void ByteRleEncoder::writeValues() +{ + if (num_literals == 0) + return; + if (repeat) + { + stream.writeByte(static_cast(num_literals - MIN_REPEAT)); + stream.writeByte(static_cast(literals[0])); + } + else + { + stream.writeByte(static_cast(-static_cast(num_literals))); + stream.write(literals, num_literals); + } + repeat = false; + tail_run_length = 0; + num_literals = 0; +} + +void ByteRleEncoder::write(char value) +{ + if (num_literals == 0) + { + literals[num_literals++] = value; + tail_run_length = 1; + } + else if (repeat) + { + if (value == literals[0]) + { + ++num_literals; + if (num_literals == MAX_REPEAT_SIZE) + writeValues(); + } + else + { + writeValues(); + literals[num_literals++] = value; + tail_run_length = 1; + } + } + else + { + if (value == literals[num_literals - 1]) + ++tail_run_length; + else + tail_run_length = 1; + + if (tail_run_length == MIN_REPEAT) + { + if (num_literals + 1 == MIN_REPEAT) + { + repeat = true; + ++num_literals; + } + else + { + num_literals -= MIN_REPEAT - 1; + writeValues(); + literals[0] = value; + repeat = true; + num_literals = MIN_REPEAT; + } + } + else + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + writeValues(); + } + } +} + +void ByteRleEncoder::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void ByteRleEncoder::flush() +{ + writeValues(); +} + + +void BooleanRleEncoder::write(bool value) +{ + current = static_cast((current << 1) | (value ? 1 : 0)); + ++bits_in_current; + if (bits_in_current == 8) + { + byte_encoder.write(static_cast(current)); + current = 0; + bits_in_current = 0; + } +} + +void BooleanRleEncoder::recordPosition(std::vector & positions) const +{ + byte_encoder.recordPosition(positions); + positions.push_back(bits_in_current); +} + +void BooleanRleEncoder::flush() +{ + if (bits_in_current) + { + byte_encoder.write(static_cast(current << (8 - bits_in_current))); + current = 0; + bits_in_current = 0; + } + byte_encoder.flush(); +} + + +void IntRleEncoderV2::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void IntRleEncoderV2::flush() +{ + size_t literal_start = 0; + size_t i = 0; + while (i < num_literals) + { + size_t j = i + 1; + while (j < num_literals && literals[j] == literals[i]) + ++j; + if (j - i >= 3) + { + if (literal_start < i) + encodeLiterals(literals + literal_start, i - literal_start); + encodeRepeat(literals[i], j - i); + literal_start = j; + } + i = j; + } + if (literal_start < num_literals) + encodeLiterals(literals + literal_start, num_literals - literal_start); + num_literals = 0; +} + +void IntRleEncoderV2::writeVarint(UInt64 value) +{ + while (value >= 0x80) + { + stream.writeByte(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + stream.writeByte(static_cast(value)); +} + +void IntRleEncoderV2::writeInts(const Int64 * values, size_t count, UInt32 bit_width) +{ + if (bit_width % 8 == 0) + { + size_t num_bytes = bit_width / 8; + for (size_t i = 0; i < count; ++i) + { + UInt64 v = static_cast(values[i]); + for (size_t b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(v >> ((b - 1) * 8))); + } + return; + } + + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + buffer = (buffer << bit_width) | (static_cast(values[i]) & mask); + bits_in_buffer += bit_width; + while (bits_in_buffer >= 8) + { + bits_in_buffer -= 8; + stream.writeByte(static_cast(buffer >> bits_in_buffer)); + } + } + if (bits_in_buffer) + stream.writeByte(static_cast(buffer << (8 - bits_in_buffer))); +} + +void IntRleEncoderV2::encodeRepeat(Int64 value, size_t count) +{ + UInt64 encoded = is_signed ? zigZag(value) : static_cast(value); + if (count <= 10) + { + /// SHORT_REPEAT + UInt32 bits = findClosestNumBits(static_cast(encoded)); + UInt32 num_bytes = (bits + 7) / 8; + stream.writeByte(static_cast(((num_bytes - 1) << 3) | (count - 3))); + for (UInt32 b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(encoded >> ((b - 1) * 8))); + return; + } + + /// DELTA with zero fixed delta. + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeVarint(encoded); + writeSignedVarint(0); +} + +void IntRleEncoderV2::writeDirect(const Int64 * values, size_t count) +{ + Int64 encoded[MAX_LITERAL_SIZE]; + UInt32 bit_width = 1; + for (size_t i = 0; i < count; ++i) + { + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + bit_width = std::max(bit_width, findClosestNumBits(encoded[i])); + } + size_t length = count - 1; + stream.writeByte(static_cast((1 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeInts(encoded, count, bit_width); +} + +namespace +{ + +/// The bit width that is enough for the given fraction `p` of the values (as in the reference implementation). +UInt32 percentileBits(const Int64 * values, size_t count, double p) +{ + UInt32 histogram[32] = {}; + for (size_t i = 0; i < count; ++i) + ++histogram[encodeBitWidth(findClosestNumBits(values[i]))]; + + Int64 per_len = static_cast(static_cast(count) * (1.0 - p)); + for (Int32 i = 31; i >= 0; --i) + { + per_len -= histogram[i]; + if (per_len < 0) + return decodeBitWidth(i); + } + return 0; +} + +} + +void IntRleEncoderV2::encodeLiterals(const Int64 * values, size_t count) +{ + if (count <= 3) + { + writeDirect(values, count); + return; + } + + Int64 min = values[0]; + Int64 max = values[0]; + bool is_increasing = true; + bool is_decreasing = true; + bool is_fixed_delta = true; + bool deltas_overflow = false; + Int64 initial_delta = 0; + if (__builtin_sub_overflow(values[1], values[0], &initial_delta)) + deltas_overflow = true; + + /// Absolute values of the deltas, starting from the second one. + Int64 abs_deltas[MAX_LITERAL_SIZE]; + UInt64 max_abs_delta = 0; + + for (size_t i = 1; i < count; ++i) + { + min = std::min(min, values[i]); + max = std::max(max, values[i]); + is_increasing &= values[i - 1] <= values[i]; + is_decreasing &= values[i - 1] >= values[i]; + + Int64 delta = 0; + if (__builtin_sub_overflow(values[i], values[i - 1], &delta)) + { + deltas_overflow = true; + is_fixed_delta = false; + continue; + } + is_fixed_delta &= (delta == initial_delta); + if (i > 1) + { + UInt64 abs_delta = delta < 0 ? (0 - static_cast(delta)) : static_cast(delta); + abs_deltas[i - 2] = static_cast(abs_delta); + max_abs_delta = std::max(max_abs_delta, abs_delta); + } + } + + Int64 range = 0; + if (__builtin_sub_overflow(max, min, &range)) + { + writeDirect(values, count); + return; + } + + if (!deltas_overflow && is_fixed_delta) + { + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + return; + } + + if (!deltas_overflow && initial_delta != 0 && (is_increasing || is_decreasing) + && max_abs_delta <= static_cast(std::numeric_limits::max())) + { + UInt32 bit_width = findClosestNumBits(static_cast(max_abs_delta)); + /// The bit width code 0 means a fixed delta, so the width 1 is not representable. + if (bit_width == 1) + bit_width = 2; + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + writeInts(abs_deltas, count - 2, bit_width); + return; + } + + /// DIRECT or PATCHED_BASE. + Int64 encoded[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + + UInt32 bits_100p = percentileBits(encoded, count, 1.0); + UInt32 bits_90p = percentileBits(encoded, count, 0.9); + + static constexpr Int64 BASE_VALUE_LIMIT = 1LL << 56; + if (bits_100p - bits_90p <= 1 || min <= -BASE_VALUE_LIMIT || min >= BASE_VALUE_LIMIT) + { + writeDirect(values, count); + return; + } + + Int64 base_reduced[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + base_reduced[i] = values[i] - min; + + UInt32 br_bits_95p = percentileBits(base_reduced, count, 0.95); + UInt32 br_bits_100p = percentileBits(base_reduced, count, 1.0); + if (br_bits_100p == br_bits_95p) + { + writeDirect(values, count); + return; + } + + UInt32 patch_width = getClosestFixedBits(br_bits_100p - br_bits_95p); + if (patch_width == 64) + { + patch_width = 56; + br_bits_95p = 8; + } + const Int64 mask = static_cast((1ULL << br_bits_95p) - 1); + + size_t gaps[MAX_LITERAL_SIZE]; + Int64 patches[MAX_LITERAL_SIZE]; + size_t num_patches = 0; + size_t previous = 0; + size_t max_gap = 0; + for (size_t i = 0; i < count; ++i) + { + if (base_reduced[i] > mask) + { + size_t gap = i - previous; + max_gap = std::max(max_gap, gap); + previous = i; + gaps[num_patches] = gap; + patches[num_patches] = base_reduced[i] >> br_bits_95p; + ++num_patches; + base_reduced[i] &= mask; + } + } + + UInt32 patch_gap_width = (max_gap == 0) ? 1 : findClosestNumBits(static_cast(max_gap)); + patch_gap_width = std::min(patch_gap_width, 8u); + + Int64 patch_list[MAX_LITERAL_SIZE]; + size_t patch_list_length = 0; + for (size_t p = 0; p < num_patches; ++p) + { + size_t gap = gaps[p]; + while (gap > 255) + { + patch_list[patch_list_length++] = static_cast(255ULL << patch_width); + gap -= 255; + } + patch_list[patch_list_length++] = static_cast((static_cast(gap) << patch_width) | static_cast(patches[p])); + } + + /// The length of the patch list is stored in 5 bits. + if (patch_list_length > 31) + { + writeDirect(values, count); + return; + } + + bool is_negative = min < 0; + UInt64 base = is_negative ? static_cast(-min) : static_cast(min); + UInt32 base_width = findClosestNumBits(static_cast(base)) + 1; + UInt32 base_bytes = (base_width + 7) / 8; + if (is_negative) + base |= 1ULL << (base_bytes * 8 - 1); + + size_t length = count - 1; + stream.writeByte(static_cast((2 << 6) | (encodeBitWidth(br_bits_95p) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + stream.writeByte(static_cast(((base_bytes - 1) << 5) | encodeBitWidth(patch_width))); + stream.writeByte(static_cast(((patch_gap_width - 1) << 5) | patch_list_length)); + for (UInt32 b = base_bytes; b > 0; --b) + stream.writeByte(static_cast(base >> ((b - 1) * 8))); + writeInts(base_reduced, count, getClosestFixedBits(br_bits_95p)); + writeInts(patch_list, patch_list_length, getClosestFixedBits(patch_gap_width + patch_width)); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.h b/src/Processors/Formats/Impl/ORC/RLE.h new file mode 100644 index 000000000000..c5212bf5fbf6 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.h @@ -0,0 +1,151 @@ +#pragma once + +#include + +#include +#include + +/// Run-length encodings of ORC: https://orc.apache.org/specification/ORCv1/#run-length-encoding +/// +/// All decoders fill the positions where `not_null` is non-zero (or all positions if it is +/// nullptr), consuming one value from the stream for each of them; the other positions are set to zero. + +namespace DB::ORC +{ + +/// Byte run-length encoding, used for the bytes and for the booleans (packed into bytes). +class ByteRleDecoder +{ +public: + explicit ByteRleDecoder(std::unique_ptr stream_) : stream(std::move(stream_)) {} + + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + void readHeader(); + + std::unique_ptr stream; + size_t remaining_values = 0; + bool repeating = false; + char value = 0; +}; + +/// Booleans packed into bytes, most significant bit first, encoded with the byte run-length encoding. +class BooleanRleDecoder +{ +public: + explicit BooleanRleDecoder(std::unique_ptr stream_) : byte_decoder(std::move(stream_)) {} + + /// Writes 0 or 1. + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + ByteRleDecoder byte_decoder; + size_t remaining_bits = 0; + UInt8 last_byte = 0; +}; + +/// Integer run-length encodings, version 1 and 2. +class IntRleDecoder +{ +public: + virtual ~IntRleDecoder() = default; + /// The values are converted to the type of the output, which can be narrower than the encoded values. + virtual void next(Int64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(UInt64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int32 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int16 * data, size_t num_values, const char * not_null) = 0; + virtual void skip(size_t num_values) = 0; + virtual void seek(PositionProvider & positions) = 0; +}; + +enum class RleVersion : UInt8 +{ + V1, + V2, +}; + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version); + +/// Reads a base 128 varint, as used by the DECIMAL columns. +UInt64 readVarint(InputByteStream & stream); +Int64 readSignedVarint(InputByteStream & stream); + + +class ByteRleEncoder +{ +public: + explicit ByteRleEncoder(OutputByteStream & stream_) : stream(stream_) {} + + void write(char value); + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + +private: + void writeValues(); + + static constexpr size_t MIN_REPEAT = 3; + static constexpr size_t MAX_LITERAL_SIZE = 128; + static constexpr size_t MAX_REPEAT_SIZE = 127 + MIN_REPEAT; + + OutputByteStream & stream; + char literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; + size_t tail_run_length = 0; + bool repeat = false; +}; + +class BooleanRleEncoder +{ +public: + explicit BooleanRleEncoder(OutputByteStream & stream_) : byte_encoder(stream_) {} + + void write(bool value); + void recordPosition(std::vector & positions) const; + void flush(); + +private: + ByteRleEncoder byte_encoder; + UInt8 current = 0; + size_t bits_in_current = 0; +}; + +/// Integer run-length encoding, version 2. +class IntRleEncoderV2 +{ +public: + IntRleEncoderV2(OutputByteStream & stream_, bool is_signed_) : stream(stream_), is_signed(is_signed_) {} + + void write(Int64 value) + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + flush(); + } + + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + + static constexpr size_t MAX_LITERAL_SIZE = 512; + +private: + void encodeLiterals(const Int64 * values, size_t count); + void encodeRepeat(Int64 value, size_t count); + void writeDirect(const Int64 * values, size_t count); + void writeVarint(UInt64 value); + void writeSignedVarint(Int64 value) { writeVarint((static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeInts(const Int64 * values, size_t count, UInt32 bit_width); + + OutputByteStream & stream; + const bool is_signed; + Int64 literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.cpp b/src/Processors/Formats/Impl/ORC/Reader.cpp new file mode 100644 index 000000000000..76c6a432d1b0 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.cpp @@ -0,0 +1,842 @@ +#include + +#include +#include +#include +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +std::future InputStream::readAsync(void * buf, UInt64 length, UInt64 offset) +{ + read(buf, length, offset); + std::promise promise; + promise.set_value(); + return promise.get_future(); +} + + +Reader::Reader(std::unique_ptr stream_, const ReaderOptions & options_) + : stream(std::move(stream_)), options(options_) +{ + readTail(); +} + +Reader::~Reader() +{ + /// The background reads write into the buffers of the cache. + for (auto & range : cache) + if (!range.ready && range.future.valid()) + range.future.wait(); +} + +void Reader::readTail() +{ + const UInt64 file_size = stream->getLength(); + /// The header "ORC" and at least the length of the postscript. + if (file_size < 4) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {} is too small ({} bytes)", stream->getName(), file_size); + + static constexpr UInt64 DIRECTORY_SIZE_GUESS = 16 * 1024; + UInt64 tail_size = std::min(file_size, DIRECTORY_SIZE_GUESS); + std::string tail(tail_size, '\0'); + stream->read(tail.data(), tail_size, file_size - tail_size); + + postscript_length = static_cast(tail.back()); + if (postscript_length + 1 > tail_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid postscript length {} in ORC file {}", postscript_length, stream->getName()); + + postscript.parse(std::string_view(tail).substr(tail_size - 1 - postscript_length, postscript_length)); + + if (postscript.magic != "ORC") + { + /// Very old files do not have the magic in the postscript, but they have it at the beginning. + char header[3]; + stream->read(header, 3, 0); + if (memcmp(header, "ORC", 3) != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {}", stream->getName()); + } + + if (postscript.compression != CompressionKind::NONE) + { + if (postscript.compression_block_size == 0 || postscript.compression_block_size > (1ULL << 30)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid compression block size {} in ORC file {}", postscript.compression_block_size, stream->getName()); + if (postscript.compression == CompressionKind::BROTLI) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "BROTLI compression in ORC files is not supported"); + } + + UInt64 tail_length = 0; + if (__builtin_add_overflow(postscript.footer_length, postscript.metadata_length, &tail_length) + || __builtin_add_overflow(tail_length, postscript_length + 1, &tail_length) + || tail_length > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Invalid footer length {} and metadata length {} in ORC file {} of size {}", + postscript.footer_length, postscript.metadata_length, stream->getName(), file_size); + + if (tail_length > tail_size) + { + tail.resize(tail_length); + tail_size = tail_length; + stream->read(tail.data(), tail_size, file_size - tail_size); + } + + std::string_view footer_data = std::string_view(tail).substr(tail_size - 1 - postscript_length - postscript.footer_length, postscript.footer_length); + footer.parse(decompress(footer_data, "footer")); + + if (footer.has_encryption) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + + schema = Type::fromProto(footer.types); + + /// Validate the stripes once, so that the sums of their offsets and lengths cannot overflow later. + if (footer.stripes.size() > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many stripes {} in ORC file {}", footer.stripes.size(), stream->getName()); + for (size_t i = 0; i < footer.stripes.size(); ++i) + { + const auto & stripe = footer.stripes[i]; + UInt64 stripe_end = 0; + if (common::addOverflow(stripe.offset, stripe.index_length, stripe_end) + || common::addOverflow(stripe_end, stripe.data_length, stripe_end) + || common::addOverflow(stripe_end, stripe.footer_length, stripe_end) + || stripe_end > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + i, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, file_size); + } + + std::string_view metadata_data = std::string_view(tail).substr( + tail_size - 1 - postscript_length - postscript.footer_length - postscript.metadata_length, postscript.metadata_length); + if (!metadata_data.empty()) + metadata.emplace().parse(decompress(metadata_data, "metadata"), footer.stripes.size(), footer.types.size()); + else + metadata.emplace(); +} + +const Proto::Metadata & Reader::getMetadata() +{ + return *metadata; +} + +std::string Reader::decompress(std::string_view data, const std::string & name) const +{ + if (postscript.compression == CompressionKind::NONE) + return std::string(data); + + std::string result; + InputByteStream in(data, postscript.compression, postscript.compression_block_size, name); + while (in.nextChunk()) + result.append(in.pos, in.end); + return result; +} + +Proto::StripeFooter Reader::readStripeFooter(size_t stripe_index) +{ + const auto & stripe = getStripe(stripe_index); + UInt64 offset = stripe.offset + stripe.index_length + stripe.data_length; + UInt64 end = 0; + if (__builtin_add_overflow(offset, stripe.footer_length, &end) || end > stream->getLength() || offset < stripe.offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + stripe_index, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, stream->getLength()); + + auto slices = readRanges({{offset, stripe.footer_length}}); + Proto::StripeFooter result; + result.parse(decompress(slices[0].data, "stripe footer"), footer.types.size()); + if (result.encryption_variants) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + return result; +} + +std::vector> Reader::getStripeRanges( + size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const +{ + const auto & stripe = getStripe(stripe_index); + std::vector> ranges; + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + for (const auto & s : stripe_footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream at offset {} of length {} in stripe {} of ORC file {}", offset, s.length, stripe_index, stream->getName()); + if (s.kind && s.column < selected.size() && selected[s.column] && s.length) + ranges.emplace_back(offset, s.length); + offset = stream_end; + } + return ranges; +} + +std::vector Reader::readRanges(const std::vector> & ranges) +{ + std::vector result(ranges.size()); + + std::vector order(ranges.size()); + for (size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return ranges[a].first < ranges[b].first; }); + + size_t i = 0; + while (i < order.size()) + { + UInt64 begin = ranges[order[i]].first; + UInt64 end = begin + ranges[order[i]].second; + size_t j = i + 1; + while (j < order.size()) + { + UInt64 next_begin = ranges[order[j]].first; + UInt64 next_end = next_begin + ranges[order[j]].second; + UInt64 new_end = std::max(end, next_end); + if (next_begin > end && next_begin - end > options.hole_size_limit) + break; + if (new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + std::shared_ptr> holder; + const char * base = nullptr; + UInt64 base_offset = begin; + { + std::lock_guard lock(cache_mutex); + for (auto & cached : cache) + { + if (cached.offset <= begin && end <= cached.offset + cached.length) + { + if (!cached.ready) + { + cached.ready = true; + cached.future.get(); + } + holder = cached.buffer; + base = cached.buffer->data(); + base_offset = cached.offset; + break; + } + } + } + + if (!holder) + { + if (end > stream->getLength()) + throw Exception(ErrorCodes::INCORRECT_DATA, "A range at {} of length {} goes beyond the end of ORC file {}", begin, end - begin, stream->getName()); + auto buffer = std::make_shared>(end - begin); + if (end > begin) + stream->read(buffer->data(), end - begin, begin); + base = buffer->data(); + holder = std::move(buffer); + } + + for (size_t k = i; k < j; ++k) + { + const auto & range = ranges[order[k]]; + result[order[k]] = Slice{holder, std::string_view(base + (range.first - base_offset), range.second)}; + } + i = j; + } + return result; +} + +void Reader::preBuffer(const std::vector & stripes, const std::vector & include_types) +{ + auto selected = selectColumnsByTypeIds(*schema, include_types); + for (UInt32 stripe_index : stripes) + { + const auto & stripe = getStripe(stripe_index); + auto stripe_footer = readStripeFooter(stripe_index); + auto ranges = getStripeRanges(stripe_index, stripe_footer, selected); + ranges.emplace_back(stripe.offset + stripe.index_length + stripe.data_length, stripe.footer_length); + std::sort(ranges.begin(), ranges.end()); + + size_t i = 0; + while (i < ranges.size()) + { + UInt64 begin = ranges[i].first; + UInt64 end = begin + ranges[i].second; + size_t j = i + 1; + while (j < ranges.size()) + { + UInt64 next_begin = ranges[j].first; + UInt64 new_end = std::max(end, next_begin + ranges[j].second); + if ((next_begin > end && next_begin - end > options.hole_size_limit) || new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + auto buffer = std::make_shared>(end - begin); + { + /// The entry must be owned by the cache before the background read starts, so that + /// the destructor waits for the read even if an exception is thrown in between. + std::lock_guard lock(cache_mutex); + auto & cached = cache.emplace_back(CachedRange{.offset = begin, .length = end - begin, .buffer = std::move(buffer), .future = {}}); + try + { + cached.future = stream->readAsync(cached.buffer->data(), end - begin, begin); + } + catch (...) + { + /// Nothing has been scheduled, so the entry can be removed safely. + cache.pop_back(); + throw; + } + } + i = j; + } + } +} + +void Reader::releaseBuffer(UInt64 boundary) +{ + std::lock_guard lock(cache_mutex); + for (auto it = cache.begin(); it != cache.end();) + { + if (it->offset + it->length <= boundary) + { + /// The buffer can be destroyed only after the background read finishes. The data has + /// not been used, so an error of reading it does not matter. + if (!it->ready && it->future.valid()) + it->future.wait(); + it = cache.erase(it); + } + else + ++it; + } +} + +std::unique_ptr Reader::createRowReader(const RowReaderOptions & row_options) +{ + return std::make_unique(*this, row_options); +} + + +class RowReader::StripeStreamsImpl final : public StripeStreams +{ +public: + StripeStreamsImpl( + Reader & reader_, + size_t stripe_index_, + Proto::StripeFooter footer_, + const std::vector & selected_columns_, + const DateLUTImpl & writer_timezone_, + const DateLUTImpl & reader_timezone_) + : reader(reader_) + , stripe_index(stripe_index_) + , footer(std::move(footer_)) + , selected_columns(selected_columns_) + , writer_timezone(writer_timezone_) + , reader_timezone(reader_timezone_) + { + const auto & stripe = reader.getStripe(stripe_index); + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + + for (const auto & s : footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: streamOffset={}, streamLength={}, stripeOffset={}, stripeIndexLength={}, stripeDataLength={}", + stripe_index, offset, s.length, stripe.offset, stripe.index_length, stripe.data_length); + if (s.kind && s.column < selected_columns.size() && selected_columns[s.column]) + { + /// Use the first stream if there are several of the same kind, as the reference implementation. + stream_ranges.try_emplace({static_cast(s.column), *s.kind}, offset, s.length); + } + else if (s.kind && s.column >= selected_columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: column {} is out of range, the file has {} columns", + stripe_index, s.column, selected_columns.size()); + offset = stream_end; + } + } + + static bool isIndexStream(UInt32 kind) + { + return kind == static_cast(Proto::StreamKind::ROW_INDEX) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER_UTF8); + } + + /// Reads the streams into memory at once, only the index streams or all of them. The streams + /// that are not read are loaded on demand by `getStream`. + void loadStreams(bool only_index) + { + std::vector> ranges; + std::vector> keys; + for (const auto & [key, range] : stream_ranges) + { + if (streams.contains(key) || (only_index && !isIndexStream(key.second))) + continue; + keys.push_back(key); + ranges.push_back(range); + } + + auto new_slices = reader.readRanges(ranges); + for (size_t i = 0; i < keys.size(); ++i) + streams.emplace(keys[i], new_slices[i].data); + slices.insert(slices.end(), std::make_move_iterator(new_slices.begin()), std::make_move_iterator(new_slices.end())); + } + + const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const override + { + if (column_id >= footer.columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC stripe {} has no encoding for column {}, it has {} column encodings", stripe_index, column_id, footer.columns.size()); + return footer.columns[column_id]; + } + + std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const override + { + std::pair key{column_id, static_cast(kind)}; + auto name = fmt::format("column {} kind {} in stripe {}", column_id, static_cast(kind), stripe_index); + if (auto it = streams.find(key); it != streams.end()) + return std::make_unique(it->second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + + auto it = stream_ranges.find(key); + if (it == stream_ranges.end()) + return nullptr; + auto loader = [&file_reader = reader, stream_offset = it->second.first](UInt64 offset, UInt64 length) + { + auto loaded = file_reader.readRanges({{stream_offset + offset, length}}); + return LoadedRange{std::move(loaded[0].holder), loaded[0].data}; + }; + return std::make_unique( + std::move(loader), it->second.second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + } + + std::optional getStreamData(UInt64 column_id, Proto::StreamKind kind) const + { + auto it = streams.find({column_id, static_cast(kind)}); + if (it == streams.end()) + return {}; + return it->second; + } + + const std::vector & getSelectedColumns() const override { return selected_columns; } + const DateLUTImpl & getWriterTimezone() const override { return writer_timezone; } + const DateLUTImpl & getReaderTimezone() const override { return reader_timezone; } + UInt64 getNumberOfRows() const override { return reader.getStripe(stripe_index).number_of_rows; } + bool isDecimalAsLong() const override + { + const auto & version = reader.getPostScript().version; + return version.size() == 2 && version[0] == 1 && version[1] == 9999; + } + + const Proto::StripeFooter & getFooter() const { return footer; } + +private: + Reader & reader; + size_t stripe_index; + Proto::StripeFooter footer; + const std::vector & selected_columns; + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + /// The offset in the file and the length of each selected stream. + std::map, std::pair> stream_ranges; + /// The streams read into memory. + std::vector slices; + std::map, std::string_view> streams; +}; + + +RowReader::RowReader(Reader & reader_, const RowReaderOptions & options_) + : reader(reader_) + , options(options_) + , reader_timezone(DateLUT::instance(options.timezone_name)) +{ + const Type & schema = reader.getType(); + if (options.include_types) + selected_columns = selectColumnsByTypeIds(schema, *options.include_types); + else + selected_columns.assign(schema.getMaximumColumnId() + 1, true); + selected_type = Type::buildSelectedType(schema, selected_columns); + + UInt64 range_end = options.range_offset + std::min(options.range_length, std::numeric_limits::max() - options.range_offset); + const auto & stripes = reader.getFooter().stripes; + current_stripe = stripes.size(); + last_stripe = 0; + for (size_t i = 0; i < stripes.size(); ++i) + { + if (stripes[i].offset >= options.range_offset && stripes[i].offset < range_end) + { + current_stripe = std::min(current_stripe, i); + last_stripe = std::max(last_stripe, i + 1); + } + } + if (current_stripe >= last_stripe) + current_stripe = last_stripe = 0; + + /// The search argument can be applied only if there are row indexes. + if (reader.getFooter().row_index_stride == 0) + options.search_argument.reset(); +} + +RowReader::~RowReader() = default; + +std::unique_ptr RowReader::createRowBatch() const +{ + return ORC::createRowBatch(*selected_type, options.enable_lazy_decoding); +} + +bool Reader::hasBadBloomFilters() const +{ + /// Same as in the reference implementation. Only the C++ writer (id 1) of some old releases wrote bad bloom filters. + if (footer.writer.value_or(0) != 1) + return false; + /// `software_version` is written since 1.5.13, 1.6.11 and 1.7.0, and the C++ writer supports bloom filters since 1.6.0, + /// so the files of the C++ writer without `software_version` have bad bloom filters. + if (!footer.software_version) + return true; + /// Strip the suffix of snapshot versions, like 1.6.12-SNAPSHOT. + std::string_view version = *footer.software_version; + version = version.substr(0, version.find('-')); + static constexpr std::string_view bad_versions[] = { + "1.6.0", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.6.7", "1.6.8", "1.6.9", "1.6.10", "1.6.11", "1.7.0"}; + return std::find(std::begin(bad_versions), std::end(bad_versions), version) != std::end(bad_versions); +} + +const DateLUTImpl & RowReader::getWriterTimezone(const Proto::StripeFooter & stripe_footer) const +{ + if (stripe_footer.writer_timezone) + return DateLUT::instance(*stripe_footer.writer_timezone); + /// The reference implementation uses the local time zone of the reader if the file does not specify it. + return DateLUT::serverTimezoneInstance(); +} + +bool RowReader::evaluateStatistics(const std::vector & stats) const +{ + const auto & leaves = options.search_argument->getLeaves(); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + UInt32 writer_version = reader.getPostScript().writer_version; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + if (column < stats.size()) + values[i] = leaves[i].evaluate(writer_version, stats[column], nullptr); + } + return isNeeded(options.search_argument->evaluate(values)); +} + +UInt64 RowReader::numberOfRowGroups() const +{ + const UInt64 stride = reader.getFooter().row_index_stride; + return rows_in_current_stripe / stride + (rows_in_current_stripe % stride != 0); +} + +void RowReader::loadStripeIndex() +{ + row_indexes.clear(); + bloom_filters.clear(); + /// One extra entry is accepted from lenient writers. + const UInt64 max_entries = std::min(numberOfRowGroups(), std::numeric_limits::max() - 1) + 1; + const bool use_bloom_filters = !reader.hasBadBloomFilters(); + const auto & stripe_footer = stripe_streams->getFooter(); + for (const auto & s : stripe_footer.streams) + { + if (!s.kind || s.column >= selected_columns.size() || !selected_columns[s.column]) + continue; + auto kind = static_cast(*s.kind); + if (kind == Proto::StreamKind::ROW_INDEX) + { + if (row_indexes.contains(s.column)) + continue; + auto data = stripe_streams->getStreamData(s.column, kind); + row_indexes[s.column].parse(reader.decompress(data.value_or(std::string_view{}), "row index"), max_entries); + } + else if (kind == Proto::StreamKind::BLOOM_FILTER_UTF8 && use_bloom_filters) + { + if (bloom_filters.contains(s.column)) + continue; + const auto & encoding = stripe_streams->getEncoding(s.column); + Proto::BloomFilterIndex index; + auto data = stripe_streams->getStreamData(s.column, kind); + index.parse(reader.decompress(data.value_or(std::string_view{}), "bloom filter"), max_entries); + auto & filters = bloom_filters[s.column]; + for (const auto & bf : index.bloom_filter) + { + /// Only the bloom filters with the UTF-8 strings and UTC timestamps can be used. + if (encoding.bloom_encoding.value_or(0) == 1 && bf.num_hash_functions && bf.utf8bitset) + filters.push_back(std::make_shared(bf)); + else + filters.push_back(nullptr); + } + } + } +} + +void RowReader::pickRowGroups() +{ + const UInt64 stride = reader.getFooter().row_index_stride; + const UInt64 groups = numberOfRowGroups(); + const auto & leaves = options.search_argument->getLeaves(); + + /// The number of the row groups comes from the file. Check it against the row indexes, which are already + /// read, before allocating memory for it. + bool has_leaf_index = false; + for (const auto & leaf : leaves) + { + auto it = row_indexes.find(leaf.getColumnId()); + if (it == row_indexes.end()) + continue; + has_leaf_index = true; + if (it->second.entry.size() < groups) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + it->first, it->second.entry.size(), groups, current_stripe); + } + + if (!has_leaf_index) + { + /// Without the row indexes all row groups are read. + next_skipped_rows.clear(); + return; + } + + next_skipped_rows.assign(groups, 0); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + const UInt32 writer_version = reader.getPostScript().writer_version; + const Proto::ColumnStatistics empty_statistics; + + UInt64 next_skipped_group = groups; + for (UInt64 group = groups; group > 0;) + { + --group; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + auto it = row_indexes.find(column); + if (it == row_indexes.end()) + { + values[i] = TruthValue::YES_NO_NULL; + continue; + } + if (group >= it->second.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + column, it->second.entry.size(), groups, current_stripe); + const auto & entry = it->second.entry[group]; + const BloomFilter * bloom_filter = nullptr; + if (auto bf = bloom_filters.find(column); bf != bloom_filters.end() && group < bf->second.size()) + bloom_filter = bf->second[group].get(); + values[i] = leaves[i].evaluate(writer_version, entry.statistics ? *entry.statistics : empty_statistics, bloom_filter); + } + + bool needed = isNeeded(options.search_argument->evaluate(values)); + if (!needed) + { + next_skipped_rows[group] = 0; + next_skipped_group = group; + } + else + next_skipped_rows[group] = (next_skipped_group == groups) ? rows_in_current_stripe : next_skipped_group * stride; + } +} + +UInt64 RowReader::advanceToNextRowGroup(UInt64 current_row) const +{ + const UInt64 groups = next_skipped_rows.size(); + if (groups == 0) + return std::min(current_row, rows_in_current_stripe); + + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return rows_in_current_stripe; + if (next_skipped_rows[group] != 0) + return current_row; + while (group < groups && next_skipped_rows[group] == 0) + ++group; + if (group < groups) + return group * stride; + return rows_in_current_stripe; +} + +UInt64 RowReader::computeBatchSize(UInt64 requested, UInt64 current_row) const +{ + UInt64 end_row = rows_in_current_stripe; + const UInt64 groups = next_skipped_rows.size(); + if (groups > 0) + { + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return 0; + UInt64 next_skipped_row = next_skipped_rows[group]; + if (next_skipped_row == 0) + return 0; + end_row = next_skipped_row; + } + return std::min(requested, end_row - current_row); +} + +void RowReader::seekToRowGroup(size_t row_group) +{ + std::unordered_map positions; + for (const auto & [column, index] : row_indexes) + { + if (row_group >= index.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, the row group {} is requested", column, index.entry.size(), row_group); + positions.emplace(column, PositionProvider(index.entry[row_group].positions)); + } + column_reader->seekToRowGroup(positions); +} + +void RowReader::startNextStripe() +{ + column_reader.reset(); + stripe_streams.reset(); + row_indexes.clear(); + bloom_filters.clear(); + next_skipped_rows.clear(); + + const auto & search_argument = options.search_argument; + const auto & footer = reader.getFooter(); + + if (search_argument && !file_statistics_evaluated) + { + file_statistics_result = footer.statistics.empty() || evaluateStatistics(footer.statistics); + file_statistics_evaluated = true; + } + if (search_argument && !file_statistics_result) + { + current_stripe = last_stripe; + return; + } + + do + { + const auto & stripe = footer.stripes[current_stripe]; + rows_in_current_stripe = stripe.number_of_rows; + + bool is_stripe_needed = true; + const auto & stripe_statistics = reader.getMetadata().stripe_stats; + if (search_argument && stripe_statistics.size() == footer.stripes.size()) + { + const auto & stats = stripe_statistics[current_stripe].col_stats; + is_stripe_needed = stats.empty() || evaluateStatistics(stats); + } + + if (is_stripe_needed) + { + auto stripe_footer = reader.readStripeFooter(current_stripe); + const DateLUTImpl & writer_timezone = getWriterTimezone(stripe_footer); + stripe_streams = std::make_unique( + reader, current_stripe, std::move(stripe_footer), selected_columns, writer_timezone, reader_timezone); + if (!search_argument) + stripe_streams->loadStreams(/* only_index */ false); + + if (search_argument) + { + stripe_streams->loadStreams(/* only_index */ true); + loadStripeIndex(); + pickRowGroups(); + bool has_selected = next_skipped_rows.empty(); + for (UInt64 group = current_row_in_stripe / footer.row_index_stride; !has_selected && group < next_skipped_rows.size(); ++group) + has_selected = next_skipped_rows[group] != 0; + if (has_selected) + { + /// If some row groups are skipped, the data is loaded on demand, only around the + /// selected row groups. Otherwise the whole stripe is read at once. + bool has_skipped = std::find(next_skipped_rows.begin(), next_skipped_rows.end(), 0) != next_skipped_rows.end(); + if (!has_skipped) + stripe_streams->loadStreams(/* only_index */ false); + break; + } + is_stripe_needed = false; + stripe_streams.reset(); + } + } + + if (!is_stripe_needed) + { + ++current_stripe; + current_row_in_stripe = 0; + } + } while (search_argument && current_stripe < last_stripe); + + if (current_stripe >= last_stripe) + return; + + column_reader = buildColumnReader(reader.getType(), *stripe_streams); + + if (search_argument) + { + current_row_in_stripe = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe > 0) + seekToRowGroup(current_row_in_stripe / footer.row_index_stride); + } +} + +bool RowReader::next(ColumnVectorBatch & batch, size_t max_rows) +{ + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + if (current_row_in_stripe == 0) + startNextStripe(); + + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + UInt64 rows_to_read = std::min(max_rows, rows_in_current_stripe - current_row_in_stripe); + if (options.search_argument && rows_to_read > 0) + rows_to_read = computeBatchSize(rows_to_read, current_row_in_stripe); + + batch.numElements = rows_to_read; + if (rows_to_read == 0) + { + current_stripe = last_stripe; + return false; + } + + if (options.enable_lazy_decoding) + column_reader->nextEncoded(batch, rows_to_read, nullptr); + else + column_reader->next(batch, rows_to_read, nullptr); + + current_row_in_stripe += rows_to_read; + + if (options.search_argument) + { + UInt64 next_row = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe != next_row) + { + current_row_in_stripe = next_row; + if (current_row_in_stripe < rows_in_current_stripe) + seekToRowGroup(current_row_in_stripe / reader.getFooter().row_index_stride); + } + } + + if (current_row_in_stripe >= rows_in_current_stripe) + { + ++current_stripe; + current_row_in_stripe = 0; + } + return true; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.h b/src/Processors/Formats/Impl/ORC/Reader.h new file mode 100644 index 000000000000..981ab8c5c799 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.h @@ -0,0 +1,188 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/// The reader of the ORC files: https://orc.apache.org/specification/ORCv1/ + +namespace DB::ORC +{ + +/// Random access to the file. +class InputStream +{ +public: + virtual ~InputStream() = default; + + virtual UInt64 getLength() const = 0; + /// Reads exactly `length` bytes at `offset`. Must be thread-safe if `readAsync` is used. + virtual void read(void * buf, UInt64 length, UInt64 offset) = 0; + /// Reads in the background. The default implementation reads synchronously. + virtual std::future readAsync(void * buf, UInt64 length, UInt64 offset); + virtual const std::string & getName() const = 0; +}; + +struct ReaderOptions +{ + /// Two ranges are read with one request if the gap between them is at most this size... + UInt64 hole_size_limit = 8192; + /// ... and the combined range is at most this size. + UInt64 range_size_limit = 32 * 1024 * 1024; +}; + +struct RowReaderOptions +{ + /// The ids of the columns to read, with the same semantics as in the reference implementation + /// (see `selectColumnsByTypeIds`). If not set, all columns are read. + std::optional> include_types; + /// Read only the stripes that start in `[range_offset, range_offset + range_length)`. + UInt64 range_offset = 0; + UInt64 range_length = std::numeric_limits::max(); + /// For the dictionary-encoded string columns, fill `EncodedStringVectorBatch`. + bool enable_lazy_decoding = false; + /// The time zone to show the values of the TIMESTAMP (not TIMESTAMP_INSTANT) columns in. + std::string timezone_name = "GMT"; + std::shared_ptr search_argument; +}; + +class RowReader; + +class Reader +{ +public: + Reader(std::unique_ptr stream_, const ReaderOptions & options_); + ~Reader(); + + const Type & getType() const { return *schema; } + UInt64 getNumberOfRows() const { return footer.number_of_rows; } + UInt64 getNumberOfStripes() const { return footer.stripes.size(); } + const Proto::StripeInformation & getStripe(size_t index) const { return footer.stripes.at(index); } + static UInt64 getStripeLength(const Proto::StripeInformation & stripe) { return stripe.index_length + stripe.data_length + stripe.footer_length; } + + const Proto::Footer & getFooter() const { return footer; } + const Proto::PostScript & getPostScript() const { return postscript; } + CompressionKind getCompression() const { return postscript.compression; } + /// Whether the bloom filters of the file were written by a version of the C++ writer + /// that hashed the integers incorrectly (ORC-1024), so they must not be used. + bool hasBadBloomFilters() const; + UInt64 getCompressionBlockSize() const { return postscript.compression_block_size; } + + /// The statistics of the whole file, one per column. + const std::vector & getStatistics() const { return footer.statistics; } + /// The statistics of the stripes, read on the first call. Can be empty. + const Proto::Metadata & getMetadata(); + + /// Reads the stripe footer. Not thread-safe. + Proto::StripeFooter readStripeFooter(size_t stripe_index); + + std::unique_ptr createRowReader(const RowReaderOptions & options); + + /// Starts reading the data of the selected columns of the stripes in the background. + void preBuffer(const std::vector & stripes, const std::vector & include_types); + /// Releases the prefetched data that ends before `boundary`. + void releaseBuffer(UInt64 boundary); + + /// A piece of the file in memory. + struct Slice + { + std::shared_ptr> holder; + std::string_view data; + }; + + /// Reads the ranges `(offset, length)` of the file, from the prefetched data if possible. + /// The adjacent ranges are coalesced according to the options. + std::vector readRanges(const std::vector> & ranges); + + /// Decompresses a whole metadata stream (a footer, an index). + std::string decompress(std::string_view data, const std::string & name) const; + +private: + void readTail(); + + struct CachedRange + { + UInt64 offset; + UInt64 length; + std::shared_ptr> buffer; + std::future future; + bool ready = false; + }; + + /// Returns the ranges of the streams of the selected columns in the stripe, and the stripe footer. + std::vector> getStripeRanges(size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const; + + std::unique_ptr stream; + ReaderOptions options; + Proto::PostScript postscript; + UInt64 postscript_length = 0; + Proto::Footer footer; + std::optional metadata; + std::unique_ptr schema; + + std::mutex cache_mutex; + std::list cache; +}; + +/// Reads the rows of the selected stripes and columns in batches. +class RowReader +{ +public: + RowReader(Reader & reader_, const RowReaderOptions & options_); + ~RowReader(); + + std::unique_ptr createRowBatch() const; + + /// Fills the batch with the next rows, at most `max_rows`. Returns false at the end. + bool next(ColumnVectorBatch & batch, size_t max_rows); + + /// The type of the file with only the selected columns. The batches have this structure. + const Type & getSelectedType() const { return *selected_type; } + +private: + class StripeStreamsImpl; + + void startNextStripe(); + void loadStripeIndex(); + UInt64 numberOfRowGroups() const; + void pickRowGroups(); + void seekToRowGroup(size_t row_group); + UInt64 advanceToNextRowGroup(UInt64 current_row) const; + UInt64 computeBatchSize(UInt64 requested, UInt64 current_row) const; + bool evaluateStatistics(const std::vector & stats) const; + const DateLUTImpl & getWriterTimezone(const Proto::StripeFooter & stripe_footer) const; + + Reader & reader; + RowReaderOptions options; + std::vector selected_columns; + std::unique_ptr selected_type; + const DateLUTImpl & reader_timezone; + + UInt64 current_stripe = 0; + UInt64 last_stripe = 0; + UInt64 rows_in_current_stripe = 0; + UInt64 current_row_in_stripe = 0; + bool file_statistics_evaluated = false; + bool file_statistics_result = true; + + std::unique_ptr stripe_streams; + std::unique_ptr column_reader; + + /// For the predicate pushdown, by the column id. + std::unordered_map row_indexes; + std::unordered_map>> bloom_filters; + /// For each row group of the current stripe: zero if it is skipped, otherwise the row (in the + /// stripe) of the next skipped row group or the number of rows in the stripe. + std::vector next_skipped_rows; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.cpp b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp new file mode 100644 index 000000000000..e0543230c614 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp @@ -0,0 +1,1075 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +TruthValue operator||(TruthValue left, TruthValue right) +{ + if (right == TruthValue::YES || left == TruthValue::YES) + return TruthValue::YES; + if (right == TruthValue::YES_NULL || left == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + if (right == TruthValue::NO) + return left; + if (left == TruthValue::NO) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::NO_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::NO_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (left == TruthValue::NO_NULL && right == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator&&(TruthValue left, TruthValue right) +{ + if (right == TruthValue::NO || left == TruthValue::NO) + return TruthValue::NO; + if (right == TruthValue::NO_NULL || left == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + if (right == TruthValue::YES) + return left; + if (left == TruthValue::YES) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::YES_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::YES_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (left == TruthValue::YES_NULL && right == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator!(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: return TruthValue::YES; + case TruthValue::YES: return TruthValue::NO; + case TruthValue::IS_NULL: + case TruthValue::YES_NO: + case TruthValue::YES_NO_NULL: + return value; + case TruthValue::NO_NULL: return TruthValue::YES_NULL; + case TruthValue::YES_NULL: return TruthValue::NO_NULL; + } + return value; +} + +bool isNeeded(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: + case TruthValue::IS_NULL: + case TruthValue::NO_NULL: + return false; + default: + return true; + } +} + + +bool Literal::Decimal::parse(std::string_view s) +{ + bool negative = false; + size_t i = 0; + if (i < s.size() && (s[i] == '-' || s[i] == '+')) + { + negative = s[i] == '-'; + ++i; + } + Int256 result = 0; + bool has_digits = false; + bool has_point = false; + Int32 result_scale = 0; + for (; i < s.size(); ++i) + { + char c = s[i]; + if (c == '.' && !has_point) + { + has_point = true; + continue; + } + if (c < '0' || c > '9') + return false; + has_digits = true; + result = result * 10 + (c - '0'); + if (has_point) + ++result_scale; + /// More than 38 digits do not fit into the 128-bit value. + if (result > Int256(std::numeric_limits::max())) + return false; + } + if (!has_digits) + return false; + value = static_cast(negative ? -result : result); + scale = result_scale; + return true; +} + +std::string Literal::Decimal::toString() const +{ + bool negative = value < 0; + std::string digits = DB::toString(negative ? -Int256(value) : Int256(value)); + std::string result; + if (scale <= 0) + result = digits; + else + { + if (digits.size() <= static_cast(scale)) + digits = std::string(scale - digits.size() + 1, '0') + digits; + result = digits.substr(0, digits.size() - scale) + "." + digits.substr(digits.size() - scale); + size_t last = result.find_last_not_of('0'); + if (result[last] == '.') + result.resize(last); + else + result.resize(last + 1); + } + return negative ? "-" + result : result; +} + +namespace +{ + +int compareDecimals(const Literal::Decimal & a, const Literal::Decimal & b) +{ + Int256 left = a.value; + Int256 right = b.value; + for (Int32 s = a.scale; s < b.scale; ++s) + left *= 10; + for (Int32 s = b.scale; s < a.scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +} + +Literal::Literal(bool value) : type(PredicateDataType::BOOLEAN), int_value(value) {} +Literal::Literal(Int64 value) : type(PredicateDataType::LONG), int_value(value) {} +Literal::Literal(double value) : type(PredicateDataType::FLOAT), float_value(value) {} +Literal::Literal(const char * data, size_t size) : type(PredicateDataType::STRING), string_value(data, size) {} + +Literal::Literal(PredicateDataType type_, Int64 value) : type(type_), int_value(value) +{ + if (type != PredicateDataType::DATE) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Only DATE literals can be created from a type and an integer"); +} + +Literal::Literal(Int64 second, Int32 nanos) : type(PredicateDataType::TIMESTAMP), timestamp_value{second, nanos} {} + +Literal::Literal(Int128 value, Int32 /*precision*/, Int32 scale) : type(PredicateDataType::DECIMAL), decimal_value{value, scale} {} + + +namespace +{ + +/// Where a point is relative to the range [min, max]. +enum class Location : UInt8 +{ + BEFORE, + MIN, + MIDDLE, + MAX, + AFTER, +}; + +template +Location compareToRange(const T & point, const T & min, const T & max, Less less, Equal equal) +{ + if (less(point, min)) + return Location::BEFORE; + if (equal(point, min)) + return Location::MIN; + if (less(max, point)) + return Location::AFTER; + if (equal(point, max)) + return Location::MAX; + return Location::MIDDLE; +} + +template +TruthValue evaluatePredicateRange( + PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null, Less less, Equal equal) +{ + auto loc_of = [&](const T & v) { return compareToRange(v, min_value, max_value, less, equal); }; + bool min_equals_max = equal(min_value, max_value); + + switch (op) + { + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::AFTER) + return TruthValue::NO; + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + auto loc = loc_of(values.at(0)); + if (min_equals_max && loc == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::MIN) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER || loc == Location::MAX || (loc == Location::MIN && min_equals_max)) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IN: + { + if (min_equals_max) + { + for (const auto & value : values) + if (loc_of(value) == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + for (const auto & value : values) + { + auto loc = loc_of(value); + if (loc == Location::MIN || loc == Location::MIDDLE || loc == Location::MAX) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + case PredicateLeaf::Operator::BETWEEN: + { + if (values.empty()) + return TruthValue::YES_NO; + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::MIN) + { + auto loc2 = loc_of(values.at(1)); + if (loc2 == Location::AFTER || loc2 == Location::MAX) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc2 == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + if (loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; +} + +template +TruthValue evaluateRange(PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null) +{ + return evaluatePredicateRange(op, values, min_value, max_value, has_null, + [](const T & a, const T & b) { return a < b; }, + [](const T & a, const T & b) { return a == b; }); +} + +TruthValue evaluateBoolPredicate(PredicateLeaf::Operator op, const std::vector & literals, const Proto::ColumnStatistics & stats) +{ + bool has_null = stats.has_null.value_or(false); + if (!stats.bucket_statistics || stats.bucket_statistics->count.empty()) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + + UInt64 true_count = stats.bucket_statistics->count[0]; + UInt64 false_count = stats.number_of_values.value_or(0) - true_count; + switch (op) + { + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return TruthValue::NO; + if (false_count == 0) + return TruthValue::YES; + } + else + { + if (false_count == 0) + return TruthValue::NO; + if (true_count == 0) + return TruthValue::YES; + } + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (false_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + else + { + if (false_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (true_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +template +std::vector literalsTo(const std::vector & literals, Get get) +{ + std::vector result; + for (const auto & literal : literals) + if (!literal.isNull()) + result.push_back(get(literal)); + return result; +} + +/// From the reference implementation: the writer version that fixed the timestamp statistics. +constexpr UInt32 WRITER_VERSION_ORC_135 = 6; + +} + +TruthValue PredicateLeaf::evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const +{ + TruthValue result = TruthValue::YES_NO_NULL; + bool has_null = stats.has_null.value_or(false); + + switch (type) + { + case PredicateDataType::LONG: + { + if (stats.int_statistics && stats.int_statistics->minimum && stats.int_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getLong(); }), + *stats.int_statistics->minimum, *stats.int_statistics->maximum, has_null); + break; + } + case PredicateDataType::FLOAT: + { + if (stats.double_statistics && stats.double_statistics->minimum && stats.double_statistics->maximum) + { + if (!std::isfinite(stats.double_statistics->sum.value_or(0))) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + else + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getFloat(); }), + *stats.double_statistics->minimum, *stats.double_statistics->maximum, has_null); + } + break; + } + case PredicateDataType::STRING: + { + if (stats.string_statistics && stats.string_statistics->minimum && stats.string_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getString(); }), + *stats.string_statistics->minimum, *stats.string_statistics->maximum, has_null); + break; + } + case PredicateDataType::DATE: + { + if (stats.date_statistics && stats.date_statistics->minimum && stats.date_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getDate(); }), + static_cast(*stats.date_statistics->minimum), static_cast(*stats.date_statistics->maximum), has_null); + break; + } + case PredicateDataType::TIMESTAMP: + { + const auto & ts = stats.timestamp_statistics; + /// The stored nanoseconds are the sub-millisecond part plus one; malformed ones disable the pruning. + auto valid_nanos = [](const std::optional & nanos) { return !nanos || (*nanos >= 1 && *nanos <= 1'000'000); }; + if (ts && ts->minimum_utc && ts->maximum_utc && valid_nanos(ts->minimum_nanos) && valid_nanos(ts->maximum_nanos)) + { + Int32 min_nanos = ts->minimum_nanos ? static_cast(*ts->minimum_nanos) - 1 : 0; + Int32 max_nanos = ts->maximum_nanos ? static_cast(*ts->maximum_nanos) - 1 : 999999; + /// The milliseconds are rounded down, so the nanoseconds are not negative, as in the literals. + auto to_timestamp = [](Int64 millis, Int32 nanos) + { + Int64 second = millis / 1000; + Int64 rest = millis % 1000; + if (rest < 0) + { + rest += 1000; + --second; + } + return Literal::Timestamp{second, static_cast(rest * 1000000) + nanos}; + }; + Literal::Timestamp min = to_timestamp(*ts->minimum_utc, min_nanos); + Literal::Timestamp max = to_timestamp(*ts->maximum_utc, max_nanos); + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getTimestamp(); }), + min, max, has_null); + } + break; + } + case PredicateDataType::DECIMAL: + { + const auto & ds = stats.decimal_statistics; + if (ds && ds->minimum && ds->maximum) + { + Literal::Decimal min; + Literal::Decimal max; + if (min.parse(*ds->minimum) && max.parse(*ds->maximum)) + result = evaluatePredicateRange(op, + literalsTo(literals, [](const Literal & l) { return l.getDecimal(); }), + min, max, has_null, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) < 0; }, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) == 0; }); + } + break; + } + case PredicateDataType::BOOLEAN: + { + if (stats.bucket_statistics) + result = evaluateBoolPredicate(op, literals, stats); + break; + } + } + + /// Respect a null literal for IN. + if (op == Operator::IN && has_null) + for (const auto & literal : literals) + if (literal.isNull()) + return TruthValue::YES_NO_NULL; + + return result; +} + +namespace +{ + +TruthValue checkInBloomFilter(PredicateDataType type, const Literal & literal, const BloomFilter & bf, bool has_null) +{ + TruthValue result = has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (literal.isNull()) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::NO; + else + { + bool found = true; + switch (type) + { + case PredicateDataType::LONG: found = bf.testLong(literal.getLong()); break; + case PredicateDataType::FLOAT: found = bf.testDouble(literal.getFloat()); break; + case PredicateDataType::STRING: found = bf.testBytes(literal.getString().data(), literal.getString().size()); break; + case PredicateDataType::DECIMAL: + { + std::string s = literal.getDecimal().toString(); + found = bf.testBytes(s.data(), s.size()); + break; + } + case PredicateDataType::TIMESTAMP: + { + /// The writers round the negative milliseconds differently: the Java one down, the C++ one toward zero. + const auto timestamp = literal.getTimestamp(); + const Int64 millis_down = timestamp.getMillis(); + const bool has_fraction = timestamp.second < 0 && timestamp.nanos % 1000000 != 0; + found = bf.testLong(millis_down) || (has_fraction && bf.testLong(millis_down + 1)); + break; + } + case PredicateDataType::DATE: found = bf.testLong(literal.getDate()); break; + case PredicateDataType::BOOLEAN: found = true; break; + } + if (found) + result = TruthValue::YES_NO_NULL; + } + + if (result == TruthValue::YES_NO_NULL && !has_null) + result = TruthValue::YES_NO; + return result; +} + +} + +TruthValue PredicateLeaf::evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const +{ + switch (op) + { + case Operator::NULL_SAFE_EQUALS: + /// Null-safe equals does not return the `*_NULL` variants. + return checkInBloomFilter(type, literals.front(), bloom_filter, false); + case Operator::EQUALS: + return checkInBloomFilter(type, literals.front(), bloom_filter, has_null); + case Operator::IN: + for (const auto & literal : literals) + { + TruthValue result = checkInBloomFilter(type, literal, bloom_filter, has_null); + if (result == TruthValue::YES_NO_NULL || result == TruthValue::YES_NO) + return result; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +TruthValue PredicateLeaf::evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const +{ + /// The files written before ORC-135 store the timestamps in the local time zone of the writer. + if (type == PredicateDataType::TIMESTAMP && writer_version < WRITER_VERSION_ORC_135) + return TruthValue::YES_NO_NULL; + + /// The files written by some writers do not have the `has_null` field. + if (!stats.has_null) + return TruthValue::YES_NO_NULL; + + bool has_null = *stats.has_null; + bool all_null = has_null && stats.number_of_values.value_or(0) == 0; + if (op == Operator::IS_NULL || ((op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS) && literals.at(0).isNull())) + return all_null ? TruthValue::YES : (has_null ? TruthValue::YES_NO : TruthValue::NO); + if (all_null) + return TruthValue::IS_NULL; + + TruthValue result = evaluatePredicateMinMax(stats); + if (bloom_filter && result != TruthValue::NO_NULL && result != TruthValue::NO + && (op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS || op == Operator::IN)) + return evaluatePredicateBloomFilter(*bloom_filter, has_null); + return result; +} + + +class ExpressionTree +{ +public: + enum class Operator : UInt8 + { + OR, + AND, + NOT, + LEAF, + CONSTANT, + }; + + explicit ExpressionTree(Operator op_) : op(op_) {} + explicit ExpressionTree(TruthValue constant_) : op(Operator::CONSTANT), constant(constant_) {} + explicit ExpressionTree(size_t leaf_) : op(Operator::LEAF), leaf(leaf_) {} + ExpressionTree(Operator op_, std::vector children_) : op(op_), children(std::move(children_)) {} + + TruthValue evaluate(const std::vector & leaves) const + { + switch (op) + { + case Operator::OR: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && !isNeeded(result); ++i) + result = children[i]->evaluate(leaves) || result; + return result; + } + case Operator::AND: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && isNeeded(result); ++i) + result = children[i]->evaluate(leaves) && result; + return result; + } + case Operator::NOT: + return !children.at(0)->evaluate(leaves); + case Operator::LEAF: + return leaves.at(leaf); + case Operator::CONSTANT: + return constant; + } + return TruthValue::YES_NO_NULL; + } + + Operator op; + TruthValue constant = TruthValue::YES_NO_NULL; + size_t leaf = 0; + std::vector children; +}; + + +SearchArgument::SearchArgument(ExpressionTreePtr root_, std::vector leaves_) + : root(std::move(root_)), leaves(std::move(leaves_)) +{ +} + +TruthValue SearchArgument::evaluate(const std::vector & leaf_values) const +{ + return root ? root->evaluate(leaf_values) : TruthValue::YES_NO_NULL; +} + + +namespace +{ + +using Op = ExpressionTree::Operator; + +/// Pushes the negations down to the leaves and removes the double negations. +ExpressionTreePtr pushDownNot(ExpressionTreePtr root) +{ + if (root->op == Op::NOT) + { + ExpressionTreePtr child = root->children.at(0); + switch (child->op) + { + case Op::NOT: + return pushDownNot(child->children.at(0)); + case Op::CONSTANT: + return std::make_shared(!child->constant); + case Op::AND: + case Op::OR: + { + auto result = std::make_shared(child->op == Op::AND ? Op::OR : Op::AND); + for (const auto & kid : child->children) + result->children.push_back(pushDownNot(std::make_shared(Op::NOT, std::vector{kid}))); + return result; + } + case Op::LEAF: + break; + } + } + else + { + for (auto & kid : root->children) + kid = pushDownNot(kid); + } + return root; +} + +/// Removes the MAYBE (YES_NO_NULL) constants: they are dropped from AND and they replace OR. +ExpressionTreePtr foldMaybe(ExpressionTreePtr expr) +{ + for (auto & kid : expr->children) + { + ExpressionTreePtr child = foldMaybe(kid); + if (child->op == Op::CONSTANT && child->constant == TruthValue::YES_NO_NULL) + { + if (expr->op == Op::AND) + kid = nullptr; + else if (expr->op == Op::OR) + return child; + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Got a maybe as a child of a NOT in ORC search argument"); + } + else + kid = child; + } + + if (!expr->children.empty()) + { + std::erase(expr->children, nullptr); + if (expr->children.empty()) + return std::make_shared(TruthValue::YES_NO_NULL); + } + return expr; +} + +/// Converts multi-level ANDs and ORs into single level ones. +ExpressionTreePtr flatten(ExpressionTreePtr root) +{ + std::vector nodes; + for (auto & kid : root->children) + { + ExpressionTreePtr child = flatten(kid); + if (child->op == root->op && child->op != Op::NOT) + nodes.insert(nodes.end(), child->children.begin(), child->children.end()); + else + nodes.push_back(child); + } + root->children = std::move(nodes); + if ((root->op == Op::OR || root->op == Op::AND) && root->children.size() == 1) + return root->children[0]; + return root; +} + +ExpressionTreePtr copyTree(const ExpressionTreePtr & node) +{ + auto result = std::make_shared(*node); + return result; +} + +void generateAllCombinations( + std::vector & result, const std::vector & and_list, size_t and_index, const std::vector & non_and_list) +{ + const auto & kids = and_list[and_index]->children; + if (result.empty()) + { + for (const auto & kid : kids) + { + auto node = std::make_shared(Op::OR); + for (const auto & non_and : non_and_list) + node->children.push_back(copyTree(non_and)); + node->children.push_back(kid); + result.push_back(node); + } + } + else + { + std::vector work = std::move(result); + result.clear(); + for (const auto & kid : kids) + { + for (const auto & node : work) + { + auto copy = copyTree(node); + copy->children.push_back(kid); + result.push_back(copy); + } + } + } + if (and_index + 1 < and_list.size()) + generateAllCombinations(result, and_list, and_index + 1, non_and_list); +} + +constexpr size_t CNF_COMBINATIONS_THRESHOLD = 256; + +/// Converts the expression into the conjunctive normal form, if it is not too large. +ExpressionTreePtr convertToCNF(ExpressionTreePtr root) +{ + for (auto & kid : root->children) + kid = convertToCNF(kid); + + if (root->op != Op::OR) + return root; + + std::vector non_and_list; + std::vector and_list; + for (const auto & child : root->children) + { + if (child->op == Op::AND) + and_list.push_back(child); + else if (child->op == Op::OR) + non_and_list.insert(non_and_list.end(), child->children.begin(), child->children.end()); + else + non_and_list.push_back(child); + } + + if (and_list.empty()) + return root; + + size_t num_combinations = 1; + for (const auto & node : and_list) + { + num_combinations *= node->children.size(); + if (num_combinations > CNF_COMBINATIONS_THRESHOLD) + return std::make_shared(TruthValue::YES_NO_NULL); + } + + auto result = std::make_shared(Op::AND); + generateAllCombinations(result->children, and_list, 0, non_and_list); + return result; +} + +void collectUsedLeaves(const ExpressionTreePtr & node, std::vector & reorder, size_t & next) +{ + if (node->op == Op::LEAF) + { + if (reorder[node->leaf] == std::numeric_limits::max()) + reorder[node->leaf] = next++; + return; + } + for (const auto & kid : node->children) + collectUsedLeaves(kid, reorder, next); +} + +/// The trees can share nodes after the CNF conversion, so rewrite every leaf node exactly once. +void rewriteLeaves(const ExpressionTreePtr & root, const std::vector & reorder) +{ + std::unordered_set leaves; + std::deque nodes{root.get()}; + while (!nodes.empty()) + { + ExpressionTree * node = nodes.front(); + nodes.pop_front(); + if (node->op == Op::LEAF) + leaves.insert(node); + else + for (const auto & kid : node->children) + nodes.push_back(kid.get()); + } + for (auto * leaf : leaves) + leaf->leaf = reorder[leaf->leaf]; +} + +} + + +SearchArgumentBuilder::SearchArgumentBuilder() +{ + root = std::make_shared(Op::AND); + stack.push_back(root); +} + +SearchArgumentBuilder & SearchArgumentBuilder::start(UInt8 op) +{ + auto node = std::make_shared(static_cast(op)); + stack.back()->children.push_back(node); + stack.push_back(node); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::startOr() { return start(static_cast(Op::OR)); } +SearchArgumentBuilder & SearchArgumentBuilder::startAnd() { return start(static_cast(Op::AND)); } +SearchArgumentBuilder & SearchArgumentBuilder::startNot() { return start(static_cast(Op::NOT)); } + +SearchArgumentBuilder & SearchArgumentBuilder::end() +{ + auto current = stack.back(); + stack.pop_back(); + if (stack.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unbalanced end() in ORC search argument builder"); + if (current->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an expression with no children in ORC search argument builder"); + if (current->op == Op::NOT && current->children.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "A NOT expression must have exactly one child in ORC search argument builder"); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::literal(TruthValue value) +{ + stack.back()->children.push_back(std::make_shared(value)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::addLeaf(PredicateLeaf leaf) +{ + size_t index = leaves.size(); + leaves.push_back(std::move(leaf)); + stack.back()->children.push_back(std::make_shared(index)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThan(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::equals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::NULL_SAFE_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::in(UInt64 column_id, PredicateDataType type, const std::vector & values) +{ + if (values.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an IN expression with no arguments in ORC search argument builder"); + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IN, type, column_id, values)); +} + +SearchArgumentBuilder & SearchArgumentBuilder::isNull(UInt64 column_id, PredicateDataType type) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IS_NULL, type, column_id, {})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::BETWEEN, type, column_id, {std::move(lower), std::move(upper)})); +} + +std::unique_ptr SearchArgumentBuilder::build() +{ + if (stack.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to end {} operations in ORC search argument builder", stack.size() - 1); + if (root->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Empty ORC search argument"); + + root = pushDownNot(root); + root = foldMaybe(root); + root = flatten(root); + root = convertToCNF(root); + root = flatten(root); + + std::vector reorder(leaves.size(), std::numeric_limits::max()); + size_t num_used = 0; + collectUsedLeaves(root, reorder, num_used); + rewriteLeaves(root, reorder); + + std::vector used_leaves; + used_leaves.reserve(num_used); + std::vector by_new_index(num_used); + for (size_t i = 0; i < leaves.size(); ++i) + if (reorder[i] != std::numeric_limits::max()) + by_new_index[reorder[i]] = &leaves[i]; + for (const auto * leaf : by_new_index) + used_leaves.push_back(*leaf); + + return std::make_unique(root, std::move(used_leaves)); +} + + +namespace +{ + +constexpr UInt32 MURMUR3_DEFAULT_SEED = 104729; + +inline UInt64 rotl64(UInt64 x, int r) +{ + return (x << r) | (x >> (64 - r)); +} + +inline UInt64 fmix64(UInt64 value) +{ + value ^= (value >> 33); + value *= 0xff51afd7ed558ccdULL; + value ^= (value >> 33); + value *= 0xc4ceb9fe1a85ec53ULL; + value ^= (value >> 33); + return value; +} + +/// The 64-bit variant of Murmur3 used by ORC (the lower half of the 128-bit hash with one state). +UInt64 murmur3Hash64(const UInt8 * data, size_t size) +{ + UInt64 h = MURMUR3_DEFAULT_SEED; + const UInt64 c1 = 0x87c37b91114253d5ULL; + const UInt64 c2 = 0x4cf5ad432745937fULL; + size_t blocks = size >> 3; + for (size_t i = 0; i < blocks; ++i) + { + UInt64 k = 0; + memcpy(&k, data + i * 8, 8); + if constexpr (std::endian::native == std::endian::big) + k = std::byteswap(k); + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + h = rotl64(h, 27); + h = h * 5 + 0x52dce729; + } + + UInt64 k = 0; + size_t idx = blocks << 3; + size_t tail = size - idx; + for (size_t i = tail; i > 0; --i) + k ^= static_cast(data[idx + i - 1]) << ((i - 1) * 8); + if (tail) + { + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + } + + h ^= static_cast(size); + return fmix64(h); +} + +/// Thomas Wang's 64-bit integer hash, as in the reference implementation. +Int64 getLongHash(Int64 key) +{ + UInt64 k = static_cast(key); + k = (~k) + (k << 21); + k = k ^ static_cast(static_cast(k) >> 24); + k = (k + (k << 3)) + (k << 8); + k = k ^ static_cast(static_cast(k) >> 14); + k = (k + (k << 2)) + (k << 4); + k = k ^ static_cast(static_cast(k) >> 28); + k = k + (k << 31); + return static_cast(k); +} + +} + +BloomFilter::BloomFilter(const Proto::BloomFilter & proto) : num_hash_functions(proto.num_hash_functions) +{ + /// The writers use a few hash functions (the optimal number for the false positive probability), + /// a huge number from a corrupt file would make every probe extremely slow. + static constexpr UInt32 MAX_HASH_FUNCTIONS = 256; + if (num_hash_functions == 0 || num_hash_functions > MAX_HASH_FUNCTIONS) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid number of hash functions {} of a bloom filter in ORC file, must be from 1 to {}", + num_hash_functions, MAX_HASH_FUNCTIONS); + const std::string & bitset = proto.utf8bitset.value(); + if (bitset.empty() || bitset.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "The size of a bloom filter in ORC file must be a positive multiple of 8 bytes"); + bits.resize(bitset.size() / 8); + memcpy(bits.data(), bitset.data(), bitset.size()); + if constexpr (std::endian::native == std::endian::big) + for (auto & word : bits) + word = std::byteswap(word); +} + +bool BloomFilter::testHash(Int64 hash) const +{ + Int32 hash1 = static_cast(hash & 0xffffffff); + Int32 hash2 = static_cast(static_cast(hash) >> 32); + UInt64 num_bits = bits.size() * 64; + for (UInt32 i = 1; i <= num_hash_functions; ++i) + { + Int32 combined = static_cast(static_cast(hash1) + i * static_cast(hash2)); + if (combined < 0) + combined = ~combined; + UInt64 pos = static_cast(combined) % num_bits; + if (!(bits[pos >> 6] & (1ULL << (pos % 64)))) + return false; + } + return true; +} + +bool BloomFilter::testLong(Int64 value) const +{ + return testHash(getLongHash(value)); +} + +bool BloomFilter::testDouble(double value) const +{ + return testLong(std::bit_cast(value)); +} + +bool BloomFilter::testBytes(const char * data, size_t size) const +{ + return testHash(static_cast(murmur3Hash64(reinterpret_cast(data), size))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.h b/src/Processors/Formats/Impl/ORC/SearchArgument.h new file mode 100644 index 000000000000..da19904275e7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.h @@ -0,0 +1,198 @@ +#pragma once + +#include + +#include +#include +#include + +/// Predicates for skipping stripes and row groups by the column statistics and the bloom filters. +/// The semantics (the truth values, the normalization of the expression, the evaluation of each +/// predicate against the statistics) are the same as in the reference implementation. + +namespace DB::ORC +{ + +/// The possible outcomes of a predicate over a set of rows: whether any row can satisfy it (YES), +/// fail it (NO), or evaluate it to NULL. +enum class TruthValue : UInt8 +{ + YES, + NO, + IS_NULL, + YES_NULL, + NO_NULL, + YES_NO, + YES_NO_NULL, +}; + +TruthValue operator||(TruthValue left, TruthValue right); +TruthValue operator&&(TruthValue left, TruthValue right); +TruthValue operator!(TruthValue value); +/// Whether the rows have to be read. +bool isNeeded(TruthValue value); + +enum class PredicateDataType : UInt8 +{ + LONG, + FLOAT, + STRING, + DATE, + DECIMAL, + TIMESTAMP, + BOOLEAN, +}; + +class Literal +{ +public: + struct Timestamp + { + Int64 second = 0; + Int32 nanos = 0; + + /// Rounded down, as the nanoseconds are not negative. + Int64 getMillis() const { return second * 1000 + nanos / 1000000; } + auto operator<=>(const Timestamp &) const = default; + }; + + struct Decimal + { + Int128 value = 0; + Int32 scale = 0; + + /// Parses a decimal number like `-123.45`. Returns false if it is malformed. + bool parse(std::string_view s); + /// Without the trailing zeros in the fraction, as in the bloom filters. + std::string toString() const; + }; + + explicit Literal(bool value); + explicit Literal(Int64 value); + explicit Literal(double value); + Literal(const char * data, size_t size); + /// Only for DATE: the number of days since the epoch. + Literal(PredicateDataType type, Int64 value); + /// TIMESTAMP: the seconds since the epoch in UTC and the nanoseconds. + Literal(Int64 second, Int32 nanos); + Literal(Int128 value, Int32 precision, Int32 scale); + + PredicateDataType getType() const { return type; } + bool isNull() const { return is_null; } + + bool getBool() const { return int_value != 0; } + Int64 getLong() const { return int_value; } + Int64 getDate() const { return int_value; } + double getFloat() const { return float_value; } + const std::string & getString() const { return string_value; } + Timestamp getTimestamp() const { return timestamp_value; } + Decimal getDecimal() const { return decimal_value; } + +private: + PredicateDataType type; + bool is_null = false; + Int64 int_value = 0; + double float_value = 0; + std::string string_value; + Timestamp timestamp_value; + Decimal decimal_value; +}; + +class BloomFilter; + +class PredicateLeaf +{ +public: + enum class Operator : UInt8 + { + EQUALS, + NULL_SAFE_EQUALS, + LESS_THAN, + LESS_THAN_EQUALS, + IN, + BETWEEN, + IS_NULL, + }; + + PredicateLeaf(Operator op_, PredicateDataType type_, UInt64 column_id_, std::vector literals_) + : op(op_), type(type_), column_id(column_id_), literals(std::move(literals_)) {} + + UInt64 getColumnId() const { return column_id; } + + /// `writer_version` is from the postscript of the file. `bloom_filter` can be nullptr. + TruthValue evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const; + +private: + TruthValue evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const; + TruthValue evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const; + + Operator op; + PredicateDataType type; + UInt64 column_id; + std::vector literals; +}; + +class ExpressionTree; +using ExpressionTreePtr = std::shared_ptr; + +class SearchArgument +{ +public: + SearchArgument(ExpressionTreePtr root_, std::vector leaves_); + + const std::vector & getLeaves() const { return leaves; } + TruthValue evaluate(const std::vector & leaf_values) const; + +private: + ExpressionTreePtr root; + std::vector leaves; +}; + +class SearchArgumentBuilder +{ +public: + SearchArgumentBuilder(); + + SearchArgumentBuilder & startOr(); + SearchArgumentBuilder & startAnd(); + SearchArgumentBuilder & startNot(); + SearchArgumentBuilder & end(); + + SearchArgumentBuilder & literal(TruthValue value); + SearchArgumentBuilder & lessThan(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & equals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & in(UInt64 column_id, PredicateDataType type, const std::vector & values); + SearchArgumentBuilder & isNull(UInt64 column_id, PredicateDataType type); + SearchArgumentBuilder & between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper); + + std::unique_ptr build(); + +private: + SearchArgumentBuilder & start(UInt8 op); + SearchArgumentBuilder & addLeaf(PredicateLeaf leaf); + + std::vector stack; + ExpressionTreePtr root; + std::vector leaves; +}; + +/// A bloom filter of a row group (or a stripe), from the BLOOM_FILTER_UTF8 stream. +class BloomFilter +{ +public: + explicit BloomFilter(const Proto::BloomFilter & proto); + + bool testLong(Int64 value) const; + bool testDouble(double value) const; + bool testBytes(const char * data, size_t size) const; + +private: + bool testHash(Int64 hash) const; + + UInt32 num_hash_functions; + std::vector bits; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.cpp b/src/Processors/Formats/Impl/ORC/Statistics.cpp new file mode 100644 index 000000000000..0b1b4c86cd9b --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.cpp @@ -0,0 +1,462 @@ +#include +#include + +#include + +#include + + +namespace DB::ORC +{ + +namespace +{ + +int compareDecimals(Int128 a, Int32 a_scale, Int128 b, Int32 b_scale) +{ + Int256 left = a; + Int256 right = b; + for (Int32 s = a_scale; s < b_scale; ++s) + left *= 10; + for (Int32 s = b_scale; s < a_scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +std::string decimalToString(Int128 value, Int32 scale) +{ + return Literal::Decimal{value, scale}.toString(); +} + +} + +void StatisticsBuilder::updateInteger(Int64 value) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + if (has_int_sum && __builtin_add_overflow(int_sum, value, &int_sum)) + has_int_sum = false; +} + +void StatisticsBuilder::updateDouble(double value) +{ + if (!has_minimum) + { + has_minimum = true; + double_minimum = double_maximum = value; + } + else + { + double_minimum = std::min(double_minimum, value); + double_maximum = std::max(double_maximum, value); + } + double_sum += value; +} + +void StatisticsBuilder::updateString(std::string_view value) +{ + if (!has_minimum) + { + has_minimum = true; + string_minimum = value; + string_maximum = value; + } + else + { + if (value < std::string_view(string_minimum)) + string_minimum = value; + if (value > std::string_view(string_maximum)) + string_maximum = value; + } + total_length += value.size(); +} + +void StatisticsBuilder::updateBinary(size_t length) +{ + total_length += length; +} + +void StatisticsBuilder::updateBoolean(bool value) +{ + if (value) + ++true_count; +} + +void StatisticsBuilder::updateDate(Int32 value) +{ + updateInteger(value); +} + +void StatisticsBuilder::updateDecimal(Int128 value, Int32 scale) +{ + if (!has_minimum) + { + has_minimum = true; + decimal_minimum = decimal_maximum = value; + decimal_minimum_scale = decimal_maximum_scale = scale; + } + else + { + if (compareDecimals(value, scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = value; + decimal_minimum_scale = scale; + } + if (compareDecimals(value, scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = value; + decimal_maximum_scale = scale; + } + } + + if (has_decimal_sum) + { + Int256 sum = decimal_sum; + Int256 addend = value; + Int32 result_scale = std::max(decimal_sum_scale, scale); + for (Int32 s = decimal_sum_scale; s < result_scale; ++s) + sum *= 10; + for (Int32 s = scale; s < result_scale; ++s) + addend *= 10; + sum += addend; + if (sum > Int256(std::numeric_limits::max()) || sum < Int256(std::numeric_limits::min())) + has_decimal_sum = false; + else + { + decimal_sum = static_cast(sum); + decimal_sum_scale = result_scale; + } + } +} + +void StatisticsBuilder::updateTimestamp(Int64 millis, Int32 nanos) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = millis; + minimum_nanos = maximum_nanos = nanos; + return; + } + if (millis <= int_minimum) + { + if (millis < int_minimum || nanos < minimum_nanos) + minimum_nanos = nanos; + int_minimum = millis; + } + if (millis >= int_maximum) + { + if (millis > int_maximum || nanos > maximum_nanos) + maximum_nanos = nanos; + int_maximum = millis; + } +} + +void StatisticsBuilder::updateCollection(UInt64 children) +{ + Int64 value = static_cast(children); + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + total_children += children; +} + +void StatisticsBuilder::merge(const StatisticsBuilder & other) +{ + number_of_values += other.number_of_values; + has_null |= other.has_null; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + case DATE: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + has_int_sum = has_int_sum && other.has_int_sum; + if (has_int_sum && __builtin_add_overflow(int_sum, other.int_sum, &int_sum)) + has_int_sum = false; + break; + case FLOAT: + case DOUBLE: + if (other.has_minimum) + { + if (!has_minimum) + { + double_minimum = other.double_minimum; + double_maximum = other.double_maximum; + } + else + { + double_minimum = std::min(double_minimum, other.double_minimum); + double_maximum = std::max(double_maximum, other.double_maximum); + } + has_minimum = true; + } + double_sum += other.double_sum; + break; + case STRING: + case CHAR: + case VARCHAR: + if (other.has_minimum) + { + if (!has_minimum) + { + string_minimum = other.string_minimum; + string_maximum = other.string_maximum; + } + else + { + if (other.string_minimum < string_minimum) + string_minimum = other.string_minimum; + if (other.string_maximum > string_maximum) + string_maximum = other.string_maximum; + } + has_minimum = true; + } + total_length += other.total_length; + break; + case BINARY: + total_length += other.total_length; + break; + case BOOLEAN: + true_count += other.true_count; + break; + case DECIMAL: + if (other.has_minimum) + { + if (!has_minimum) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + else + { + if (compareDecimals(other.decimal_minimum, other.decimal_minimum_scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + } + if (compareDecimals(other.decimal_maximum, other.decimal_maximum_scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + } + has_minimum = true; + } + has_decimal_sum = has_decimal_sum && other.has_decimal_sum; + if (has_decimal_sum) + { + /// Reuse the update of the sum without touching the minimum and the maximum. + bool saved_has_minimum = has_minimum; + Int128 saved_min = decimal_minimum; + Int32 saved_min_scale = decimal_minimum_scale; + Int128 saved_max = decimal_maximum; + Int32 saved_max_scale = decimal_maximum_scale; + updateDecimal(other.decimal_sum, other.decimal_sum_scale); + has_minimum = saved_has_minimum; + decimal_minimum = saved_min; + decimal_minimum_scale = saved_min_scale; + decimal_maximum = saved_max; + decimal_maximum_scale = saved_max_scale; + } + break; + case TIMESTAMP: + case TIMESTAMP_INSTANT: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + minimum_nanos = other.minimum_nanos; + maximum_nanos = other.maximum_nanos; + has_minimum = true; + } + else + { + if (other.int_minimum <= int_minimum) + { + if (other.int_minimum < int_minimum || other.minimum_nanos < minimum_nanos) + minimum_nanos = other.minimum_nanos; + int_minimum = other.int_minimum; + } + if (other.int_maximum >= int_maximum) + { + if (other.int_maximum > int_maximum || other.maximum_nanos > maximum_nanos) + maximum_nanos = other.maximum_nanos; + int_maximum = other.int_maximum; + } + } + } + break; + case LIST: + case MAP: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + total_children += other.total_children; + break; + default: + break; + } +} + +void StatisticsBuilder::reset() +{ + *this = StatisticsBuilder(kind); +} + +Proto::ColumnStatistics StatisticsBuilder::toProto() const +{ + Proto::ColumnStatistics res; + res.has_null = has_null; + res.number_of_values = number_of_values; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + { + auto & stats = res.int_statistics.emplace(); + if (has_minimum) + { + stats.minimum = int_minimum; + stats.maximum = int_maximum; + } + if (has_int_sum) + stats.sum = int_sum; + break; + } + case DATE: + { + auto & stats = res.date_statistics.emplace(); + if (has_minimum) + { + stats.minimum = static_cast(int_minimum); + stats.maximum = static_cast(int_maximum); + } + break; + } + case FLOAT: + case DOUBLE: + { + auto & stats = res.double_statistics.emplace(); + if (has_minimum) + { + stats.minimum = double_minimum; + stats.maximum = double_maximum; + } + stats.sum = double_sum; + break; + } + case STRING: + case CHAR: + case VARCHAR: + { + auto & stats = res.string_statistics.emplace(); + if (has_minimum) + { + stats.minimum = string_minimum; + stats.maximum = string_maximum; + } + stats.sum = static_cast(total_length); + break; + } + case BINARY: + res.binary_statistics.emplace().sum = static_cast(total_length); + break; + case BOOLEAN: + res.bucket_statistics.emplace().count.push_back(true_count); + break; + case DECIMAL: + { + auto & stats = res.decimal_statistics.emplace(); + if (has_minimum) + { + stats.minimum = decimalToString(decimal_minimum, decimal_minimum_scale); + stats.maximum = decimalToString(decimal_maximum, decimal_maximum_scale); + } + if (has_decimal_sum) + stats.sum = decimalToString(decimal_sum, decimal_sum_scale); + break; + } + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + auto & stats = res.timestamp_statistics.emplace(); + if (has_minimum) + { + stats.minimum_utc = int_minimum; + stats.maximum_utc = int_maximum; + if (minimum_nanos != 0) + stats.minimum_nanos = static_cast(minimum_nanos) + 1; + if (maximum_nanos != 999999) + stats.maximum_nanos = static_cast(maximum_nanos) + 1; + } + break; + } + case LIST: + case MAP: + { + auto & stats = res.collection_statistics.emplace(); + if (has_minimum) + { + stats.min_children = static_cast(int_minimum); + stats.max_children = static_cast(int_maximum); + } + stats.total_children = total_children; + break; + } + default: + break; + } + return res; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.h b/src/Processors/Formats/Impl/ORC/Statistics.h new file mode 100644 index 000000000000..c00c00e07b94 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.h @@ -0,0 +1,71 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// Accumulates the statistics of a column for a row group, a stripe or the whole file, +/// in the same way as the reference implementation. +class StatisticsBuilder +{ +public: + explicit StatisticsBuilder(TypeKind kind_) : kind(kind_) {} + + void increase(UInt64 count) { number_of_values += count; } + void setHasNull() { has_null = true; } + + void updateInteger(Int64 value); + void updateDouble(double value); + void updateString(std::string_view value); + void updateBinary(size_t length); + void updateBoolean(bool value); + void updateDate(Int32 value); + void updateDecimal(Int128 value, Int32 scale); + /// `millis` since the epoch in UTC, `nanos` is the sub-millisecond part. + void updateTimestamp(Int64 millis, Int32 nanos); + void updateCollection(UInt64 children); + + void merge(const StatisticsBuilder & other); + void reset(); + + Proto::ColumnStatistics toProto() const; + +private: + TypeKind kind; + UInt64 number_of_values = 0; + bool has_null = false; + bool has_minimum = false; + + Int64 int_minimum = 0; + Int64 int_maximum = 0; + Int64 int_sum = 0; + bool has_int_sum = true; + + double double_minimum = 0; + double double_maximum = 0; + double double_sum = 0; + + std::string string_minimum; + std::string string_maximum; + UInt64 total_length = 0; + + UInt64 true_count = 0; + + Int128 decimal_minimum = 0; + Int32 decimal_minimum_scale = 0; + Int128 decimal_maximum = 0; + Int32 decimal_maximum_scale = 0; + Int128 decimal_sum = 0; + Int32 decimal_sum_scale = 0; + bool has_decimal_sum = true; + + Int32 minimum_nanos = 0; + Int32 maximum_nanos = 999999; + + UInt64 total_children = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.cpp b/src/Processors/Formats/Impl/ORC/Stream.cpp new file mode 100644 index 000000000000..275e75915dca --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.cpp @@ -0,0 +1,248 @@ +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +UInt64 PositionProvider::next() +{ + if (index >= positions.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not enough positions in a row index entry of ORC file"); + return positions[index++]; +} + + +InputByteStream::InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_) + : data(data_), length(data_.size()), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +InputByteStream::InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_) + : length(length_), loader(std::move(loader_)), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +std::string_view InputByteStream::getRange(UInt64 offset, UInt64 size) +{ + if (!loader) + return data.substr(offset, size); + + if (offset < window_offset || offset + size > window_offset + data.size()) + { + UInt64 load_size = std::min(length - offset, std::max(size, LAZY_READ_SIZE)); + auto range = loader(offset, load_size); + if (range.data.size() != load_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Loaded {} bytes instead of {} from ORC stream {}", range.data.size(), load_size, name); + window_holder = std::move(range.holder); + data = range.data; + window_offset = offset; + } + return data.substr(offset - window_offset, size); +} + +bool InputByteStream::nextChunk() +{ + while (next_chunk_offset < length) + { + if (compression == CompressionKind::NONE) + { + UInt64 size = length - next_chunk_offset; + if (loader) + size = std::min(size, LAZY_READ_SIZE); + pos = getRange(next_chunk_offset, size).data(); + end = pos + size; + next_chunk_offset += size; + return true; + } + + if (length - next_chunk_offset < COMPRESSION_HEADER_SIZE) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated compression chunk header in ORC stream {}", name); + + const UInt8 * header = reinterpret_cast(getRange(next_chunk_offset, COMPRESSION_HEADER_SIZE).data()); + UInt32 header_value = header[0] | (header[1] << 8) | (header[2] << 16); + bool is_original = header_value & 1; + size_t chunk_length = header_value >> 1; + size_t chunk_offset = next_chunk_offset + COMPRESSION_HEADER_SIZE; + + if (chunk_length > length - chunk_offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Compression chunk of size {} at offset {} goes beyond the end of ORC stream {} of size {}", + chunk_length, next_chunk_offset, name, length); + + next_chunk_offset = chunk_offset + chunk_length; + const char * chunk = getRange(chunk_offset, chunk_length).data(); + + if (is_original) + { + pos = chunk; + end = chunk + chunk_length; + } + else + { + /// The chunk length is at most 8 MiB, so the bound does not overflow. + size_t capacity = std::min(block_size, maxDecompressedSize(compression, chunk, chunk_length)); + if (decompressed.size() < capacity) + decompressed.resize(capacity); + size_t size = decompressChunk(compression, chunk, chunk_length, decompressed.data(), capacity); + pos = decompressed.data(); + end = decompressed.data() + size; + } + + if (pos != end) + return true; + } + + pos = end = nullptr; + return false; +} + +void InputByteStream::readBytes(char * to, size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + memcpy(to, pos, count); + pos += count; + to += count; + n -= count; + } +} + +void InputByteStream::skipBytes(size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + pos += count; + n -= count; + } +} + +void InputByteStream::seek(PositionProvider & positions) +{ + if (compression == CompressionKind::NONE) + { + UInt64 offset = positions.next(); + if (offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", offset, name, length); + next_chunk_offset = offset; + pos = end = nullptr; + nextChunk(); + return; + } + + UInt64 chunk_offset = positions.next(); + UInt64 uncompressed_offset = positions.next(); + if (chunk_offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", chunk_offset, name, length); + + next_chunk_offset = chunk_offset; + pos = end = nullptr; + if (!nextChunk()) + { + if (uncompressed_offset != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {}", uncompressed_offset, name); + return; + } + + if (uncompressed_offset > static_cast(end - pos)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Seek position {} is beyond the end of the compression chunk of size {} in ORC stream {}", + uncompressed_offset, end - pos, name); + pos += uncompressed_offset; +} + +void InputByteStream::throwUnexpectedEnd() const +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected end of ORC stream {}", name); +} + + +OutputByteStream::OutputByteStream(Compressor * compressor_, size_t block_size_) + : compressor(compressor_), block_size(block_size_) +{ + buffer.reserve(std::min(block_size, 64 * 1024)); +} + +void OutputByteStream::write(const char * data, size_t size) +{ + while (size) + { + if (buffer.size() == block_size) + flushChunk(); + size_t count = std::min(size, block_size - buffer.size()); + buffer.append(data, count); + data += count; + size -= count; + } +} + +void OutputByteStream::recordPosition(std::vector & positions) const +{ + if (compressor) + { + positions.push_back(output.size()); + positions.push_back(buffer.size()); + } + else + positions.push_back(output.size() + buffer.size()); +} + +void OutputByteStream::flushChunk() +{ + if (buffer.empty()) + return; + + if (!compressor) + { + output.append(buffer); + buffer.clear(); + return; + } + + size_t header_offset = output.size(); + output.append(COMPRESSION_HEADER_SIZE, '\0'); + size_t compressed_size = compressor->compress(buffer.data(), buffer.size(), output); + + UInt32 header_value = 0; + if (compressed_size) + header_value = static_cast(compressed_size << 1); + else + { + output.append(buffer); + header_value = static_cast((buffer.size() << 1) | 1); + } + + output[header_offset] = static_cast(header_value & 0xFF); + output[header_offset + 1] = static_cast((header_value >> 8) & 0xFF); + output[header_offset + 2] = static_cast((header_value >> 16) & 0xFF); + buffer.clear(); +} + +size_t OutputByteStream::finish() +{ + flushChunk(); + return output.size(); +} + +void OutputByteStream::reset() +{ + buffer.clear(); + output.clear(); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.h b/src/Processors/Formats/Impl/ORC/Stream.h new file mode 100644 index 000000000000..44d209d38321 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace DB::ORC +{ + +/// A sequence of positions from a row index entry, consumed by the streams and the decoders of a +/// column in their order. +class PositionProvider +{ +public: + explicit PositionProvider(const std::vector & positions_) : positions(positions_) {} + UInt64 next(); + +private: + const std::vector & positions; + size_t index = 0; +}; + +/// A piece of a stream loaded from the file. `data` is valid while `holder` is alive. +struct LoadedRange +{ + std::shared_ptr holder; + std::string_view data; +}; + +/// Loads the range `(offset, length)` of a stream from the file. +using RangeLoader = std::function; + +/// A stream of an ORC column, such as PRESENT or DATA, decompressed chunk by chunk. The decoders +/// read from the buffer `[pos, end)` of the current chunk directly. +class InputByteStream +{ +public: + /// The whole stream in memory. `data` must outlive the stream. + InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_); + /// The stream of `length_` bytes is loaded from the file on demand, by `loader_`, a window of + /// at least `LAZY_READ_SIZE` bytes at a time. Used when only some row groups are read. + InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_); + + static constexpr size_t LAZY_READ_SIZE = 1024 * 1024; + + /// Loads the next chunk. Returns false at the end of the stream. + bool nextChunk(); + + bool eof() + { + return pos == end && !nextChunk(); + } + + UInt8 readByte() + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + return static_cast(*pos++); + } + + void readBytes(char * to, size_t n); + void skipBytes(size_t n); + + /// Moves to the position from the row index: one value (the byte offset) for an uncompressed + /// stream, two values (the offset of the compressed chunk and the offset in its decompressed + /// data) for a compressed one. + void seek(PositionProvider & positions); + + [[noreturn]] void throwUnexpectedEnd() const; + + const std::string & getName() const { return name; } + + const char * pos = nullptr; + const char * end = nullptr; + +private: + /// Returns the range `[offset, offset + length)` of the stream. It is valid until the next call. + std::string_view getRange(UInt64 offset, UInt64 length); + + /// The stream in memory, or the currently loaded window of a lazily loaded stream. + std::string_view data; + UInt64 length; + RangeLoader loader; + /// For a lazily loaded stream: the offset of `data` in the stream, and its owner. + UInt64 window_offset = 0; + std::shared_ptr window_holder; + + CompressionKind compression; + size_t block_size; + std::string name; + + /// The offset of the next chunk to read in `data`. + size_t next_chunk_offset = 0; + PODArray decompressed; +}; + +/// Accumulates a stream of an ORC column, compressing it chunk by chunk. +class OutputByteStream +{ +public: + /// `compressor` can be nullptr, which means no compression. + OutputByteStream(Compressor * compressor_, size_t block_size_); + + void writeByte(UInt8 byte) + { + if (buffer.size() == block_size) + flushChunk(); + buffer.push_back(static_cast(byte)); + } + + void write(const char * data, size_t size); + + /// Appends the current position to `positions`, in the format that `InputByteStream::seek` expects. + void recordPosition(std::vector & positions) const; + + /// Finishes the stream and returns its size in bytes. + size_t finish(); + + const std::string & getOutput() const { return output; } + + /// Clears the stream to start a new stripe. + void reset(); + + size_t estimateSize() const { return output.size() + buffer.size(); } + +private: + void flushChunk(); + + Compressor * compressor; + size_t block_size; + std::string buffer; + std::string output; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.cpp b/src/Processors/Formats/Impl/ORC/Timezone.cpp new file mode 100644 index 000000000000..33a1574507d2 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.cpp @@ -0,0 +1,87 @@ +#include + +#include +#include + +#include + +/// The embedded time zone files, see `DateLUTImpl.cpp`. +std::string_view getTimeZone(const char * name); /// NOLINT(misc-use-internal-linkage) + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +TimezoneOffset::TimezoneOffset(const DateLUTImpl & lut_) + : lut(lut_) +{ + const std::string & name = lut.getTimeZone(); + const std::string_view file = getTimeZone(name.c_str()); + /// `Fixed/UTC±HH:MM:SS` zones have no file. On this branch `DateLUT` also loads zones that are not embedded + /// (`libc:` names, the host database), so keep the offsets of `DateLUTImpl` for all of them. + if (file.empty()) + return; + + /// Raw records, as `cctz::time_zone::next_transition` skips no-op ones (Europe/Lisbon has one in 1884). + static constexpr size_t header_size = 44; + size_t pos = 0; + auto check = [&](size_t size) + { + if (size > file.size() - pos) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + }; + auto read_count = [&](size_t index) { return unalignedLoadBigEndian(file.data() + pos + 20 + index * 4); }; + + check(header_size); + if (!file.starts_with("TZif")) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + size_t time_size = 4; + /// Version 2 and later repeat the data with 64-bit times after the 32-bit section. + if (file[4] != '\0') + { + const size_t v1_size = read_count(3) * 5 + read_count(4) * 6 + read_count(5) + read_count(2) * 8 + read_count(1) + read_count(0); + check(header_size + v1_size); + pos += header_size + v1_size; + check(header_size); + time_size = 8; + } + const size_t time_count = read_count(3); + const size_t type_count = read_count(4); + pos += header_size; + check(time_count * (time_size + 1) + type_count * 6); + if (time_count == 0) + return; + + const char * times = file.data() + pos; + const auto * type_indices = reinterpret_cast(times + time_count * time_size); + const char * types = times + time_count * (time_size + 1); + auto type_record = [&](size_t type) + { + if (type >= type_count) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + return types + type * 6; + }; + + first_transition = time_size == 8 ? unalignedLoadBigEndian(times) : unalignedLoadBigEndian(times); + /// The oldest standard time, or the first type if all of them are daylight saving time. + const char * ancient = type_record(0); + for (size_t i = 0; i < time_count; ++i) + { + const char * record = type_record(type_indices[i]); + if (record[4] == 0) + { + ancient = record; + break; + } + } + ancient_offset = unalignedLoadBigEndian(ancient); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.h b/src/Processors/Formats/Impl/ORC/Timezone.h new file mode 100644 index 000000000000..8a7dbd7361fd --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// The UTC offset as in the reference implementation: before the first transition record it is the oldest +/// standard time, not the local mean time (Asia/Shanghai +08:00, not +08:05:43). Shared by reader and writer. +class TimezoneOffset +{ +public: + explicit TimezoneOffset(const DateLUTImpl & lut_); + + Int64 operator()(Int64 t) const { return t < first_transition ? ancient_offset : lut.timezoneOffset(t); } + +private: + const DateLUTImpl & lut; + Int64 first_transition = std::numeric_limits::min(); + Int64 ancient_offset = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.cpp b/src/Processors/Formats/Impl/ORC/Type.cpp new file mode 100644 index 000000000000..b716b8c9ccb1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.cpp @@ -0,0 +1,380 @@ +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int UNKNOWN_TYPE; + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +namespace +{ + +bool isUnquotedFieldName(const std::string & name) +{ + for (char c : name) + if (!isalnum(static_cast(c)) && c != '_') + return false; + return true; +} + +std::string algorithmToString(UInt32 algorithm) +{ + switch (algorithm) + { + case 0: return "spherical"; + case 1: return "vincenty"; + case 2: return "thomas"; + case 3: return "andoyer"; + case 4: return "karney"; + default: return std::to_string(algorithm); + } +} + +/// The same limit as in the reference implementation. +constexpr size_t MAX_TYPE_NESTING_DEPTH = 2000; + +std::unique_ptr convertType(const std::vector & types, UInt64 index, UInt64 & next_id, size_t depth) +{ + checkStackSize(); + + if (depth > MAX_TYPE_NESTING_DEPTH) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: type nesting depth exceeds the limit of {}", MAX_TYPE_NESTING_DEPTH); + + /// The types are listed in pre-order and the column id of each type is its index in the list. + if (index != next_id || index >= types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: the types are not a tree listed in pre-order (type {} is referenced at position {})", + index, next_id); + ++next_id; + + const auto & proto = types[index]; + if (proto.kind > GEOGRAPHY) + throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown ORC type kind {}", proto.kind); + + auto kind = static_cast(proto.kind); + auto result = std::make_unique(kind); + + switch (kind) + { + case LIST: + if (proto.subtypes.size() != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC LIST type that doesn't contain one subtype"); + break; + case MAP: + if (proto.subtypes.size() != 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC MAP type that doesn't contain two subtypes"); + break; + case UNION: + if (proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type that doesn't contain any subtypes"); + /// The tags of a union are bytes. + if (proto.subtypes.size() > 256) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type with {} subtypes, more than 256", proto.subtypes.size()); + break; + case STRUCT: + if (proto.subtypes.size() > proto.field_names.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC STRUCT type that contains less field names than subtypes"); + break; + default: + if (!proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC type {} with subtypes", proto.kind); + break; + } + + if (kind == CHAR || kind == VARCHAR) + result->setMaximumLength(proto.maximum_length.value_or(0)); + if (kind == DECIMAL) + result->setPrecisionAndScale(proto.precision.value_or(0), proto.scale.value_or(0)); + if (kind == GEOMETRY || kind == GEOGRAPHY) + result->setGeospatial(proto.crs.value_or("OGC:CRS84"), proto.algorithm.value_or(0)); + + for (size_t i = 0; i < proto.subtypes.size(); ++i) + { + auto child = convertType(types, proto.subtypes[i], next_id, depth + 1); + if (kind == STRUCT) + result->addStructField(proto.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + + for (const auto & attribute : proto.attributes) + result->setAttribute(attribute.key, attribute.value); + + return result; +} + +void selectChildren(std::vector & selected, const Type & type) +{ + for (UInt64 c = type.getColumnId(); c <= type.getMaximumColumnId(); ++c) + selected[c] = true; +} + +bool selectParents(std::vector & selected, const Type & type) +{ + size_t id = type.getColumnId(); + bool result = selected[id]; + size_t num_selected_subtypes = 0; + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + { + if (selectParents(selected, *type.getSubtype(c))) + { + result = true; + ++num_selected_subtypes; + } + } + selected[id] = result; + + /// The branches of a union are either all selected or all not selected. + if (type.getKind() == UNION && result && num_selected_subtypes > 0 && num_selected_subtypes < type.getSubtypeCount()) + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + selectChildren(selected, *type.getSubtype(c)); + + return result; +} + +} + + +std::string Type::toString() const +{ + switch (kind) + { + case BOOLEAN: return "boolean"; + case BYTE: return "tinyint"; + case SHORT: return "smallint"; + case INT: return "int"; + case LONG: return "bigint"; + case FLOAT: return "float"; + case DOUBLE: return "double"; + case STRING: return "string"; + case BINARY: return "binary"; + case TIMESTAMP: return "timestamp"; + case TIMESTAMP_INSTANT: return "timestamp with local time zone"; + case LIST: return "array<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + ">"; + case MAP: + return "map<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + "," + + (subtypes.size() < 2 ? std::string("void") : subtypes[1]->toString()) + ">"; + case STRUCT: + { + std::string result = "struct<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + if (isUnquotedFieldName(field_names[i])) + result += field_names[i]; + else + { + result += "`"; + for (char c : field_names[i]) + { + if (c == '`') + result += "``"; + else + result += c; + } + result += "`"; + } + result += ":"; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case UNION: + { + std::string result = "uniontype<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case DECIMAL: return "decimal(" + std::to_string(precision) + "," + std::to_string(scale) + ")"; + case DATE: return "date"; + case VARCHAR: return "varchar(" + std::to_string(maximum_length) + ")"; + case CHAR: return "char(" + std::to_string(maximum_length) + ")"; + case GEOMETRY: return "geometry(" + crs + ")"; + case GEOGRAPHY: return "geography(" + crs + "," + algorithmToString(algorithm) + ")"; + } + return "unknown"; +} + +Type * Type::addStructField(const std::string & name, std::unique_ptr field) +{ + field_names.push_back(name); + return addChild(std::move(field)); +} + +Type * Type::addChild(std::unique_ptr child) +{ + subtypes.push_back(std::move(child)); + return subtypes.back().get(); +} + +UInt64 Type::assignIds(UInt64 start) +{ + column_id = start; + UInt64 next = start + 1; + for (auto & subtype : subtypes) + next = subtype->assignIds(next); + maximum_column_id = next - 1; + return next; +} + +void Type::toProto(std::vector & out) const +{ + size_t index = out.size(); + if (index != column_id) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type ids are not assigned in pre-order"); + out.emplace_back(); + { + auto & proto = out.back(); + proto.kind = kind; + for (const auto & subtype : subtypes) + proto.subtypes.push_back(subtype->getColumnId()); + proto.field_names = field_names; + if (kind == CHAR || kind == VARCHAR) + proto.maximum_length = static_cast(maximum_length); + if (kind == DECIMAL) + { + proto.precision = static_cast(precision); + proto.scale = static_cast(scale); + } + for (const auto & [key, value] : attributes) + proto.attributes.push_back({key, value}); + } + /// `out` may be reallocated by the recursive calls, so do not keep the reference. + for (const auto & subtype : subtypes) + subtype->toProto(out); +} + +std::unique_ptr Type::createPrimitiveType(TypeKind kind) +{ + return std::make_unique(kind); +} + +std::unique_ptr Type::createCharType(TypeKind kind, UInt64 maximum_length) +{ + auto result = std::make_unique(kind); + result->maximum_length = maximum_length; + return result; +} + +std::unique_ptr Type::createDecimalType(UInt64 precision, UInt64 scale) +{ + auto result = std::make_unique(DECIMAL); + result->precision = precision; + result->scale = scale; + return result; +} + +std::unique_ptr Type::createStructType() +{ + return std::make_unique(STRUCT); +} + +std::unique_ptr Type::createListType(std::unique_ptr element) +{ + auto result = std::make_unique(LIST); + result->addChild(std::move(element)); + return result; +} + +std::unique_ptr Type::createMapType(std::unique_ptr key, std::unique_ptr value) +{ + auto result = std::make_unique(MAP); + result->addChild(std::move(key)); + result->addChild(std::move(value)); + return result; +} + +std::unique_ptr Type::createUnionType() +{ + return std::make_unique(UNION); +} + +std::unique_ptr Type::fromProto(const std::vector & types) +{ + if (types.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: it has no types"); + UInt64 next_id = 0; + auto root = convertType(types, 0, next_id, 0); + if (next_id != types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: {} of {} types are not reachable from the root type", types.size() - next_id, types.size()); + root->assignIds(0); + return root; +} + +std::unique_ptr Type::buildSelectedType(const Type & type, const std::vector & selected) +{ + if (!selected.at(type.column_id)) + return nullptr; + + auto result = std::make_unique(type.kind); + result->maximum_length = type.maximum_length; + result->precision = type.precision; + result->scale = type.scale; + result->crs = type.crs; + result->algorithm = type.algorithm; + result->attributes = type.attributes; + result->column_id = type.column_id; + result->maximum_column_id = type.maximum_column_id; + + for (size_t i = 0; i < type.subtypes.size(); ++i) + { + auto child = buildSelectedType(*type.subtypes[i], selected); + if (!child) + continue; + if (type.kind == STRUCT) + result->addStructField(type.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + return result; +} + +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids) +{ + std::vector selected(root.getMaximumColumnId() + 1, false); + + /// Find the types by ids with a walk over the tree. + std::vector by_id(selected.size()); + std::vector stack{&root}; + while (!stack.empty()) + { + const Type * type = stack.back(); + stack.pop_back(); + by_id[type->getColumnId()] = type; + for (UInt64 i = 0; i < type->getSubtypeCount(); ++i) + stack.push_back(type->getSubtype(i)); + } + + for (UInt64 id : type_ids) + { + if (id >= selected.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid ORC type id {} selected out of {}", id, selected.size()); + selectChildren(selected, *by_id[id]); + } + + selectParents(selected, root); + selected[0] = true; + return selected; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.h b/src/Processors/Formats/Impl/ORC/Type.h new file mode 100644 index 000000000000..9a30f4455076 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.h @@ -0,0 +1,114 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace DB::ORC +{ + +enum TypeKind : UInt32 +{ + BOOLEAN = 0, + BYTE = 1, + SHORT = 2, + INT = 3, + LONG = 4, + FLOAT = 5, + DOUBLE = 6, + STRING = 7, + BINARY = 8, + TIMESTAMP = 9, + LIST = 10, + MAP = 11, + STRUCT = 12, + UNION = 13, + DECIMAL = 14, + DATE = 15, + VARCHAR = 16, + CHAR = 17, + TIMESTAMP_INSTANT = 18, + GEOMETRY = 19, + GEOGRAPHY = 20, +}; + +/// A node of the type tree of an ORC file. Every node is a column of the file; the column ids are +/// assigned in pre-order, so the subtree of a column `c` occupies the ids `[c, c.getMaximumColumnId()]`. +class Type +{ +public: + explicit Type(TypeKind kind_) : kind(kind_) {} + + TypeKind getKind() const { return kind; } + UInt64 getColumnId() const { return column_id; } + UInt64 getMaximumColumnId() const { return maximum_column_id; } + UInt64 getSubtypeCount() const { return subtypes.size(); } + const Type * getSubtype(UInt64 i) const { return subtypes.at(i).get(); } + /// Only for STRUCT. + const std::string & getFieldName(UInt64 i) const { return field_names.at(i); } + /// Only for CHAR and VARCHAR. + UInt64 getMaximumLength() const { return maximum_length; } + /// Only for DECIMAL. + UInt64 getPrecision() const { return precision; } + UInt64 getScale() const { return scale; } + + bool hasAttributeKey(const std::string & key) const { return attributes.contains(key); } + const std::string & getAttributeValue(const std::string & key) const { return attributes.at(key); } + void setAttribute(const std::string & key, const std::string & value) { attributes[key] = value; } + const std::map & getAttributes() const { return attributes; } + + /// The type name in the same format as in the reference implementation (Hive type names). + std::string toString() const; + + void setMaximumLength(UInt64 value) { maximum_length = value; } + void setPrecisionAndScale(UInt64 precision_, UInt64 scale_) { precision = precision_; scale = scale_; } + void setGeospatial(std::string crs_, UInt32 algorithm_) { crs = std::move(crs_); algorithm = algorithm_; } + + Type * addStructField(const std::string & name, std::unique_ptr field); + Type * addChild(std::unique_ptr child); + + /// Assigns the column ids in pre-order, starting from `start`. Returns the next free id. + UInt64 assignIds(UInt64 start); + + /// Appends the types of this subtree to `out` in pre-order. The ids must be assigned. + void toProto(std::vector & out) const; + + static std::unique_ptr createPrimitiveType(TypeKind kind); + static std::unique_ptr createCharType(TypeKind kind, UInt64 maximum_length); + static std::unique_ptr createDecimalType(UInt64 precision, UInt64 scale); + static std::unique_ptr createStructType(); + static std::unique_ptr createListType(std::unique_ptr element); + static std::unique_ptr createMapType(std::unique_ptr key, std::unique_ptr value); + static std::unique_ptr createUnionType(); + + /// Builds the type tree from the types in the file footer. Throws `INCORRECT_DATA` if they do + /// not form a tree with the ids in pre-order. + static std::unique_ptr fromProto(const std::vector & types); + + /// Builds a copy of the tree with only the selected columns (by id). The parent of every + /// selected column must also be selected. Returns nullptr if the root is not selected. + static std::unique_ptr buildSelectedType(const Type & type, const std::vector & selected); + +private: + TypeKind kind; + UInt64 column_id = 0; + UInt64 maximum_column_id = 0; + std::vector> subtypes; + std::vector field_names; + UInt64 maximum_length = 0; + UInt64 precision = 0; + UInt64 scale = 0; + std::string crs; + UInt32 algorithm = 0; + std::map attributes; +}; + +/// The column selection with the same semantics as in the reference implementation: +/// selecting a column selects its whole subtree, and then all parents of the selected columns +/// are selected. If only some branches of a UNION are selected, all its branches are selected. +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids); + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.cpp b/src/Processors/Formats/Impl/ORC/Vector.cpp new file mode 100644 index 000000000000..ce7b5cdac8de --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int NOT_IMPLEMENTED; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values) +{ + const size_t dictionary_size = dictionary.size(); + const auto & dictionary_offsets = dictionary.getOffsets(); + const auto & dictionary_chars = dictionary.getChars(); + + auto result = ColumnString::create(); + auto & chars = result->getChars(); + auto & offsets = result->getOffsets(); + offsets.resize(num_values); + + size_t total = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + Int64 entry = index[i]; + if (entry < 0 || static_cast(entry) >= dictionary_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC dictionary index {} at row {} is out of range [0, {})", entry, i, dictionary_size); + total += dictionary_offsets[entry] - dictionary_offsets[entry - 1]; + } + offsets[i] = total; + } + + chars.resize(total); + UInt8 * out = chars.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + size_t begin = dictionary_offsets[index[i] - 1]; + size_t size = dictionary_offsets[index[i]] - begin; + memcpy(out, dictionary_chars.data() + begin, size); + out += size; + } + } + return result; +} + +ColumnPtr getStringColumn(const StringVectorBatch & batch) +{ + if (!batch.isEncoded) + return batch.column; + + const auto & encoded = typeid_cast(batch); + return decodeDictionary( + assert_cast(*encoded.dictionary->column), + encoded.index.data(), + batch.hasNulls ? batch.notNull.data() : nullptr, + batch.numElements); +} + +std::unique_ptr createRowBatch(const Type & type, bool encoded) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(); + case BYTE: + return std::make_unique(); + case SHORT: + return std::make_unique(); + case INT: + return std::make_unique(); + case LONG: + case DATE: + return std::make_unique(); + case FLOAT: + return std::make_unique(); + case DOUBLE: + return std::make_unique(); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + if (encoded) + return std::make_unique(); + return std::make_unique(); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + return std::make_unique(); + case STRUCT: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addField(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case LIST: + { + auto result = std::make_unique(); + if (type.getSubtypeCount()) + result->elements = createRowBatch(*type.getSubtype(0), encoded); + return result; + } + case MAP: + { + auto result = std::make_unique(); + if (type.getSubtypeCount() > 0) + result->keys = createRowBatch(*type.getSubtype(0), encoded); + if (type.getSubtypeCount() > 1) + result->elements = createRowBatch(*type.getSubtype(1), encoded); + return result; + } + case UNION: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addChild(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case DECIMAL: + if (type.getPrecision() == 0 || type.getPrecision() > 18) + return std::make_unique(); + return std::make_unique(); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.h b/src/Processors/Formats/Impl/ORC/Vector.h new file mode 100644 index 000000000000..1e44a80a61d1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.h @@ -0,0 +1,174 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +/// Batches of column values filled by the reader. The values of the primitive types are decoded +/// directly into ClickHouse columns, which the conversion to the requested types takes without +/// copying. The structure follows the reference implementation: a batch has the null mask of its +/// values, and the batches of the compound types have the batches of their children. + +namespace DB::ORC +{ + +struct ColumnVectorBatch +{ + ColumnVectorBatch() = default; + virtual ~ColumnVectorBatch() = default; + + ColumnVectorBatch(const ColumnVectorBatch &) = delete; + ColumnVectorBatch & operator=(const ColumnVectorBatch &) = delete; + + /// Prepares the batch for `num_values` values. + void reset(size_t num_values) + { + numElements = num_values; + notNull.resize(num_values); + } + + size_t numElements = 0; + /// Non-zero for the non-null values, valid only if `hasNulls`. + PaddedPODArray notNull; + bool hasNulls = false; + /// For string batches read with lazy dictionary decoding. + bool isEncoded = false; +}; + +/// The values of a primitive type in a ClickHouse column (`ColumnVector` of `T`). The null values are zeros. +template +struct NumericVectorBatch : public ColumnVectorBatch +{ + using Container = PaddedPODArray; + + /// Creates a new column for the next values: the previous column can be still referenced. + Container & prepareColumn(size_t num_values) + { + auto new_column = ColumnVector::create(num_values); + auto & data = new_column->getData(); + column = std::move(new_column); + return data; + } + + const Container & getData() const { return assert_cast &>(*column).getData(); } + + ColumnPtr column; +}; + +/// BOOLEAN: 0 or 1. +using BoolVectorBatch = NumericVectorBatch; +using ByteVectorBatch = NumericVectorBatch; +using ShortVectorBatch = NumericVectorBatch; +using IntVectorBatch = NumericVectorBatch; +/// LONG and DATE (days since the epoch, not narrowed, so that the range can be checked). +using LongVectorBatch = NumericVectorBatch; +using FloatVectorBatch = NumericVectorBatch; +using DoubleVectorBatch = NumericVectorBatch; + +/// The values in a `ColumnString`. The null values are empty strings. +struct StringVectorBatch : public ColumnVectorBatch +{ + ColumnPtr column; +}; + +struct StringDictionary +{ + /// The entries of the dictionary. + ColumnPtr column; +}; + +/// A string batch with the dictionary indices, without decoding the values. `column` is not set. +struct EncodedStringVectorBatch : public StringVectorBatch +{ + std::shared_ptr dictionary; + PaddedPODArray index; +}; + +/// Builds a `ColumnString` from the dictionary entries by the indices (the null values are empty strings). +/// Throws `INCORRECT_DATA` if an index is out of range. +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values); + +/// Returns the values of a string batch as a `ColumnString`, decoding the dictionary for an encoded batch. +ColumnPtr getStringColumn(const StringVectorBatch & batch); + +struct StructVectorBatch : public ColumnVectorBatch +{ + void addField(std::unique_ptr field) + { + fields.push_back(field.get()); + owned_fields.push_back(std::move(field)); + } + + std::vector fields; + +private: + std::vector> owned_fields; +}; + +/// LIST and MAP: the end offsets of the values in the children, as in `ColumnArray`. +struct ListVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr elements; +}; + +struct MapVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr keys; + std::unique_ptr elements; +}; + +struct UnionVectorBatch : public ColumnVectorBatch +{ + void addChild(std::unique_ptr child) + { + children.push_back(child.get()); + owned_children.push_back(std::move(child)); + } + + /// The branch of each value. + PaddedPODArray tags; + /// The position of each value in its branch. + PaddedPODArray offsets; + std::vector children; + +private: + std::vector> owned_children; +}; + +/// For DECIMAL with the precision at most 18. +struct Decimal64VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +/// For DECIMAL with the precision above 18 or unspecified (zero). +struct Decimal128VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +struct TimestampVectorBatch : public ColumnVectorBatch +{ + /// Seconds since the epoch in UTC. + PaddedPODArray data; + PaddedPODArray nanoseconds; +}; + +/// Creates a batch tree matching the type. With `encoded`, the string columns get +/// `EncodedStringVectorBatch`, which the reader fills without decoding the dictionaries. +std::unique_ptr createRowBatch(const Type & type, bool encoded = false); + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.cpp b/src/Processors/Formats/Impl/ORC/Writer.cpp new file mode 100644 index 000000000000..cfab65634955 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.cpp @@ -0,0 +1,1493 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; + extern const int LOGICAL_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE; +} +} + +namespace DB::ORC +{ + +struct WriterContext +{ + Compressor * compressor = nullptr; + size_t block_size = 0; + bool enable_index = false; + double dictionary_key_size_threshold = 0; + std::optional timezone_offset; + bool timezone_is_utc = true; + /// 2015-01-01 00:00:00 in the time zone of the writer, as seconds since the epoch. + Int64 epoch_offset = 0; +}; + +namespace +{ + +struct StreamData +{ + Proto::StreamKind kind; + UInt32 column; + std::string data; +}; + +std::string compressWhole(const WriterContext & context, const std::string & data) +{ + OutputByteStream stream(context.compressor, context.block_size); + stream.write(data.data(), data.size()); + stream.finish(); + return stream.getOutput(); +} + +} + +class ColumnWriter +{ +public: + ColumnWriter(const Type & type, WriterContext & context_) + : column_id(type.getColumnId()) + , context(context_) + , present_stream(context.compressor, context.block_size) + , present_encoder(present_stream) + , index_statistics(type.getKind()) + , stripe_statistics(type.getKind()) + , file_statistics(type.getKind()) + { + } + + virtual ~ColumnWriter() = default; + + /// Must be called by the most derived constructor, after the streams are created. + void init() + { + if (context.enable_index) + recordPositions(); + } + + /// Adds the values `[offset, offset + num_values)` of `column`, which is not `Nullable`. + /// `null_map` (1 for a null) and `parent_null_map` (1 for a null in the parent struct, for which + /// no value is written at all) are for these values only, so they start at the first value. + virtual void add(const IColumn & /*column*/, const UInt8 * null_map, size_t /*offset*/, size_t num_values, const UInt8 * parent_null_map) + { + addPresent(null_map, num_values, parent_null_map); + } + + /// Writes the PRESENT stream for the values. + void addPresent(const UInt8 * null_map, size_t num_values, const UInt8 * parent_null_map) + { + for (size_t i = 0; i < num_values; ++i) + { + if (parent_null_map && parent_null_map[i]) + continue; + present_encoder.write(!null_map || !null_map[i]); + } + if (null_map) + { + for (size_t i = 0; i < num_values && !has_null_value; ++i) + if (null_map[i]) + has_null_value = true; + } + } + + virtual void createRowIndexEntry() + { + entries.push_back(Entry{std::move(current_present_positions), std::move(current_data_positions), index_statistics.toProto()}); + current_present_positions.clear(); + current_data_positions.clear(); + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + recordPositions(); + } + + virtual void mergeRowGroupStatsIntoStripeStats() + { + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + } + + /// Encodes the deferred data of the stripe. + virtual void finalizeStripe() {} + + virtual void writeIndex(std::vector & streams) + { + Proto::RowIndex index; + for (const auto & entry : entries) + { + auto & proto_entry = index.entry.emplace_back(); + /// The positions of the PRESENT stream are written only if the stream is written. + if (has_null_value) + proto_entry.positions = entry.present_positions; + proto_entry.positions.insert(proto_entry.positions.end(), entry.data_positions.begin(), entry.data_positions.end()); + proto_entry.statistics = entry.statistics; + } + streams.push_back({Proto::StreamKind::ROW_INDEX, static_cast(column_id), compressWhole(context, index.serialize())}); + } + + virtual void flush(std::vector & streams) + { + present_encoder.flush(); + present_stream.finish(); + if (has_null_value) + streams.push_back({Proto::StreamKind::PRESENT, static_cast(column_id), present_stream.getOutput()}); + } + + virtual void getColumnEncodings(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + + virtual void getStripeStatistics(std::vector & stats) const + { + stats.push_back(stripe_statistics.toProto()); + } + + virtual void getFileStatistics(std::vector & stats) const + { + stats.push_back(file_statistics.toProto()); + } + + virtual void mergeStripeStatsIntoFileStats() + { + file_statistics.merge(stripe_statistics); + stripe_statistics.reset(); + } + + virtual size_t estimateSize() const + { + return present_stream.estimateSize(); + } + + /// Starts a new stripe. + virtual void reset() + { + present_stream.reset(); + has_null_value = false; + entries.clear(); + current_present_positions.clear(); + current_data_positions.clear(); + resetStreams(); + if (context.enable_index) + recordPositions(); + } + +protected: + /// Appends the positions of the data streams, in the order the reader seeks them. + virtual void recordDataPositions(std::vector & positions) = 0; + /// Clears the data streams for a new stripe. + virtual void resetStreams() = 0; + + /// The number of the non-null values, also updates the statistics with the count. + size_t countValues(const UInt8 * null_map, size_t num_values) + { + size_t count = num_values; + if (null_map) + { + count = 0; + for (size_t i = 0; i < num_values; ++i) + count += !null_map[i]; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + return count; + } + + struct Entry + { + std::vector present_positions; + std::vector data_positions; + Proto::ColumnStatistics statistics; + }; + + const UInt64 column_id; + WriterContext & context; + OutputByteStream present_stream; + BooleanRleEncoder present_encoder; + bool has_null_value = false; + StatisticsBuilder index_statistics; + StatisticsBuilder stripe_statistics; + StatisticsBuilder file_statistics; + std::vector entries; + +private: + void recordPositions() + { + present_encoder.recordPosition(current_present_positions); + recordDataPositions(current_data_positions); + } + + std::vector current_present_positions; + std::vector current_data_positions; +}; + +namespace +{ + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type, WriterContext & context); + +/// Adds the values of a column that can be `Nullable`. The values that are null in the parent +/// (`outer_null_map`, for the fields of a struct) are null as well. +void addColumn( + ColumnWriter & writer, const IColumn & column, const UInt8 * outer_null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) +{ + if (const auto * nullable = typeid_cast(&column)) + { + const UInt8 * null_map = nullable->getNullMapData().data() + offset; + if (!outer_null_map) + { + writer.add(nullable->getNestedColumn(), null_map, offset, num_values, parent_null_map); + return; + } + PaddedPODArray merged(num_values); + for (size_t i = 0; i < num_values; ++i) + merged[i] = null_map[i] | outer_null_map[i]; + writer.add(nullable->getNestedColumn(), merged.data(), offset, num_values, parent_null_map); + return; + } + writer.add(column, outer_null_map, offset, num_values, parent_null_map); +} + +/// The raw values of a column with fixed-size values. +template +const T * getRawValues(const IColumn & column) +{ + auto raw = column.getRawData(); + if (column.sizeOfValueIfFixed() != sizeof(T)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} with values of size {} for ORC (expected {})", + column.getName(), column.sizeOfValueIfFixed(), sizeof(T)); + return reinterpret_cast(raw.data()); +} + +/// The value of the integer column (of any width up to 8 bytes) as a signed number of the same width, +/// as ORC does not have unsigned types. +Int64 readSignedValue(const char * data, size_t width, size_t row) +{ + switch (width) + { + case 1: return unalignedLoad(data + row); + case 2: return unalignedLoad(data + row * 2); + case 4: return unalignedLoad(data + row * 4); + default: return unalignedLoad(data + row * 8); + } +} + +/// The writers that have children call the same methods for them. +class CompoundColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void createRowIndexEntry() override + { + ColumnWriter::createRowIndexEntry(); + for (auto & child : children) + child->createRowIndexEntry(); + } + + void mergeRowGroupStatsIntoStripeStats() override + { + ColumnWriter::mergeRowGroupStatsIntoStripeStats(); + for (auto & child : children) + child->mergeRowGroupStatsIntoStripeStats(); + } + + void finalizeStripe() override + { + for (auto & child : children) + child->finalizeStripe(); + } + + void writeIndex(std::vector & streams) override + { + ColumnWriter::writeIndex(streams); + for (auto & child : children) + child->writeIndex(streams); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + flushOwnStreams(streams); + for (auto & child : children) + child->flush(streams); + } + + void getColumnEncodings(std::vector & encodings) const override + { + getOwnColumnEncoding(encodings); + for (const auto & child : children) + child->getColumnEncodings(encodings); + } + + void getStripeStatistics(std::vector & stats) const override + { + ColumnWriter::getStripeStatistics(stats); + for (const auto & child : children) + child->getStripeStatistics(stats); + } + + void getFileStatistics(std::vector & stats) const override + { + ColumnWriter::getFileStatistics(stats); + for (const auto & child : children) + child->getFileStatistics(stats); + } + + void mergeStripeStatsIntoFileStats() override + { + ColumnWriter::mergeStripeStatsIntoFileStats(); + for (auto & child : children) + child->mergeStripeStatsIntoFileStats(); + } + + size_t estimateSize() const override + { + size_t size = ColumnWriter::estimateSize() + estimateOwnSize(); + for (const auto & child : children) + size += child->estimateSize(); + return size; + } + + void reset() override + { + ColumnWriter::reset(); + for (auto & child : children) + (*child).reset(); + } + +protected: + virtual void flushOwnStreams(std::vector &) {} + virtual void getOwnColumnEncoding(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + virtual size_t estimateOwnSize() const { return 0; } + + std::vector> children; +}; + +class StructColumnWriter final : public CompoundColumnWriter +{ +public: + StructColumnWriter(const Type & type, const DataTypes & field_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + { + if (field_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC struct {} has {} fields, the ClickHouse type has {}", + type.toString(), type.getSubtypeCount(), field_types.size()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), field_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & tuple = assert_cast(column); + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The fields of the null values are null, and they are not written. + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], tuple.getColumn(i), null_map, offset, num_values, null_map); + countValues(null_map, num_values); + } + + /// Adds the rows of the root struct, which are the columns of the file. + void addRoot(const Columns & columns, size_t offset, size_t num_values) + { + if (columns.size() != children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Expected {} columns for ORC, got {}", children.size(), columns.size()); + addPresent(nullptr, num_values, nullptr); + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], *columns[i], nullptr, offset, num_values, nullptr); + countValues(nullptr, num_values); + } + +protected: + void recordDataPositions(std::vector &) override {} + void resetStreams() override {} +}; + +template +class CollectionColumnWriter final : public CompoundColumnWriter +{ +public: + CollectionColumnWriter(const Type & type, const DataTypes & child_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , length_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + { + if (child_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), child_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const ColumnArray & array = is_map ? assert_cast(column).getNestedColumn() : assert_cast(column); + /// The offsets of `ColumnArray` are the end offsets, and the one before the first is zero. + const auto & offsets = array.getOffsets(); + + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + + UInt64 element_offset = offsets[static_cast(offset) - 1]; + UInt64 total_elements = offsets[offset + num_values - 1] - element_offset; + + if constexpr (is_map) + { + const auto & key_value = assert_cast(array.getData()); + addColumn(*children[0], key_value.getColumn(0), nullptr, element_offset, total_elements, nullptr); + addColumn(*children[1], key_value.getColumn(1), nullptr, element_offset, total_elements, nullptr); + } + else + { + addColumn(*children[0], array.getData(), nullptr, element_offset, total_elements, nullptr); + } + + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + UInt64 length = offsets[row] - offsets[static_cast(row) - 1]; + length_encoder.write(static_cast(length)); + index_statistics.updateCollection(length); + ++count; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + length_encoder.recordPosition(positions); + } + + void resetStreams() override + { + length_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + + void getOwnColumnEncoding(std::vector & encodings) const override + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT_V2, 0, {}}); + } + + size_t estimateOwnSize() const override { return length_stream.estimateSize(); } + +private: + OutputByteStream length_stream; + IntRleEncoderV2 length_encoder; +}; + +class UnionColumnWriter final : public CompoundColumnWriter +{ +public: + /// The branches of the union are in the same order as the variants of the `Variant` type, + /// so the global discriminator of a value is its tag. + UnionColumnWriter(const Type & type, const DataTypes & variant_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , tag_stream(context.compressor, context.block_size) + , tag_encoder(tag_stream) + { + if (variant_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC union {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), variant_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & variant = assert_cast(column); + + /// A `NULL` of `Variant` is a null value of the union. + PaddedPODArray union_null_map(num_values); + bool has_nulls = false; + for (size_t i = 0; i < num_values; ++i) + { + union_null_map[i] = (null_map && null_map[i]) || variant.globalDiscriminatorAt(offset + i) == ColumnVariant::NULL_DISCRIMINATOR; + has_nulls |= union_null_map[i]; + } + const UInt8 * union_nulls = has_nulls ? union_null_map.data() : nullptr; + + ColumnWriter::add(column, union_nulls, offset, num_values, parent_null_map); + + std::vector child_offset(children.size(), -1); + std::vector child_length(children.size(), 0); + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (union_nulls && union_nulls[i]) + continue; + size_t row = offset + i; + auto tag = variant.globalDiscriminatorAt(row); + if (tag >= children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid union tag {} for union with {} children", static_cast(tag), children.size()); + if (child_offset[tag] == -1) + child_offset[tag] = static_cast(variant.offsetAt(row)); + ++child_length[tag]; + tag_encoder.write(static_cast(tag)); + ++count; + } + + /// The values of each branch are consecutive in its column. + for (size_t i = 0; i < children.size(); ++i) + if (child_length[i]) + addColumn(*children[i], variant.getVariantByGlobalDiscriminator(i), nullptr, static_cast(child_offset[i]), child_length[i], nullptr); + + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + tag_encoder.recordPosition(positions); + } + + void resetStreams() override + { + tag_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + tag_encoder.flush(); + tag_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), tag_stream.getOutput()}); + } + + size_t estimateOwnSize() const override { return tag_stream.estimateSize(); } + +private: + OutputByteStream tag_stream; + ByteRleEncoder tag_encoder; +}; + + +/// The writers of the primitive columns. +class PrimitiveColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void getColumnEncodings(std::vector & encodings) const override + { + encodings.push_back({encoding_kind, dictionary_size, {}}); + } + +protected: + Proto::ColumnEncodingKind encoding_kind = Proto::ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; +}; + +class BooleanColumnWriter final : public PrimitiveColumnWriter +{ +public: + BooleanColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const UInt8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(data[i] != 0); + index_statistics.updateBoolean(data[i] != 0); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + BooleanRleEncoder encoder; +}; + +class ByteColumnWriter final : public PrimitiveColumnWriter +{ +public: + ByteColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width. + const Int8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(static_cast(data[i])); + index_statistics.updateInteger(data[i]); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + ByteRleEncoder encoder; +}; + +/// SHORT, INT, LONG and DATE. +class IntegerColumnWriter final : public PrimitiveColumnWriter +{ +public: + IntegerColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream, true) + , is_date(type.getKind() == DATE) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width (except `Date`). + const size_t width = column.sizeOfValueIfFixed(); + if (width != 2 && width != 4 && width != 8) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC integer", column.getName()); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + /// `Date` is the unsigned number of days (up to 2149), which must not wrap around + /// to the negative ones after 2059. `Date32` is signed, as the other integers. + Int64 value = (is_date && width == 2) + ? unalignedLoad(data + (offset + i) * sizeof(UInt16)) + : readSignedValue(data, width, offset + i); + encoder.write(value); + if (is_date) + index_statistics.updateDate(static_cast(value)); + else + index_statistics.updateInteger(value); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + IntRleEncoderV2 encoder; + const bool is_date; +}; + +template +class FloatingColumnWriter final : public PrimitiveColumnWriter +{ +public: + FloatingColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const ItemType * data = getRawValues(column) + offset; + if (!null_map && std::endian::native == std::endian::little) + { + data_stream.write(reinterpret_cast(data), num_values * sizeof(ItemType)); + for (size_t i = 0; i < num_values; ++i) + index_statistics.updateDouble(static_cast(data[i])); + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + ItemType value = data[i]; + if constexpr (std::endian::native == std::endian::big) + value = std::bit_cast(std::byteswap(std::bit_cast>(value))); + data_stream.write(reinterpret_cast(&value), sizeof(value)); + index_statistics.updateDouble(static_cast(data[i])); + } + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { data_stream.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; +}; + +/// STRING, VARCHAR, CHAR and BINARY. The values of a stripe are kept in memory and encoded at the +/// end of the stripe, either directly or with a dictionary. +class StringColumnWriter final : public PrimitiveColumnWriter +{ +public: + StringColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , is_binary(type.getKind() == BINARY) + , data_stream(context.compressor, context.block_size) + , length_stream(context.compressor, context.block_size) + , dictionary_data_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + , index_encoder(data_stream, false) + { + /// The binary columns never use dictionaries, as in the reference implementation. + if (is_binary || context.dictionary_key_size_threshold <= 0) + use_dictionary = false; + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `String`, or the raw bytes of the values of fixed size (`FixedString`, `IPv6`, big integers). + auto add_value = [&](std::string_view value) + { + blob.append(value); + value_ends.push_back(blob.size()); + if (is_binary) + index_statistics.updateBinary(value.size()); + else + index_statistics.updateString(value); + }; + + if (const auto * strings = typeid_cast(&column)) + { + const auto & offsets = strings->getOffsets(); + const auto * chars = reinterpret_cast(strings->getChars().data()); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + add_value(std::string_view(chars + offsets[row - 1], offsets[row] - offsets[row - 1])); + } + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + add_value(column.getDataAt(offset + i)); + } + } + countValues(null_map, num_values); + } + + void createRowIndexEntry() override + { + if (!use_dictionary) + decideDictionary(); + ColumnWriter::createRowIndexEntry(); + } + + void finalizeStripe() override + { + if (!use_dictionary) + decideDictionary(); + + /// The start of the group without an entry is not needed. + group_starts.resize(entries.size()); + + if (*use_dictionary) + encodeWithDictionary(); + else + encodeDirect(); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + if (*use_dictionary) + { + index_encoder.flush(); + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + dictionary_data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::DICTIONARY_DATA, static_cast(column_id), dictionary_data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + else + { + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + blob.size() + value_ends.size() * sizeof(UInt64); + } + +protected: + void recordDataPositions(std::vector &) override + { + /// The positions are known only after the encoding, at the end of the stripe. + group_starts.push_back(value_ends.size()); + } + + void resetStreams() override + { + data_stream.reset(); + length_stream.reset(); + dictionary_data_stream.reset(); + blob.clear(); + value_ends.clear(); + group_starts.clear(); + dictionary_size = 0; + } + +private: + std::string_view getValue(size_t i) const + { + size_t begin = i ? value_ends[i - 1] : 0; + return std::string_view(blob.data() + begin, value_ends[i] - begin); + } + + /// The decision is made once for the file, by the values of the first row group (or the first + /// stripe without the row index), as in the reference implementation. + void decideDictionary() + { + std::unordered_set distinct; + for (size_t i = 0; i < value_ends.size(); ++i) + distinct.insert(getValue(i)); + /// Compare as doubles: the threshold is user-provided and the product may not fit in `size_t`. + use_dictionary = static_cast(distinct.size()) <= static_cast(value_ends.size()) * context.dictionary_key_size_threshold; + } + + void encodeDirect() + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + auto & positions = entries[group].data_positions; + data_stream.recordPosition(positions); + length_encoder.recordPosition(positions); + ++group; + } + if (i == value_ends.size()) + break; + auto value = getValue(i); + data_stream.write(value.data(), value.size()); + length_encoder.write(static_cast(value.size())); + } + } + + void encodeWithDictionary() + { + encoding_kind = Proto::ColumnEncodingKind::DICTIONARY_V2; + + /// The dictionary is sorted, as in the reference implementation. + std::unordered_map index_of; + std::vector keys; + for (size_t i = 0; i < value_ends.size(); ++i) + { + auto value = getValue(i); + if (index_of.emplace(value, 0).second) + keys.push_back(value); + } + std::sort(keys.begin(), keys.end()); + for (size_t i = 0; i < keys.size(); ++i) + index_of[keys[i]] = static_cast(i); + dictionary_size = static_cast(keys.size()); + + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + index_encoder.recordPosition(entries[group].data_positions); + ++group; + } + if (i == value_ends.size()) + break; + index_encoder.write(index_of[getValue(i)]); + } + + for (const auto & key : keys) + { + dictionary_data_stream.write(key.data(), key.size()); + length_encoder.write(static_cast(key.size())); + } + } + + const bool is_binary; + std::optional use_dictionary; + OutputByteStream data_stream; + OutputByteStream length_stream; + OutputByteStream dictionary_data_stream; + IntRleEncoderV2 length_encoder; + IntRleEncoderV2 index_encoder; + + std::string blob; + std::vector value_ends; + /// The index of the first value of each row group. + std::vector group_starts; +}; + +class TimestampColumnWriter final : public PrimitiveColumnWriter +{ +public: + /// `scale` is of `DateTime64`, or nullopt for `DateTime` (`UInt32` seconds). + TimestampColumnWriter(const Type & type, std::optional scale_, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(scale_) + , seconds_stream(context.compressor, context.block_size) + , nanos_stream(context.compressor, context.block_size) + , seconds_encoder(seconds_stream, true) + , nanos_encoder(nanos_stream, false) + , is_utc(type.getKind() == TIMESTAMP_INSTANT || context.timezone_is_utc) + , epoch_offset(type.getKind() == TIMESTAMP_INSTANT ? 1420070400 : context.epoch_offset) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const char * data = column.getRawData().data(); + const Int64 multiplier = scale ? common::exp10_i64(static_cast(*scale)) : 1; + const Int64 nanos_multiplier = scale ? common::exp10_i64(9 - static_cast(*scale)) : 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + Int64 secs = 0; + Int64 nano = 0; + if (scale) + { + /// For the values before the epoch, the nanoseconds are negative (as in the Arrow ORC adapter). + Int64 value = unalignedLoad(data + (offset + i) * sizeof(Int64)); + secs = value / multiplier; + nano = (value % multiplier) * nanos_multiplier; + } + else + { + secs = unalignedLoad(data + (offset + i) * sizeof(UInt32)); + nano = 0; + } + + /// The statistics have the milliseconds rounded down and the rest of the nanoseconds, which is not negative. + Int64 nano_millis = nano / 1000000; + Int64 nano_rest = nano % 1000000; + if (nano_rest < 0) + { + nano_rest += 1000000; + --nano_millis; + } + Int64 utc_seconds = secs; + Int64 millis = 0; + Int64 encoded_seconds = 0; + if ((!is_utc && common::addOverflow(secs, (*context.timezone_offset)(secs), utc_seconds)) + || common::mulOverflow(utc_seconds, Int64{1000}, millis) + || common::addOverflow(millis, nano_millis, millis) + || common::subOverflow(secs + (secs < 0 && nano > 999999), epoch_offset, encoded_seconds)) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp (seconds={}, nanoseconds={}) in ORC column {} is out of the range supported by the ORC format", secs, nano, column_id); + index_statistics.updateTimestamp(millis, static_cast(nano_rest)); + + seconds_encoder.write(encoded_seconds); + nanos_encoder.write(formatNanos(nano)); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + seconds_encoder.flush(); + seconds_stream.finish(); + nanos_encoder.flush(); + nanos_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), seconds_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), nanos_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + seconds_stream.estimateSize() + nanos_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + seconds_encoder.recordPosition(positions); + nanos_encoder.recordPosition(positions); + } + + void resetStreams() override + { + seconds_stream.reset(); + nanos_stream.reset(); + } + +private: + /// The trailing zeros are removed and their number is kept in the lowest 3 bits. + static Int64 formatNanos(Int64 nanos) + { + if (nanos == 0) + return 0; + if (nanos % 100 != 0) + return nanos << 3; + nanos /= 100; + Int64 trailing_zeros = 1; + while (nanos % 10 == 0 && trailing_zeros < 7) + { + nanos /= 10; + ++trailing_zeros; + } + return (nanos << 3) | trailing_zeros; + } + + const std::optional scale; + OutputByteStream seconds_stream; + OutputByteStream nanos_stream; + IntRleEncoderV2 seconds_encoder; + IntRleEncoderV2 nanos_encoder; + const bool is_utc; + const Int64 epoch_offset; +}; + +class DecimalColumnWriter final : public PrimitiveColumnWriter +{ +public: + DecimalColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(static_cast(type.getScale())) + , value_stream(context.compressor, context.block_size) + , scale_stream(context.compressor, context.block_size) + , scale_encoder(scale_stream, true) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `Decimal32`, `Decimal64` or `Decimal128`. + const size_t width = column.sizeOfValueIfFixed(); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + Int128 value; + if (width == 16) + value = unalignedLoad(data + row * 16); + else if (width == 8) + value = unalignedLoad(data + row * 8); + else if (width == 4) + value = unalignedLoad(data + row * 4); + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC decimal", column.getName()); + + /// Zigzag-encoded base 128 varint. + UInt128 encoded = (static_cast(value) << 1) ^ static_cast(value >> 127); + while (encoded >= 0x80) + { + char byte = static_cast(static_cast(encoded & 0x7F) | 0x80); + value_stream.write(&byte, 1); + encoded >>= 7; + } + char last = static_cast(static_cast(encoded)); + value_stream.write(&last, 1); + + scale_encoder.write(scale); + index_statistics.updateDecimal(value, scale); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + value_stream.finish(); + scale_encoder.flush(); + scale_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), value_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), scale_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + value_stream.estimateSize() + scale_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + value_stream.recordPosition(positions); + scale_encoder.recordPosition(positions); + } + + void resetStreams() override + { + value_stream.reset(); + scale_stream.reset(); + } + +private: + const Int32 scale; + OutputByteStream value_stream; + OutputByteStream scale_stream; + IntRleEncoderV2 scale_encoder; +}; + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type_with_nulls, WriterContext & context) +{ + checkStackSize(); + + /// The nulls are handled by `addColumn`. + DataTypePtr data_type = removeNullable(data_type_with_nulls); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, context); + case BYTE: + return std::make_unique(type, context); + case SHORT: + case INT: + case LONG: + case DATE: + return std::make_unique(type, context); + case FLOAT: + return std::make_unique>(type, context); + case DOUBLE: + return std::make_unique>(type, context); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + return std::make_unique(type, context); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + std::optional scale; + if (const auto * datetime64 = typeid_cast(data_type.get())) + scale = datetime64->getScale(); + return std::make_unique(type, scale, context); + } + case DECIMAL: + return std::make_unique(type, context); + case STRUCT: + return std::make_unique(type, assert_cast(*data_type).getElements(), context); + case LIST: + return std::make_unique>( + type, DataTypes{assert_cast(*data_type).getNestedType()}, context); + case MAP: + { + const auto & map_type = assert_cast(*data_type); + return std::make_unique>(type, DataTypes{map_type.getKeyType(), map_type.getValueType()}, context); + } + case UNION: + return std::make_unique(type, assert_cast(*data_type).getVariants(), context); + case GEOMETRY: + case GEOGRAPHY: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC type {} is not supported", type.toString()); +} + +} + + +Writer::Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_) + : out(out_), options(options_) +{ + if (options.compression_block_size == 0 || options.compression_block_size >= (1ULL << 23)) + throw Exception(ErrorCodes::BAD_ARGUMENTS, + "The ORC compression block size must be positive and less than 8 MiB, got {}", options.compression_block_size); + + schema = Type::buildSelectedType(schema_, std::vector(schema_.getMaximumColumnId() + 1, true)); + schema->assignIds(0); + + compressor = createCompressor(options.compression); + + context = std::make_unique(); + context->compressor = compressor.get(); + context->block_size = options.compression_block_size; + context->enable_index = options.row_index_stride > 0; + context->dictionary_key_size_threshold = options.dictionary_key_size_threshold; + context->timezone_offset.emplace(DateLUT::instance(options.timezone_name)); + context->timezone_is_utc = options.timezone_name == "GMT" || options.timezone_name == "UTC"; + static constexpr Int64 UTC_2015_01_01 = 1420070400; + context->epoch_offset = UTC_2015_01_01 - (*context->timezone_offset)(UTC_2015_01_01); + + if (schema->getKind() != STRUCT) + throw Exception(ErrorCodes::LOGICAL_ERROR, "The root type of ORC file must be a struct"); + column_writer = std::make_unique(*schema, column_types, *context); + + write("ORC"); + footer.header_length = current_offset; + footer.row_index_stride = static_cast(options.row_index_stride); + /// The identifier of the C++ writer of the reference implementation, which this writer follows. + footer.writer = 1; + footer.software_version = "ClickHouse"; + schema->toProto(footer.types); +} + +Writer::~Writer() = default; + +void Writer::write(const std::string & data) +{ + out.write(data.data(), data.size()); + current_offset += data.size(); +} + +void Writer::add(const Columns & columns, size_t num_rows) +{ + auto & root = typeid_cast(*column_writer); + + if (context->enable_index) + { + size_t position = 0; + while (position < num_rows) + { + size_t chunk = std::min(num_rows - position, options.row_index_stride - index_rows); + root.addRoot(columns, position, chunk); + position += chunk; + index_rows += chunk; + stripe_rows += chunk; + if (index_rows >= options.row_index_stride) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + } + } + else + { + stripe_rows += num_rows; + root.addRoot(columns, 0, num_rows); + } + + if (column_writer->estimateSize() >= options.stripe_size) + writeStripe(); +} + +void Writer::writeStripe() +{ + if (context->enable_index && index_rows != 0) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + else + column_writer->mergeRowGroupStatsIntoStripeStats(); + + column_writer->finalizeStripe(); + + std::vector index_streams; + std::vector data_streams; + if (context->enable_index) + column_writer->writeIndex(index_streams); + column_writer->flush(data_streams); + + Proto::StripeFooter stripe_footer; + UInt64 index_length = 0; + UInt64 data_length = 0; + for (const auto & s : index_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + index_length += s.data.size(); + } + for (const auto & s : data_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + data_length += s.data.size(); + } + column_writer->getColumnEncodings(stripe_footer.columns); + stripe_footer.writer_timezone = options.timezone_name; + + auto & stripe_statistics = metadata.stripe_stats.emplace_back(); + column_writer->getStripeStatistics(stripe_statistics.col_stats); + column_writer->mergeStripeStatsIntoFileStats(); + + Proto::StripeInformation stripe; + stripe.offset = current_offset; + + for (const auto & s : index_streams) + write(s.data); + for (const auto & s : data_streams) + write(s.data); + + std::string footer_data = compressWhole(*context, stripe_footer.serialize()); + write(footer_data); + + stripe.index_length = index_length; + stripe.data_length = data_length; + stripe.footer_length = footer_data.size(); + stripe.number_of_rows = stripe_rows; + footer.stripes.push_back(stripe); + + total_rows += stripe_rows; + stripe_rows = 0; + index_rows = 0; + (*column_writer).reset(); +} + +void Writer::close() +{ + if (stripe_rows > 0) + writeStripe(); + + Proto::PostScript postscript; + + /// The content length covers only the stripes, not the metadata section with the stripe statistics. + footer.content_length = current_offset - footer.header_length; + + std::string metadata_data = compressWhole(*context, metadata.serialize()); + write(metadata_data); + postscript.metadata_length = metadata_data.size(); + + footer.number_of_rows = total_rows; + footer.statistics.clear(); + column_writer->getFileStatistics(footer.statistics); + std::string footer_data = compressWhole(*context, footer.serialize()); + write(footer_data); + + postscript.footer_length = footer_data.size(); + postscript.compression = options.compression; + postscript.compression_block_size = options.compression_block_size; + postscript.version = {0, 12}; + /// ORC-135: the timestamp statistics are in UTC. + postscript.writer_version = 6; + postscript.magic = "ORC"; + std::string postscript_data = postscript.serialize(); + if (postscript_data.size() > 255) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC postscript is too large: {} bytes", postscript_data.size()); + write(postscript_data); + write(std::string(1, static_cast(postscript_data.size()))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.h b/src/Processors/Formats/Impl/ORC/Writer.h new file mode 100644 index 000000000000..111c20ac0fab --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +class OutputStream +{ +public: + virtual ~OutputStream() = default; + virtual void write(const void * buf, size_t length) = 0; +}; + +struct WriterOptions +{ + CompressionKind compression = CompressionKind::ZSTD; + UInt64 compression_block_size = 256 * 1024; + /// The number of rows between the row index entries; 0 means no row index. + UInt64 row_index_stride = 10000; + /// Use the dictionary encoding for a string column if the number of distinct values in the + /// first row group is at most this fraction of the number of values. 0 disables the dictionaries. + double dictionary_key_size_threshold = 0.0; + /// The time zone of the writer, which is written into the stripe footers. + std::string timezone_name = "GMT"; + /// A stripe is written when the estimated size of its data reaches this size. + UInt64 stripe_size = 64 * 1024 * 1024; +}; + +class ColumnWriter; +struct WriterContext; + +class Writer +{ +public: + /// `column_types` are the ClickHouse types (without `LowCardinality`) of the columns of the file, + /// which are the fields of `schema` (a struct). The values are converted as follows: + /// the unsigned integers are written as the signed ones of the same width (but `Date` as is); + /// `DateTime` and `DateTime64` as TIMESTAMP; `FixedString`, `IPv6` and the big integers + /// as their raw bytes; `Variant` as UNION with the branches in the order of its variants. + Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_); + ~Writer(); + + /// Adds the rows of the columns (in the order of the fields of the schema). + void add(const Columns & columns, size_t num_rows); + + /// Writes the remaining data and the file footer. + void close(); + +private: + void writeStripe(); + void write(const std::string & data); + + std::unique_ptr schema; + OutputStream & out; + WriterOptions options; + std::unique_ptr compressor; + std::unique_ptr context; + std::unique_ptr column_writer; + + Proto::Footer footer; + Proto::Metadata metadata; + UInt64 current_offset = 0; + UInt64 stripe_rows = 0; + UInt64 index_rows = 0; + UInt64 total_rows = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp deleted file mode 100644 index 95d9cd537d74..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp +++ /dev/null @@ -1,276 +0,0 @@ -#include -#include - -#if USE_ORC -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -namespace DB -{ - -namespace ErrorCodes -{ - extern const int BAD_ARGUMENTS; - extern const int CANNOT_READ_ALL_DATA; -} - -ORCBlockInputFormat::ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_) - : IInputFormat(std::move(header_), &in_) - , block_missing_values(getPort().getHeader().columns()) - , format_settings(format_settings_) - , skip_stripes(format_settings.orc.skip_stripes) -{ -} - -Chunk ORCBlockInputFormat::read() -{ - block_missing_values.clear(); - - if (!file_reader) - prepareReader(); - - if (is_stopped) - return {}; - - for (; stripe_current < stripe_total && skip_stripes.contains(stripe_current); ++stripe_current) - ; - - if (stripe_current >= stripe_total) - return {}; - - if (need_only_count) - return getChunkForCount(file_reader->GetRawORCReader()->getStripe(stripe_current++)->getNumberOfRows()); - - auto batch_result = file_reader->ReadStripe(stripe_current, include_indices); - if (!batch_result.ok()) - throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Failed to create batch reader: {}", batch_result.status().ToString()); - - auto batch = batch_result.ValueOrDie(); - if (!batch) - return {}; - - /// Validate validity bitmaps before building the table: Table::FromRecordBatches computes - /// each column's null_count, and Arrow derives an unknown FieldNode null_count by scanning - /// the bitmap over the declared length, which reads out of bounds on a truncated bitmap. - ArrowColumnToCHColumn::checkRecordBatchValidityBitmaps(*batch); - - auto table_result = arrow::Table::FromRecordBatches({batch}); - if (!table_result.ok()) - throw Exception( - ErrorCodes::CANNOT_READ_ALL_DATA, "Error while reading batch of ORC data: {}", table_result.status().ToString()); - - /// We should extract the number of rows directly from the stripe, because in case when - /// record batch contains 0 columns (for example if we requested only columns that - /// are not presented in data) the number of rows in record batch will be 0. - size_t num_rows = file_reader->GetRawORCReader()->getStripe(stripe_current)->getNumberOfRows(); - - const auto & table = table_result.ValueOrDie(); - if (!table || !num_rows) - return {}; - - approx_bytes_read_for_chunk = file_reader->GetRawORCReader()->getStripe(stripe_current)->getDataLength(); - ++stripe_current; - - /// If defaults_for_omitted_fields is true, calculate the default values from default expression for omitted fields. - /// Otherwise fill the missing columns with zero values of its type. - BlockMissingValues * block_missing_values_ptr = format_settings.defaults_for_omitted_fields ? &block_missing_values : nullptr; - std::shared_ptr metadata; - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueOrDie(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected error while reading parquet metadata {}", status.status().message()); - - return arrow_column_to_ch_column->arrowTableToCHChunk(table, num_rows, metadata, block_missing_values_ptr); -} - -void ORCBlockInputFormat::resetParser() -{ - IInputFormat::resetParser(); - - file_reader.reset(); - include_indices.clear(); - block_missing_values.clear(); -} - -const BlockMissingValues * ORCBlockInputFormat::getMissingValues() const -{ - return &block_missing_values; -} - - -static void getFileReaderAndSchema( - ReadBuffer & in, - std::unique_ptr & file_reader, - std::shared_ptr & schema, - const FormatSettings & format_settings, - std::atomic & is_stopped) -{ - auto arrow_file = asArrowFile(in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES); - if (is_stopped) - return; - - auto result = arrow::adapters::orc::ORCFileReader::Open(arrow_file, ArrowMemoryPool::instance()); - if (!result.ok()) - throw Exception::createDeprecated(result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - file_reader = std::move(result).ValueOrDie(); - - auto read_schema_result = file_reader->ReadSchema(); - if (!read_schema_result.ok()) - throw Exception::createDeprecated(read_schema_result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - schema = std::move(read_schema_result).ValueOrDie(); -} - -void ORCBlockInputFormat::prepareReader() -{ - std::shared_ptr schema; - getFileReaderAndSchema(*in, file_reader, schema, format_settings, is_stopped); - if (is_stopped) - return; - - stripe_total = static_cast(file_reader->NumberOfStripes()); - stripe_current = 0; - - arrow_column_to_ch_column = std::make_unique( - getPort().getHeader(), - "ORC", - format_settings, - std::nullopt, - std::nullopt, - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.date_time_overflow_behavior, - format_settings.parquet.allow_geoparquet_parser, - format_settings.orc.case_insensitive_column_matching); - - const bool ignore_case = format_settings.orc.case_insensitive_column_matching; - std::unordered_set nested_table_names = Nested::getAllTableNames(getPort().getHeader(), ignore_case); - for (int i = 0; i < schema->num_fields(); ++i) - { - const auto & name = schema->field(i)->name(); - if (getPort().getHeader().has(name, ignore_case) || nested_table_names.contains(ignore_case ? boost::to_lower_copy(name) : name)) - include_indices.push_back(i); - } -} - -ORCSchemaReader::ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_) - : ISchemaReader(in_), format_settings(format_settings_) -{ -} - -void ORCSchemaReader::initializeIfNeeded() -{ - if (file_reader) - return; - - std::atomic is_stopped = 0; - getFileReaderAndSchema(in, file_reader, schema, format_settings, is_stopped); - - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueUnsafe(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Error while reading incorrect metadata of ORC {}", status.status().message()); -} - -NamesAndTypesList ORCSchemaReader::readSchema() -{ - initializeIfNeeded(); - - auto header = ArrowColumnToCHColumn::arrowSchemaToCHHeader( - *schema, - metadata, - "ORC", - format_settings, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.schema_inference_make_columns_nullable != 0, - false, - format_settings.parquet.allow_geoparquet_parser); - if (format_settings.schema_inference_make_columns_nullable == 1) - return getNamesAndRecursivelyNullableTypes(header, format_settings); - return header.getNamesAndTypesList(); -} - -std::optional ORCSchemaReader::readNumberOrRows() -{ - initializeIfNeeded(); - return file_reader->NumberOfRows(); -} - -void registerInputFormatORC(FormatFactory & factory) -{ - factory.registerRandomAccessInputFormat( - "ORC", - [](ReadBuffer & buf, - const Block & sample, - const FormatSettings & settings, - const ReadSettings & read_settings, - bool is_remote_fs, - FormatParserSharedResourcesPtr, - FormatFilterInfoPtr format_filter_info) - { - InputFormatPtr res; - if (settings.orc.use_fast_decoder) - { - const bool has_file_size = isBufferWithFileSize(buf); - auto * seekable_in = dynamic_cast(&buf); - const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in - && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; - const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; - res = std::make_shared( - buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); - } - else - res = std::make_shared(buf, std::make_shared(sample), settings); - - return res; - }); - factory.markFormatSupportsSubsetOfColumns("ORC"); -} - -void registerORCSchemaReader(FormatFactory & factory) -{ - factory.registerSchemaReader( - "ORC", - [](ReadBuffer & buf, const FormatSettings & settings) - { - SchemaReaderPtr res; - if (settings.orc.use_fast_decoder) - res = std::make_shared(buf, settings); - else - res = std::make_shared(buf, settings); - - return res; - } - ); - - factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) - { - return fmt::format("schema_inference_make_columns_nullable={}", settings.schema_inference_make_columns_nullable); - }); -} - -} -#else - -namespace DB -{ - class FormatFactory; - void registerInputFormatORC(FormatFactory &) - { - } - - void registerORCSchemaReader(FormatFactory &) - { - } -} - -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.h b/src/Processors/Formats/Impl/ORCBlockInputFormat.h deleted file mode 100644 index 622a6276c344..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once -#include "config.h" -#if USE_ORC - -#include -#include -#include -#include - -#include - -namespace arrow::adapters::orc -{ - class ORCFileReader; -} - -namespace DB -{ - -class ArrowColumnToCHColumn; - -class ORCBlockInputFormat : public IInputFormat -{ -public: - ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_); - - String getName() const override { return "ORCBlockInputFormat"; } - - void resetParser() override; - - const BlockMissingValues * getMissingValues() const override; - - size_t getApproxBytesReadForChunk() const override { return approx_bytes_read_for_chunk; } - -protected: - Chunk read() override; - - void onCancel() noexcept override - { - is_stopped = 1; - } - -private: - void prepareReader(); - - // TODO: check that this class implements every part of its parent - - std::unique_ptr file_reader; - - std::unique_ptr arrow_column_to_ch_column; - - // indices of columns to read from ORC file - std::vector include_indices; - - BlockMissingValues block_missing_values; - size_t approx_bytes_read_for_chunk = 0; - - const FormatSettings format_settings; - const std::unordered_set & skip_stripes; - - int stripe_total = 0; - int stripe_current = 0; - - std::atomic is_stopped{0}; -}; - -class ORCSchemaReader : public ISchemaReader -{ -public: - ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); - - NamesAndTypesList readSchema() override; - std::optional readNumberOrRows() override; - -private: - void initializeIfNeeded(); - - std::unique_ptr file_reader; - std::shared_ptr metadata; - std::shared_ptr schema; - const FormatSettings format_settings; -}; - -} -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp index b9f8bd463152..acf3371b9249 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp @@ -1,5 +1,9 @@ #include +#include + +#include + #if USE_ORC #include @@ -11,6 +15,7 @@ #include #include #include +#include #include #include @@ -20,8 +25,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -38,495 +45,257 @@ namespace ErrorCodes namespace { -orc::CompressionKind getORCCompression(FormatSettings::ORCCompression method) +ORC::CompressionKind getORCCompression(FormatSettings::ORCCompression method) { if (method == FormatSettings::ORCCompression::NONE) - return orc::CompressionKind::CompressionKind_NONE; + return ORC::CompressionKind::NONE; #if USE_SNAPPY if (method == FormatSettings::ORCCompression::SNAPPY) - return orc::CompressionKind::CompressionKind_SNAPPY; + return ORC::CompressionKind::SNAPPY; #endif if (method == FormatSettings::ORCCompression::ZSTD) - return orc::CompressionKind::CompressionKind_ZSTD; + return ORC::CompressionKind::ZSTD; if (method == FormatSettings::ORCCompression::LZ4) - return orc::CompressionKind::CompressionKind_LZ4; + return ORC::CompressionKind::LZ4; if (method == FormatSettings::ORCCompression::ZLIB) - return orc::CompressionKind::CompressionKind_ZLIB; + return ORC::CompressionKind::ZLIB; throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported compression method"); } -} - -ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} - -uint64_t ORCOutputStream::getLength() const +/// Two ORC types get the same key exactly when `parseORCType` (NativeORCBlockInputFormat.cpp) reads +/// them back as the same ClickHouse type: `BINARY` and `STRING` both read as `String`, and a nested +/// `UNION` reads as a `Variant`, which sorts its branches, while ORC keeps them positional. +/// A field name is length-prefixed so a name containing `:` or `,` cannot forge another key. +String orcTypeDedupKey(const ORC::Type & type) { - return out.count(); + const auto kind = type.getKind(); + if (kind == ORC::TypeKind::BINARY || kind == ORC::TypeKind::STRING) + return "string"; + if (kind == ORC::TypeKind::DECIMAL) + return fmt::format("decimal({},{})", type.getPrecision(), type.getScale()); + + std::vector children; + for (size_t i = 0; i < type.getSubtypeCount(); ++i) + { + auto child = orcTypeDedupKey(*type.getSubtype(i)); + if (kind == ORC::TypeKind::STRUCT) + child = fmt::format("{}:{}:{}", type.getFieldName(i).size(), type.getFieldName(i), child); + children.push_back(std::move(child)); + } + if (kind == ORC::TypeKind::UNION) + std::sort(children.begin(), children.end()); + /// Every remaining kind the writer emits is a parameterless primitive mapping to a distinct + /// ClickHouse type, so for those the kind alone is the key and there are no children. + return fmt::format("{}<{}>", static_cast(kind), fmt::join(children, ",")); } -uint64_t ORCOutputStream::getNaturalWriteSize() const -{ - out.nextIfAtEnd(); - return out.available(); } +ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} + void ORCOutputStream::write(const void* buf, size_t length) { out.write(static_cast(buf), length); } -ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_) +ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_) : IOutputFormat(header_, out_) , format_settings{format_settings_} , output_stream(out_) + , column_mapper(std::move(column_mapper_)) { for (const auto & type : header_->getDataTypes()) data_types.push_back(recursiveRemoveLowCardinality(type)); } -std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type) +std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type, const String & column_path) { - switch (type->getTypeId()) + /// Nullable(T) maps to the same ORC node as T; only the Iceberg `required` flag differs. + bool required = !type->isNullable(); + const DataTypePtr unwrapped = removeNullable(type); + + std::unique_ptr result; + switch (unwrapped->getTypeId()) { case TypeIndex::UInt8: { - if (isBool(type)) - return orc::createPrimitiveType(orc::TypeKind::BOOLEAN); - return orc::createPrimitiveType(orc::TypeKind::BYTE); + if (isBool(unwrapped)) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BOOLEAN); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum8: [[fallthrough]]; case TypeIndex::Int8: { - return orc::createPrimitiveType(orc::TypeKind::BYTE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum16: [[fallthrough]]; case TypeIndex::UInt16: [[fallthrough]]; case TypeIndex::Int16: { - return orc::createPrimitiveType(orc::TypeKind::SHORT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::SHORT); + break; } case TypeIndex::UInt32: [[fallthrough]]; case TypeIndex::IPv4: [[fallthrough]]; case TypeIndex::Int32: { - return orc::createPrimitiveType(orc::TypeKind::INT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::INT); + break; } case TypeIndex::UInt64: [[fallthrough]]; case TypeIndex::Int64: { - return orc::createPrimitiveType(orc::TypeKind::LONG); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::LONG); + break; } case TypeIndex::Float32: { - return orc::createPrimitiveType(orc::TypeKind::FLOAT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::FLOAT); + break; } case TypeIndex::Float64: { - return orc::createPrimitiveType(orc::TypeKind::DOUBLE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DOUBLE); + break; } case TypeIndex::Date32: [[fallthrough]]; case TypeIndex::Date: { - return orc::createPrimitiveType(orc::TypeKind::DATE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DATE); + break; } case TypeIndex::DateTime: [[fallthrough]]; case TypeIndex::DateTime64: { - return orc::createPrimitiveType(orc::TypeKind::TIMESTAMP); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::TIMESTAMP); + break; } case TypeIndex::Int128: [[fallthrough]]; case TypeIndex::UInt128: [[fallthrough]]; case TypeIndex::Int256: [[fallthrough]]; case TypeIndex::UInt256: [[fallthrough]]; case TypeIndex::Decimal256: - return orc::createPrimitiveType(orc::TypeKind::BINARY); - case TypeIndex::FixedString: [[fallthrough]]; - case TypeIndex::String: - { - if (format_settings.orc.output_string_as_string) - return orc::createPrimitiveType(orc::TypeKind::STRING); - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::IPv6: - { - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::Nullable: - { - return getORCType(removeNullable(type)); - } - case TypeIndex::Array: - { - const auto * array_type = assert_cast(type.get()); - return orc::createListType(getORCType(array_type->getNestedType())); - } - case TypeIndex::Decimal32: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal64: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal128: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Tuple: - { - const auto * tuple_type = assert_cast(type.get()); - const auto & nested_names = tuple_type->getElementNames(); - const auto & nested_types = tuple_type->getElements(); - auto struct_type = orc::createStructType(); - for (size_t i = 0; i < nested_types.size(); ++i) - struct_type->addStructField(nested_names[i], getORCType(nested_types[i])); - return struct_type; - } - case TypeIndex::Map: - { - const auto * map_type = assert_cast(type.get()); - return orc::createMapType( - getORCType(map_type->getKeyType()), - getORCType(map_type->getValueType()) - ); - } - default: - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); - } - } -} - -template -void ORCBlockOutputFormat::writeNumbers( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - NumberVectorBatch & number_orc_column = dynamic_cast(orc_column); - const auto & number_column = assert_cast &>(column); - - number_orc_column.data.resize(number_column.size()); - for (size_t i = 0; i != number_column.size(); ++i) - number_orc_column.data[i] = convert(number_column.getElement(i)); -} - -template -void ORCBlockOutputFormat::writeDecimals( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - DecimalVectorBatch & decimal_orc_column = dynamic_cast(orc_column); - const auto & decimal_column = assert_cast &>(column); - const auto * decimal_type = assert_cast *>(type.get()); - decimal_orc_column.precision = decimal_type->getPrecision(); - decimal_orc_column.scale = decimal_type->getScale(); - decimal_orc_column.resize(decimal_column.size()); - - decimal_orc_column.values.resize(decimal_column.size()); - for (size_t i = 0; i != decimal_column.size(); ++i) - decimal_orc_column.values[i] = convert(decimal_column.getElement(i).value); -} - -template -void ORCBlockOutputFormat::writeStrings( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * null_bytemap) -{ - orc::StringVectorBatch & string_orc_column = dynamic_cast(orc_column); - const auto & string_column = assert_cast(column); - - string_orc_column.data.resize(string_column.size()); - string_orc_column.length.resize(string_column.size()); - for (size_t i = 0; i != string_column.size(); ++i) - { - const std::string_view string = string_column.getDataAt(i); - string_orc_column.data[i] = (null_bytemap && (*null_bytemap)[i]) ? nullptr : const_cast(string.data()); - string_orc_column.length[i] = string.size(); - } -} - -template -void ORCBlockOutputFormat::writeDateTimes( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - GetSecondsFunc get_seconds, - GetNanosecondsFunc get_nanoseconds) -{ - orc::TimestampVectorBatch & timestamp_orc_column = dynamic_cast(orc_column); - const auto & timestamp_column = assert_cast(column); - - timestamp_orc_column.data.resize(timestamp_column.size()); - timestamp_orc_column.nanoseconds.resize(timestamp_column.size()); - for (size_t i = 0; i != timestamp_column.size(); ++i) - { - timestamp_orc_column.data[i] = static_cast(get_seconds(timestamp_column.getElement(i))); - timestamp_orc_column.nanoseconds[i] = static_cast(get_nanoseconds(timestamp_column.getElement(i))); - } -} - -void ORCBlockOutputFormat::writeColumn( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * null_bytemap) -{ - size_t rows = column.size(); - orc_column.resize(rows); - orc_column.numElements = rows; - - /// Calculate orc_column.hasNulls - if (null_bytemap) - orc_column.hasNulls = !memoryIsZero(null_bytemap->data(), 0, null_bytemap->size()); - else - orc_column.hasNulls = false; - - /// Fill orc_column.notNull - if (orc_column.hasNulls) - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = !(*null_bytemap)[i]; - } - else - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = 1; - } - - /// ORC doesn't have unsigned types, so cast everything to signed and sign-extend to Int64 to - /// make the ORC library calculate min and max correctly. - switch (type->getTypeId()) - { - case TypeIndex::Enum8: [[fallthrough]]; - case TypeIndex::Int8: - { - /// Note: Explicit cast to avoid clang-tidy error: 'signed char' to 'long' conversion; consider casting to 'unsigned char' first. - writeNumbers(orc_column, column, null_bytemap, [](const Int8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::UInt8: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::Enum16: [[fallthrough]]; - case TypeIndex::Int16: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int16 & value){ return value; }); - break; - } - case TypeIndex::Date: [[fallthrough]]; - case TypeIndex::UInt16: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt16 & value){ return Int64(Int16(value)); }); - break; - } - case TypeIndex::Date32: [[fallthrough]]; - case TypeIndex::Int32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int32 & value){ return value; }); - break; - } - case TypeIndex::UInt32: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt32 & value){ return Int64(Int32(value)); }); - break; - } - case TypeIndex::IPv4: - { - writeNumbers(orc_column, column, null_bytemap, [](const IPv4 & value){ return Int64(Int32(value.toUnderType())); }); - break; - } - case TypeIndex::Int64: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int64 & value){ return value; }); - break; - } - case TypeIndex::UInt64: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt64 & value){ return value; }); - break; - } - case TypeIndex::Int128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Int256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Float32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Float32 & value){ return value; }); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; - } - case TypeIndex::Float64: + case TypeIndex::String: { - writeNumbers(orc_column, column, null_bytemap, [](const Float64 & value){ return value; }); + bool force_string = format_settings.orc.output_string_as_string; + result = ORC::Type::createPrimitiveType(force_string ? ORC::TypeKind::STRING : ORC::TypeKind::BINARY); break; } case TypeIndex::FixedString: { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::String: - { - writeStrings(orc_column, column, null_bytemap); + /// Iceberg `fixed[L]` (FixedString) must stay ORC `binary`, so for Iceberg writes + /// force `binary` regardless of the setting; keep the setting-driven choice otherwise. + if (format_settings.orc.output_string_as_string && !column_mapper) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::STRING); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } case TypeIndex::IPv6: { - writeStrings(orc_column, column, null_bytemap); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } - case TypeIndex::DateTime: + case TypeIndex::Array: { - writeDateTimes( - orc_column, - column, null_bytemap, - [](UInt32 value){ return value; }, - [](UInt32){ return 0; }); + const auto * array_type = assert_cast(unwrapped.get()); + result = ORC::Type::createListType(getORCType(array_type->getNestedType(), Nested::concatenateName(column_path, "element"))); break; } - case TypeIndex::DateTime64: + case TypeIndex::Decimal32: { - const auto * timestamp_type = assert_cast(type.get()); - UInt32 scale = timestamp_type->getScale(); - writeDateTimes( - orc_column, - column, - null_bytemap, - [scale](Int64 value) { return value / Int64(std::pow(10, scale)); }, - [scale](Int64 value) { return (value % Int64(std::pow(10, scale))) * Int64(std::pow(10, 9 - scale)); }); - break; - } - case TypeIndex::Decimal32: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int32 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal64: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int64 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal128: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int128 value){ return orc::Int128(static_cast(value >> 64), static_cast((value << 64) >> 64)); }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } - case TypeIndex::Decimal256: + case TypeIndex::Tuple: { - writeStrings>(orc_column, column, null_bytemap); + const auto * tuple_type = assert_cast(unwrapped.get()); + const auto & nested_names = tuple_type->getElementNames(); + const auto & nested_types = tuple_type->getElements(); + auto struct_type = ORC::Type::createStructType(); + for (size_t i = 0; i < nested_types.size(); ++i) + struct_type->addStructField(nested_names[i], getORCType(nested_types[i], Nested::concatenateName(column_path, nested_names[i]))); + result = std::move(struct_type); break; } - case TypeIndex::Nullable: + case TypeIndex::Map: { - chassert(!null_bytemap); - const auto & nullable_column = assert_cast(column); - const PaddedPODArray & new_null_bytemap = assert_cast &>(*nullable_column.getNullMapColumnPtr()).getData(); - auto nested_type = removeNullable(type); - writeColumn(orc_column, nullable_column.getNestedColumn(), nested_type, &new_null_bytemap); + const auto * map_type = assert_cast(unwrapped.get()); + result = ORC::Type::createMapType( + getORCType(map_type->getKeyType(), Nested::concatenateName(column_path, "key")), + getORCType(map_type->getValueType(), Nested::concatenateName(column_path, "value")) + ); break; } - case TypeIndex::Array: - { - orc::ListVectorBatch & list_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column); - auto nested_type = assert_cast(*type).getNestedType(); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - list_orc_column.offsets.resize(column_size + 1); - - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - list_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - list_orc_column.offsets[i + 1] = offsets[i]; - - orc::ColumnVectorBatch & nested_orc_column = *list_orc_column.elements; - writeColumn(nested_orc_column, list_column.getData(), nested_type, nullptr); + case TypeIndex::Variant: + { + const auto & variant_type = assert_cast(*unwrapped); + auto union_type = ORC::Type::createUnionType(); + /// ORC keeps one physical stream per union branch and identifies a branch only by its + /// ORC type, so two variants that map to the same ORC type (e.g. `Int32` and `UInt32`, + /// both ORC `int`) would produce a union with duplicate branches, which the reader + /// rejects. Branches whose ORC types merely read back as one ClickHouse type collide the + /// same way, so they are keyed by `orcTypeDedupKey` rather than by the ORC type itself. + std::unordered_map> variant_by_orc_type; + /// A union child is addressed by its type name, the way a `Variant` subcolumn is + /// (`v.Int32`). Iceberg has no union type, so no field id is expected to be found there. + for (const auto & nested_type : variant_type.getVariants()) + { + auto child_type = getORCType(nested_type, Nested::concatenateName(column_path, nested_type->getName())); + auto [it, inserted] = variant_by_orc_type.emplace( + orcTypeDedupKey(*child_type), std::pair{nested_type->getName(), child_type->toString()}); + if (!inserted) + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Type {} is not supported for ORC output format: variant {} is written as ORC type '{}' and variant {} as " + "'{}', which are read back as the same type, and ORC unions with duplicate branch types cannot be read back", + unwrapped->getName(), it->second.first, it->second.second, nested_type->getName(), child_type->toString()); + union_type->addChild(std::move(child_type)); + } + result = std::move(union_type); break; } - case TypeIndex::Tuple: + default: { - orc::StructVectorBatch & struct_orc_column = dynamic_cast(orc_column); - const auto & tuple_column = assert_cast(column); - auto nested_types = assert_cast(type.get())->getElements(); - for (size_t i = 0; i != tuple_column.tupleSize(); ++i) - writeColumn(*struct_orc_column.fields[i], tuple_column.getColumn(i), nested_types[i], nullptr); - break; + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", unwrapped->getName()); } - case TypeIndex::Map: - { - orc::MapVectorBatch & map_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column).getNestedColumn(); - const auto & map_type = assert_cast(*type); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - - map_orc_column.offsets.resize(column_size + 1); - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - map_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - map_orc_column.offsets[i + 1] = offsets[i]; - - const auto nested_columns = assert_cast(list_column.getDataPtr().get())->getColumns(); - - orc::ColumnVectorBatch & keys_orc_column = *map_orc_column.keys; - auto key_type = map_type.getKeyType(); - writeColumn(keys_orc_column, *nested_columns[0], key_type, nullptr); + } - orc::ColumnVectorBatch & values_orc_column = *map_orc_column.elements; - auto value_type = map_type.getValueType(); - writeColumn(values_orc_column, *nested_columns[1], value_type, nullptr); - break; + /// Attach Iceberg field-id attributes so spec-compliant readers project columns by id. + if (column_mapper) + { + const auto & encoding = column_mapper->getStorageColumnEncoding(); + if (auto it = encoding.find(column_path); it != encoding.end()) + { + result->setAttribute("iceberg.id", std::to_string(it->second)); + result->setAttribute("iceberg.required", required ? "true" : "false"); } - default: - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); } + + return result; } void ORCBlockOutputFormat::consume(Chunk chunk) @@ -534,21 +303,13 @@ void ORCBlockOutputFormat::consume(Chunk chunk) if (!writer) prepareWriter(); - size_t columns_num = chunk.getNumColumns(); size_t rows_num = chunk.getNumRows(); - - std::unique_ptr batch = writer->createRowBatch(chunk.getNumRows()); - orc::StructVectorBatch & root = dynamic_cast(*batch); - auto columns = chunk.detachColumns(); for (auto & column : columns) column = recursiveRemoveLowCardinality(column); - for (size_t i = 0; i != columns_num; ++i) - writeColumn(*root.fields[i], *columns[i], data_types[i], nullptr); - - root.numElements = rows_num; - writer->add(*batch); + /// The values are encoded directly from the columns. + writer->add(columns, rows_num); } void ORCBlockOutputFormat::finalizeImpl() @@ -567,19 +328,22 @@ void ORCBlockOutputFormat::resetFormatterImpl() void ORCBlockOutputFormat::prepareWriter() { const Block & header = getPort(PortKind::Main).getHeader(); - schema = orc::createStructType(); - options.setMemoryPool(&getORCMemoryPool()); - options.setCompression(getORCCompression(format_settings.orc.output_compression_method)); - options.setRowIndexStride(format_settings.orc.output_row_index_stride); - options.setDictionaryKeySizeThreshold(format_settings.orc.output_dictionary_key_size_threshold); - options.setCompressionBlockSize(format_settings.orc.output_compression_block_size); - options.setTimezoneName(format_settings.orc.writer_time_zone_name); + schema = ORC::Type::createStructType(); + options.compression = getORCCompression(format_settings.orc.output_compression_method); + options.row_index_stride = format_settings.orc.output_row_index_stride; + options.dictionary_key_size_threshold = format_settings.orc.output_dictionary_key_size_threshold; + options.compression_block_size = format_settings.orc.output_compression_block_size; + options.timezone_name = format_settings.orc.writer_time_zone_name; size_t columns_count = header.columns(); for (size_t i = 0; i != columns_count; ++i) - schema->addStructField(header.safeGetByPosition(i).name, getORCType(recursiveRemoveLowCardinality(data_types[i]))); - writer = orc::createWriter(*schema, &output_stream, options); + { + const auto & column_name = header.safeGetByPosition(i).name; + schema->addStructField(column_name, getORCType(recursiveRemoveLowCardinality(data_types[i]), column_name)); + } + writer = std::make_unique(*schema, data_types, output_stream, options); } +void registerOutputFormatORC(FormatFactory & factory); void registerOutputFormatORC(FormatFactory & factory) { factory.registerOutputFormat("ORC", []( @@ -603,6 +367,7 @@ void registerOutputFormatORC(FormatFactory & factory) namespace DB { class FormatFactory; + void registerOutputFormatORC(FormatFactory &); void registerOutputFormatORC(FormatFactory &) { } diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h index 0e47f7333d9d..5c9ebc4da420 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h @@ -7,7 +7,8 @@ #include #include #include -#include +#include +#include namespace DB @@ -19,29 +20,22 @@ using DataTypes = std::vector; class WriteBuffer; -/// orc::Writer writes only in orc::OutputStream -class ORCOutputStream : public orc::OutputStream +class ORCOutputStream : public ORC::OutputStream { public: explicit ORCOutputStream(WriteBuffer & out_); - uint64_t getLength() const override; - uint64_t getNaturalWriteSize() const override; void write(const void * buf, size_t length) override; - void close() override {} - const std::string& getName() const override { return name; } - private: WriteBuffer & out; - std::string name = "ORCOutputStream"; }; -class ORCBlockOutputFormat : public IOutputFormat +class ORCBlockOutputFormat final : public IOutputFormat { public: - ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_); + ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_ = nullptr); String getName() const override { return "ORCBlockOutputFormat"; } @@ -50,37 +44,20 @@ class ORCBlockOutputFormat : public IOutputFormat void finalizeImpl() override; void resetFormatterImpl() override; - std::unique_ptr getORCType(const DataTypePtr & type); - - /// ConvertFunc is needed for type UInt8, because firstly UInt8 (char8_t) must be - /// converted to unsigned char (bugprone-signed-char-misuse in clang). - template - void writeNumbers(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, ConvertFunc convert); - - /// ConvertFunc is needed to convert ClickHouse Int128 to ORC Int128. - template - void writeDecimals(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, - const PaddedPODArray * null_bytemap, ConvertFunc convert); - - template - void writeStrings(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap); - - /// ORC column TimestampVectorBatch stores only seconds and nanoseconds, - /// GetSecondsFunc and GetNanosecondsFunc are needed to extract them from DateTime type. - template - void writeDateTimes(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, - GetSecondsFunc get_seconds, GetNanosecondsFunc get_nanoseconds); - - void writeColumn(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, const PaddedPODArray * null_bytemap); + /// For Iceberg writes, attaches the field-id `iceberg.id` type attribute so readers project + /// by id. `column_path` is the dotted name (`t.x`, `arr.element`) used to look the id up. + std::unique_ptr getORCType(const DataTypePtr & type, const String & column_path); void prepareWriter(); const FormatSettings format_settings; ORCOutputStream output_stream; DataTypes data_types; - std::unique_ptr writer; - std::unique_ptr schema; - orc::WriterOptions options; + std::unique_ptr writer; + std::unique_ptr schema; + ORC::WriterOptions options; + /// Non-null only for Iceberg writes; maps dotted column name -> Iceberg field-id. + ColumnMapperPtr column_mapper; }; } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.cpp b/src/Processors/Formats/Impl/Parquet/Decoding.cpp index 840abe3265b2..e52e24dce6a8 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp +++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp @@ -1676,6 +1676,8 @@ Int96Converter::Int96Converter() void Int96Converter::convertColumn(std::span data, size_t num_values, IColumn & col) const { + const bool saturate = overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate; + std::span to_span = col.insertRawUninitialized(num_values); Int64 * to = reinterpret_cast(to_span.data()); for (size_t i = 0; i < num_values; ++i) @@ -1700,16 +1702,17 @@ void Int96Converter::convertColumn(std::span data, size_t num_values /// This interpretation is consistent with the arrow reader code (DecodeInt96Timestamp in /// arrow/cpp/src/parquet/types.h) and with a test file written by spark /// (tests/queries/0_stateless/02998_native_parquet_reader.sh). - bool overflow = false; - Int64 x; - overflow |= common::subOverflow(julian_day, static_cast(2440588l), x); // unix day number - overflow |= common::mulOverflow(x, day_nanos, x); // unix nanoseconds - overflow |= common::addOverflow(x, nanos, x); - - if (overflow) - throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); - to[i] = x; + /// julian_day comes from Int32, so neither the subtraction nor the product can overflow Int128. + const Int128 total = Int128(julian_day - 2440588l) * day_nanos + nanos; + if (total < std::numeric_limits::min() || total > std::numeric_limits::max()) + { + if (!saturate) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); + to[i] = julian_day < 2440588l ? std::numeric_limits::min() : std::numeric_limits::max(); + } + else + to[i] = static_cast(total); } } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.h b/src/Processors/Formats/Impl/Parquet/Decoding.h index 05f6ef6a2e02..266176171e45 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.h +++ b/src/Processors/Formats/Impl/Parquet/Decoding.h @@ -298,6 +298,9 @@ extern template struct BigEndianDecimalStringConverter; struct Int96Converter : public FixedSizeConverter { + /// A value that does not fit into Int64 nanoseconds is clamped to the `DateTime64(9)` range with Saturate, otherwise throws. + FormatSettings::DateTimeOverflowBehavior overflow_behavior = FormatSettings::DateTimeOverflowBehavior::Ignore; + Int96Converter(); void convertColumn(std::span data, size_t num_values, IColumn & col) const override; diff --git a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp index 8053f644407c..b1633c13f7e2 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp @@ -1258,7 +1258,9 @@ void SchemaConverter::processPrimitiveColumn( case parq::Type::INT96: { out_inferred_type = std::make_shared(9, "UTC"); - out_decoder.fixed_size_converter = std::make_shared(); + auto converter = std::make_shared(); + converter->overflow_behavior = options.format.date_time_overflow_behavior; + out_decoder.fixed_size_converter = std::move(converter); /// (Leaving allow_stats == false because INT96 sort order is undefined.) return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp index 3e938fddea10..317478590c98 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp @@ -6,21 +6,17 @@ #include #include +#include #include #include +#include + #include #include #include -namespace CurrentMetrics -{ - extern const Metric ParquetEncoderThreads; - extern const Metric ParquetEncoderThreadsActive; - extern const Metric ParquetEncoderThreadsScheduled; -} - namespace DB { @@ -87,11 +83,10 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Custom parquet encoder doesn't support parquet versions < 2.6. Use output_format_parquet_use_custom_encoder = 0."); if (format_settings.parquet.parallel_encoding && format_settings.max_threads > 1) - pool = std::make_unique( - CurrentMetrics::ParquetEncoderThreads, - CurrentMetrics::ParquetEncoderThreadsActive, - CurrentMetrics::ParquetEncoderThreadsScheduled, - format_settings.max_threads); + { + getParquetEncoderThreadPool().initializeWithDefaultSettingsIfNotInitialized(); + pool = &getParquetEncoderThreadPool().get(); + } using C = FormatSettings::ParquetCompression; switch (format_settings.parquet.output_compression_method) @@ -130,10 +125,14 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea ParquetBlockOutputFormat::~ParquetBlockOutputFormat() { if (pool) - { - is_stopped = true; - pool->wait(); - } + stopThreads(); +} + +void ParquetBlockOutputFormat::stopThreads() +{ + is_stopped = true; + std::unique_lock lock(mutex); + condvar.wait(lock, [this] { return threads_running == 0; }); } void ParquetBlockOutputFormat::consume(Chunk chunk) @@ -279,8 +278,7 @@ void ParquetBlockOutputFormat::resetFormatterImpl() { if (pool) { - is_stopped = true; - pool->wait(); + stopThreads(); is_stopped = false; } @@ -497,17 +495,16 @@ void ParquetBlockOutputFormat::startMoreThreadsIfNeeded(const std::unique_locktrySchedule(job)) break; + ++threads_running; } } } -void ParquetBlockOutputFormat::threadFunction() +void ParquetBlockOutputFormat::threadFunction(ThreadGroupPtr & thread_group) { + std::optional switcher; + switcher.emplace(thread_group, ThreadName::PARQUET_ENCODER); + std::unique_lock lock(mutex); while (true) @@ -540,7 +541,12 @@ void ParquetBlockOutputFormat::threadFunction() { /// The check and the decrement need to be in the same critical section, to make sure /// we never get stuck with tasks but no threads. + /// Leave the query's thread group before stopThreads() can see the decrement. + switcher.reset(); + thread_group.reset(); --threads_running; + if (threads_running == 0) + condvar.notify_all(); return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h index f22447850e82..b553a00ba391 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h @@ -28,6 +28,9 @@ namespace DB class CHColumnToArrowColumn; +class ThreadGroup; +using ThreadGroupPtr = std::shared_ptr; + class ParquetBlockOutputFormat : public IOutputFormat { public: @@ -118,8 +121,9 @@ class ParquetBlockOutputFormat : public IOutputFormat void writeRowGroupInOneThread(Chunk chunk); void writeRowGroupInParallel(std::vector chunks); - void threadFunction(); + void threadFunction(ThreadGroupPtr & thread_group); void startMoreThreadsIfNeeded(const std::unique_lock & lock); + void stopThreads(); /// Called in single-threaded fashion. Writes to the file. void reapCompletedRowGroups(std::unique_lock & lock); @@ -140,13 +144,15 @@ class ParquetBlockOutputFormat : public IOutputFormat size_t base_offset = 0; // initial out.count(), just for assert std::mutex mutex; - std::condition_variable condvar; // wakes up consume() - std::unique_ptr pool; + std::condition_variable condvar; // wakes up consume() and stopThreads() + /// Shared by all Parquet writers of the process (`getParquetEncoderThreadPool`). + ThreadPool * pool = nullptr; std::atomic_bool is_stopped{false}; std::exception_ptr background_exception = nullptr; /// Invariant: if there's at least one task then there's at least one thread. + /// Counts the jobs scheduled on `pool` until they exit, queued ones included. size_t threads_running = 0; std::atomic bytes_in_flight{0}; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 5e9a4bfd7565..119112f9838a 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -56,9 +56,16 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat( format_filter_info = std::make_shared(); } -void ParquetV3BlockInputFormat::initializeIfNeeded() +void ParquetV3BlockInputFormat::prefetch() { - if (!reader) + if (need_only_count) + return; + readFileFooterIfNeeded(); +} + +void ParquetV3BlockInputFormat::readFileFooterIfNeeded() +{ + if (!reader && !reader_with_footer) { format_filter_info->initKeyConditionOnce(getPort().getHeader()); parser_shared_resources->initOnce([&] @@ -87,11 +94,24 @@ void ParquetV3BlockInputFormat::initializeIfNeeded() parser_shared_resources->opaque = ext; }); + auto new_reader = std::make_unique(); + new_reader->reader.prefetcher.init(in, read_options, parser_shared_resources); + new_reader->reader.file_metadata = getFileMetadata(new_reader->reader.prefetcher); + + std::lock_guard lock(reader_mutex); + reader_with_footer = std::move(new_reader); + } +} + +void ParquetV3BlockInputFormat::initializeIfNeeded() +{ + if (!reader) + { + readFileFooterIfNeeded(); + { std::lock_guard lock(reader_mutex); - reader.emplace(); - reader->reader.prefetcher.init(in, read_options, parser_shared_resources); - reader->reader.file_metadata = getFileMetadata(reader->reader.prefetcher); + reader = std::move(reader_with_footer); reader->reader.init(read_options, getPort().getHeader(), format_filter_info); reader->init(parser_shared_resources, buckets_to_read ? std::optional(buckets_to_read->row_group_ids) : std::nullopt); } @@ -169,6 +189,7 @@ void ParquetV3BlockInputFormat::resetReadBuffer() std::lock_guard lock(reader_mutex); if (reader) reader->shutdownTasks(); + reader_with_footer.reset(); } IInputFormat::resetReadBuffer(); } @@ -178,6 +199,7 @@ void ParquetV3BlockInputFormat::resetParser() { std::lock_guard lock(reader_mutex); reader.reset(); + reader_with_footer.reset(); } previous_block_missing_values.clear(); IInputFormat::resetParser(); diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h index a66ea4d97c2e..892771da231f 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h @@ -43,6 +43,8 @@ class ParquetV3BlockInputFormat : public IInputFormat private: Chunk read() override; + void prefetch() override; + void onCancel() noexcept override; const FormatSettings format_settings; @@ -52,17 +54,20 @@ class ParquetV3BlockInputFormat : public IInputFormat ParquetMetadataCachePtr metadata_cache; const std::optional object_with_metadata; - /// (This mutex is not important. It protects `reader.emplace` in a weird case where onCancel() + /// (This mutex is not important. It protects setting `reader` in a weird case where onCancel() /// may be called in parallel with first read(). ReadManager itself is thread safe for that, - /// but initializing vs checking the std::optional would race without this mutex.) + /// but initializing vs checking the pointer would race without this mutex.) std::mutex reader_mutex; - std::optional reader; + std::unique_ptr reader; + /// Has the file footer, but is not initialized: initializing it starts reading and decoding the column chunks. + std::unique_ptr reader_with_footer; bool reported_count = false; // if need_only_count BlockMissingValues previous_block_missing_values; size_t previous_approx_bytes_read_for_chunk = 0; + void readFileFooterIfNeeded(); void initializeIfNeeded(); std::shared_ptr buckets_to_read; diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp index a2c57cf0ed3a..48d880484d33 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include #include #include @@ -10,14 +12,24 @@ namespace DB RawBLOBRowOutputFormat::RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_) + SharedHeader header_, + const FormatSettings & format_settings_) : IRowOutputFormat(header_, out_) + , format_settings(format_settings_) { } -void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization &, size_t row_num) +void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) { + /// `getDataAt` of `ColumnAggregateFunction` returns the bytes of the pointer to the state, not the state itself. + /// Write the serialized state, the same as its conversion to `String`. + if (typeid_cast(&column)) + { + serialization.serializeBinary(column, row_num, out, format_settings); + return; + } + if (!column.isNullAt(row_num)) { auto value = column.getDataAt(row_num); @@ -31,10 +43,10 @@ void registerOutputFormatRawBLOB(FormatFactory & factory) factory.registerOutputFormat("RawBLOB", []( WriteBuffer & buf, const Block & sample, - const FormatSettings &, + const FormatSettings & settings, FormatFilterInfoPtr /*format_filter_info*/) { - return std::make_shared(buf, std::make_shared(sample)); + return std::make_shared(buf, std::make_shared(sample), settings); }); } diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h index e2afa209faaa..9418d3c33028 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h @@ -1,5 +1,6 @@ #pragma once +#include #include @@ -28,12 +29,15 @@ class RawBLOBRowOutputFormat final : public IRowOutputFormat public: RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_); + SharedHeader header_, + const FormatSettings & format_settings_); String getName() const override { return "RawBLOBRowOutputFormat"; } private: - void writeField(const IColumn & column, const ISerialization &, size_t row_num) override; + void writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) override; + + const FormatSettings format_settings; }; } diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp index 8fd5aba82710..005d5379243a 100644 --- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp +++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp @@ -49,7 +49,6 @@ #include #include #include -#include #include #include #include @@ -520,9 +519,7 @@ Pipe ReadFromMergeTree::readFromPoolParallelReplicas( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); pipes.emplace_back(std::move(source)); @@ -631,9 +628,7 @@ Pipe ReadFromMergeTree::readFromPool( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); @@ -750,9 +745,7 @@ Pipe ReadFromMergeTree::readInOrder( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); processor->addPartLevelToChunk(isQueryWithFinal()); diff --git a/src/Processors/Transforms/AddingDefaultsTransform.cpp b/src/Processors/Transforms/AddingDefaultsTransform.cpp index 9e0fe0f5c260..9650df7204bb 100644 --- a/src/Processors/Transforms/AddingDefaultsTransform.cpp +++ b/src/Processors/Transforms/AddingDefaultsTransform.cpp @@ -157,7 +157,8 @@ void AddingDefaultsTransform::transform(Chunk & chunk) return; const auto * block_missing_values = input_format.getMissingValues(); - if (!block_missing_values) + /// `BlockMissingValues::empty` is also true when the mask holds no columns at all, where the lookups below would be out of range. + if (!block_missing_values || block_missing_values->empty()) return; const auto & header = getOutputPort().getHeader(); diff --git a/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp new file mode 100644 index 000000000000..89e4391079a6 --- /dev/null +++ b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp @@ -0,0 +1,127 @@ +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, so a chunk holding more +/// than that becomes several record batches, each covering a row range. A range not starting at row 0 has +/// to rebase those offsets against the row before it. Reaching the real limit needs more than 2 GiB of +/// data, so these tests lower it. +/// +/// `CHColumnToArrowColumn` is the Apache Arrow library writer, used by the `Arrow` output format, +/// `ArrowFlight`, `StorageArrowFlight` and Delta Lake writes. + +namespace DB +{ + +namespace +{ + +constexpr size_t NUM_ROWS = 8; +constexpr size_t VALUE_SIZE = 16; + +std::string valueAt(size_t row) +{ + return std::string(VALUE_SIZE, static_cast('a' + row)); +} + +CHColumnToArrowColumn::Settings settingsWithLimit(UInt64 max_record_batch_bytes) +{ + CHColumnToArrowColumn::Settings settings; + settings.output_string_as_string = true; + settings.output_max_record_batch_bytes = max_record_batch_bytes; + return settings; +} + +std::shared_ptr convertToArrow(const DataTypePtr & type, MutableColumnPtr column, UInt64 max_record_batch_bytes) +{ + ColumnsWithTypeAndName header_columns{ColumnWithTypeAndName(type->createColumn(), type, "t")}; + + Columns columns; + columns.emplace_back(std::move(column)); + + std::vector chunks; + chunks.emplace_back(std::move(columns), NUM_ROWS); + + CHColumnToArrowColumn converter(header_columns, "Arrow", settingsWithLimit(max_record_batch_bytes)); + std::shared_ptr arrow_table; + converter.chChunkToArrowTable(arrow_table, chunks, 1); + return arrow_table; +} + +} + +TEST(CHColumnToArrowColumn, StringSplitAcrossRecordBatches) +{ + auto type = std::make_shared(); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(valueAt(row)); + + /// Two values per batch, so most batches start past row 0. + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & array = assert_cast(*chunked.chunk(chunk_i)); + /// Every batch addresses its own values from zero. + ASSERT_EQ(array.value_offset(0), 0); + for (int64_t i = 0; i < array.length(); ++i, ++row) + ASSERT_EQ(array.GetString(i), valueAt(row)); + } + ASSERT_EQ(row, NUM_ROWS); +} + +TEST(CHColumnToArrowColumn, ArraySplitAcrossRecordBatches) +{ + auto type = std::make_shared(std::make_shared()); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(Array{Field(valueAt(row)), Field(valueAt(row))}); + + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & list = assert_cast(*chunked.chunk(chunk_i)); + ASSERT_EQ(list.value_offset(0), 0); + for (int64_t i = 0; i < list.length(); ++i, ++row) + { + /// `value_slice` returns a new array by value: keep it alive while it is inspected. + const auto values_holder = list.value_slice(i); + const auto & values = assert_cast(*values_holder); + ASSERT_EQ(values.length(), 2); + ASSERT_EQ(values.GetString(0), valueAt(row)); + ASSERT_EQ(values.GetString(1), valueAt(row)); + } + } + ASSERT_EQ(row, NUM_ROWS); +} + +} + +#endif diff --git a/src/Server/HTTP/ReadHeaders.cpp b/src/Server/HTTP/ReadHeaders.cpp index 142b47a8d6d2..4a5ef642b68b 100644 --- a/src/Server/HTTP/ReadHeaders.cpp +++ b/src/Server/HTTP/ReadHeaders.cpp @@ -87,7 +87,12 @@ void readHeaders( skipToNextLineOrEOF(in); Poco::trimRightInPlace(value); - headers.add(name, Poco::Net::MessageHeader::decodeWord(value)); + std::string decoded_value = Poco::Net::MessageHeader::decodeWord(value); + /// RFC 2047 decoding can produce bytes that are forbidden in a field value (RFC 9110, section 5.5), + /// e.g. `=0D=0A` would become a line break that splits the header when it is written out again. + if (decoded_value.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Poco::Net::MessageException(fmt::format("Value of field \"{}\" contains CR, LF or NUL", name)); + headers.add(name, decoded_value); ++fields; } } diff --git a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp index f17e4f25ce44..d93ae95ec67b 100644 --- a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp +++ b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp @@ -59,6 +59,7 @@ namespace ErrorCodes extern const int WRONG_PASSWORD; extern const int REQUIRED_PASSWORD; extern const int AUTHENTICATION_FAILED; + extern const int REQUIRED_SECOND_FACTOR; extern const int SET_NON_GRANTED_ROLE; extern const int HTTP_LENGTH_REQUIRED; @@ -76,7 +77,8 @@ Poco::Net::HTTPResponse::HTTPStatus exceptionCodeToHTTPStatus(int exception_code return HTTPResponse::HTTP_UNAUTHORIZED; } if (exception_code == ErrorCodes::UNKNOWN_USER || exception_code == ErrorCodes::WRONG_PASSWORD - || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE) + || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE + || exception_code == ErrorCodes::REQUIRED_SECOND_FACTOR) { return HTTPResponse::HTTP_FORBIDDEN; } diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index 1d7b6d09bf16..92be0d801fac 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2525,8 +2525,10 @@ bool TCPHandler::processData(QueryState & state, bool scalar) if (scalar) { - /// Scalar value - state.query_context->addScalar(temporary_id.table_name, block); + /// Scalar value received from the client over the wire. It must not be trusted as a + /// server-computed scalar-subquery result (see Context::addClientScalar): otherwise a client + /// could name it with a row policy's scalar-subquery hash and forge the policy's result. + state.query_context->addClientScalar(temporary_id.table_name, block); } else if (!state.need_receive_data_for_insert && !state.need_receive_data_for_input) { diff --git a/src/Storages/AlterCommands.cpp b/src/Storages/AlterCommands.cpp index b1661cffc376..c026d44cb772 100644 --- a/src/Storages/AlterCommands.cpp +++ b/src/Storages/AlterCommands.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -1314,6 +1315,33 @@ bool AlterCommands::hasVectorSimilarityIndex(const StorageInMemoryMetadata & met return false; } +NameSet AlterCommands::getAddedIndexNames(const IndicesDescription & existing) const +{ + NameSet present; + for (const auto & index : existing) + present.insert(index.name); + + NameSet added; + for (const AlterCommand & command : *this) + { + if (command.ignore) + continue; + + if (command.type == AlterCommand::ADD_INDEX) + { + /// Otherwise `AlterCommand::apply` either skips it, with `IF NOT EXISTS`, or throws. + if (present.insert(command.index_name).second) + added.insert(command.index_name); + } + else if (command.type == AlterCommand::DROP_INDEX && !command.partition && !command.clear) + { + present.erase(command.index_name); + added.erase(command.index_name); + } + } + return added; +} + void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context) const { if (!prepared) @@ -1371,6 +1399,16 @@ void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context } } + /// Only the declared ones, and only now: the rebuild above resolves them against the schema every + /// command produced, which is what gets stored. Existing indices stay unauthorised on purpose. + const NameSet declared_indices = getAddedIndexNames(metadata.secondary_indices); + + for (const auto & index : metadata_copy.secondary_indices) + { + if (declared_indices.contains(index.name)) + checkTextIndexPreAndPostProcessorPermissions(index, context); + } + /// Changes in columns may lead to changes in projections ProjectionsDescription new_projections; for (const auto & projection : metadata_copy.projections) diff --git a/src/Storages/AlterCommands.h b/src/Storages/AlterCommands.h index 22a9253baa10..82501af8dd29 100644 --- a/src/Storages/AlterCommands.h +++ b/src/Storages/AlterCommands.h @@ -219,6 +219,9 @@ class AlterCommands : public std::vector /// Commands have to be prepared before apply. void apply(StorageInMemoryMetadata & metadata, ContextPtr context) const; + /// Indices the commands actually add: `ADD INDEX IF NOT EXISTS` of an existing name adds nothing. + NameSet getAddedIndexNames(const IndicesDescription & existing) const; + /// At least one command modify settings or comments. bool hasNonReplicatedAlterCommand() const; diff --git a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp index 7b54bd1a72fc..d2b3e89891d2 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp @@ -21,6 +21,7 @@ #include #include +#include #include namespace CurrentMetrics @@ -217,6 +218,11 @@ bool DistributedAsyncInsertBatch::recoverBatch() } files.erase(files.begin(), first_existing_file); + /// The batch is sent with the `ClientInfo` of its first file. Older servers could put files of different + /// users (or originating hosts) into one batch, so a restored batch of mixed identities must not be resent + /// as a whole: it is dropped, and its files are batched again by identity like any other pending files. + std::optional> batch_identity; + /// A missing file inside the surviving suffix cannot be recovered safely. for (const auto & file : files) { @@ -228,13 +234,25 @@ bool DistributedAsyncInsertBatch::recoverBatch() try { - ReadBufferFromFile header_buffer(files.back()); + ReadBufferFromFile header_buffer(file); const DistributedAsyncInsertHeader & header = DistributedAsyncInsertHeader::read(header_buffer, parent.log); if (header.rows) { total_rows += header.rows; total_bytes += header.bytes; } + + auto identity = getRemoteAuthenticationIdentity(header.client_info); + if (!batch_identity) + { + batch_identity = std::move(identity); + } + else if (identity != *batch_identity) + { + LOG_WARNING(parent.log, "File {} has a different user or originating host than the first file of the batch, " + "the files of the batch will be sent in new batches", file); + return false; + } } catch (Exception & e) { diff --git a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp index 172028d48813..c94608ea330d 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp @@ -494,8 +494,11 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader bool operator==(const BatchHeader & other) const { + /// The whole batch is sent with the `ClientInfo` of its first file, so files that the shard would + /// authenticate differently must never be merged into one batch. return std::tie(settings, query, client_info.query_kind) == std::tie(other.settings, other.query, other.client_info.query_kind) && + getRemoteAuthenticationIdentity(client_info) == getRemoteAuthenticationIdentity(other.client_info) && blocksHaveEqualStructure(header, other.header); } @@ -505,6 +508,9 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader { SipHash hash_state; hash_state.update(batch_header.query.data(), batch_header.query.size()); + const auto [initial_user, initial_host] = getRemoteAuthenticationIdentity(batch_header.client_info); + hash_state.update(initial_user.data(), initial_user.size()); + hash_state.update(initial_host.data(), initial_host.size()); batch_header.header.updateHash(hash_state); return hash_state.get64(); } diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp index e14d376583c7..ef6564f896e7 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp @@ -68,6 +68,14 @@ void writeAndConvert(RemoteInserter & remote, const DistributedAsyncInsertHeader } } +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info) +{ + String initial_host; + if (client_info.initial_address) + initial_host = client_info.initial_address->host().toString(); + return {client_info.initial_user, initial_host}; +} + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h index 202d9ff6fff8..3cc335c169f9 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h @@ -1,12 +1,16 @@ #pragma once #include +#include + +#include namespace DB { struct DistributedAsyncInsertHeader; +class ClientInfo; class ReadBufferFromFile; class RemoteInserter; @@ -23,6 +27,11 @@ class RemoteInserter; /// and mark batch as broken. bool isDistributedSendBroken(int code, bool remote_error); +/// The identity the shard authenticates a queued insert as (with the interserver ``): `initial_user` +/// and the host of `initial_address`, which is checked against the allowed hosts of that user. +/// A batch is sent with the `ClientInfo` of its first file, so all files of a batch must have the same identity. +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info); + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedSink.cpp b/src/Storages/Distributed/DistributedSink.cpp index dc3fa7f31036..b0d05d4d5ebb 100644 --- a/src/Storages/Distributed/DistributedSink.cpp +++ b/src/Storages/Distributed/DistributedSink.cpp @@ -864,17 +864,21 @@ void DistributedSink::writeToShard(const Cluster::ShardInfo & shard_info, const writeStringBinary(query_string, header_buf); context->getSettingsRef().write(header_buf); - if (OpenTelemetry::CurrentContext().isTraceEnabled()) { - // if the distributed tracing is enabled, use the trace context in current thread as parent of next span auto client_info = context->getClientInfo(); - client_info.client_trace_context = OpenTelemetry::CurrentContext(); + // if the distributed tracing is enabled, use the trace context in current thread as parent of next span + if (OpenTelemetry::CurrentContext().isTraceEnabled()) + client_info.client_trace_context = OpenTelemetry::CurrentContext(); + /// Background contexts (e.g. the ones of `Kafka` / `RabbitMQ` streaming into views) have + /// `query_kind = NO_QUERY`, for which `ClientInfo::write` stores nothing but the kind. The + /// replayed insert would then reach the shard with an empty `initial_user`, which a shard + /// accepting the interserver `` executes with full access, losing the identity + /// (e.g. the definer of a `SQL SECURITY DEFINER` view) that the query is bound to. + /// `RemoteInserter` sends the insert as a secondary query anyway, so persist it as such. + if (client_info.query_kind == ClientInfo::QueryKind::NO_QUERY) + client_info.query_kind = ClientInfo::QueryKind::SECONDARY_QUERY; client_info.write(header_buf, DBMS_TCP_PROTOCOL_VERSION); } - else - { - context->getClientInfo().write(header_buf, DBMS_TCP_PROTOCOL_VERSION); - } writeVarUInt(block.rows(), header_buf); writeVarUInt(block.bytes(), header_buf); diff --git a/src/Storages/Hive/HiveFile.cpp b/src/Storages/Hive/HiveFile.cpp index 18c9bf27a6f6..f2c467937ddb 100644 --- a/src/Storages/Hive/HiveFile.cpp +++ b/src/Storages/Hive/HiveFile.cpp @@ -8,12 +8,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -33,31 +33,16 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } -#define THROW_ARROW_NOT_OK(status) \ - do \ - { \ - if (const ::arrow::Status & _s = (status); !_s.ok()) \ - throw Exception::createDeprecated(_s.ToString(), ErrorCodes::BAD_ARGUMENTS); \ - } while (false) - - -template -Range createRangeFromOrcStatistics(const StatisticsType * stats) +template +Range createRangeFromOrcStatistics(const std::optional & minimum, const std::optional & maximum) { /// Null values or NaN/Inf values of double type. - if (stats->hasMinimum() && stats->hasMaximum()) - { - return Range(FieldType(stats->getMinimum()), true, FieldType(stats->getMaximum()), true); - } - if (stats->hasMinimum()) - { - return Range::createLeftBounded(FieldType(stats->getMinimum()), true); - } - if (stats->hasMaximum()) - { - return Range::createRightBounded(FieldType(stats->getMaximum()), true); - } - + if (minimum && maximum) + return Range(FieldType(*minimum), true, FieldType(*maximum), true); + if (minimum) + return Range::createLeftBounded(FieldType(*minimum), true); + if (maximum) + return Range::createRightBounded(FieldType(*maximum), true); return Range::createWholeUniverseWithoutNull(); } @@ -116,48 +101,40 @@ void IHiveFile::loadSplitMinMaxIndexes() split_minmax_idxes_loaded = true; } -Range HiveORCFile::buildRange(const orc::ColumnStatistics * col_stats) +Range HiveORCFile::buildRange(const ORC::Proto::ColumnStatistics * col_stats) { - if (!col_stats || col_stats->hasNull()) + /// A missing `has_null` means that the column may contain nulls. + if (!col_stats || col_stats->has_null.value_or(true)) return Range::createWholeUniverseWithoutNull(); - if (const auto * int_stats = dynamic_cast(col_stats)) + if (const auto & int_stats = col_stats->int_statistics) + return createRangeFromOrcStatistics(int_stats->minimum, int_stats->maximum); + if (const auto & double_stats = col_stats->double_statistics) + return createRangeFromOrcStatistics(double_stats->minimum, double_stats->maximum); + if (const auto & string_stats = col_stats->string_statistics) + return createRangeFromOrcStatistics(string_stats->minimum, string_stats->maximum); + if (const auto & bool_stats = col_stats->bucket_statistics) { - return createRangeFromOrcStatistics(int_stats); - } - if (const auto * double_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(double_stats); - } - if (const auto * string_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(string_stats); - } - if (const auto * bool_stats = dynamic_cast(col_stats)) - { - auto false_cnt = bool_stats->getFalseCount(); - auto true_cnt = bool_stats->getTrueCount(); + if (bool_stats->count.empty()) + return Range::createWholeUniverseWithoutNull(); + UInt64 true_cnt = bool_stats->count[0]; + UInt64 false_cnt = col_stats->number_of_values.value_or(0) - true_cnt; if (false_cnt && true_cnt) - { return Range(UInt8(0), true, UInt8(1), true); - } if (false_cnt) - { return Range::createLeftBounded(UInt8(0), true); - } if (true_cnt) - { return Range::createRightBounded(UInt8(1), true); - } - } - else if (const auto * timestamp_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(timestamp_stats); + return Range::createWholeUniverseWithoutNull(); } - else if (const auto * date_stats = dynamic_cast(col_stats)) + if (const auto & timestamp_stats = col_stats->timestamp_statistics) { - return createRangeFromOrcStatistics(date_stats); + /// The deprecated `minimum` and `maximum` are in the local time zone of the writer, which is + /// unknown for the statistics of the whole file, so only the UTC bounds are usable. + return createRangeFromOrcStatistics(timestamp_stats->minimum_utc, timestamp_stats->maximum_utc); } + if (const auto & date_stats = col_stats->date_statistics) + return createRangeFromOrcStatistics(date_stats->minimum, date_stats->maximum); return Range::createWholeUniverseWithoutNull(); } @@ -166,14 +143,12 @@ void HiveORCFile::prepareReader() in = std::make_unique(namenode_url, path, getContext()->getGlobalContext()->getConfigRef(), getContext()->getReadSettings()); auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; - auto result = arrow::adapters::orc::ORCFileReader::Open(asArrowFile(*in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(result.status()); - reader = std::move(result).ValueOrDie(); + reader = createORCReader(asORCInputStream(*in, format_settings, /*use_prefetch=*/false, is_stopped), ORC::ReaderOptions{}); } void HiveORCFile::prepareColumnMapping() { - const orc::Type & type = reader->GetRawORCReader()->getType(); + const ORC::Type & type = reader->getType(); size_t count = type.getSubtypeCount(); for (size_t pos = 0; pos < count; pos++) { @@ -190,7 +165,7 @@ bool HiveORCFile::useFileMinMaxIndex() const } -std::unique_ptr HiveORCFile::buildMinMaxIndex(const orc::Statistics * statistics) +std::unique_ptr HiveORCFile::buildMinMaxIndex(const std::vector * statistics) { if (!statistics) return nullptr; @@ -213,7 +188,7 @@ std::unique_ptr HiveORCFile::buildMinMaxIndex(c { size_t pos = it->second; /// Attention: column statistics start from 1. 0 has special purpose. - const orc::ColumnStatistics * col_stats = statistics->getColumnStatistics(static_cast(pos + 1)); + const ORC::Proto::ColumnStatistics * col_stats = pos + 1 < statistics->size() ? &(*statistics)[pos + 1] : nullptr; idx->hyperrectangle[i] = buildRange(col_stats); } ++i; @@ -230,8 +205,7 @@ void HiveORCFile::loadFileMinMaxIndexImpl() prepareColumnMapping(); } - auto statistics = reader->GetRawORCReader()->getStatistics(); - file_minmax_idx = buildMinMaxIndex(statistics.get()); + file_minmax_idx = buildMinMaxIndex(&reader->getStatistics()); } bool HiveORCFile::useSplitMinMaxIndex() const @@ -248,9 +222,10 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); auto stripe_num = raw_reader->getNumberOfStripes(); - auto stripe_stats_num = raw_reader->getNumberOfStripeStatistics(); + const auto & stripe_statistics = raw_reader->getMetadata().stripe_stats; + auto stripe_stats_num = stripe_statistics.size(); if (stripe_num != stripe_stats_num) throw Exception(ErrorCodes::BAD_ARGUMENTS, "orc file:{} has different strip num {} and strip statistics num {}", path, stripe_num, stripe_stats_num); @@ -258,8 +233,7 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() split_minmax_idxes.resize(stripe_num); for (size_t i = 0; i < stripe_num; ++i) { - auto stripe_stats = raw_reader->getStripeStatistics(i); - split_minmax_idxes[i] = buildMinMaxIndex(stripe_stats.get()); + split_minmax_idxes[i] = buildMinMaxIndex(&stripe_statistics[i].col_stats); } } @@ -271,7 +245,7 @@ std::optional HiveORCFile::getRowsImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); return raw_reader->getNumberOfRows(); } @@ -286,7 +260,8 @@ void HiveParquetFile::prepareReader() auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; auto open_file_res = parquet::arrow::OpenFile(asArrowFile(*in, format_settings, is_stopped, "Parquet", PARQUET_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(open_file_res.status()); + if (!open_file_res.ok()) + throw Exception::createDeprecated(open_file_res.status().ToString(), ErrorCodes::BAD_ARGUMENTS); reader = *std::move(open_file_res); } diff --git a/src/Storages/Hive/HiveFile.h b/src/Storages/Hive/HiveFile.h index 611302693b1d..50d9e0cbc6c2 100644 --- a/src/Storages/Hive/HiveFile.h +++ b/src/Storages/Hive/HiveFile.h @@ -5,9 +5,10 @@ #include #include +#include #include -#include +#include #include #include @@ -217,18 +218,18 @@ class HiveORCFile : public IHiveFile bool useSplitMinMaxIndex() const override; private: - static Range buildRange(const orc::ColumnStatistics * col_stats); + static Range buildRange(const ORC::Proto::ColumnStatistics * col_stats); void loadFileMinMaxIndexImpl() override; void loadSplitMinMaxIndexesImpl() override; - std::unique_ptr buildMinMaxIndex(const orc::Statistics * statistics); + std::unique_ptr buildMinMaxIndex(const std::vector * statistics); void prepareReader(); void prepareColumnMapping(); std::optional getRowsImpl() override; std::unique_ptr in; - std::unique_ptr reader; + std::unique_ptr reader; std::map orc_column_positions; }; diff --git a/src/Storages/Hive/StorageHive.cpp b/src/Storages/Hive/StorageHive.cpp index fccccb7c7fca..15e23429c5ad 100644 --- a/src/Storages/Hive/StorageHive.cpp +++ b/src/Storages/Hive/StorageHive.cpp @@ -608,6 +608,10 @@ HiveFiles StorageHive::collectHiveFilesFromPartition( throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, "Partition value size not match, expect {}, but got {}", partition_names.size(), partition.values.size()); + if (!partition_key_expr) + throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, + "Hive metastore returned a partition for table {}.{}, but the table has no partition key", hive_database, hive_table); + /// Join partition values in CSV format WriteBufferFromOwnString wb; for (size_t i = 0; i < partition.values.size(); ++i) diff --git a/src/Storages/IStorage.h b/src/Storages/IStorage.h index 8c58fa27b6a5..e10d484de8b3 100644 --- a/src/Storages/IStorage.h +++ b/src/Storages/IStorage.h @@ -167,6 +167,9 @@ class IStorage : public std::enable_shared_from_this, public TypePromo virtual bool supportsSubcolumns() const { return false; } /// Returns true if storage supports optimizations of functions by reading subcolumns. virtual bool supportsOptimizationToSubcolumns() const { return supportsSubcolumns(); } + /// Returns true if the storage writes `Map` columns with the bucketed serialization, where a single key + /// can be read without reading the whole column. Gates the `m['key']` -> `m.key_` rewrite. + virtual bool hasBucketedMapSerialization() const { return false; } /// Returns true if the storage supports transactions for SELECT, INSERT and ALTER queries. /// Storage may throw an exception later if some query kind is not fully supported. diff --git a/src/Storages/IndicesDescription.cpp b/src/Storages/IndicesDescription.cpp index 9d716df4428b..6bdb804cd4c6 100644 --- a/src/Storages/IndicesDescription.cpp +++ b/src/Storages/IndicesDescription.cpp @@ -1,12 +1,20 @@ #include #include +#include #include +#include #include +#include +#include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -25,6 +33,122 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } +namespace +{ + +/// Calls `fn` with the value of each `preprocessor` / `postprocessor` argument of a text index. +template +void forEachTransformArgument(const ASTPtr & arguments, F && fn) +{ + for (const auto & child : arguments->children) + { + auto * func = child->as(); + if (!func || func->name != "equals" || !func->arguments || func->arguments->children.size() != 2) + continue; + + const auto * key = func->arguments->children[0]->as(); + if (key && (key->name() == "preprocessor" || key->name() == "postprocessor")) + fn(func->arguments->children[1]); + } +} + +/// Resolving a name runs the function's `create`, where `checkAccess` lives. Names only: building the +/// expression would report its type errors from here, not from the validator. +/// +/// A transform is analysed under the global context, so reading a table or a dictionary during analysis +/// would happen with full access. Such access depends on the arguments, not the function name, so +/// authorizing names cannot cover it, and these constructs are refused. Only here, where a user declares +/// the index: metadata stored by an older version must still load and stay alterable. +void checkFunctionsAsUser(const ASTPtr & ast, const ContextPtr & context) +{ + if (ast->as() || ast->as() || ast->as() || ast->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, "A text index transform expression must not contain subqueries or table references"); + + if (const auto * function = ast->as()) + { + if (functionIsInOrGlobalInOperator(function->name) && function->arguments && function->arguments->children.size() == 2) + { + const auto & set = function->arguments->children[1]; + if (set->as() || set->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not use a table or a set as the right side of `{}`", function->name); + } + + /// Only the name, which for `dictGet` and the like does not touch the dictionary; analysis would. + if (auto resolver = FunctionFactory::instance().tryGet(function->name, context); resolver && !resolver->isDeterministic()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not contain non-deterministic functions. Got `{}`", function->name); + } + + for (const auto & child : ast->children) + checkFunctionsAsUser(child, context); +} + +void checkTransformPermissions(const ASTPtr & arguments, const ContextPtr & context) +{ + forEachTransformArgument(arguments, [&](ASTPtr & argument) + { + auto expression = argument->clone(); + /// Inlines SQL UDF bodies, as `TreeRewriter` does, so a function used only inside one is seen. + if (!UserDefinedSQLFunctionFactory::instance().empty()) + UserDefinedSQLFunctionVisitor::visit(expression, context); + + checkFunctionsAsUser(expression, context); + }); +} + +} + +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context) +{ + if (index.type == TEXT_INDEX_NAME && index.arguments) + checkTransformPermissions(index.arguments, context); +} + +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index) +{ + if (index.type != TEXT_INDEX_NAME || !index.arguments) + return false; + + bool found = false; + forEachTransformArgument(index.arguments, [&](ASTPtr &) { found = true; }); + return found; +} + +[[noreturn]] static void throwTransformNeedsInitiatorUser() +{ + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "A text index preprocessor or postprocessor is authorized on the host the query is submitted to, and the " + "other hosts resolve it against their own schema without that user. Let every host run the query as the " + "initiating user instead: enable the server setting distributed_ddl_use_initial_user_and_roles on every " + "host, and set distributed_ddl_entry_format_version to at least {}", + DDLLogEntry::INITIATOR_USER_VERSION); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration) +{ + if (hasTextIndexPreOrPostProcessor(declaration)) + throwTransformNeedsInitiatorUser(); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index) +{ + if (hasTextIndexPreOrPostProcessor(index)) + throwTransformNeedsInitiatorUser(); +} + +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration) +{ + const auto * type = declaration.getType() ? declaration.getType()->as() : nullptr; + if (!type || Poco::toLower(type->name) != TEXT_INDEX_NAME || !type->arguments) + return false; + + bool found = false; + forEachTransformArgument(type->arguments, [&](ASTPtr &) { found = true; }); + return found; +} + IndexDescription::IndexDescription(const IndexDescription & other) : definition_ast(other.definition_ast ? other.definition_ast->clone() : nullptr) , expression_list_ast(other.expression_list_ast ? other.expression_list_ast->clone() : nullptr) diff --git a/src/Storages/IndicesDescription.h b/src/Storages/IndicesDescription.h index 207e3c76b154..5d1daf8affaa 100644 --- a/src/Storages/IndicesDescription.h +++ b/src/Storages/IndicesDescription.h @@ -16,6 +16,7 @@ namespace DB class ExpressionActions; using ExpressionActionsPtr = std::shared_ptr; +class ASTIndexDeclaration; /// Description of non-primary index for Storage struct IndexDescription @@ -86,6 +87,20 @@ struct IndexDescription bool isSimpleSingleColumnIndex() const; }; +/// Checks that the functions referenced by the text index preprocessor and postprocessor expressions +/// may run with the permissions of `context`, and that they read no table, set or dictionary. Call only +/// where a user declares an index, on the node they submitted it to; elsewhere these resolve under the +/// global context, and stored metadata is not re-checked. +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context); + +/// Refuses a transform when the other hosts of an `ON CLUSTER` query do not run it as the initiator. +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration); +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index); + +/// Whether the declaration is a text index with a `preprocessor` or a `postprocessor` argument. +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration); +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index); + /// All secondary indices in storage struct IndicesDescription : public std::vector, IHints<> { diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp index 5b0543026617..b0cf4a2bb646 100644 --- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp +++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp @@ -540,8 +540,7 @@ MergeTreeReadTaskColumns getReadTaskColumns( index_read_tasks, actions_settings, reader_settings.enable_multiple_prewhere_read_steps, - reader_settings.force_short_circuit_execution, - &storage_snapshot->metadata->getColumns()); + reader_settings.force_short_circuit_execution); for (const auto & step : prewhere_actions.steps) add_step(*step); diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index fd61defc239a..7c8f71bd5502 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -293,6 +293,7 @@ namespace MergeTreeSetting extern const MergeTreeSettingsMergeTreeStringSerializationVersion string_serialization_version; extern const MergeTreeSettingsMergeTreeNullableSerializationVersion nullable_serialization_version; extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version; + extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version_for_zero_level_parts; extern const MergeTreeSettingsUInt32 min_level_for_wide_part; extern const MergeTreeSettingsBool propagate_types_serialization_versions_to_nested_types; } @@ -894,6 +895,14 @@ bool MergeTreeData::supportsFinal() const || merging_params.mode == MergingParams::VersionedCollapsing; } +bool MergeTreeData::hasBucketedMapSerialization() const +{ + /// Inserted parts use the zero-level setting, merged parts the other one. + auto settings = getSettings(); + return (*settings)[MergeTreeSetting::map_serialization_version] == MergeTreeMapSerializationVersion::WITH_BUCKETS + || (*settings)[MergeTreeSetting::map_serialization_version_for_zero_level_parts] == MergeTreeMapSerializationVersion::WITH_BUCKETS; +} + static void checkKeyExpression(const ExpressionActions & expr, const Block & sample_block, const String & key_name, bool allow_nullable_key) { if (expr.hasArrayJoin()) @@ -10134,7 +10143,7 @@ QueryPipeline MergeTreeData::updateLightweightImpl(const MutationCommands & comm if (it != commands.end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Got unexpected command with type {} in lightweight update", it->type); - LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.toString(false)); + LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.ast(false)->formatForLogging()); MutationCommands commands_to_run; const auto & system_columns = getPatchPartSystemColumns(); @@ -10665,6 +10674,16 @@ StorageSnapshotPtr MergeTreeData::getStorageSnapshot(const StorageMetadataPtr & return cache->emplace(this, createStorageSnapshot(metadata_snapshot, query_context, false)).first->second; } +void MergeTreeData::discardSharedStorageSnapshot(const ContextPtr & query_context) const +{ + auto query_metadata_cache = query_context->getQueryMetadataCache(); + if (!query_metadata_cache) + return; + + auto [cache, lock] = query_metadata_cache->getStorageSnapshotCache(); + cache->erase(this); +} + StorageSnapshotPtr MergeTreeData::getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const { diff --git a/src/Storages/MergeTree/MergeTreeData.h b/src/Storages/MergeTree/MergeTreeData.h index 24c347de459d..c19156cfd60f 100644 --- a/src/Storages/MergeTree/MergeTreeData.h +++ b/src/Storages/MergeTree/MergeTreeData.h @@ -548,6 +548,8 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; + bool supportsTTL() const override { return true; } bool supportsColumnsWithDynamicStructure() const override { return true; } @@ -648,6 +650,11 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr /// The same as above but does not hold vector of data parts. StorageSnapshotPtr getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const override; + /// Removes the snapshot of this table from the query-scoped snapshot cache of + /// `enable_shared_storage_snapshot_in_query`, so that the next `getStorageSnapshot` in the query + /// takes a fresh one. Holders of the removed snapshot keep it. + void discardSharedStorageSnapshot(const ContextPtr & query_context) const; + /// Load the set of data parts from disk. Call once - immediately after the object is created. void loadDataParts(bool skip_sanity_checks, std::optional> expected_parts); diff --git a/src/Storages/MergeTree/MergeTreeDataWriter.cpp b/src/Storages/MergeTree/MergeTreeDataWriter.cpp index 0eda0376f9db..94aa1b21eb17 100644 --- a/src/Storages/MergeTree/MergeTreeDataWriter.cpp +++ b/src/Storages/MergeTree/MergeTreeDataWriter.cpp @@ -514,6 +514,11 @@ Block MergeTreeDataWriter::mergeBlock( span.addAttribute("clickhouse.rows", block_size); span.addAttribute("clickhouse.columns", header->columns()); + /// The block can lose all its rows before this point, e.g. when insert deduplication removes + /// duplicate rows of a materialized view block. Merging algorithms do not expect an empty input. + if (block_size == 0) + return *header; + auto get_merging_algorithm = [&]() -> std::shared_ptr { switch (merging_params.mode) diff --git a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp index 8d0538e64453..1964c89f521f 100644 --- a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace DB @@ -28,6 +29,7 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int CORRUPTED_DATA; extern const int ILLEGAL_COLUMN; extern const int INCORRECT_QUERY; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; @@ -87,9 +89,22 @@ void MergeTreeIndexGranuleBloomFilter::deserializeBinary(ReadBuffer & istr, Merg throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown index version {}.", version); readVarUInt(total_rows, istr); + if (total_rows == 0) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Bloom filter index granule has zero rows"); - static size_t atom_size = 8; - size_t bytes_size = (bits_per_row * total_rows + atom_size - 1) / atom_size; + static constexpr size_t atom_size = 8; + size_t bits_size = 0; + if (common::mulOverflow(bits_per_row, total_rows, bits_size) + || common::addOverflow(bits_size, atom_size - 1, bits_size)) + { + throw Exception( + ErrorCodes::CORRUPTED_DATA, + "Bloom filter index granule size overflows for {} rows and {} bits per row", + total_rows, + bits_per_row); + } + + size_t bytes_size = bits_size / atom_size; size_t read_size = bytes_size; for (auto & filter : bloom_filters) { diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp index db7da52fdaf7..a4e9b9a702a5 100644 --- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp +++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp @@ -1596,6 +1596,14 @@ void MergeTreeRangeReader::executePrewhereActionsAndFilterColumns(ReadResult & r /// Columns might be projected out. We need to store them here so that default columns can be evaluated later. Block additional_columns = block; + /// Carry over columns projected out at earlier steps: they may be needed + /// to evaluate defaults of columns missing in the part. + for (const auto & col : result.additional_columns) + { + if (!additional_columns.has(col.name)) + additional_columns.insert(col); + } + if (prewhere_info->actions) { const String dummy_column = addDummyColumnWithRowCount(block, result.num_rows); diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp index 147e7778daad..f20a455b4f2b 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp @@ -132,8 +132,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_, - LazyMaterializingRowsPtr lazy_materializing_rows_, - const ColumnsDescription * columns_) + LazyMaterializingRowsPtr lazy_materializing_rows_) : pool(std::move(pool_)) , algorithm(std::move(algorithm_)) , row_level_filter(row_level_filter_) @@ -145,8 +144,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( index_read_tasks_, actions_settings, reader_settings_.enable_multiple_prewhere_read_steps, - reader_settings_.force_short_circuit_execution, - columns_)) + reader_settings_.force_short_circuit_execution)) , reader_settings(reader_settings_) , result_header(transformHeader(pool->getHeader(), row_level_filter, prewhere_info)) , merge_tree_index_build_context(std::move(merge_tree_index_build_context_)) @@ -174,8 +172,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { PrewhereExprInfo prewhere_actions; @@ -208,7 +205,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( } if (prewhere_info && - (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution, columns))) + (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution))) { PrewhereExprStep prewhere_step { diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.h b/src/Storages/MergeTree/MergeTreeSelectProcessor.h index b044ff67fc1f..5909f164ed45 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.h +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.h @@ -108,8 +108,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_ = {}, - LazyMaterializingRowsPtr lazy_materializing_rows_ = {}, - const ColumnsDescription * columns_ = nullptr); + LazyMaterializingRowsPtr lazy_materializing_rows_ = {}); String getName() const; @@ -138,8 +137,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); void addPartLevelToChunk(bool add_part_level_) { add_part_level = add_part_level_; } diff --git a/src/Storages/MergeTree/MergeTreeSettings.cpp b/src/Storages/MergeTree/MergeTreeSettings.cpp index d6317adfe555..edb023a8c897 100644 --- a/src/Storages/MergeTree/MergeTreeSettings.cpp +++ b/src/Storages/MergeTree/MergeTreeSettings.cpp @@ -1171,7 +1171,7 @@ namespace ErrorCodes in the Keeper, the cache will update as soon as possible, so that we are able to filter the duplicated inserts in the memory. )", 0) \ - DECLARE(UInt64, max_replicated_logs_to_keep, 1000, R"( + DECLARE(NonZeroUInt64, max_replicated_logs_to_keep, 1000, R"( How many records may be in the ClickHouse Keeper log if there is inactive replica. An inactive replica becomes lost when when this number exceed. diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp index 52c20d4ee7d8..abf6b4c90f7e 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp @@ -1,8 +1,5 @@ #include -#include -#include - namespace DB { @@ -22,29 +19,10 @@ namespace struct NodeInfo { NameSet required_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column are placed into one step. - NameSet required_storage_columns; }; -/// Resolves a column name to its storage (physical) name. -/// For subcolumns like `map.key_k0`, returns `map`. -/// For regular columns, returns the name unchanged. -String resolveStorageColumnName(const String & column_name, const ColumnsDescription * columns) -{ - if (columns) - { - if (auto col = columns->tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, column_name)) - return col->getNameInStorage(); - } - return column_name; -} - /// Fills the list of required columns for a node in the DAG. -void fillRequiredColumns( - const ActionsDAG::Node * node, - std::unordered_map & nodes_info, - const ColumnsDescription * columns) +void fillRequiredColumns(const ActionsDAG::Node * node, std::unordered_map & nodes_info) { if (nodes_info.contains(node)) return; @@ -54,16 +32,14 @@ void fillRequiredColumns( if (node->type == ActionsDAG::ActionType::INPUT) { node_info.required_columns.insert(node->result_name); - node_info.required_storage_columns.insert(resolveStorageColumnName(node->result_name, columns)); return; } for (const auto & child : node->children) { - fillRequiredColumns(child, nodes_info, columns); + fillRequiredColumns(child, nodes_info); const auto & child_info = nodes_info[child]; node_info.required_columns.insert(child_info.required_columns.begin(), child_info.required_columns.end()); - node_info.required_storage_columns.insert(child_info.required_storage_columns.begin(), child_info.required_storage_columns.end()); } } @@ -226,8 +202,7 @@ bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { if (!prewhere_info) return true; @@ -243,37 +218,21 @@ bool tryBuildPrewhereSteps( std::unordered_map nodes_info; for (const auto & node : condition_nodes) { - fillRequiredColumns(node, nodes_info, columns); + fillRequiredColumns(node, nodes_info); } /// 3. Sort condition nodes by the number of columns used in them and the overall size of those columns /// TODO: not sorting for now because the conditions are already sorted by Where Optimizer - /// 4. Group adjacent conditions that read from the same set of physical storage columns into a single step. - /// Conditions on subcolumns of the same column (e.g. `map.key_k0` and `map.key_k1`) are placed into one group - /// when they appear next to each other in the condition list. - /// - /// Only adjacent conditions are merged to preserve the user's explicit PREWHERE evaluation order. - /// Non-adjacent conditions on the same storage column are kept in separate steps even though this - /// may cause redundant reads, because the user may have intentionally interleaved a guard predicate - /// (e.g. `PREWHERE tags['safe'] != '' AND value > 0 AND toUInt64(tags['unsafe']) > 0` — the - /// `value > 0` step must filter rows before evaluating the potentially-throwing conversion). - /// - /// For the WHERE-to-PREWHERE path this is not a problem: `MergeTreeWhereOptimizer` already groups - /// conditions by their physical storage columns, so subcolumns of the same column arrive here adjacent. + /// 4. Group conditions with the same set of columns into a single read/compute step std::vector> condition_groups; for (const auto & node : condition_nodes) { const auto & node_info = nodes_info[node]; - if (!condition_groups.empty() - && nodes_info[condition_groups.back().front()].required_storage_columns == node_info.required_storage_columns) - { - condition_groups.back().push_back(node); - } + if (!condition_groups.empty() && nodes_info[condition_groups.back().back()].required_columns == node_info.required_columns) + condition_groups.back().push_back(node); /// Add to the last group else - { - condition_groups.push_back({node}); - } + condition_groups.push_back({node}); /// Start new group } /// 5. Build DAGs for each step diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h index 4d3845a7e048..833e6f506992 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h @@ -13,13 +13,10 @@ namespace DB { -class ColumnsDescription; - bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index dbfc28547453..39df2ecbc8ef 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -338,17 +338,6 @@ void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const RPNBuilderTree cond.columns_size = getColumnsSize(cond.table_columns); - /// Resolve each column to its physical storage name so that subcolumns - /// of the same column (e.g. `map.key_k0`, `map.key_k1`) share one group. - const auto & storage_columns_description = storage_metadata->getColumns(); - for (const auto & col : cond.table_columns) - { - if (auto resolved = storage_columns_description.tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, col)) - cond.table_storage_columns.insert(resolved->getNameInStorage()); - else - cond.table_storage_columns.insert(col); - } - cond.viable = !has_invalid_column /// Condition depend on some column. Constant expressions are not moved. @@ -495,20 +484,17 @@ std::optional MergeTreeWhereOptimizer:: } }; - /// Move condition and all other conditions that depend on the same set of physical storage columns. - /// Grouping by storage columns (rather than the exact column set) keeps subcolumns of the - /// same column (e.g. `map.key_k0` and `map.key_k1`) in one group, so they are moved to - /// PREWHERE together and arrive adjacent for the prewhere-splitting step. + /// Move condition and all other conditions depend on the same set of columns. auto move_condition = [&](Conditions::iterator cond_it) { move_to_prewhere_conditions(cond_it); total_size_of_moved_conditions += cond_it->columns_size; total_number_of_moved_columns += cond_it->table_columns.size(); - /// Move all other viable conditions that depend on the same set of storage columns. + /// Move all other viable conditions that depend on the same set of columns. for (auto jt = where_conditions.begin(); jt != where_conditions.end();) { - if (jt->viable && jt->table_storage_columns == cond_it->table_storage_columns) + if (jt->viable && jt->columns_size == cond_it->columns_size && jt->table_columns == cond_it->table_columns) { move_to_prewhere_conditions(jt++); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h index bf2b97b3640d..b0a8bfdb2173 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h @@ -69,10 +69,6 @@ class MergeTreeWhereOptimizer : private boost::noncopyable UInt64 columns_size = 0; NameSet table_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column - /// (e.g. `map.key_k0` and `map.key_k1`) are grouped and moved to PREWHERE together. - NameSet table_storage_columns; /// Can condition be moved to prewhere? bool viable = false; diff --git a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp index 3f8edc6d4cc1..c94d1390bf19 100644 --- a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp +++ b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp @@ -144,7 +144,7 @@ ReplicatedMergeMutateTaskBase::PrepareResult MutateFromLogEntryTask::prepare() Strings mutation_ids; commands = std::make_shared(storage.queue.getMutationCommands(source_part, new_part_info.mutation, mutation_ids)); LOG_TRACE(log, "Mutating part {} with mutation commands from {} mutations ({}): {}", - entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->toString(true)); + entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->ast(true)->formatForLogging()); /// mutation_ids can be empty here. mutation_ids_for_log = mutation_ids; diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index 3735c427cffc..a2490c3ec29e 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -12,7 +12,7 @@ namespace MergeTreeSetting { extern const MergeTreeSettingsUInt64 finished_mutations_to_keep; extern const MergeTreeSettingsSeconds lock_acquire_timeout_for_background_operations; - extern const MergeTreeSettingsUInt64 max_replicated_logs_to_keep; + extern const MergeTreeSettingsNonZeroUInt64 max_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 min_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 replicated_deduplication_window; extern const MergeTreeSettingsUInt64 replicated_deduplication_window_for_async_inserts; diff --git a/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp new file mode 100644 index 000000000000..007d155521ef --- /dev/null +++ b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include +#include + +#include + +using namespace DB; + +namespace DB::ErrorCodes +{ + extern const int CORRUPTED_DATA; +} + +namespace +{ + +String encodeRowCount(size_t row_count) +{ + WriteBufferFromOwnString out; + writeVarUInt(row_count, out); + return out.str(); +} + +void expectCorruptedRowCount(size_t bits_per_row, size_t row_count) +{ + MergeTreeIndexGranuleBloomFilter granule(bits_per_row, 3, 1); + String encoded = encodeRowCount(row_count); + ReadBufferFromString in(encoded); + + try + { + granule.deserializeBinary(in, 1); + FAIL() << "Expected a corrupted Bloom-filter granule to be rejected"; + } + catch (const Exception & exception) + { + EXPECT_EQ(exception.code(), ErrorCodes::CORRUPTED_DATA); + } +} + +} + +TEST(MergeTreeIndexBloomFilterTest, DeserializesValidGranule) +{ + String encoded = encodeRowCount(1); + encoded.append(sizeof(BloomFilter::UnderType), '\0'); + + MergeTreeIndexGranuleBloomFilter granule(12, 3, 1); + ReadBufferFromString in(encoded); + + EXPECT_NO_THROW(granule.deserializeBinary(in, 1)); + EXPECT_FALSE(granule.empty()); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsZeroRowGranule) +{ + expectCorruptedRowCount(12, 0); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsFilterSizeOverflow) +{ + constexpr size_t bits_per_row = 12; + constexpr size_t overflowing_rows = std::numeric_limits::max() / bits_per_row + 1; + expectCorruptedRowCount(bits_per_row, overflowing_rows); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsRoundedFilterSizeOverflow) +{ + expectCorruptedRowCount(1, std::numeric_limits::max()); +} diff --git a/src/Storages/ObjectStorage/Azure/Configuration.cpp b/src/Storages/ObjectStorage/Azure/Configuration.cpp index 574921743d36..03767ddf2d66 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.cpp +++ b/src/Storages/ObjectStorage/Azure/Configuration.cpp @@ -44,7 +44,6 @@ namespace ErrorCodes { extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; - extern const int LOGICAL_ERROR; } const std::unordered_set required_configuration_keys = { @@ -69,7 +68,7 @@ const std::unordered_set optional_configuration_keys = { void StorageAzureConfiguration::check(ContextPtr context) { - auto url = Poco::URI(connection_params.getConnectionURL()); + auto url = Poco::URI(connection_params.getConnectionURLWithoutQuery()); context->getGlobalContext()->getRemoteHostFilter().checkURL(url); StorageObjectStorageConfiguration::check(context); } @@ -163,9 +162,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url if (pos_container != std::string::npos) { - String container_blob_path = connection_url.substr(pos_container+5); - connection_url = connection_url.substr(0,pos_container+4); - container_name = connection_url.substr(pos_container+4); + size_t host_end = pos_container + suffix.size(); + String container_blob_path = host_end < connection_url.size() ? connection_url.substr(host_end + 1) : ""; + connection_url.resize(host_end); auto pos_blob_path = container_blob_path.find('/'); if (pos_blob_path != std::string::npos) @@ -185,9 +184,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url auto pos_net = connection_url.find(suffix); if (pos_slash == std::string::npos || pos_at == std::string::npos|| pos_dot == std::string::npos || pos_net == std::string::npos - || pos_at-pos_slash-3 <= 0 || pos_dot-pos_at-1 <= 0) + || pos_at <= pos_slash + 3 || pos_dot <= pos_at + 1) { - throw Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect url format for a abfss url {}", connection_url); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Incorrect url format for a abfss url {}", connection_url); } auto container_name_abfss = connection_url.substr(pos_slash+3, pos_at-pos_slash-3); auto name = connection_url.substr(pos_at+1, pos_dot-pos_at-1); diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 3a346c1d28f2..08aa8818f4a3 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -106,7 +106,7 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration void setPaths(const Paths & paths) override { blobs_paths = paths; } String getNamespace() const override { return connection_params.getContainer(); } - String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURL()) / connection_params.getContainer(); } + String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURLWithoutQuery()) / connection_params.getContainer(); } StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; void check(ContextPtr context) override; diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp index e7b956fd20c6..28c9ba764fd3 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp @@ -51,6 +51,7 @@ try } metadata = manifest_file_reader->metadata(); + bytes_read = buffer->count(); parsed_column = std::move(columns[0]); parsed_column_data_type = std::dynamic_pointer_cast(data_type); parsed_manifest_file_entries.resize(parsed_column->size()); diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h index 2cf4c8a61d61..997c587f1880 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h @@ -45,6 +45,8 @@ class AvroForIcebergDeserializer std::map> metadata; + size_t bytes_read = 0; + /// Shared mutex to protect mutable cache members for thread safety mutable SharedMutex cache_mutex; @@ -71,6 +73,9 @@ class AvroForIcebergDeserializer size_t rows() const; + /// The constructor consumes the whole file, so this is its size on storage. + size_t bytesRead() const { return bytes_read; } + /// Allow to access avro paths like "a.b.c" bool hasPath(const std::string & path) const; DB::TypeIndex getTypeForPath(const std::string & path) const; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp index 3e9dd4058b3f..cac54224ac17 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp @@ -90,6 +90,30 @@ Field parseFieldFromString(const String & value, DB::DataTypePtr data_type) namespace DeltaLake { +namespace +{ + +/// A data file with the size its `add` action records. +struct DataObjectInfo : public DB::ObjectInfo +{ + DataObjectInfo(std::string path_, int64_t size_) + : DB::ObjectInfo(DB::RelativePathWithMetadata(std::move(path_))) + , size(size_) + { + } + + std::optional getFileSizeHint() const override + { + if (size > 0) + return static_cast(size); + return std::nullopt; + } + + const int64_t size; +}; + +} + class TableSnapshot::Iterator final : public DB::IObjectIterator { private: @@ -120,7 +144,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator const TableSchema & table_schema_, const DB::NameToNameMap & physical_names_map_, const DB::Names & partition_columns_, - DB::ObjectStoragePtr object_storage_, const DB::ActionsDAG * filter_, DB::IDataLakeMetadata::FileProgressCallback callback_, size_t list_batch_size_, @@ -135,7 +158,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator , read_schema(read_schema_) , expression_schema(table_schema_) , partition_columns(partition_columns_) - , object_storage(object_storage_) , callback(callback_) , list_batch_size(list_batch_size_) , log(log_) @@ -437,13 +459,9 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator } parseDVHandle(*scan_item, object); - object->setObjectMetadata(object_storage->getObjectMetadata(object->getPath(), /*with_tags=*/ false)); if (callback) - { - chassert(object->getObjectMetadata()); - callback(DB::FileProgress(0, object->getObjectMetadata()->size_bytes)); - } + callback(DB::FileProgress(0, object->getFileSizeHint().value_or(0))); return object; } } @@ -597,7 +615,7 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator std::string full_path = DB::resolvePathInsideTable( context->getDataPath(), DB::unescapeForFileName(KernelUtils::fromDeltaString(path))); - auto object = std::make_shared(DB::RelativePathWithMetadata(std::move(full_path))); + auto object = std::make_shared(std::move(full_path), size); object->data_lake_metadata.emplace(); LOG_TEST( @@ -641,7 +659,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator DB::NamesAndTypesList read_schema; DB::NamesAndTypesList expression_schema; DB::Names partition_columns; - const DB::ObjectStoragePtr object_storage; const DB::IDataLakeMetadata::FileProgressCallback callback; const size_t list_batch_size; const LoggerPtr log; @@ -966,7 +983,6 @@ DB::ObjectIterator TableSnapshot::iterate( schema->table_schema, schema->physical_names_map, schema->partition_columns, - object_storage, filter_dag, callback, list_batch_size, diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp index 94c263c0e7e7..dc22ef8c5954 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp @@ -45,18 +45,13 @@ UInt64 getCurrentTime() return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } -void exportTable( - std::shared_ptr table, +void exportRecordBatch( + const arrow::RecordBatch & batch, ffi::FFI_ArrowArray & array, ffi::FFI_ArrowSchema & schema) { - auto batch = table->CombineChunksToBatch(); - if (!batch.ok()) - throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, - "Failed to create chunks batch: {}", batch.status().ToString()); - arrow::Status status = arrow::ExportRecordBatch( - **batch, + batch, reinterpret_cast(&array), reinterpret_cast(&schema)); @@ -230,30 +225,61 @@ void WriteTransaction::commit(const std::vector & files) LOG_TEST(log, "Will commit {} files", files.size()); auto write_metadata = getWriteMetadata(files, log); - ffi::FFI_ArrowArray array; - ffi::FFI_ArrowSchema schema; - SCOPE_EXIT({ - if (schema.release) - schema.release(&schema); - }); - exportTable(write_metadata, array, schema); - - KernelEngineData engine_data; - try + /// Metadata too large for one Arrow record batch comes back as several table chunks. Recombining them + /// would hit the same 32-bit offset limit, so each record batch is added to the transaction on its own. + /// `TableBatchReader` yields nothing for an empty table, which still has to reach the kernel as before. + arrow::RecordBatchVector batches; + if (write_metadata->num_rows() == 0) { - /// Takes ownership of `array` (but not`schema`) if successfully called. - engine_data = DeltaLake::KernelUtils::unwrapResult( - ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), - "get_engine_data"); + auto empty_batch = arrow::RecordBatch::MakeEmpty(write_metadata->schema()); + if (!empty_batch.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to create an empty record batch: {}", empty_batch.status().ToString()); + batches.push_back(*std::move(empty_batch)); } - catch (...) + else { - if (array.release) - array.release(&array); - throw; + arrow::TableBatchReader batch_reader(*write_metadata); + while (true) + { + std::shared_ptr batch; + arrow::Status read_status = batch_reader.ReadNext(&batch); + if (!read_status.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to read a record batch: {}", read_status.ToString()); + if (!batch) + break; + batches.push_back(std::move(batch)); + } } - ffi::add_files(transaction.get(), engine_data.release()); + for (const auto & batch : batches) + { + ffi::FFI_ArrowArray array{}; + ffi::FFI_ArrowSchema schema{}; + SCOPE_EXIT({ + if (schema.release) + schema.release(&schema); + }); + exportRecordBatch(*batch, array, schema); + + KernelEngineData engine_data; + try + { + /// Takes ownership of `array` (but not`schema`) if successfully called. + engine_data = DeltaLake::KernelUtils::unwrapResult( + ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), + "get_engine_data"); + } + catch (...) + { + if (array.release) + array.release(&array); + throw; + } + + ffi::add_files(transaction.get(), engine_data.release()); + } auto version = DeltaLake::KernelUtils::unwrapResult(ffi::commit(transaction.release(), engine.get()), "commit"); LOG_TEST(log, "Commit version: {}", version); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp index c0072e3e576b..74fcc2accefb 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp @@ -182,8 +182,7 @@ std::optional SingleThreadIcebergKeysIterator::ne persistent_components, local_context, log, - mle.manifest_file_path, - mle.manifest_file_byte_size); + mle.manifest_file_path); current_manifest_file_iterator = Iceberg::ManifestFileIterator::create( manifest_file_cacheable_part.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h index 44309f94e60a..63479720f676 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h @@ -74,7 +74,7 @@ struct IcebergMetadataFilesCacheCell : private boost::noncopyable /// - manifest list consists of cache keys which will retrieve the manifest file from cache [file_path --> ManifestFileCacheKeys] /// - manifest file [file_path --> Iceberg::ManifestFileCacheableInfo] std::variant cached_element; - Int64 memory_bytes; + size_t memory_bytes; explicit IcebergMetadataFilesCacheCell(String && metadata_json_str) : cached_element(std::move(metadata_json_str)) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp index e8226dadcd76..fd279ca1936a 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp @@ -74,6 +74,9 @@ void MultipleFileWriter::finalize() output_format->finalize(); buffer->finalize(); total_bytes += buffer->count(); + + /// A finished format can still hold resources: a Parquet one keeps its idle encoder threads. + release(); } void MultipleFileWriter::release() diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp index 5039abab707a..859b46f2b219 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp @@ -259,6 +259,8 @@ static std::optional writeDataFiles( delete_data_writers[partition_key]->finalize(); delete_data_write_buffers[partition_key]->finalize(); delete_data_result[partition_key].total_bytes = static_cast(delete_data_write_buffers[partition_key]->count()); + delete_data_writers[partition_key].reset(); + delete_data_write_buffers[partition_key].reset(); } } @@ -317,6 +319,8 @@ static std::optional writeDataFiles( update_data_writers[partition_key]->finalize(); update_data_write_buffers[partition_key]->finalize(); update_data_result[partition_key].total_bytes = static_cast(update_data_write_buffers[partition_key]->count()); + update_data_writers[partition_key].reset(); + update_data_write_buffers[partition_key].reset(); } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp index b65109e9f697..d342906b3302 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp @@ -69,8 +69,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size) + const String & filename) { auto log_level = local_context->getSettingsRef()[Setting::iceberg_metadata_log_level].value; @@ -90,7 +89,8 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( auto manifest_file_deserializer = std::make_unique( std::move(buffer), filename, getFormatSettings(local_context)); - return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), bytes_size}; + const size_t manifest_file_bytes = manifest_file_deserializer->bytesRead(); + return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), manifest_file_bytes}; }; if (use_iceberg_metadata_cache && persistent_table_components.table_uuid.has_value()) @@ -115,8 +115,7 @@ Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesH persistent_table_components, local_context, log, - cache_key.manifest_file_path, - static_cast(cache_key.manifest_file_byte_size)); + cache_key.manifest_file_path); auto iterator = Iceberg::ManifestFileIterator::create( cacheable_info.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h index ac5a7f7bc06e..5df057a2bb49 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h @@ -28,8 +28,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size); + const String & filename); /// Creates a fully initialized ManifestFileIterator from a cache key. /// All entries are drained so that aggregate methods (e.g. getRowsCountInAllFilesExcludingDeleted) diff --git a/src/Storages/ObjectStorage/IObjectIterator.h b/src/Storages/ObjectStorage/IObjectIterator.h index 83c645e915fd..1b191139ce67 100644 --- a/src/Storages/ObjectStorage/IObjectIterator.h +++ b/src/Storages/ObjectStorage/IObjectIterator.h @@ -41,6 +41,7 @@ struct ObjectInfo virtual size_t fileSizeInArchive() const { throw Exception(ErrorCodes::LOGICAL_ERROR, "Not an archive"); } virtual std::string getPathOrPathToArchiveIfArchive() const; virtual std::optional getFileFormat() const { return std::nullopt; } + virtual std::optional getFileSizeHint() const { return std::nullopt; } std::optional getObjectMetadata() const { return relative_path_with_metadata.metadata; } void setObjectMetadata(const ObjectMetadata & metadata) { relative_path_with_metadata.metadata = metadata; } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp index 2acdbf6da675..1d4de8b623cd 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp @@ -95,6 +95,15 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + String getObjectStorageHash(const IObjectStorage & object_storage) + { + const String description = object_storage.getDescription(); + return sipHash128String(description.substr(0, description.find('?')) + '\0' + object_storage.getObjectsNamespace()); + } +} + StorageObjectStorageSource::StorageObjectStorageSource( String name_, ObjectStoragePtr object_storage_, @@ -536,7 +545,7 @@ void StorageObjectStorageSource::addNumRowsToCache(const ObjectInfo & object_inf schema_cache.addNumRows(cache_key, num_rows); } -StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader() +StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader(bool prefetch_input_format) { return createReader( 0, @@ -551,7 +560,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade max_block_size, parser_shared_resources, format_filter_info, - need_only_count); + need_only_count, + prefetch_input_format); } StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader( @@ -567,7 +577,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count) + bool need_only_count, + bool prefetch_input_format) { ObjectInfoPtr object_info; auto query_settings = configuration->getQuerySettings(context_); @@ -832,6 +843,9 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade if (need_only_count) input_format->needOnlyCount(); + if (prefetch_input_format) + input_format->prefetch(); + builder.init(Pipe(input_format)); configuration->addDeleteTransformers(object_info, builder, format_settings, parser_shared_resources, context_); @@ -977,7 +991,7 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade std::future StorageObjectStorageSource::createReaderAsync() { - return create_reader_scheduler([=, this] { return createReader(); }, Priority{}); + return create_reader_scheduler([=, this] { return createReader(/* prefetch_input_format */ true); }, Priority{}); } std::unique_ptr createReadBuffer( @@ -1099,6 +1113,7 @@ std::unique_ptr createReadBuffer( else { SipHash hash; + hash.update(getObjectStorageHash(*object_storage)); hash.update(object_info.getPath()); hash.update(object_info.metadata->etag); @@ -1147,7 +1162,9 @@ std::unique_ptr createReadBuffer( if (use_page_cache) { - PageCacheKey key = {.path = "s3:" + object_info.getPath(), .file_version = "etag:" + object_info.metadata->etag}; + PageCacheKey key = { + .path = fmt::format("s3:{}:{}", getObjectStorageHash(*object_storage), object_info.getPath()), + .file_version = "etag:" + object_info.metadata->etag}; impl = std::make_unique(key, effective_read_settings.page_cache, std::move(impl), modified_read_settings); } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.h b/src/Storages/ObjectStorage/StorageObjectStorageSource.h index 5cbe931a047e..375187276c51 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.h @@ -136,9 +136,10 @@ class StorageObjectStorageSource : public ISource size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count); + bool need_only_count, + bool prefetch_input_format = false); - ReaderHolder createReader(); + ReaderHolder createReader(bool prefetch_input_format = false); std::future createReaderAsync(); diff --git a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h index e9d9bd0f7414..a338ae7dead0 100644 --- a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h +++ b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h @@ -1,7 +1,7 @@ #pragma once #include #include -#include +#include #include namespace AzureQueue @@ -20,10 +20,7 @@ static inline std::unordered_map SETTINGS_TO_HIDE = std::string masked_value; if (!value.tryGet(masked_value)) return {}; - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - RE2::Replace(&masked_value, account_key_pattern, "AccountKey=[HIDDEN]\\1"); - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - RE2::Replace(&masked_value, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1"); + DB::maskAzureConnectionStringSecrets(masked_value); return fmt::format("'{}'", masked_value); }}, }; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp new file mode 100644 index 000000000000..e845fa34a6c0 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -0,0 +1,119 @@ +#include + +#include "config.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include + + +namespace DB +{ + +namespace +{ + +enum class MoveDestinationKind : uint8_t +{ + S3, + Azure, +}; + +std::optional getMoveDestinationKind(std::string_view name) +{ + /// The prefix is accepted for every queue setting, see `normalizeSetting` in `StorageObjectStorageQueue.cpp`. + static constexpr std::string_view legacy_prefix = "s3queue_"; + if (name.starts_with(legacy_prefix)) + name.remove_prefix(legacy_prefix.size()); + + if (name == "after_processing_move_uri") + return MoveDestinationKind::S3; + if (name == "after_processing_move_connection_string" || name == "after_processing_move_container") + return MoveDestinationKind::Azure; + return std::nullopt; +} + +AccessTypeObjects::Source getAccessSource(MoveDestinationKind kind) +{ + switch (kind) + { + case MoveDestinationKind::S3: + return AccessTypeObjects::Source::S3; + case MoveDestinationKind::Azure: + return AccessTypeObjects::Source::AZURE; + } +} + +/// A value that is not a `String` is never empty here: it is checked like a destination that cannot be parsed. +bool isEmptyValue(const Field & value) +{ + return value.getType() == Field::Types::String && value.safeGet().empty(); +} + +/// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +{ + const bool sets_destination = std::ranges::any_of( + changes, + [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); + if (!sets_destination) + return {}; + + /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only + /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against + /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). + const auto source = getAccessSource(table_kind); + AccessRightsElements res; + res.emplace_back(AccessType::WRITE, AccessTypeObjects::toStringSource(source)); + return res; +} + +} + +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::S3); +} + +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); +} + +void checkObjectStorageQueueS3MoveDestinationHost( + [[maybe_unused]] const String & move_uri, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AWS_S3 + if (!move_uri.empty()) + S3::URI(move_uri).checkRemoteHostFilter(filter); +#endif +} + +void checkObjectStorageQueueAzureMoveDestinationHost( + [[maybe_unused]] const String & move_connection_string, + [[maybe_unused]] const String & move_container, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AZURE_BLOB_STORAGE + if (!move_connection_string.empty()) + { + AzureBlobStorage::ConnectionParams connection_params; + AzureBlobStorage::processURL(move_connection_string, move_container, connection_params.endpoint, connection_params.auth_method); + /// Without the query: a connection string can carry a SAS, which the message of `checkURL` must not show. + String url = connection_params.getConnectionURL(); + url = url.substr(0, url.find_first_of("?#")); + filter.checkURL(Poco::URI(url)); + } +#endif +} + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h new file mode 100644 index 000000000000..40601b4b1145 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +namespace DB +{ + +class RemoteHostFilter; + +/// The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +/// `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads every processed file +/// with its own source credentials and writes it to the destination. So setting the destination needs +/// `WRITE` on the `S3` (or `AZURE`) source without a URL filter: the move writes keys built from +/// `after_processing_move_prefix` and the source keys, not from the URI, so a filtered grant cannot authorize them. +/// For `ALTER` it also needs `SELECT` on the table, because the creator of the table, not the user of the `ALTER`, +/// supplied the source and its credentials. + +/// The `StorageFactory::GetExportAccessFn` of `S3Queue` and `AzureQueue`: unfiltered `WRITE` if a setting moves files outside +/// the source bucket or container. Only these settings choose such a destination: `after_processing_move_uri` for S3, +/// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy +/// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. +/// An empty value disables the move destination, so it is not a destination and needs no grant. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); + +/// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. +/// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. +/// Does nothing when `move_uri` is empty. +void checkObjectStorageQueueS3MoveDestinationHost(const String & move_uri, const RemoteHostFilter & filter); + +/// The same for a move to another Azure container (see `StorageAzureConfiguration::check`). +/// Does nothing when `move_connection_string` is empty. +void checkObjectStorageQueueAzureMoveDestinationHost( + const String & move_connection_string, const String & move_container, const RemoteHostFilter & filter); + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp index cd48a45926ea..a89c5ec4923a 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,11 @@ namespace S3AuthSetting extern const S3AuthSettingsString secret_access_key; } +namespace S3RequestSetting +{ + extern const S3RequestSettingsBool allow_native_copy; +} + #endif namespace ErrorCodes @@ -285,6 +291,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move S3 objects"); } + /// The settings are checked at `CREATE` and `ALTER` too. This is defense in depth for a table that was created before + /// those checks existed, or before the list of allowed hosts was tightened. If it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueS3MoveDestinationHost(move_uri, getContext()->getRemoteHostFilter()); + if (auto * s3_storage = dynamic_cast(object_storage.get()); s3_storage != nullptr) { auto src_client = s3_storage->getS3StorageClient(); @@ -304,6 +314,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object /* for_disk_s3 */ false ); auto dst_uri = S3::URI(move_uri); + /// Native copy sends `CopyObject` through the source client, so it writes to the source endpoint. That is the checked + /// destination only if both clients use the same endpoint, otherwise use the buffered copy, which uploads with `dst_client`. + if (src_client->getInitialEndpoint() != dst_client->getInitialEndpoint()) + s3_settings->request_settings[S3RequestSetting::allow_native_copy] = false; auto read_settings = getReadSettings(); const auto read_settings_to_use = s3_storage->patchSettings(read_settings); auto scheduler = threadPoolCallbackRunnerUnsafe( @@ -391,6 +405,9 @@ void ObjectStorageQueuePostProcessor::moveAzureBlobs(const StoredObjects & objec throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move Azure blobs"); } + /// See the comment in `moveS3Objects`: if it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, getContext()->getRemoteHostFilter()); + if (auto * azure_storage = dynamic_cast(object_storage.get()); azure_storage != nullptr) { auto contextPtr = getContext(); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp index 643418d037d7..45987c8046d3 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp @@ -5,7 +5,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -58,14 +60,14 @@ namespace ErrorCodes DECLARE(String, partition_component, "", "Name of the capture group from partition_regex to use as partition key. Required when using partitioning_mode='regex'. Example: 'hostname'", 0) \ DECLARE(ObjectStorageQueueBucketingMode, bucketing_mode, ObjectStorageQueueBucketingMode::PATH, "Bucketing strategy for Ordered mode parallel processing: PATH (hash full file path, default), PARTITION (hash partition key, requires partitioning_mode != NONE)", 0) \ DECLARE(UInt32, after_processing_retries, 10, "Number of retries for the after_processing action before giving up", 0) \ - DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to", 0) \ + DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to. Setting it requires the `WRITE` grant on the `S3` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The URL must be allowed by `remote_url_allow_hosts`", 0) \ DECLARE(String, after_processing_move_prefix, "", "Path prefix to move processed files to", 0) \ DECLARE(String, after_processing_tag_key, "", "Tag key to tag processed files in the storage", 0) \ DECLARE(String, after_processing_tag_value, "", "Tag value to tag processed files in the storage", 0) \ DECLARE(String, after_processing_move_access_key_id, "", "S3 Access Key ID accompanying after_processing_move_uri", 0) \ DECLARE(String, after_processing_move_secret_access_key, "", "S3 Secret Access Key accompanying after_processing_move_uri", 0) \ - DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to", 0) \ - DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string", 0) \ + DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The endpoint must be allowed by `remote_url_allow_hosts`", 0) \ + DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table", 0) \ DECLARE(Bool, use_hive_partitioning, false, "DEPRECATED: Use partitioning_mode='hive' instead. Whether path contains hive partitioning and this engine should process such files with a separate processed files tracking per partition.", 0) \ #define LIST_OF_OBJECT_STORAGE_QUEUE_SETTINGS(M, ALIAS) \ @@ -107,7 +109,8 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const + const StorageObjectStorageQueue & storage, + bool display_secrets) const { MutableColumns & res_columns = params.res_columns; auto settings_changes_ast = storage.getInMemoryMetadataPtr()->settings_changes; @@ -127,6 +130,23 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( { return StorageObjectStorageQueue::isSettingChangeable(setting_name, (*this)[ObjectStorageQueueSetting::mode]); }; + /// Hides what `SHOW CREATE TABLE` hides. A secret is hidden whole, as its masker renders SQL. + auto render_value = [&](const std::string & setting_name, const Field & value) -> String + { + static constexpr std::string_view hidden_secret = "[HIDDEN]"; + if (!display_secrets) + { + for (const auto * settings_to_hide : {&S3Queue::SETTINGS_TO_HIDE, &AzureQueue::SETTINGS_TO_HIDE}) + { + auto it = settings_to_hide->find(setting_name); + if (it == settings_to_hide->end()) + continue; + if (auto masked = it->second(value); masked && masked->contains(hidden_secret)) + return String(hidden_secret); + } + } + return convertFieldToString(value); + }; for (const auto & change : impl->all()) { @@ -135,7 +155,7 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( res_columns[i++]->insert(database_name); res_columns[i++]->insert(table_name); res_columns[i++]->insert(name); - res_columns[i++]->insert(convertFieldToString(change.getValue())); + res_columns[i++]->insert(render_value(name, change.getValue())); res_columns[i++]->insert(change.getTypeName()); res_columns[i++]->insert(is_changed(name)); res_columns[i++]->insert(change.getDescription()); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h index dad7144540bc..37c784da6d07 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h @@ -61,7 +61,8 @@ struct ObjectStorageQueueSettings MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const; + const StorageObjectStorageQueue & storage, + bool display_secrets) const; void loadFromQuery(ASTStorage & storage_def, bool is_attach, const StorageID & storage_id); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 10e4f39ec00e..718da1abc8cf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include @@ -22,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -140,9 +144,26 @@ namespace ErrorCodes namespace { + /// The move uses only the destination of the storage type of the table, so only that one is checked. + void checkMoveDestinationHost( + ObjectStorageType type, + const String & move_uri, + const String & move_connection_string, + const String & move_container, + const RemoteHostFilter & filter) + { + if (type == ObjectStorageType::S3) + checkObjectStorageQueueS3MoveDestinationHost(move_uri, filter); + else if (type == ObjectStorageType::Azure) + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, filter); + } + void validateSettings( ObjectStorageQueueSettings & queue_settings, - bool is_attach) + ObjectStorageType type, + const RemoteHostFilter & remote_host_filter, + bool is_attach, + bool is_loading_from_existing_metadata) { if (!is_attach && !queue_settings[ObjectStorageQueueSetting::mode].changed) { @@ -201,6 +222,21 @@ namespace "Move of processed objects requires specifying target bucket/container or prefix"); } } + + /// The host filter of `configuration` covers the source only, so the move destination is checked here. + /// It is checked whenever it is set, not only for `after_processing = 'move'`: otherwise a table created with + /// `after_processing = 'keep'` and a destination that is not allowed could be switched to `move` by an `ALTER` + /// that does not change the destination. A table loaded from existing metadata must never fail to load. + if (!is_loading_from_existing_metadata) + { + checkMoveDestinationHost( + type, + queue_settings[ObjectStorageQueueSetting::after_processing_move_uri].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_connection_string].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_container].value, + remote_host_filter); + } + if (queue_settings[ObjectStorageQueueSetting::after_processing] == ObjectStorageQueueAction::TAG) { if (queue_settings[ObjectStorageQueueSetting::after_processing_tag_key].toString().empty()) @@ -307,7 +343,7 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( } const bool is_attach = mode > LoadingStrictnessLevel::CREATE; - validateSettings(*queue_settings_, is_attach); + validateSettings(*queue_settings_, type, context_->getRemoteHostFilter(), is_attach, isLoadingFromExistingMetadata(mode)); object_storage = configuration->createObjectStorage(context_, /* is_readonly */true, std::nullopt); FormatFactory::instance().checkFormatName(configuration->format); @@ -413,12 +449,18 @@ void StorageObjectStorageQueue::startup() /// Create metadata in keeper if it does not exits yet. /// Create a persistent node for the table under /registry node. bool created_new_metadata = false; - files_metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( + /// Keep a local handle: the factory call and the startup below do keeper I/O, which must not + /// run under `mutex`. + auto metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( zookeeper_name, zk_path, std::move(temp_metadata), getStorageID(), created_new_metadata); + { + std::lock_guard lock(mutex); + files_metadata = metadata; + } /// Register the metadata in startup(), unregister in shutdown. /// (If startup is never called, shutdown also won't be called.) @@ -435,6 +477,7 @@ void StorageObjectStorageQueue::startup() /* is_drop */created_new_metadata, /* keep_data_in_keeper */false); + std::lock_guard lock(mutex); files_metadata.reset(); } }); @@ -453,7 +496,7 @@ void StorageObjectStorageQueue::startup() }); /// Start background tasks. - files_metadata->startup(); + metadata->startup(); for (auto & task : streaming_tasks) task->activateAndSchedule(); @@ -496,11 +539,19 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) tryLogCurrentException(log); } - if (files_metadata) + /// Drop the handle before the keeper cleanup below, so a concurrent reader sees the + /// shut-down state. The local copy keeps the metadata alive for that cleanup. + std::shared_ptr metadata; + { + std::lock_guard lock(mutex); + metadata = std::move(files_metadata); + } + + if (metadata) { try { - files_metadata->unregisterActive(getStorageID()); + metadata->unregisterActive(getStorageID()); } catch (...) { @@ -508,8 +559,6 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) } ObjectStorageQueueMetadataFactory::instance().remove(zookeeper_name, zk_path, getStorageID(), is_drop, keep_data_in_keeper); - - files_metadata.reset(); } LOG_TRACE(log, "Shut down storage"); } @@ -1316,6 +1365,35 @@ void StorageObjectStorageQueue::checkAlterIsPossible(const AlterCommands & comma } } } + + /// The host filter of `configuration` covers the source only, so a new move destination is checked here. + /// `checkAlterIsPossible` runs on every host and the check depends only on the server config, so it is correct everywhere. + static constexpr std::array move_destination_settings{ + "after_processing_move_uri", "after_processing_move_connection_string", "after_processing_move_container"}; + + auto get_move_destination_value = [](const SettingsChanges * settings, std::string_view name) -> String + { + const Field * value = settings ? settings->tryGet(name) : nullptr; + return value ? convertFieldToString(*value) : String{}; + }; + + const bool move_destination_changed = std::ranges::any_of( + move_destination_settings, + [&](std::string_view name) + { return get_move_destination_value(old_settings, name) != get_move_destination_value(&new_settings, name); }); + + if (move_destination_changed) + { + const String move_connection_string = get_move_destination_value(&new_settings, "after_processing_move_connection_string"); + const String move_container = get_move_destination_value(&new_settings, "after_processing_move_container"); + + checkMoveDestinationHost( + type, + get_move_destination_value(&new_settings, "after_processing_move_uri"), + move_connection_string, + move_container, + local_context->getRemoteHostFilter()); + } } void StorageObjectStorageQueue::alter( @@ -1532,6 +1610,12 @@ const ObjectStorageQueueTableMetadata & StorageObjectStorageQueue::getTableMetad return files_metadata->getTableMetadata(); } +std::shared_ptr StorageObjectStorageQueue::tryGetFilesMetadata() const +{ + std::lock_guard lock(mutex); + return files_metadata; +} + std::shared_ptr StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate) { @@ -1571,11 +1655,16 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), /// so let's reconstruct. ObjectStorageQueueSettings settings; - /// If startup() for a table was not called, just use the default queue settings + /// If startup() for a table was not called, just use the default queue settings. + /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. if (!startup_finished) return settings; - const auto & table_metadata = getTableMetadata(); + auto metadata = tryGetFilesMetadata(); + if (!metadata) + return settings; + + const auto & table_metadata = metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) @@ -1591,12 +1680,12 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const settings[ObjectStorageQueueSetting::tracked_files_limit] = table_metadata.tracked_files_limit; settings[ObjectStorageQueueSetting::buckets] = table_metadata.buckets; - auto cleanup_interval_ms = files_metadata->getCleanupIntervalMS(); + auto cleanup_interval_ms = metadata->getCleanupIntervalMS(); settings[ObjectStorageQueueSetting::cleanup_interval_min_ms] = static_cast(cleanup_interval_ms.first); settings[ObjectStorageQueueSetting::cleanup_interval_max_ms] = static_cast(cleanup_interval_ms.second); - settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(files_metadata->getPersistentProcessingNodeTTLSeconds()); - settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = files_metadata->usePersistentProcessingNode(); - const auto & file_statuses_cache = files_metadata->getFileStatusesCache(); + settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(metadata->getPersistentProcessingNodeTTLSeconds()); + settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = metadata->usePersistentProcessingNode(); + const auto & file_statuses_cache = metadata->getFileStatusesCache(); settings[ObjectStorageQueueSetting::metadata_cache_size_bytes] = file_statuses_cache.maxSizeInBytes(); settings[ObjectStorageQueueSetting::metadata_cache_size_elements] = file_statuses_cache.maxCount(); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index 5a251e7b7e16..902ec55b54bf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -147,6 +147,8 @@ class StorageObjectStorageQueue : public IStorage, WithContext bool supportsColumnsWithDynamicStructure() const override { return true; } const ObjectStorageQueueTableMetadata & getTableMetadata() const; + /// Returns nullptr if the table is not started up or is already shut down. + std::shared_ptr tryGetFilesMetadata() const; std::shared_ptr createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate); std::shared_ptr createSource( diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 27f3c6004559..d7ddf6e5d128 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -143,6 +144,7 @@ void registerStorageS3Queue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::S3, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getS3QueueMoveDestinationAccess, }); } #endif @@ -161,6 +163,7 @@ void registerStorageAzureQueue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::AZURE, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getAzureQueueMoveDestinationAccess, }); } #endif diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp index f5e81a4a4843..ec0c6ea0433a 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp @@ -275,6 +275,14 @@ void StorageMaterializedPostgreSQL::dropInnerTableIfAny(bool sync, ContextPtr lo } +bool StorageMaterializedPostgreSQL::hasBucketedMapSerialization() const +{ + if (auto nested = tryGetNested()) + return nested->hasBucketedMapSerialization(); + return false; +} + + bool StorageMaterializedPostgreSQL::needRewriteQueryWithFinal(const Names & column_names) const { return needRewriteQueryWithFinalForStorage(column_names, getNested()); diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h index 0933a2772d9d..c133fee077bf 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h @@ -91,6 +91,8 @@ class StorageMaterializedPostgreSQL final : public IStorage, WithContext bool needRewriteQueryWithFinal(const Names & column_names) const override; + bool hasBucketedMapSerialization() const override; + void read( QueryPlan & query_plan, const Names & column_names, diff --git a/src/Storages/StorageAlias.cpp b/src/Storages/StorageAlias.cpp index eb8bc370f85a..5160352e3432 100644 --- a/src/Storages/StorageAlias.cpp +++ b/src/Storages/StorageAlias.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -15,6 +16,9 @@ #include #include #include +#include +#include +#include namespace DB @@ -31,6 +35,7 @@ namespace ErrorCodes extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int BAD_ARGUMENTS; extern const int SUPPORT_IS_DISABLED; + extern const int NOT_IMPLEMENTED; } StorageAlias::StorageAlias( @@ -171,6 +176,26 @@ SinkToStoragePtr StorageAlias::write( return std::make_shared(*this, local_context, target_metadata); } +void StorageAlias::checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const +{ + /// `InterpreterAlterQuery` checks the export grants (`SELECT` on the table and its row policy) on the name in the query, + /// which is the alias, not the target. The refusal does not need the user, so it also holds on the hosts of `ON CLUSTER`. + for (const auto & command : commands) + { + if (command.type == AlterCommand::MODIFY_SETTING && !StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes).empty()) + { + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Changing the settings that send the data of a table elsewhere through an alias is not supported. " + "Execute the ALTER directly on the target table: {}.{}", + backQuoteIfNeed(target_database), + backQuoteIfNeed(target_table)); + } + } + + getTargetTable()->checkAlterIsPossible(commands, local_context); +} + void StorageAlias::alter( const AlterCommands & params, ContextPtr local_context, diff --git a/src/Storages/StorageAlias.h b/src/Storages/StorageAlias.h index 0753decac7e5..99a9167dd58d 100644 --- a/src/Storages/StorageAlias.h +++ b/src/Storages/StorageAlias.h @@ -55,7 +55,7 @@ class StorageAlias final : public IStorage, WithContext /// Distributed write to target table std::optional distributedWrite(const ASTInsertQuery & query, ContextPtr local_context) override; - void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override { getTargetTable()->checkAlterIsPossible(commands, local_context); } + void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override; /// Alter target table void alter( @@ -143,6 +143,7 @@ class StorageAlias final : public IStorage, WithContext std::optional supportedPrewhereColumns() const override { return getTargetTable()->supportedPrewhereColumns(); } bool canMoveConditionsToPrewhere() const override { return getTargetTable()->canMoveConditionsToPrewhere(); } bool supportsOptimizationToSubcolumns() const override { return getTargetTable()->supportsOptimizationToSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsDeduplication() const override { return getTargetTable()->supportsDeduplication(); } bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageBuffer.cpp b/src/Storages/StorageBuffer.cpp index 090058a95a95..2993357d6658 100644 --- a/src/Storages/StorageBuffer.cpp +++ b/src/Storages/StorageBuffer.cpp @@ -887,6 +887,13 @@ bool StorageBuffer::supportsPrewhere() const return false; } +bool StorageBuffer::hasBucketedMapSerialization() const +{ + if (auto destination = getDestinationTable()) + return destination->hasBucketedMapSerialization(); + return false; +} + bool StorageBuffer::checkThresholds(const Buffer & buffer, bool direct, time_t current_time, size_t additional_rows, size_t additional_bytes) const { time_t time_passed = 0; diff --git a/src/Storages/StorageBuffer.h b/src/Storages/StorageBuffer.h index 481647a89625..8da3169b9b2f 100644 --- a/src/Storages/StorageBuffer.h +++ b/src/Storages/StorageBuffer.h @@ -91,6 +91,7 @@ friend class BufferSink; bool supportsParallelInsert() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } diff --git a/src/Storages/StorageDistributed.cpp b/src/Storages/StorageDistributed.cpp index 478abb8530f7..2bdf34ab918b 100644 --- a/src/Storages/StorageDistributed.cpp +++ b/src/Storages/StorageDistributed.cpp @@ -1,5 +1,10 @@ #include +#include +#include +#include +#include + #include #include @@ -179,6 +184,7 @@ namespace Setting extern const SettingsBool prefer_global_in_and_join; extern const SettingsBool skip_unavailable_shards; extern const SettingsBool enable_global_with_statement; + extern const SettingsMap additional_table_filters; } namespace DistributedSetting @@ -1364,6 +1370,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser auto & select = query.select->as(); StoragePtr src_storage; + bool src_is_table_function = false; /// Distributed write only works in the most trivial case INSERT ... SELECT /// without any unions or joins on the right side @@ -1380,6 +1387,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (joined_tables.tablesCount() == 1) { src_storage = joined_tables.getLeftTableStorage(); + src_is_table_function = joined_tables.isLeftTableFunction(); } } } @@ -1387,6 +1395,19 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (!src_storage) return {}; + /// This is the only place source SELECT access is enforced in this case + /// (table functions have been already checked in ITableFunction::execute) + const auto src_id = src_storage->getStorageID(); + if (!src_is_table_function + && !local_context->getAccess()->isGranted(AccessType::SELECT, src_id.database_name, src_id.table_name)) + return {}; + if (auto row_policy_filter = local_context->getRowPolicyFilter(src_id.database_name, src_id.table_name, RowPolicyFilterType::SELECT_FILTER); + row_policy_filter && !row_policy_filter->isAlwaysTrue()) + return {}; + /// It is not easy to match this table only, analyzer also do not do it + if (!settings[Setting::additional_table_filters].value.empty()) + return {}; + if (auto src_distributed = std::dynamic_pointer_cast(src_storage)) { return distributedWriteBetweenDistributedTables(*src_distributed, query, local_context); diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 0cc905ab1d3c..4ced2fa21aa6 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -1,9 +1,12 @@ #include +#include #include #include #include #include +#include #include +#include #include #include #include @@ -267,4 +270,37 @@ const StorageFactory::StorageFeatures & StorageFactory::getStorageFeatures(const return it->second.features; } +AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & create) const +{ + AccessRightsElements res; + auto add = [&](const ASTStorage & storage) + { + if (!storage.engine || !storage.settings) + return; + auto it = storages.find(storage.engine->name); + if (it != storages.end() && it->second.features.get_export_access_fn) + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + }; + + if (create.storage) + add(*create.storage); + if (create.targets) + { + for (const ASTStorage * inner_engine : create.targets->getInnerEngines()) + add(*inner_engine); + } + return res; +} + +AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const +{ + AccessRightsElements res; + for (const auto & [_, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes)); + } + return res; +} + } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index d3e4ccc969d4..6babf823c358 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -16,6 +16,8 @@ namespace DB class Context; class ASTCreateQuery; class ASTStorage; +class AccessRightsElements; +class SettingsChanges; struct StorageID; struct ConstraintsDescription; @@ -33,6 +35,10 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// Used to validate if table settings belong to the engine or the query before the start of the query interpretation using HasBuiltinSettingFn = bool(std::string_view); + /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. + /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + struct Arguments { const String & engine_name; @@ -76,6 +82,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> std::optional source_access_type = std::nullopt; HasBuiltinSettingFn * has_builtin_setting_fn = nullptr; + GetExportAccessFn * get_export_access_fn = nullptr; }; using CreatorFn = std::function; @@ -111,6 +118,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> .supports_schema_inference = false, .source_access_type = std::nullopt, .has_builtin_setting_fn = nullptr, + .get_export_access_fn = nullptr, }); const Storages & getAllStorages() const @@ -140,6 +148,13 @@ class StorageFactory : private boost::noncopyable, public IHints<> const StorageFeatures & getStorageFeatures(const String & storage_name) const; + /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` + /// table. An unknown engine needs nothing here: creating it fails later. + AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, + /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. + AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; + private: Storages storages; }; diff --git a/src/Storages/StorageInMemoryMetadata.cpp b/src/Storages/StorageInMemoryMetadata.cpp index 7982f7de575a..f99761a93ff7 100644 --- a/src/Storages/StorageInMemoryMetadata.cpp +++ b/src/Storages/StorageInMemoryMetadata.cpp @@ -20,6 +20,8 @@ #include #include +#include + namespace DB { @@ -198,6 +200,47 @@ ContextMutablePtr StorageInMemoryMetadata::getSQLSecurityOverriddenContext(Conte new_context->setUser(getDefinerID(context)); + /// `Context::setUser` only sets the access-control identity (`user_id`); it does not touch the + /// user names in `ClientInfo`. That is harmless when there is an invoker whose names were copied + /// above, but a scheduled refresh of a refreshable materialized view builds its context from the + /// global context, where `current_user`, `initial_user` and `authenticated_user` are empty. + /// `RemoteQueryExecutor` sends the names as-is, and a shard that accepts the interserver + /// `` treats an empty `initial_user` as "interserver mode": it skips authentication + /// (see `TCPHandler::receiveQuery`) and executes the query with full access + /// (see `Context::getAccess`, `full_access = !user_id`). Stamp the definer into the empty fields + /// so the remote leg of the query is bounded by the same identity as the local one. Non-empty + /// fields are left alone so `currentUser` inside an ordinary `DEFINER` view still returns the + /// invoker. `AsynchronousInsertQueue` and `InterpreterExecuteAsQuery` do the same. + { + const auto & new_client_info = new_context->getClientInfo(); + const bool current_user_empty = new_client_info.current_user.empty(); + const bool initial_user_empty = new_client_info.initial_user.empty(); + const bool authenticated_user_empty = new_client_info.authenticated_user.empty(); + + if (current_user_empty || initial_user_empty || authenticated_user_empty) + { + const auto definer_name = new_context->getUserName(); + if (current_user_empty) + new_context->setCurrentUserName(definer_name); + if (initial_user_empty) + { + new_context->setInitialUserName(definer_name); + /// The shard authenticates the definer by `initial_user` and checks `initial_address` + /// against the allowed hosts of that user. Without an invoker, the address is the + /// unspecified `0.0.0.0`, which only matches users with `HOST ANY`. The query is + /// produced by this server itself, so present it as coming from the local host. + if (!new_client_info.initial_address || new_client_info.initial_address->host().isWildcard()) + new_context->setInitialAddress(Poco::Net::SocketAddress(Poco::Net::IPAddress("127.0.0.1"), 0)); + } + if (authenticated_user_empty) + { + ClientInfo client_info_with_definer = new_context->getClientInfo(); + client_info_with_definer.authenticated_user = definer_name; + new_context->setClientInfo(client_info_with_definer); + } + } + } + new_context->clampToSettingsConstraints(changed_settings, SettingSource::QUERY); new_context->applySettingsChanges(changed_settings); new_context->setSetting("allow_ddl", 1); diff --git a/src/Storages/StorageMaterializedView.cpp b/src/Storages/StorageMaterializedView.cpp index cd9b89b12c7b..05223ca73bf7 100644 --- a/src/Storages/StorageMaterializedView.cpp +++ b/src/Storages/StorageMaterializedView.cpp @@ -559,10 +559,19 @@ ContextMutablePtr StorageMaterializedView::createRefreshContext(const String & l { ContextPtr table_context = getContext(); ClientInfo client_info = table_context->getClientInfo(); - client_info.interface = ClientInfo::Interface::BACKGROUND; - client_info.client_name = "refreshable materialized view"; - auto refresh_context = getInMemoryMetadataPtr()->getSQLSecurityOverriddenContext(table_context, &client_info); - refresh_context->setClientInfo(client_info); + auto view_metadata = getInMemoryMetadataPtr(); + auto refresh_context = view_metadata->getSQLSecurityOverriddenContext(table_context, &client_info); + /// For `SQL SECURITY DEFINER`, `getSQLSecurityOverriddenContext` fills the empty user names in + /// the context's `ClientInfo` with the definer. Do not assign the local `client_info` copy to + /// the context: `setClientInfo` replaces the whole struct and would wipe that identity out. + /// Re-read it instead, so that a view without SQL security (which gets a plain copy) also gets + /// these fields. + { + ClientInfo refresh_client_info = refresh_context->getClientInfo(); + refresh_client_info.interface = ClientInfo::Interface::BACKGROUND; + refresh_client_info.client_name = "refreshable materialized view"; + refresh_context->setClientInfo(refresh_client_info); + } refresh_context->setSetting("database_replicated_allow_replicated_engine_arguments", 3); refresh_context->setSetting("log_comment", log_comment); refresh_context->setQueryKind(ClientInfo::QueryKind::INITIAL_QUERY); diff --git a/src/Storages/StorageMaterializedView.h b/src/Storages/StorageMaterializedView.h index 62331b24f329..a4d72e909292 100644 --- a/src/Storages/StorageMaterializedView.h +++ b/src/Storages/StorageMaterializedView.h @@ -36,6 +36,7 @@ class StorageMaterializedView final : public IStorage, WithMutableContext bool supportsFinal() const override { return getTargetTable()->supportsFinal(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsSubcolumns() const override { return getTargetTable()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override; bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageMerge.cpp b/src/Storages/StorageMerge.cpp index 202aae98818e..a70dd5e4659b 100644 --- a/src/Storages/StorageMerge.cpp +++ b/src/Storages/StorageMerge.cpp @@ -318,6 +318,12 @@ bool StorageMerge::supportsPrewhere() const return traverseTablesUntil([](const auto & table) { return !table->supportsPrewhere(); }) == nullptr; } +bool StorageMerge::hasBucketedMapSerialization() const +{ + /// The rewritten query is sent to every underlying table, so all of them must benefit from it. + return traverseTablesUntil([](const auto & table) { return !table->hasBucketedMapSerialization(); }) == nullptr; +} + bool StorageMerge::canMoveConditionsToPrewhere() const { /// NOTE: This check and the above check are used during query analysis as condition for applying diff --git a/src/Storages/StorageMerge.h b/src/Storages/StorageMerge.h index 2c1eafc7f808..948a5f50694f 100644 --- a/src/Storages/StorageMerge.h +++ b/src/Storages/StorageMerge.h @@ -51,6 +51,7 @@ class StorageMerge final : public IStorage, WithContext bool supportsSampling() const override { return true; } bool supportsFinal() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } bool supportsPrewhere() const override; std::optional supportedPrewhereColumns() const override; diff --git a/src/Storages/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index 8419b2aea6c2..cecedf79cca5 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -1114,6 +1114,11 @@ QueryPipeline StorageMergeTree::updateLightweight(const MutationCommands & comma /// Updates currently don't work with parallel replicas. context_copy->setSetting("max_parallel_replicas", Field(1)); + /// A snapshot cached by `enable_shared_storage_snapshot_in_query` before the wait for committing + /// inserts above (e.g. by the validation of `IN` operands in `InterpreterUpdateQuery`) would hide + /// the parts committed during the wait from the update. See `StorageReplicatedMergeTree::updateLightweight`. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); auto sink = std::make_shared(*this, std::move(patch_metadata), std::move(update_holder), context_copy); @@ -2800,25 +2805,24 @@ void StorageMergeTree::replacePartitionFrom(const StoragePtr & source_table, con String partition_id; + /// The merges_blocker must live until the end of the function to prevent background mutations + /// from starting on parts in the target partition between when we stop waiting and when we + /// actually remove old parts via removePartsInRangeFromWorkingSet. Without this, a mutation + /// could "resurrect" old data by completing on an already-removed part and adding a new version + /// of it back to the working set. + ActionLock merges_blocker; if (is_all) { if (replace) throw DB::Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Only support DROP/DETACH/ATTACH PARTITION ALL currently"); + merges_blocker = stopMergesAndWait(); } else { partition_id = getPartitionIDFromQuery(partition, local_context); + merges_blocker = stopMergesAndWaitForPartition(partition_id); } - /// We use the global `stopMergesAndWait` (not the per-partition variant) because the - /// per-partition blocker check in `scheduleDataProcessingJob` happens outside - /// `currently_processing_in_background_mutex`, creating a race window where a mutation - /// can be selected inside the mutex, pass the per-partition check outside the mutex, - /// and get scheduled after the blocker was set but before we call - /// `removePartsInRangeFromWorkingSet`, "resurrecting" old data. - /// The global blocker is checked inside the mutex, eliminating this race. - ActionLock merges_blocker = stopMergesAndWait(); - auto source_metadata_snapshot = source_table->getInMemoryMetadataPtr(); auto my_metadata_snapshot = getInMemoryMetadataPtr(); diff --git a/src/Storages/StorageMongoDB.cpp b/src/Storages/StorageMongoDB.cpp index 6a6fbeca720e..e4dff78729a2 100644 --- a/src/Storages/StorageMongoDB.cpp +++ b/src/Storages/StorageMongoDB.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -36,6 +37,7 @@ #include #include +#include #include using bsoncxx::builder::basic::document; @@ -49,6 +51,7 @@ namespace DB namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int NOT_IMPLEMENTED; @@ -78,6 +81,53 @@ void MongoDBConfiguration::checkCollection() const throw Exception(ErrorCodes::BAD_ARGUMENTS, "MongoDB collection name must be non-empty and must not contain NUL characters"); } +namespace +{ + +void throwIfServerCredentials(const mongocxx::uri & uri, std::string_view remedy) +{ + /// Only these take the credentials from the connection string; `MONGODB-OIDC`, `MONGODB-AWS`, `GSSAPI` and + /// `MONGODB-X509` use the server's. Without a mechanism the driver uses SCRAM or no authentication. Names are case-insensitive. + static constexpr std::string_view allowed_mechanisms[] = {"SCRAM-SHA-1", "SCRAM-SHA-256", "PLAIN"}; + + const String mechanism = uri.auth_mechanism(); + const bool is_allowed_mechanism = mechanism.empty() + || std::ranges::any_of(allowed_mechanisms, [&](std::string_view allowed) { return equalsCaseInsensitive(mechanism, allowed); }); + + if (!is_allowed_mechanism) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB authentication mechanism '{}' is not allowed, because it authenticates with " + "credentials of the server process. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a password " + "in the connection string{}.", + mechanism, remedy); + + /// The driver stores the deprecated `sslClientCertificateKeyFile` under the canonical name, so this covers both. + if (uri.tls_certificate_key_file()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB connection option `tlsCertificateKeyFile` is not allowed, because it makes the server present a " + "client certificate from its own filesystem. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a " + "password in the connection string{}.", + remedy); +} + +} + +void MongoDBConfiguration::checkServerCredentialsForTable(const ContextPtr & context) const +{ + /// In `clickhouse-local` the user is the operator, so the credentials of the process are theirs to use. + if (context->getApplicationType() != Context::ApplicationType::SERVER) + return; + + throwIfServerCredentials(*uri, ""); +} + +void MongoDBConfiguration::checkServerCredentialsForDictionary() const +{ + throwIfServerCredentials(*uri, ", or define the dictionary in the server configuration files"); +} + StorageMongoDB::StorageMongoDB( const StorageID & table_id_, MongoDBConfiguration configuration_, @@ -104,6 +154,9 @@ Pipe StorageMongoDB::read( size_t max_block_size, size_t /*num_streams*/) { + /// Checked per read, with the query's settings: a table created with `mongodb(...)` is built with the global context. + configuration.checkServerCredentialsForTable(context); + storage_snapshot->check(column_names); Block sample_block; diff --git a/src/Storages/StorageMongoDB.h b/src/Storages/StorageMongoDB.h index 5d436a874803..ee514c16762a 100644 --- a/src/Storages/StorageMongoDB.h +++ b/src/Storages/StorageMongoDB.h @@ -53,6 +53,9 @@ struct MongoDBConfiguration void checkHosts(const ContextPtr & context) const; void checkCollection() const; + void checkServerCredentialsForTable(const ContextPtr & context) const; + void checkServerCredentialsForDictionary() const; + bool isOidColumn(const std::string & name) const { return oid_fields.contains(name); diff --git a/src/Storages/StorageProxy.h b/src/Storages/StorageProxy.h index 57c14568e56d..aa24e39addb6 100644 --- a/src/Storages/StorageProxy.h +++ b/src/Storages/StorageProxy.h @@ -38,6 +38,7 @@ class StorageProxy : public IStorage bool noPushingToViewsOnInserts() const override { return getNested()->noPushingToViewsOnInserts(); } bool hasEvenlyDistributedRead() const override { return getNested()->hasEvenlyDistributedRead(); } bool supportsSubcolumns() const override { return getNested()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getNested()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override { return getNested()->supportsColumnsWithDynamicStructure(); } ColumnSizeByName getColumnSizes() const override { return getNested()->getColumnSizes(); } diff --git a/src/Storages/StorageReplicatedMergeTree.cpp b/src/Storages/StorageReplicatedMergeTree.cpp index 853396096da3..9707592466a1 100644 --- a/src/Storages/StorageReplicatedMergeTree.cpp +++ b/src/Storages/StorageReplicatedMergeTree.cpp @@ -249,6 +249,7 @@ namespace FailPoints extern const char rmt_merge_selecting_task_no_free_threads[]; extern const char rmt_merge_selecting_task_max_part_size[]; extern const char rmt_delay_execute_drop_range[]; + extern const char rmt_restore_replica_pause_before_metadata_version_raise[]; } namespace ErrorCodes @@ -7069,6 +7070,7 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( createReplica(metadata_snapshot, zookeeper_retries_info); createNewZooKeeperNodes(zookeeper_retries_info); + FailPointInjection::pauseFailPoint(FailPoints::rmt_restore_replica_pause_before_metadata_version_raise); /// Bump the /metadata ZNode version to match the max parts metadata version. /// The table's in-memory metadata_version is derived from the /metadata ZNode stat.version @@ -7076,12 +7078,41 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( if (max_parts_metadata_version > 0) { auto zookeeper = getZooKeeper(); - String metadata_str = zookeeper->get(zookeeper_path + "/metadata"); - for (int32_t i = 0; i < max_parts_metadata_version; ++i) - zookeeper->set(zookeeper_path + "/metadata", metadata_str); - zookeeper->set(replica_path + "/metadata_version", std::to_string(max_parts_metadata_version)); + /// Each batch logs an ALTER_METADATA entry of the version it reaches, so a replica that cloned an earlier one catches up. + Coordination::Stat metadata_stat; + Coordination::Stat columns_stat; + String metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + String columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + while (metadata_stat.version < max_parts_metadata_version) + { + const auto target = static_cast(std::min( + max_parts_metadata_version, Int64{metadata_stat.version} + static_cast(zkutil::MULTI_BATCH_SIZE))); + + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(zookeeper_path + "/columns", columns_stat.version)); + for (int32_t version = metadata_stat.version; version < target; ++version) + ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/metadata", version + 1 == target ? metadata_str : "", version)); + + ReplicatedMergeTreeLogEntryData entry; + entry.type = LogEntry::ALTER_METADATA; + entry.source_replica = replica_name; + entry.metadata_str = metadata_str; + entry.columns_str = columns_str; + entry.alter_version = target; + entry.create_time = time(nullptr); + entry.have_mutation = false; + ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/log/log-", entry.toString(), zkutil::CreateMode::PersistentSequential)); - LOG_INFO(log, "Bumped metadata version to {} to match parts", max_parts_metadata_version); + Coordination::Responses responses; + const Coordination::Error code = zookeeper->tryMulti(ops, responses); + if (code != Coordination::Error::ZOK && code != Coordination::Error::ZBADVERSION) + zkutil::KeeperMultiException::check(code, ops, responses); + + metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + } + + LOG_INFO(log, "Raised metadata version to {} to match parts", metadata_stat.version); } LOG_INFO(log, "Created ZK nodes for table"); @@ -8433,6 +8464,13 @@ QueryPipeline StorageReplicatedMergeTree::updateLightweight(const MutationComman waitForCommittingOpsToFinish(zookeeper, context_copy->getPartitionIdToMaxBlock(getStorageID().uuid), ops, backoff_ms, sync_timeout); } + /// With `enable_shared_storage_snapshot_in_query` the update reads with the snapshot of this table + /// cached for the whole query. Anything analyzed before this point may have cached one, e.g. the + /// validation of `IN` operands in `InterpreterUpdateQuery`. Such a snapshot predates the wait for committing inserts above, so the + /// parts that arrived during the wait would be invisible to the update and their rows would stay + /// unchanged. Discard it, so that the update and its subqueries share a snapshot taken now. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); diff --git a/src/Storages/System/StorageSystemMutations.cpp b/src/Storages/System/StorageSystemMutations.cpp index 7514ed309af7..b3b65c6003ed 100644 --- a/src/Storages/System/StorageSystemMutations.cpp +++ b/src/Storages/System/StorageSystemMutations.cpp @@ -10,14 +10,67 @@ #include #include #include +#include #include #include #include +#include +#include +#include namespace DB { +namespace Setting +{ + extern const SettingsUInt64 max_parser_depth; + extern const SettingsUInt64 max_parser_backtracks; +} + +namespace ErrorCodes +{ + extern const int SYNTAX_ERROR; + extern const int TOO_DEEP_RECURSION; + extern const int TOO_SLOW_PARSING; +} + +/// The mutation entry keeps the real text of the command, because the mutation is executed from it +/// (on every replica, for replicated tables). Hide the secrets on the way out instead, the way +/// `system.distributed_ddl_queue` does. The command is formatted the same way as the stored text, +/// so only the secrets differ from it. +static String hideSecretsInCommand(const ContextPtr & context, const String & command) +{ + /// Nothing to parse, see `MutationCommand::ast`. + if (command.empty()) + return command; + + const auto & settings = context->getSettingsRef(); + ParserAlterCommandList parser; + ASTPtr ast; + try + { + ast = parseQuery(parser, command, 0, settings[Setting::max_parser_depth], settings[Setting::max_parser_backtracks]); + } + catch (const Exception & e) + { + /// The text may be unparseable on another server version, so hide the whole command instead of failing the table. + if (e.code() != ErrorCodes::SYNTAX_ERROR + && e.code() != ErrorCodes::TOO_DEEP_RECURSION + && e.code() != ErrorCodes::TOO_SLOW_PARSING) + throw; + return "[HIDDEN]"; + } + + return ast->formatWithPossiblyHidingSensitiveData( + /*max_length=*/0, + /*one_line=*/true, + /*show_secrets=*/false, + /*print_pretty_type_names=*/false, + /*identifier_quoting_rule=*/IdentifierQuotingRule::WhenNecessary, + /*identifier_quoting_style=*/IdentifierQuotingStyle::Backticks); +} + ColumnsDescription StorageSystemMutations::getColumnsDescription() { @@ -65,10 +118,11 @@ Block StorageSystemMutations::getFilterSampleBlock() const }; } -void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const +void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const { const auto access = context->getAccess(); const bool check_access_for_databases = !access->isGranted(AccessType::SHOW_TABLES); + const bool show_secrets = canDisplaySecrets(context); /// Collect a set of *MergeTree tables. std::map> merge_tree_tables; @@ -169,25 +223,43 @@ void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr c parts_postpone_reasons_map.emplace_back(std::move(key_value)); } - size_t col_num = 0; - res_columns[col_num++]->insert(database); - res_columns[col_num++]->insert(table); - - res_columns[col_num++]->insert(status.id); - res_columns[col_num++]->insert(status.command); - res_columns[col_num++]->insert(UInt64(status.create_time)); - res_columns[col_num++]->insert(block_partition_ids); - res_columns[col_num++]->insert(block_numbers); - res_columns[col_num++]->insert(parts_in_progress_names); - res_columns[col_num++]->insert(parts_to_do_names); - res_columns[col_num++]->insert(parts_to_do_names.size()); - res_columns[col_num++]->insert(parts_postpone_reasons_map); - res_columns[col_num++]->insert(status.is_done); - res_columns[col_num++]->insert(status.is_killed); - res_columns[col_num++]->insert(status.latest_failed_part); - res_columns[col_num++]->insert(UInt64(status.latest_fail_time)); - res_columns[col_num++]->insert(status.latest_fail_reason); - res_columns[col_num++]->insert(status.latest_fail_error_code_name); + size_t src_index = 0; + size_t res_index = 0; + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(database); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(table); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.id); + /// Parsing the command costs much more than everything else here, so it is done only when the column is queried. + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(show_secrets ? status.command : hideSecretsInCommand(context, status.command)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.create_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_partition_ids); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_numbers); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_in_progress_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names.size()); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_postpone_reasons_map); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_done); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_killed); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_failed_part); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.latest_fail_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_reason); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_error_code_name); } } } diff --git a/src/Storages/System/StorageSystemMutations.h b/src/Storages/System/StorageSystemMutations.h index 5341838a65e3..c3f897491fc7 100644 --- a/src/Storages/System/StorageSystemMutations.h +++ b/src/Storages/System/StorageSystemMutations.h @@ -21,8 +21,9 @@ class StorageSystemMutations final : public IStorageSystemOneBlock protected: using IStorageSystemOneBlock::IStorageSystemOneBlock; - void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const override; + void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const override; Block getFilterSampleBlock() const override; + bool supportsColumnsMask() const override { return true; } }; } diff --git a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp index b573828ddee1..444e3d74a08b 100644 --- a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp +++ b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( const ActionsDAG::Node *, std::vector) const { + const bool display_secrets = canDisplaySecrets(context); auto add_table = [&]( const DatabaseTablesIteratorPtr & it, StorageObjectStorageQueue & storage) { @@ -52,7 +54,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( auto constraints_and_current_profiles = context->getSettingsConstraintsAndCurrentProfiles(); const auto & constraints = constraints_and_current_profiles->constraints; MutableColumnsAndConstraints params(res_columns, constraints); - storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage); + storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage, display_secrets); }; const auto access = context->getAccess(); diff --git a/src/TableFunctions/ITableFunction.cpp b/src/TableFunctions/ITableFunction.cpp index fcd19f5b5408..9624c7464e48 100644 --- a/src/TableFunctions/ITableFunction.cpp +++ b/src/TableFunctions/ITableFunction.cpp @@ -55,11 +55,22 @@ void ITableFunction::checkEngineAccess(ContextPtr context) const context->checkAccess(AccessType::TABLE_ENGINE, engine); } +void ITableFunction::checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const +{ + auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); + if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) + context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); +} + ColumnsDescription ITableFunction::getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const { /// Resolving table structure is always a read operation. checkSourceAccess(context, /*is_insert_query*/ false); checkEngineAccess(context); + /// Resolving the structure may access the source (e.g. schema inference fetches a URL), so it must be + /// gated in the same way as `execute`: otherwise `DESCRIBE TABLE url(...)` would let a user who cannot + /// run the table function (e.g. under `readonly = 1`) make the server request an endpoint. + checkCreateTemporaryTableAccess(context, /*is_insert_query*/ false); return getActualTableStructure(context, is_insert_query); } @@ -73,9 +84,7 @@ StoragePtr ITableFunction::execute(const ASTPtr & ast_function, ContextPtr conte /// Deliberately not under `check_source_access`: no caller takes over the engine check. checkEngineAccess(context); - auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); - if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) - context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); + checkCreateTemporaryTableAccess(context, is_insert_query); auto context_to_use = use_global_context ? context->getGlobalContext() : context; diff --git a/src/TableFunctions/ITableFunction.h b/src/TableFunctions/ITableFunction.h index 0aeb1d497e1a..6579ff2ce25a 100644 --- a/src/TableFunctions/ITableFunction.h +++ b/src/TableFunctions/ITableFunction.h @@ -88,8 +88,9 @@ class ITableFunction : public std::enable_shared_from_this StoragePtr execute(const ASTPtr & ast_function, ContextPtr context, const std::string & table_name, ColumnsDescription cached_columns_ = {}, bool use_global_context = false, bool is_insert_query = false) const; - /// Returns actual table structure after enforcing source access checks. - /// Use this instead of getActualTableStructure() from outside execute(). + /// Returns actual table structure after enforcing the same access checks as `execute`: source, engine, + /// and `CREATE TEMPORARY TABLE` (for table functions not allowed in readonly mode). + /// Use this instead of `getActualTableStructure` from outside `execute`. ColumnsDescription getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const; /// Check that the user has the required source access (e.g. READ ON MYSQL, WRITE ON S3). @@ -98,6 +99,10 @@ class ITableFunction : public std::enable_shared_from_this /// Check the `TABLE ENGINE` grant, for engines that opt in via `requiresTableEngineGrant`. void checkEngineAccess(ContextPtr context) const; + /// Check the `CREATE TEMPORARY TABLE` grant, required to use a table function unless it is allowed + /// in readonly mode and the query is not an insert. + void checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const; + virtual ~ITableFunction() = default; protected: diff --git a/src/configure_config.cmake b/src/configure_config.cmake index 39b16eeebbe7..0d3a4da3abaa 100644 --- a/src/configure_config.cmake +++ b/src/configure_config.cmake @@ -150,6 +150,9 @@ endif() if (TARGET ch_contrib::parquet) set(USE_PARQUET 1) set(USE_ARROW 1) +endif() +# The ORC reader and writer are implemented in ClickHouse and need only the compression libraries. +if (TARGET ch_contrib::snappy) set(USE_ORC 1) endif() if (TARGET ch_contrib::liburing) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 26adc0ca8970..08f04e9081b2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -59,8 +59,38 @@ def tune_local_port_range(): ) +def is_xdist_replacement_worker(): + """True when this worker was spawned to replace one that died mid-run. + + `pytest-xdist` numbers a replacement past the size of the original pool, so `gw8` in a pool of + eight (`gw0`..`gw7`) is a replacement. A replacement starts a fresh pytest *session*, which + re-runs every session-scoped fixture - and `cleanup_environment` kills every container on the + host, including the ones the workers that are still running own. One worker dying, from an OOM + kill for instance, would otherwise take the containers of the whole job with it. + """ + worker = os.environ.get("PYTEST_XDIST_WORKER", "") + count = os.environ.get("PYTEST_XDIST_WORKER_COUNT", "") + if not worker.startswith("gw") or not count.isdigit(): + return False + + index = worker.removeprefix("gw") + if not index.isdigit(): + return False + + return int(index) >= int(count) + + @pytest.fixture(autouse=True, scope="session") def cleanup_environment(): + if is_xdist_replacement_worker(): + logging.info( + "Worker %s replaces a worker that died, so the containers of the workers which are " + "still running are not ours to clean up. Skipping the environment cleanup.", + os.environ["PYTEST_XDIST_WORKER"], + ) + yield + return + try: result = run_and_check(["docker ps | wc -l"], shell=True) if int(result) > 1: diff --git a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml index d4ac4986c22d..ad199feefc1e 100644 --- a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml +++ b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml @@ -2,6 +2,7 @@ host:80 ^[a-z]*\.ru$ + .*\.allowed\.example diff --git a/tests/integration/test_allowed_url_from_config/test.py b/tests/integration/test_allowed_url_from_config/test.py index 78ff4b22d321..b43422300bba 100644 --- a/tests/integration/test_allowed_url_from_config/test.py +++ b/tests/integration/test_allowed_url_from_config/test.py @@ -72,6 +72,43 @@ def test_azure_host_filter_before_client_creation(start_cluster, query): assert node5.query(container_requests) == before +def test_object_storage_queue_move_destination_host_filter(start_cluster): + # The source is on an allowed host (`host:80`), so only the move destination can be rejected. `node1` has no + # Keeper, so a rejection with "not allowed" must come from the settings validation, which runs before any + # Keeper access. + s3_queue = ( + "CREATE TABLE s3queue_move_host (x UInt8) " + "ENGINE = S3Queue('http://host:80/bucket/data/', 'key', 'secret', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_uri = '{}', " + "after_processing_move_access_key_id = 'key', after_processing_move_secret_access_key = 'secret'" + ) + azure_queue = ( + "CREATE TABLE azurequeue_move_host (x UInt8) " + "ENGINE = AzureQueue('http://host:80', 'container', '*', 'account', 'YQ==', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_connection_string = " + "'DefaultEndpointsProtocol=http;AccountName=account;AccountKey=YQ==;BlobEndpoint=http://host:123/account;', " + "after_processing_move_container = 'dst'" + ) + + try: + error = node1.query_and_get_error(s3_queue.format("http://host:123/bucket/")) + assert "not allowed" in error, error + + error = node1.query_and_get_error( + azure_queue, settings={"azure_sdk_max_retries": 0} + ) + assert "not allowed" in error, error + + # Control: an allowed destination passes the host check and only fails later, on the missing Keeper. + error = node1.query_and_get_error(s3_queue.format("http://host:80/bucket/")) + assert "not allowed" not in error, error + finally: + node1.query("DROP TABLE IF EXISTS s3queue_move_host SYNC") + node1.query("DROP TABLE IF EXISTS azurequeue_move_host SYNC") + + def test_config_with_only_primary_hosts(start_cluster): assert ( node2.query( @@ -217,6 +254,34 @@ def test_mysql_dictionary_host_filter(start_cluster): node5.query("DROP DICTIONARY IF EXISTS default.test_mysql_host_filter") +def test_mysql_database_host_filter(start_cluster): + # node5 denies all hosts; the check runs before any connection attempt. + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('10.0.0.1:3306', 'db', 'u', 'p')" + ) + node5.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nc AS " + "host = '10.0.0.1', port = 3306, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nc)" + ) + node5.query("DROP NAMED COLLECTION test_mysql_db_filter_nc") + + # node1's suffix rule would match the whole string, but the connector stops at the NUL; reject it. + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('127.0.0.1\\0.allowed.example:1', 'db', 'u', 'p')" + ) + node1.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nul_nc AS " + "host = '127.0.0.1\\0.allowed.example', port = 1, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nul_nc)" + ) + node1.query("DROP NAMED COLLECTION test_mysql_db_filter_nul_nc") + + def test_mysql_dictionary_replica_host_filter(start_cluster): """MySQL dictionary source with REPLICA(...) syntax should respect RemoteHostFilter.""" # Covers the replica branch: if (config.has(settings_config_prefix + ".replica")) @@ -335,3 +400,58 @@ def test_table_function_remote(start_cluster): "SELECT * FROM remote('localhost:800', system, metrics)" ) ) + + +# The catalog is built lazily on first use, so a query on a table connects to the metastore. +def hive_catalog_error(node, database, url): + node.query( + f"CREATE DATABASE {database} ENGINE = DataLakeCatalog('{url}') " + "SETTINGS catalog_type = 'hive', warehouse = 'test_warehouse'", + settings={"allow_experimental_database_hms_catalog": 1}, + ) + return node.query_and_get_error(f"SELECT * FROM {database}.`ns.tbl`") + + +def test_hive_catalog_host_filter(start_cluster): + url = "thrift://localhost:1" + try: + # Control first: `node4` declares no `remote_url_allow_hosts` at all, so its filter stays + # uninitialized and allows everything - the same statement gets past the check and fails at + # the network instead. Without this arm, a filter that rejected everything would also pass. + error = hive_catalog_error(node4, "test_hive_host_filter", url) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + + # `node5` declares an empty `remote_url_allow_hosts`, which allows nothing. + error = hive_catalog_error(node5, "test_hive_host_filter", url) + assert "UNACCEPTABLE_URL" in error, error + # The check must run before the connect, so the refusal carries no connection error. + assert "Connection refused" not in error, error + finally: + node4.query("DROP DATABASE IF EXISTS test_hive_host_filter") + node5.query("DROP DATABASE IF EXISTS test_hive_host_filter") + + +def test_hive_catalog_host_filter_rejects_nul(start_cluster): + try: + # Control: the suffix rule in `config_with_hosts.xml` admits this host, so it gets past the + # filter and fails at name resolution instead. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://hms.allowed.example:1" + ) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + node1.query("DROP DATABASE test_hive_host_filter_nul") + + # The same rule matches the whole string including the NUL, but `getaddrinfo` would stop at the + # NUL and connect to 127.0.0.1. The host must be refused before any connection attempt. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://127.0.0.1\\0.allowed.example:1" + ) + assert "BAD_ARGUMENTS" in error, error + assert "Unexpected character" in error, error + assert "Connection refused" not in error, error + finally: + node1.query("DROP DATABASE IF EXISTS test_hive_host_filter_nul") diff --git a/tests/integration/test_arrowflight_interface/test.py b/tests/integration/test_arrowflight_interface/test.py index 634ade912d13..4a1c124f986e 100644 --- a/tests/integration/test_arrowflight_interface/test.py +++ b/tests/integration/test_arrowflight_interface/test.py @@ -519,6 +519,43 @@ def test_doget_multiple_chunks(): assert actual[1].column("name").equals(pa.chunked_array([pa.array(["cde"], type=pa.string())])) +# A result is split across several Arrow arrays only when it exceeds the 32-bit offsets of the +# String/Binary/List buffers, so a small one must arrive as a single chunk per column for every type. +def test_doget_single_chunk_per_column(): + node.query( + """ + CREATE TABLE mytable ( + id Int64, + s String, + ns Nullable(String), + lc LowCardinality(String), + arr Array(String), + m Map(String, String), + t Tuple(String, String), + fs FixedString(3) + ) ORDER BY id + """ + ) + node.query( + """ + INSERT INTO mytable SELECT + number, toString(number), if(number % 2, NULL, toString(number)), toString(number % 2), + [toString(number)], map('k', toString(number)), (toString(number), 'x'), toFixedString('abc', 3) + FROM numbers(4) + """ + ) + + client, options = get_client() + + descriptor = flight.FlightDescriptor.for_command("SELECT * FROM mytable ORDER BY id") + flight_info = client.get_flight_info(descriptor, options) + table = client.do_get(flight_info.endpoints[0].ticket, options).read_all() + + assert table.num_rows == 4 + for name, column in zip(table.schema.names, table.columns): + assert column.num_chunks == 1, f"column {name} was split into {column.num_chunks} chunks" + + # We don't support any formats different from "Arrow". def test_doget_cmd_select_invalid_format(): node.query("CREATE TABLE mytable (id Int64, name String) ORDER BY id") diff --git a/tests/integration/test_backup_restore_new/test.py b/tests/integration/test_backup_restore_new/test.py index d317a99a0b49..0df792a10ecc 100644 --- a/tests/integration/test_backup_restore_new/test.py +++ b/tests/integration/test_backup_restore_new/test.py @@ -1474,6 +1474,131 @@ def test_system_users_required_privileges(): instance.query("DROP USER u2") +# Access backups include every entity of a type, so these checks need this module's isolated server. +def test_restore_row_policy_replace_requires_scoped_drop(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROW POLICY ON test.table TO u2") + instance.query( + "CREATE ROW POLICY rowpol1 ON test.table AS RESTRICTIVE USING 1 TO ALL" + ) + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.row_policies TO {backup_name}") + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + + restore = f"RESTORE TABLE system.row_policies FROM {backup_name}" + select_filter = "SELECT select_filter FROM system.row_policies WHERE short_name = 'rowpol1' AND database = 'test' AND table = 'table'" + instance.query(f"{restore} SETTINGS create_access='if-not-exists'", user="u2") + assert instance.query(select_filter) == "owner = 1\n" + + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("GRANT DROP ROW POLICY ON test.another_table TO u2") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("DROP ROW POLICY rowpol1 ON test.table") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "" + + instance.query(f"{restore} SETTINGS create_access='create'", user="u2") + assert instance.query(select_filter) == "1\n" + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + instance.query("GRANT DROP ROW POLICY ON test.table TO u2") + instance.query(f"{restore} SETTINGS create_access='replace'", user="u2") + assert instance.query(select_filter) == "1\n" + + +@pytest.mark.parametrize( + "kind,system_table,target", [("USER", "users", "u1"), ("ROLE", "roles", "r1")] +) +def test_restore_access_partial_revoke_cannot_cancel_drop(kind, system_table, target): + instance.query(f"CREATE {kind} {target} SETTINGS max_threads = 1") + instance.query(f"GRANT DROP {kind} ON * TO {target}") + instance.query(f"REVOKE DROP {kind} ON {target} FROM {target}") + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.{system_table} TO {backup_name}") + instance.query(f"ALTER {kind} {target} SETTINGS max_threads = 2") + + # Create the actor after the backup so its grants cannot mask the target's partial revoke. + instance.query("CREATE USER u2") + instance.query(f"GRANT CREATE {kind} ON {target} TO u2") + instance.query(f"GRANT DROP {kind} ON * TO u2 WITH GRANT OPTION") + instance.query(f"REVOKE DROP {kind} ON {target} FROM u2") + restore = f"RESTORE TABLE system.{system_table} FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert f"DROP {kind}" in error + assert "max_threads = 2" in instance.query(f"SHOW CREATE {kind} {target}") + + # Ordinary `DROP` is sufficient; the target's grants exclude `DROP` on itself. + instance.query(f"GRANT DROP {kind} ON {target} TO u2") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query(f"SHOW CREATE {kind} {target}") + + +def test_restore_access_partial_revokes_preserve_grant_and_table_requirements(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("INSERT INTO test.table VALUES (1)") + instance.query("CREATE ROLE r1 SETTINGS max_threads = 1") + instance.query("GRANT SELECT, INSERT ON test.* TO r1 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM r1") + instance.query("REVOKE INSERT ON test.table FROM r1") + backup_name = new_backup_name() + backup_tables = "TABLE system.roles, TABLE test.table" + instance.query(f"BACKUP {backup_tables} TO {backup_name}") + instance.query("ALTER ROLE r1 SETTINGS max_threads = 2") + + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROLE, DROP ROLE ON r1 TO u2") + instance.query("GRANT CREATE TABLE ON test.table TO u2") + instance.query("GRANT SELECT, INSERT ON test.* TO u2 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM u2") + restore = f"RESTORE TABLE system.roles FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert "SELECT" in error + assert "WITH GRANT OPTION" in error + assert "max_threads = 2" in instance.query("SHOW CREATE ROLE r1") + + instance.query("GRANT SELECT ON test.table TO u2 WITH GRANT OPTION") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query("SHOW CREATE ROLE r1") + + instance.query("TRUNCATE TABLE test.table") + instance.query("REVOKE INSERT ON test.table FROM u2") + restore_with_table = ( + f"RESTORE {backup_tables} FROM {backup_name} SETTINGS create_access='replace'" + ) + error = instance.query_and_get_error(restore_with_table, user="u2") + assert "ACCESS_DENIED" in error + assert "INSERT" in error + assert instance.query("SELECT count() FROM test.table") == "0\n" + + instance.query("GRANT INSERT ON test.table TO u2") + instance.query(restore_with_table, user="u2") + assert instance.query("SELECT * FROM test.table") == "1\n" + + def test_system_users_async(): instance.query("CREATE USER u1 IDENTIFIED BY 'qwe123' SETTINGS custom_c = 3") diff --git a/tests/integration/test_crash_log/test.py b/tests/integration/test_crash_log/test.py index 3c11c28add8e..9990917c913c 100644 --- a/tests/integration/test_crash_log/test.py +++ b/tests/integration/test_crash_log/test.py @@ -55,9 +55,14 @@ def test_crash_log_synchronous(started_node): wait_for_clickhouse_stop(started_node) started_node.restart_clickhouse() crashes_count += 1 + # Report the rows that are there. Without them a lost row leaves only `'1' == '2'` behind, + # which says nothing about which of the two crashes failed to record itself. assert ( started_node.query("SELECT COUNT(*) FROM system.crash_log") == f"{crashes_count}\n" + ), started_node.query( + "SELECT event_time_microseconds, signal, signal_description, query " + "FROM system.crash_log ORDER BY event_time_microseconds FORMAT Vertical" ) diff --git a/tests/integration/test_database_glue/test.py b/tests/integration/test_database_glue/test.py index 585fe2899b5c..eac84dd81389 100644 --- a/tests/integration/test_database_glue/test.py +++ b/tests/integration/test_database_glue/test.py @@ -588,6 +588,62 @@ def test_timestamps(started_cluster): assert node.query(f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}`") == "2024-01-01 12:00:00.000000\t2024-01-01 12:00:00.000000\n" +def test_timestamp_types_cache_does_not_keep_metadata(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_ts_cache_{uuid.uuid4().hex}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + database_name = f"db_{test_ref}" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + schema = Schema( + NestedField(field_id=1, name="timestamp", field_type=TimestampType(), required=False), + NestedField(field_id=2, name="timestamptz", field_type=TimestamptzType(), required=False), + ) + table = create_table(catalog, root_namespace, table_name, schema, dir=test_ref) + + create_clickhouse_glue_database(started_cluster, node, database_name) + + def cache_metrics(): + return [ + int(value) + for value in node.query( + "SELECT value FROM system.metrics " + "WHERE metric IN ('GlueCatalogSchemaCacheBytes', 'GlueCatalogSchemaCacheEntries') ORDER BY metric" + ).split() + ] + + bytes_before, entries_before = cache_metrics() + + row = pa.Table.from_pylist( + [{"timestamp": datetime(2024, 1, 1, 12), "timestamptz": datetime(2024, 1, 1, 12, tzinfo=pytz.UTC)}] + ) + versions = 30 + for _ in range(versions): + table.append(row) + description = node.query(f"DESCRIBE TABLE {database_name}.`{root_namespace}.{table_name}`") + assert [line.split("\t")[1] for line in description.splitlines()] == [ + "Nullable(DateTime64(6))", + "Nullable(DateTime64(6, \\'UTC\\'))", + ] + + bytes_after, entries_after = cache_metrics() + assert entries_after - entries_before == versions + + metadata_size = int( + node.query( + f"SELECT max(_size) FROM s3('http://minio1:9001/warehouse-glue/{test_ref}/metadata/*.metadata.json', " + f"'{minio_access_key}', '{minio_secret_key}', 'One')" + ) + ) + assert bytes_after - bytes_before < metadata_size + + node.query(f"DROP DATABASE {database_name}") + + def test_insert(started_cluster): node = started_cluster.instances["node1"] diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index e979a99c18b8..fcdcf17d2989 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -806,3 +806,500 @@ def test_invalid_auth_header_format(started_cluster): """ ) assert "Invalid auth header format" in str(err.value) + + +def test_writes_mutate_update(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_update_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String, y Int32)") + + node.query(f"INSERT INTO {table_ref} VALUES ('123', 1);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456', 2);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('999', 3);", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\t1\n456\t2\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = '777' WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n777\t1\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'goshan dr' WHERE x = '777';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n999\t3\ngoshan dr\t1\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'pudge1000-7' WHERE y = 2;", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "999\t3\ngoshan dr\t1\npudge1000-7\t2\n" + + +def test_writes_mutate_delete(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_delete_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String)") + + # DELETE on empty table is a no-op. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "" + + node.query(f"INSERT INTO {table_ref} VALUES ('123');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('789'), ('890'), ('999');", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + # No-match DELETE keeps the table intact. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '789';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n890\n999\n" + + # Lightweight DELETE syntax should work identically against catalog tables. + node.query(f"DELETE FROM {table_ref} WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '999';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n" + + +def test_iceberg_file_progress_callback(started_cluster): + """ + Regression test for the `IcebergIterator::next` file-progress callback wiring (PR #105413). + + `IcebergIterator` stored a `FileProgressCallback` but never invoked it, so the + per-query `Progress.total_bytes_to_read` stayed at zero for Iceberg scans and + the progress bar showed no estimate. The fix invokes the callback with the data + file size for every object info returned. The assertion below uses the + `FileProgressCallbackInvocations` ProfileEvent, which is incremented inside the + callback lambda installed by `TCPHandler::setFileProgressCallback`, so removing + the `callback(...)` call in `IcebergIterator::next` makes this event stay at + zero for the test query. + """ + node = started_cluster.instances["node1"] + + test_ref = f"test_progress_callback_{uuid.uuid4().hex[:8]}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + table = create_table( + catalog, + root_namespace, + table_name, + DEFAULT_SCHEMA, + PartitionSpec(), + DEFAULT_SORT_ORDER, + ) + + # Append a small but non-empty batch so the iterator returns a data-file entry. + num_rows = 50 + data = [generate_record() for _ in range(num_rows)] + df = pa.Table.from_pylist(data) + table.append(df) + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + # `node.query` uses native TCP, the only protocol path where + # `setFileProgressCallback` is currently wired. `SELECT *` with `FORMAT Null` + # forces a full scan: the metadata-only `SELECT count()` path resolves the row + # count from manifest statistics and bypasses the data-file iterator. + query_id = f"iceberg_progress_callback_{uuid.uuid4().hex}" + node.query( + f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}` FORMAT Null", + query_id=query_id, + ) + + node.query("SYSTEM FLUSH LOGS") + + # `FileProgressCallbackInvocations` is incremented inside the lambda installed + # by `TCPHandler::setFileProgressCallback`. For an Iceberg-table scan it can + # only fire from `IcebergIterator::next` (the generic + # `StorageObjectStorageSource::KeysIterator` path is replaced by + # `IcebergIterator` for Iceberg storage), so a non-zero value proves the + # iterator's `callback(FileProgress(...))` invocation was executed. + profile_event_value = node.query( + f""" + SELECT ProfileEvents['FileProgressCallbackInvocations'] + FROM system.query_log + WHERE query_id = '{query_id}' AND type = 'QueryFinish' + ORDER BY event_time_microseconds DESC + LIMIT 1 + """ + ).strip() + assert profile_event_value, ( + f"`system.query_log` has no `QueryFinish` row for query_id={query_id}." + ) + file_progress_callback_invocations = int(profile_event_value) + assert file_progress_callback_invocations > 0, ( + f"Expected `FileProgressCallbackInvocations` > 0 from the Iceberg scan, " + f"got {file_progress_callback_invocations}. " + f"`IcebergIterator::next` did not invoke the file-progress callback " + f"(regression of PR #105413 wiring)." + ) + + +def test_alter_database_settings_not_supported(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"iceberg_alter_settings_{uuid.uuid4().hex}" + create_clickhouse_iceberg_database(started_cluster, node, db_name) + + fake_token = f"fake_secret_token_{uuid.uuid4().hex}" + + qid_alter = uuid.uuid4().hex + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = '{fake_token}'", + query_id=qid_alter, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING no_such_setting = 1" + ) + assert "BAD_ARGUMENTS" in error or "UNKNOWN_SETTING" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "other_warehouse" not in show_result + assert "onelake_bearer_token" not in show_result + node.query( + f"SELECT name FROM system.tables WHERE database = '{db_name}' SETTINGS show_data_lake_catalogs_in_system_tables = true" + ) + + node.query("SYSTEM FLUSH LOGS system.query_log") + logged_query = node.query( + f"SELECT arrayStringConcat(groupArray(query), '\\n') FROM system.query_log WHERE query_id = '{qid_alter}'" + ) + assert fake_token not in logged_query + assert "[HIDDEN]" in logged_query + + node.query(f"DROP DATABASE {db_name}") + + glue_db_name = f"glue_alter_settings_{uuid.uuid4().hex}" + node.query( + f""" + ATTACH DATABASE {glue_db_name} ENGINE = DataLakeCatalog('http://fake-glue:1') + SETTINGS catalog_type = 'glue', region = 'us-east-1', storage_endpoint = 'http://fake-glue:1/x' + """ + ) + error = node.query_and_get_error( + f"ALTER DATABASE {glue_db_name} MODIFY SETTING region = 'eu-west-1'" + ) + assert "NOT_IMPLEMENTED" in error + node.query(f"DROP DATABASE {glue_db_name}") + + +def test_alter_database_settings_rest_auth_header(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"rest_alter_auth_header_{uuid.uuid4().hex}" + old_header = f"Authorization: Bearer old_{uuid.uuid4().hex}" + new_header = f"Authorization: Bearer new_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-rest:1/api') + SETTINGS catalog_type = 'rest', warehouse = 'wh', auth_header = '{old_header}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING auth_header = '{new_header}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING catalog_credential = 'id:secret'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_header not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_header in engine_full_with_secrets + assert old_header not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_persistence(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_alter_persist_{uuid.uuid4().hex}" + old_token = f"secret_token_{uuid.uuid4().hex}" + new_token = f"secret_token_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-0', onelake_tenant_id = 'tenant-1', onelake_bearer_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_tenant_id = 'tenant-2', onelake_bearer_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_client_id = 'client-1'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = ''" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert new_token not in show_result + assert old_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert "tenant-2" in engine_full_with_secrets + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.restart_clickhouse() + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert "tenant-0" not in show_result + assert "tenant-1" not in show_result + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert "tenant-2" in engine_full + assert "tenant-0" not in engine_full + assert "tenant-1" not in engine_full + assert new_token not in engine_full + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_refresh_token(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_refresh_token_{uuid.uuid4().hex}" + old_token = f"refresh_token_{uuid.uuid4().hex}" + new_token = f"refresh_token_{uuid.uuid4().hex}" + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_refresh_token = '{old_token}' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', oauth_server_use_request_body = 0 + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "oauth_server_use_request_body" in error + + # In refresh-token mode the catalog access token is reused for Azure storage, + # so a non-storage auth_scope is rejected at CREATE time. + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', auth_scope = 'api://my-catalog/.default' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "auth_scope" in error + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_refresh_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = 'token'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert new_token not in engine_full + + node.query(f"DROP DATABASE {db_name}") + + +def test_catalog_listing_error_surfaces_in_system_tables(started_cluster): + """ + Regression test: an error from the catalog while listing tables (e.g. expired + catalog credentials) must not be silently turned into an empty listing when the + user explicitly opted into showing datalake catalogs in system tables with + show_data_lake_catalogs_in_system_tables=1. Without the opt-in the old tolerant + behaviour is kept (system tables must not fail because of one broken catalog). + """ + node = started_cluster.instances["node1"] + + root_namespace = f"clickhouse_{uuid.uuid4()}" + namespace = f"{root_namespace}_test_listing_error" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(namespace) + create_table(catalog, namespace, "table_x") + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + node.query("SYSTEM ENABLE FAILPOINT datalake_get_tables_throw") + try: + assert ( + node.query( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}'" + ).strip() + == "0" + ) + + error = node.query_and_get_error( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name, engine FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + finally: + node.query("SYSTEM DISABLE FAILPOINT datalake_get_tables_throw") + + result = node.query( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "table_x" in result + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") + + +def test_catalog_commit_conflict_reaches_caller_at_once(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_catalog_commit_conflict_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node, root_namespace, table_name, "(x UInt64)" + ) + + # Every sink reads the branch tip in its constructor, and all `max_insert_threads` sinks are + # constructed before the pipeline starts, so all but one of them commit against a stale parent + # and are refused with `409`. That makes the conflict a property of the plan rather than a race. + num_writers = 4 + query_id = uuid.uuid4().hex + node.query( + f"INSERT INTO {table_ref} SELECT number FROM numbers_mt(4000000)", + query_id=query_id, + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + "max_insert_threads": num_writers, + "max_threads": num_writers, + }, + ) + + node.query("SYSTEM FLUSH LOGS system.text_log") + + conflicts, http_requests = map( + int, + node.query( + f""" + SELECT + countIf(logger_name LIKE 'RestCatalog%' AND message LIKE '%updateMetadata conflict%'), + countIf(logger_name = 'ReadWriteBufferFromHTTP') + FROM system.text_log + WHERE query_id = '{query_id}' AND message LIKE '%409%' + """ + ).split(), + ) + + assert conflicts, ( + "no writer was refused, so nothing about conflict handling was exercised" + ) + assert http_requests == conflicts, ( + f"{conflicts} refused commit(s) cost {http_requests} catalog requests, so a conflict is " + f"resent with backoff instead of being handed back to the sink at once" + ) + + assert int(node.query(f"SELECT count() FROM {table_ref}")) == 4000000 + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") diff --git a/tests/integration/test_dotnet_client/test.py b/tests/integration/test_dotnet_client/test.py index 76778a84edbd..80fea52d791a 100644 --- a/tests/integration/test_dotnet_client/test.py +++ b/tests/integration/test_dotnet_client/test.py @@ -54,11 +54,14 @@ def test_dotnet_client(started_cluster, dotnet_container): reference = fp.read() code, (stdout, stderr) = dotnet_container.exec_run( - "dotnet run --host {host} --port {port} --user default --password 123 --database default".format( + "dotnet /client/out/clickhouse.test.dll --host {host} --port {port} --user default --password 123 --database default".format( host=started_cluster.get_instance_ip("node"), port=8123 ), demux=True, ) - assert code == 0 - assert stdout == reference + # These two streams exist nowhere else: the client runs in its own container and nothing in the + # job collects its output. Reporting them here is what makes a client that died on a signal + # diagnosable at all, instead of leaving a bare exit code behind. + assert code == 0, f"stdout:\n{stdout!r}\nstderr:\n{stderr!r}" + assert stdout == reference, f"stderr:\n{stderr!r}" diff --git a/tests/integration/test_git_import/test.py b/tests/integration/test_git_import/test.py index 13c76498e0a5..e1c6fc623d29 100644 --- a/tests/integration/test_git_import/test.py +++ b/tests/integration/test_git_import/test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import logging +import re import time import pytest @@ -40,8 +41,24 @@ def clone_git_repository(repo, dir, commit=None): time.sleep(1) +# `ClickHouseCluster` gives the whole container the running server's profraw merge pool +# (`LLVM_PROFILE_FILE=/debug/it-%c%4m.profraw`), which every `docker exec`-ed process inherits. +# A second writer cannot merge into a continuous-mode profile - it records its own writer's counter +# bias - so in a coverage build the profiling runtime writes +# `LLVM Profile Warning: Unable to merge profile data: source profile file is not compatible.` and +# two `File exists` errors to stderr. Give this one-shot process a file of its own: its coverage is +# still collected and it no longer touches the server's pool. +GIT_IMPORT_PROFILE_FILE = "/debug/git-import-%p.profraw" + +# One progress line per processed commit, which `git-import` writes to stderr. +COMMIT_PROGRESS_RE = re.compile(r"^\d+% \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [0-9a-f]{40} ") + + def run_git_import(dir): - command = f"cd {dir} && /usr/bin/clickhouse git-import 2>&1" + command = ( + f"cd {dir} && LLVM_PROFILE_FILE={GIT_IMPORT_PROFILE_FILE} " + "/usr/bin/clickhouse git-import 2>&1" + ) return node.exec_in_container(["bash", "-c", command]) @@ -176,7 +193,15 @@ def test_git_import(): create_tables() insert_into_tables(dir) - assert output.count("\n") == 26 + # `git-import` prints the `git log` command it runs and the commit count to stdout, and one + # progress line per commit to stderr, which the `2>&1` above merges into the same stream. Match + # those shapes instead of counting every newline, so that a line written by anything other than + # `git-import` - a profiling or sanitizer runtime, a loader warning - fails the thing it + # actually broke rather than this count. + lines = output.splitlines() + assert "git log --reverse --no-merges --pretty=%H" in lines, output + assert "Total 24 commits to process." in lines, output + assert sum(1 for line in lines if COMMIT_PROGRESS_RE.match(line)) == 24, output assert node.query("SELECT count() FROM commits") == "24\n" assert node.query("SELECT count() FROM file_changes") == "35\n" assert node.query("SELECT count(), round(avg(indent), 1) FROM line_changes") == TSV( diff --git a/tests/integration/test_keeper_persistent_watches/test.py b/tests/integration/test_keeper_persistent_watches/test.py index 51eacd351e82..d11c077eaaf2 100644 --- a/tests/integration/test_keeper_persistent_watches/test.py +++ b/tests/integration/test_keeper_persistent_watches/test.py @@ -6,6 +6,7 @@ import os import threading import re +import struct import helpers.keeper_utils as keeper_utils from helpers.cluster import ClickHouseCluster @@ -343,3 +344,57 @@ def cb(_): destroy_zk_client(client) data = keeper_utils.send_4lw_cmd(cluster, node1, cmd="mntr") assert "zk_watch_count\t0" in data + +CHECK_WATCH, REMOVE_WATCH, ADD_WATCH = 17, 18, 106 +ZOK, ZBADARGUMENTS, ZNOWATCHER = 0, -8, -121 +# (opnum, type or mode, expected error): types are 1..5 and modes 0..1, so the last request of each op is valid. +UNKNOWN_TYPE_REQUESTS = [ + (CHECK_WATCH, 0, ZBADARGUMENTS), + (CHECK_WATCH, 6, ZBADARGUMENTS), + (CHECK_WATCH, 1, ZNOWATCHER), + (REMOVE_WATCH, 0, ZBADARGUMENTS), + (REMOVE_WATCH, 6, ZBADARGUMENTS), + (REMOVE_WATCH, 1, ZNOWATCHER), + (ADD_WATCH, -1, ZBADARGUMENTS), + (ADD_WATCH, 2, ZBADARGUMENTS), + (ADD_WATCH, 0, ZOK), +] + +def recv_exactly(sock, size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise EOFError("Keeper closed the connection") + data += chunk + return data + +def send_unknown_type_requests(): + with get_keeper_socket(node1.name) as sock: + handshake = struct.pack(">iqiqi16s", 0, 0, 30000, 0, 16, b"\0" * 16) + sock.sendall(struct.pack(">i", len(handshake)) + handshake) + reply = recv_exactly(sock, struct.unpack(">i", recv_exactly(sock, 4))[0]) + assert struct.unpack(">q", reply[8:16])[0] != 0 + path = b"/testUnknownWatchType" + for xid, (opnum, value, expected) in enumerate(UNKNOWN_TYPE_REQUESTS, start=1): + body = struct.pack(">iii", xid, opnum, len(path)) + path + struct.pack(">i", value) + sock.sendall(struct.pack(">i", len(body)) + body) + reply = recv_exactly(sock, struct.unpack(">i", recv_exactly(sock, 4))[0]) + reply_xid, _, error = struct.unpack(">iqi", reply[:16]) + assert (reply_xid, error) == (xid, expected), (opnum, value) + +def test_watch_requests_with_unknown_type(started_cluster): + # Through Raft (`quorum_reads`), then a restart that replays the logged requests, then through the local read path. + config = "/etc/clickhouse-server/config.d/keeper_config1.xml" + try: + node1.replace_in_config(config, "", "1") + node1.restart_clickhouse() + keeper_utils.wait_until_connected(cluster, node1) + assert "quorum_reads=true" in keeper_utils.send_4lw_cmd(cluster, node1, cmd="conf") + send_unknown_type_requests() + finally: + node1.replace_in_config(config, "1", "") + node1.restart_clickhouse(kill=True) + keeper_utils.wait_until_connected(cluster, node1) + assert "quorum_reads=false" in keeper_utils.send_4lw_cmd(cluster, node1, cmd="conf") + send_unknown_type_requests() diff --git a/tests/integration/test_keeper_remove_rejoin_leader/test.py b/tests/integration/test_keeper_remove_rejoin_leader/test.py index 8cb03c599d26..e51bbbdc7041 100644 --- a/tests/integration/test_keeper_remove_rejoin_leader/test.py +++ b/tests/integration/test_keeper_remove_rejoin_leader/test.py @@ -28,6 +28,7 @@ import json import os +import re import time import uuid from typing import NamedTuple @@ -132,6 +133,46 @@ def started_cluster(): pass +def _relax_timeouts_for_sanitizer(config_path): + """Rewrite a keeper config with relaxed Raft timeouts for sanitizer builds. + + Under sanitizers (ASan, MSan, TSan) CPU overhead can delay Raft + heartbeats enough to trigger spurious leader elections. This bumps + the heartbeat interval and election timeout so the cluster stays + stable even with 3-5x slowdown. + """ + with open(config_path) as f: + content = f.read() + + content = re.sub( + r"\d+", + "2000", + content, + ) + content = re.sub( + r"\d+", + "5000", + content, + ) + content = re.sub( + r"\d+", + "10000", + content, + ) + # Configs for nodes 1/2/3 omit election timeouts — add them. + if "" not in content: + content = re.sub( + r"([ \t]*)", + r"\g<1> 5000\n" + r"\g<1> 10000\n" + r"\g<1>", + content, + ) + + with open(config_path, "w") as f: + f.write(content) + + def send_rcfg(cluster, node, command, timeout_sec=60): result_str = keeper_utils.send_4lw_cmd( cluster, @@ -183,6 +224,30 @@ def test_leader_election_after_rolling_membership_change(started_cluster): for n in [node1, node2, node3]: keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Under sanitizers, Raft heartbeats can be delayed enough to trigger + # spurious leader elections. Detect and relax timeouts if needed. + if node1.is_built_with_sanitizer(): + # Patch all 6 config files on disk. Nodes 4/5/6 will pick them + # up later when start_keeper copies them into the container. + for i in range(1, 7): + _relax_timeouts_for_sanitizer( + os.path.join(CONFIG_DIR, _get_generated_cfg(node_names, i)) + ) + + # Rolling-restart nodes 1/2/3 so they pick up the relaxed + # timeouts. Only one node is down at a time, so quorum is kept. + for node_obj in [node1, node2, node3]: + cfg_name = _get_generated_cfg(node_names, node_id(node_obj)) + node_obj.stop_clickhouse() + node_obj.copy_file_to_container( + os.path.join(CONFIG_DIR, cfg_name), + "/etc/clickhouse-server/config.d/" + cfg_name, + ) + node_obj.start_clickhouse() + + for n in [node1, node2, node3]: + keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Identify the current leader and the two followers dynamically so the # test does not depend on which node wins the initial election. leader = keeper_utils.get_leader(cluster, [node1, node2, node3]) diff --git a/tests/integration/test_mask_sensitive_info/test.py b/tests/integration/test_mask_sensitive_info/test.py index 83dd82d92c8b..7f17c145e335 100644 --- a/tests/integration/test_mask_sensitive_info/test.py +++ b/tests/integration/test_mask_sensitive_info/test.py @@ -725,13 +725,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"icebergAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] # DeltaLake table functions are not available under Memory Sanitizer (Rust code is not instrumented) @@ -742,9 +742,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: @@ -764,13 +764,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"icebergAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_delta_lake: @@ -780,9 +780,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..362c39c90ed8 --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,11 @@ + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py new file mode 100644 index 000000000000..3996927d149f --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py @@ -0,0 +1,102 @@ +import pytest + +from helpers.cluster import ClickHouseCluster, QueryRuntimeException + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) + +TENANT = {"user": "tenant", "password": "tpass"} + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def test_scheduled_refresh_of_definer_view_carries_definer_to_remote_shard( + started_cluster, +): + # Protected data lives only on node2. The tenant exists on both nodes but has no grant on it. + node2.query( + """ + CREATE DATABASE lab; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + CREATE TABLE lab.secrets (id UInt64, payload String) ENGINE = MergeTree ORDER BY id; + INSERT INTO lab.secrets VALUES (1, 'a'), (2, 'b'), (3, 'c'); + """ + ) + # With `table_engines_require_grant = false`, `TABLE ENGINE ON Distributed` is revoked unless the + # user also has `READ` and `WRITE` on the `REMOTE` source. + node1.query( + """ + CREATE DATABASE tenant_db; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT CREATE TABLE, SELECT, INSERT ON tenant_db.* TO tenant; + GRANT TABLE ENGINE ON Distributed TO tenant; + GRANT READ, WRITE ON REMOTE TO tenant; + """ + ) + + node1.query( + """ + CREATE TABLE tenant_db.dist (id UInt64, payload String) + ENGINE = Distributed('secure', 'lab', 'secrets', rand()); + CREATE TABLE tenant_db.target + (id UInt64, payload String, current_user String, authenticated_user String) + ENGINE = MergeTree ORDER BY id; + """, + **TENANT, + ) + + # A direct read through the Distributed table is denied on the remote shard. + assert "ACCESS_DENIED" in node1.query_and_get_error( + "SELECT * FROM tenant_db.dist", **TENANT + ) + + # The shard also checks the allowed hosts of the definer against `initial_address`. A scheduled + # refresh has no client, so it must present itself as coming from the local host of the + # initiator rather than from the unspecified address, which only `HOST ANY` users accept. + node2.query("ALTER USER tenant HOST LOCAL") + + # The refresh runs under the definer's identity and must be denied on the remote shard too. + # Before the fix, the refresh query was sent with an empty `initial_user`, which the remote + # shard treated as interserver mode and executed without any access checks. + node1.query( + """ + CREATE MATERIALIZED VIEW tenant_db.rmv REFRESH EVERY 1 YEAR APPEND TO tenant_db.target + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT id, payload, currentUser() AS current_user, authenticatedUser() AS authenticated_user + FROM tenant_db.dist; + """, + **TENANT, + ) + + with pytest.raises(QueryRuntimeException, match="ACCESS_DENIED"): + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT count() FROM tenant_db.target") == "0\n" + assert "ACCESS_DENIED" in node1.query( + "SELECT exception FROM system.view_refreshes WHERE database = 'tenant_db' AND view = 'rmv'" + ) + + # Once the definer is granted access on the remote shard, the refresh succeeds and the remote + # shard sees the definer as the current and authenticated user. + node2.query("GRANT SELECT ON lab.secrets TO tenant") + node1.query("SYSTEM REFRESH VIEW tenant_db.rmv") + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT * FROM tenant_db.target ORDER BY id", **TENANT) == ( + "1\ta\ttenant\ttenant\n2\tb\ttenant\ttenant\n3\tc\ttenant\ttenant\n" + ) diff --git a/tests/integration/test_restore_replica_metadata_version/test.py b/tests/integration/test_restore_replica_metadata_version/test.py index b35af4075c11..4fc23ce116ae 100644 --- a/tests/integration/test_restore_replica_metadata_version/test.py +++ b/tests/integration/test_restore_replica_metadata_version/test.py @@ -36,6 +36,79 @@ def start_cluster(): cluster.shutdown() +def test_alter_after_concurrent_restore(start_cluster): + zk = cluster.get_kazoo_client("zoo1") + table = "test_concurrent_restore" + zk_path = f"/clickhouse/tables/{table}" + failpoint = "rmt_restore_replica_pause_before_metadata_version_raise" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + for node in [node_1, node_2]: + node.query( + f"CREATE TABLE {table} (n UInt32) " + f"ENGINE = ReplicatedMergeTree('{zk_path}/', '{node.name}') ORDER BY n" + ) + + # Two ALTERs bring the metadata version of the table, and of the part inserted after them, to 2 + for column in ["a", "b"]: + node_1.query( + f"ALTER TABLE {table} ADD COLUMN {column} UInt32", + settings={"alter_sync": 2}, + ) + node_1.query(f"INSERT INTO {table} VALUES (1, 1, 1)") + node_2.query(f"SYSTEM SYNC REPLICA {table}") + for node in [node_1, node_2]: + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + zk_rmr_with_retries(zk, zk_path) + for node in [node_1, node_2]: + node.query(f"SYSTEM RESTART REPLICA {table}") + + # Restore both replicas at the same time, as ON CLUSTER does: node_1 stops after it has + # restored the table in Keeper, before it raises the metadata version to the one of its part, + # and node_2 restores in the meantime by copying node_1 + node_1.query(f"SYSTEM ENABLE FAILPOINT {failpoint}") + restore = node_1.get_query_request(f"SYSTEM RESTORE REPLICA {table}") + node_1.query(f"SYSTEM WAIT FAILPOINT {failpoint} PAUSE") + node_2.query(f"SYSTEM RESTORE REPLICA {table}") + assert ( + node_2.query(f"SELECT is_readonly FROM system.replicas WHERE table = '{table}'") + == "0\n" + ) + node_1.query(f"SYSTEM DISABLE FAILPOINT {failpoint}") + restore.get_answer() + + for node in [node_1, node_2]: + node.query(f"SYSTEM SYNC REPLICA {table}") + + _, stat = zk.get(f"{zk_path}/metadata") + assert stat.version == 2 + for node in [node_1, node_2]: + version, _ = zk.get(f"{zk_path}/replicas/{node.name}/metadata_version") + assert version == b"2" + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + # A replica left below the metadata version of the table rejects every ALTER with CANNOT_ASSIGN_ALTER + node_2.query(f"ALTER TABLE {table} ADD COLUMN c UInt32", settings={"alter_sync": 2}) + node_1.query(f"ALTER TABLE {table} ADD COLUMN d UInt32", settings={"alter_sync": 2}) + for node in [node_1, node_2]: + assert node.query(f"SELECT n, a, b, c, d FROM {table}") == "1\t1\t1\t0\t0\n" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + + def test_fix_metadata_version_on_attach_part_after_restore(start_cluster): zk = cluster.get_kazoo_client("zoo1") diff --git a/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py new file mode 100644 index 000000000000..d90720f797bd --- /dev/null +++ b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py @@ -0,0 +1,99 @@ +""" +An Iceberg manifest-list entry may declare any `manifest_length`. Reading such a table must not +depend on that number: it used to become the metadata cache cell weight and terminate the server. +""" +import os +import shutil +import tempfile + +from helpers.iceberg_utils import get_uuid_str +from test_storage_iceberg_no_spark.test_local_path_traversal import ( + _download_table_from_container, + _get_manifest_paths_from_chain, + _modify_avro_file, +) + +NOCACHE = { + "use_iceberg_metadata_files_cache": False, + "use_parquet_metadata_cache": False, +} +CACHE = {"use_iceberg_metadata_files_cache": True} +HUGE_MANIFEST_LENGTH = 2**62 + + +def _make_table_with_manifest_length(instance, table_name, table_path, new_length): + """Build a well-formed IcebergLocal table with the cache off, then rewrite every + manifest-list entry's `manifest_length`. new_length=None rewrites the file without + changing the value. Returns the manifest files' real total size on disk.""" + instance.query( + f"CREATE TABLE {table_name} (c0 Int) ENGINE = IcebergLocal('{table_path}/', 'Parquet');", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + instance.query( + f"INSERT INTO {table_name} VALUES (1), (2), (3)", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + assert instance.query(f"SELECT count() FROM {table_name}", settings=NOCACHE).strip() == "3" + instance.query(f"DROP TABLE {table_name}") + + temp_dir = tempfile.mkdtemp() + try: + host_path = os.path.join(temp_dir, table_name) + os.makedirs(host_path, exist_ok=True) + _download_table_from_container(instance, table_path, host_path) + manifest_list_rel, manifest_rels = _get_manifest_paths_from_chain(host_path, table_path) + local_manifest_list = os.path.join(host_path, manifest_list_rel) + _modify_avro_file( + local_manifest_list, + ["manifest_length"], + (lambda v: v) if new_length is None else (lambda _: new_length), + ) + instance.copy_file_to_container(local_manifest_list, f"{table_path}/{manifest_list_rel}") + return sum(os.path.getsize(os.path.join(host_path, rel)) for rel in manifest_rels) + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + + +def _read_back(instance, table_path): + """Read with the metadata cache ON, from a cold cache: the cache-miss path is the only + one that builds the cell whose weight the declared length used to set. Returns the + query results plus the cache weight those reads produced.""" + instance.query("SYSTEM DROP ICEBERG METADATA CACHE") + count = instance.query(f"SELECT count() FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + total = instance.query(f"SELECT sum(c0) FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + weight = instance.query( + "SELECT value FROM system.metrics WHERE metric = 'IcebergMetadataFilesCacheBytes'" + ).strip() + return count, total, int(weight) + + +def _assert_weighed_by_real_size(weight, manifest_bytes): + """A manifest is charged three times its size on storage, so the total must clear that + bound. Reading the size from the file rather than hardcoding it keeps this stable while + still failing if the weight ever comes from something other than the real size.""" + assert weight >= 3 * manifest_bytes, f"weight {weight} < 3 * {manifest_bytes}" + + +def test_iceberg_rewritten_manifest_list_is_readable(started_cluster_iceberg_no_spark): + """Control for the test below: the same Avro round-trip with the declared length + untouched. It runs first so that a regression of the fix, which aborts the server and + makes every later query in the package fail to connect, cannot mask this result.""" + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_manifest_list_roundtrip" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length(instance, table_name, table_path, None) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) + + +def test_iceberg_huge_manifest_length_is_readable(started_cluster_iceberg_no_spark): + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_huge_manifest_length" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length( + instance, table_name, table_path, HUGE_MANIFEST_LENGTH + ) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) diff --git a/tests/integration/test_storage_s3/test.py b/tests/integration/test_storage_s3/test.py index eb975f052251..be913f27a387 100644 --- a/tests/integration/test_storage_s3/test.py +++ b/tests/integration/test_storage_s3/test.py @@ -2683,6 +2683,41 @@ def test_page_cache(started_cluster): assert 0 < int(gets) +def test_cache_key_includes_storage(started_cluster): + # The same key with the same content, so the same ETag, in another bucket or behind another endpoint: + # the filesystem cache and the page cache must not serve it the entry filled by the first object. + instance = started_cluster.instances["dummy"] + table_name = f"test_cache_key_includes_storage-{uuid.uuid4()}" + host = f"{started_cluster.minio_host}:{started_cluster.minio_port}" + ip = f"{started_cluster.minio_ip}:{started_cluster.minio_port}" + + for bucket in [started_cluster.minio_bucket, started_cluster.minio_bucket_2]: + instance.query( + f"insert into function s3('http://{host}/{bucket}/{table_name}.tsv', auto, 'x UInt64') select number from numbers(100) SETTINGS s3_truncate_on_insert=1" + ) + + urls = [ + f"http://{host}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{ip}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{host}/{started_cluster.minio_bucket_2}/{table_name}.tsv", + ] + for settings in ["filesystem_cache_name = 'cache1', enable_filesystem_cache=1", "use_page_cache_for_object_storage=1"]: + for url in urls: + query_id = f"{table_name}-{uuid.uuid4()}" + assert "100\n" == instance.query( + f"select sum(ignore(*) + 1) from s3('{url}', 'TSV', 'x UInt64') SETTINGS {settings}", + query_id=query_id, + ) + + instance.query("SYSTEM FLUSH LOGS") + + assert 0 < int( + instance.query( + f"SELECT ProfileEvents['S3GetObject'] FROM system.query_log WHERE query_id = '{query_id}' AND type = 'QueryFinish'" + ) + ) + + def test_archive(started_cluster): id = uuid.uuid4() bucket = started_cluster.minio_bucket diff --git a/tests/integration/test_storage_url/test.py b/tests/integration/test_storage_url/test.py index 8c7bc908f932..fa68686b1f67 100644 --- a/tests/integration/test_storage_url/test.py +++ b/tests/integration/test_storage_url/test.py @@ -115,7 +115,8 @@ def test_table_function_url_access_rights(): f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1" ) - node1.query("GRANT READ ON URL TO u1") + # Like `SELECT`, `DESCRIBE` of a table function also needs `CREATE TEMPORARY TABLE`. + node1.query("GRANT READ ON URL, CREATE TEMPORARY TABLE ON *.* TO u1") assert node1.query( f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1", diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py b/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml new file mode 100644 index 000000000000..0b5411455b46 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml @@ -0,0 +1,6 @@ + + + root + clickhouse + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..af0b7ad21cab --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,14 @@ + + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml new file mode 100644 index 000000000000..ae00b3b543f9 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + ::/0 + + default + default + 1 + + + + + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/test.py b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py new file mode 100644 index 000000000000..f14f501904b5 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py @@ -0,0 +1,299 @@ +# pylint: disable=unused-argument +# pylint: disable=redefined-outer-name +# pylint: disable=line-too-long + +""" +Pushes from streaming engines into a `Distributed` table must reach the shard under the definer. + +`Kafka`, `RabbitMQ` and the other streaming engines never write anywhere themselves: a consumed +batch is pushed only into the dependent materialized views, from a copy of the global context that +has no user. A view with `SQL SECURITY DEFINER` switches that push to the definer. When the view's +target is a `Distributed` table over a cluster with an interserver ``, the definer's name +must travel with the query: before the fix `Context::setUser` left the `ClientInfo` user names +empty, the shard received an empty `initial_user`, treated the query as interserver mode and +executed it with full access. A tenant that could create tables only in its own database could +chain `Kafka -> MATERIALIZED VIEW -> Distributed('secure', default, secret_data)` and write into +a table on the shard it had no `INSERT` grant on. + +The `secure` cluster consists of `node2` only, so a table on `node1` can reach `default.secret_data` +solely over the interserver connection. Every pipeline is built twice with the same statements: by +`tenant`, who has no grants on `node2` and whose rows must be rejected there, and by `writer`, who +has `INSERT` on the target and whose rows must arrive. In both cases the shard must see the +definer's name in `system.query_log`. + +The push is also checked with `distributed_foreground_insert = 0`, where the rows go through the +background directory queue of the `Distributed` table: the persisted insert must keep the definer's +name, although the streaming context has `query_kind = NO_QUERY`. +""" + +import json +import time + +import pika +import pytest + +import helpers.kafka.common as k +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml", "configs/rabbitmq.xml"], + user_configs=["configs/users.xml"], + with_kafka=True, + with_rabbitmq=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + user_configs=["configs/users.xml"], +) + +WRITER = "writer" +TENANT = "tenant" +CREDENTIALS = { + WRITER: {"user": WRITER, "password": "wpass"}, + TENANT: {"user": TENANT, "password": "tpass"}, +} +ROWS_PER_PIPELINE = 2 + +# How long a streaming engine gets to consume the messages and push them to the shard. Consumer +# group setup in Kafka alone can take several seconds. +DELIVERY_WAIT_SECONDS = 60 + +users = pytest.mark.parametrize("user", [WRITER, TENANT]) + + +def database(user): + return f"{user}_db" + + +def query_as(user, sql): + return node1.query(sql, **CREDENTIALS[user]) + + +def remote_rows(): + return int(node2.query("SELECT count() FROM default.secret_data")) + + +def shard_inserts(user, condition): + """Number of `INSERT` queries into the protected table that the shard executed under `user`.""" + node2.query("SYSTEM FLUSH LOGS") + return int( + node2.query( + f""" + SELECT count() FROM system.query_log + WHERE user = '{user}' AND query LIKE 'INSERT INTO default.secret_data%' AND {condition} + """ + ) + ) + + +def shard_finished_inserts(user): + return shard_inserts(user, "type = 'QueryFinish'") + + +def shard_denied_inserts(user): + # The access check happens before the pipeline starts, so the shard logs the denial as + # `ExceptionBeforeStart`. + return shard_inserts( + user, + "type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing') AND exception_code = 497", + ) + + +def wait_until(condition, timeout=DELIVERY_WAIT_SECONDS): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(1) + return False + + +@pytest.fixture(scope="module", autouse=True) +def started_cluster(): + try: + cluster.start() + + # The protected table lives on the shard only. Both users exist on both nodes, but on + # the shard only `writer` may insert into it. + node2.query( + """ + CREATE TABLE default.secret_data (key Int) ENGINE = MergeTree ORDER BY key; + CREATE USER writer IDENTIFIED WITH plaintext_password BY 'wpass'; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT INSERT ON default.secret_data TO writer; + """ + ) + for user in (WRITER, TENANT): + db = database(user) + # Send to the shard synchronously by default, so that a push either delivers the rows + # or fails right away, without a background directory queue in between. + # With `table_engines_require_grant = false`, `TABLE ENGINE` on a source engine is + # revoked unless the user also has `READ` and `WRITE` on its source. + node1.query( + f""" + CREATE USER {user} IDENTIFIED WITH plaintext_password BY '{CREDENTIALS[user]["password"]}' + SETTINGS distributed_foreground_insert = 1; + CREATE DATABASE {db}; + GRANT ALL ON {db}.* TO {user}; + GRANT TABLE ENGINE ON Distributed, TABLE ENGINE ON Kafka, TABLE ENGINE ON RabbitMQ TO {user}; + GRANT READ, WRITE ON REMOTE, READ, WRITE ON KAFKA, READ, WRITE ON RABBITMQ TO {user}; + """ + ) + query_as( + user, + f"CREATE TABLE {db}.dist (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + + yield cluster + finally: + cluster.shutdown() + + +@pytest.fixture(autouse=True) +def clean_remote_table(): + node2.query("TRUNCATE TABLE default.secret_data") + yield + + +def drop_pipeline(user, source): + """Stop the streaming table, so that a rejected push is not retried into the next test.""" + db = database(user) + query_as(user, f"DROP TABLE {db}.{source}_to_dist") + query_as(user, f"DROP TABLE {db}.{source} SYNC") + + +def create_definer_view(user, source, target="dist"): + """A view owned by `user` that pushes the source rows into the user's `Distributed` table.""" + db = database(user) + query_as( + user, + f""" + CREATE MATERIALIZED VIEW {db}.{source}_to_dist TO {db}.{target} + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT key FROM {db}.{source} + """, + ) + + +def check_delivery(user, finished_before, denied_before): + """The shard must have executed the push under the user's name, with the outcome the user's + grants dictate: the rows arrive for `writer` and are rejected for `tenant`.""" + if user == WRITER: + assert wait_until(lambda: remote_rows() == ROWS_PER_PIPELINE) + assert shard_finished_inserts(WRITER) > finished_before + else: + assert wait_until( + lambda: shard_denied_inserts(TENANT) > denied_before or remote_rows() > 0 + ) + assert remote_rows() == 0 + assert shard_denied_inserts(TENANT) > denied_before + + +def check_direct_insert(user): + """The control case: a direct `INSERT` carries the user's name to the shard, where it is checked. + + It passes without the fix as well, so it is not a separate test: bugfix validation requires every + new test to fail on the unfixed binary. It runs before a streaming pipeline instead.""" + db = database(user) + if user == WRITER: + query_as(WRITER, f"INSERT INTO {db}.dist VALUES (1)") + assert remote_rows() == 1 + else: + error = node1.query_and_get_error( + f"INSERT INTO {db}.dist VALUES (1)", **CREDENTIALS[TENANT] + ) + assert "ACCESS_DENIED" in error + assert remote_rows() == 0 + node2.query("TRUNCATE TABLE default.secret_data") + + +@users +@pytest.mark.parametrize("foreground", [1, 0]) +def test_kafka(user, foreground): + db = database(user) + topic = f"definer_interserver_{user}_{foreground}" + k.kafka_create_topic(k.get_admin_client(cluster), topic) + + query_as( + user, + f""" + CREATE TABLE {db}.kafka (key Int) ENGINE = Kafka + SETTINGS kafka_broker_list = 'kafka1:19092', + kafka_topic_list = '{topic}', + kafka_group_name = '{topic}', + kafka_format = 'JSONEachRow', + kafka_flush_interval_ms = 1000 + """, + ) + # A separate `Distributed` table per mode, so that a rejected file left in the background queue + # is dropped together with the table and is not retried into the next test. + target = f"dist_{foreground}" + query_as( + user, + f"CREATE TABLE {db}.{target} (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + # The definer's settings apply to the push. It is not set in the server's profile, because the + # settings of the context the push starts from would override the definer's ones. + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = {foreground}") + create_definer_view(user, "kafka", target) + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + k.kafka_produce( + cluster, topic, [json.dumps({"key": i}) for i in range(ROWS_PER_PIPELINE)] + ) + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "kafka") + query_as(user, f"DROP TABLE {db}.{target} SYNC") + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = 1") + + +@users +def test_rabbitmq(user): + check_direct_insert(user) + db = database(user) + exchange = f"definer_interserver_{user}" + + query_as( + user, + f""" + CREATE TABLE {db}.rabbitmq (key Int) ENGINE = RabbitMQ + SETTINGS rabbitmq_host_port = 'rabbitmq1:5672', + rabbitmq_exchange_name = '{exchange}', + rabbitmq_format = 'JSONEachRow', + rabbitmq_flush_interval_ms = 1000, + rabbitmq_max_block_size = 100 + """, + ) + create_definer_view(user, "rabbitmq") + + # The exchange and the queue are declared by the table in the background; messages + # published before that are dropped by RabbitMQ. + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: RabbitMQ setup completed") + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: Queue .* is declared") + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + + credentials = pika.PlainCredentials("root", "clickhouse") + parameters = pika.ConnectionParameters( + cluster.rabbitmq_ip, cluster.rabbitmq_port, "/", credentials + ) + connection = pika.BlockingConnection(parameters) + channel = connection.channel() + for i in range(ROWS_PER_PIPELINE): + channel.basic_publish( + exchange=exchange, routing_key="", body=json.dumps({"key": i}) + ) + connection.close() + + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "rabbitmq") diff --git a/tests/integration/test_totp_auth/test_totp.py b/tests/integration/test_totp_auth/test_totp.py index d682ecf94848..7aa30c96a53c 100644 --- a/tests/integration/test_totp_auth/test_totp.py +++ b/tests/integration/test_totp_auth/test_totp.py @@ -98,9 +98,37 @@ def test_one_time_password(started_cluster): query_text, user="totuser", password=f"aa+bb+{old_password}" ) - assert "REQUIRED_SECOND_FACTOR" in node.query_and_get_error( - query_text, user="totuser", password=f"aa+bb" + # Without a code the response does not depend on the password, so the error REQUIRED_SECOND_FACTOR + # does not confirm a guessed password: a wrong or an empty password gets exactly the same error + error_without_code = node.query_and_get_error( + query_text, user="totuser", password="aa+bb" ) + assert "REQUIRED_SECOND_FACTOR" in error_without_code + for password in ["wrongpwd", ""]: + assert error_without_code == node.query_and_get_error( + query_text, user="totuser", password=password + ) + + http_responses = [ + node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": password}, + ) + for password in ["aa+bb", "wrongpwd"] + ] + for response in http_responses: + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "767" + assert http_responses[0].text == http_responses[1].text + + response = node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": "aa+bb+000000000"}, + ) + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "516" assert "totuser42\n" == node.query( query_text, user="totuser", password=f"aa+bb+{get_otp('totuser')}" @@ -196,13 +224,17 @@ def test_interactive_totp_authentication(started_cluster): # Then enter wrong TOTP when prompted c.expect("TOTP.*:") - c.send(f"000000", eol="\r") + c.send("000000000", eol="\r") c.expect(expected_error) - with client(command=f"{client_command(user0)} --password aa+bb+000000") as c: + # A wrong code of the configured length (9 digits); a suffix of another length counts as no code + with client(command=f"{client_command(user0)} --password aa+bb+000000000") as c: c.expect(expected_error) + # A wrong password without a code is asked for the code like a right one, and fails only after that with client(command=f"{client_command(user0)} --password wrongpwd") as c: + c.expect("TOTP.*:") + c.send(get_otp(user0), eol="\r") c.expect(expected_error) with client( @@ -370,7 +402,10 @@ def test_one_time_only_no_password(started_cluster): assert f"{user0}42\n" == node.query(query_text, user=user0, password=get_otp(user0)) + # The client cannot know that the account has no password: it asks for the password first with client(command=f"{client_command(user0)}") as c: + c.expect("Password.*:") + c.send("", eol="\r") c.expect("TOTP.*:") c.send(get_otp(user0, offset_steps=1), eol="\r") c.expect(prompt) diff --git a/tests/performance/map_bucketed_serialization.xml b/tests/performance/map_bucketed_serialization.xml index d86c681a4f3b..e5016ad60d46 100644 --- a/tests/performance/map_bucketed_serialization.xml +++ b/tests/performance/map_bucketed_serialization.xml @@ -1,6 +1,6 @@ @@ -107,7 +107,7 @@ CREATE TABLE map_subcol_pw_mixed (id UInt64, tags Map(String, String), value UInt32) @@ -126,7 +126,7 @@ OPTIMIZE TABLE map_subcol_pw_mixed FINAL SETTINGS mutations_sync=1 - diff --git a/tests/performance/prewhere_subcolumn_read_steps.xml b/tests/performance/prewhere_subcolumn_read_steps.xml new file mode 100644 index 000000000000..04cb68d9dd07 --- /dev/null +++ b/tests/performance/prewhere_subcolumn_read_steps.xml @@ -0,0 +1,19 @@ + + + 0 + + + CREATE TABLE t_prewhere_json (id UInt64, j JSON(max_dynamic_paths = 0)) ENGINE = MergeTree ORDER BY id + CREATE TABLE t_prewhere_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0 + + INSERT INTO t_prewhere_json SELECT number, concat('{{"kind":"a","n":', toString(number), ',"payload":"', repeat('x', 2000), '"}}') FROM numbers_mt(3000000) + INSERT INTO t_prewhere_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> repeat('v', 60), range(16))) FROM numbers_mt(10000000) + + + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j)) > 10 + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 + SELECT count() FROM t_prewhere_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 + + DROP TABLE IF EXISTS t_prewhere_json + DROP TABLE IF EXISTS t_prewhere_map + diff --git a/tests/queries/0_stateless/00900_long_parquet_load_2.sh b/tests/queries/0_stateless/00900_long_parquet_load_2.sh index dc8d68888463..b58b54143176 100755 --- a/tests/queries/0_stateless/00900_long_parquet_load_2.sh +++ b/tests/queries/0_stateless/00900_long_parquet_load_2.sh @@ -47,6 +47,10 @@ EXCLUDE=( # malformed on purpose, so loading it here would print an exception. 05035_delta_byte_array_zero_values.parquet 05035_delta_byte_array_decimal.parquet + # `INT96` timestamps outside the `DateTime64(9)` range (throws with the default `date_time_overflow_behavior`), tested by 05443. + 05443_int96_out_of_range.parquet + # `INT96` timestamp on the lower boundary day of the `DateTime64(9)` range, tested by 05444. + 05444_int96_lower_boundary.parquet ) for NAME in $(find "$DATA_DIR" -type f \( -iname '*.parquet' -o -iname '*.parquet.gz' \) -print0 | xargs -0 -n 1 basename | LC_ALL=C sort | grep -vFf <(printf '%s\n' "${EXCLUDE[@]}")); do diff --git a/tests/queries/0_stateless/01035_avg.reference b/tests/queries/0_stateless/01035_avg.reference index 1f47b3a8b7ea..192bceec0560 100644 --- a/tests/queries/0_stateless/01035_avg.reference +++ b/tests/queries/0_stateless/01035_avg.reference @@ -1,6 +1,6 @@ nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan --0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.493856 32355.57552 499999.5 499999.5 499999.5 499999.5 499999.5 499999.5 -0.000500002 0.49999949943727 -0.000005 -0.000004999999999999992 --2767.546272 -999999 --0.50000449943727 +-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.467744 31470.715104 124999.5 124999.5 124999.5 124999.5 124999.5 124999.5 -0.0005000056 0.12499949943764 -0.000005000000000000001 -0.0000050000000000000334 +-3182.944672 +249999 +-0.12500449943764 1 1 \N \N 1 1 diff --git a/tests/queries/0_stateless/01035_avg.sql b/tests/queries/0_stateless/01035_avg.sql index 0f7baddaec57..a8aae4480e66 100644 --- a/tests/queries/0_stateless/01035_avg.sql +++ b/tests/queries/0_stateless/01035_avg.sql @@ -27,7 +27,7 @@ SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(f32), avg(f64), avg(d32), avg(d64), avg(d128), avg(d256) FROM test_01035_avg; -INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 1000000; +INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 250000; SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(u8), avg(u16), avg(u32), avg(u64), avg(u128), avg(u256), diff --git a/tests/queries/0_stateless/01252_weird_time_zone.reference b/tests/queries/0_stateless/01252_weird_time_zone.reference index 90f5bf0e30dd..a93b19a6dd70 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.reference +++ b/tests/queries/0_stateless/01252_weird_time_zone.reference @@ -5,3 +5,41 @@ Pacific/Kwajalein 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Apia 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Enderbury 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Fakaofo 2020-01-02 03:04:05 2020-01-02 00:00:00 3 +--- offset of zones that crossed the international date line +Pacific/Kiritimati 50400 +Pacific/Apia 46800 +Pacific/Fakaofo 46800 +Pacific/Enderbury 46800 +Pacific/Kanton 46800 +Pacific/Kwajalein 43200 +Kwajalein 43200 +--- the same zones before their jump, and a +13:45 zone, must not move +Pacific/Apia -39600 +Pacific/Fakaofo -39600 +Pacific/Chatham 49500 +Pacific/Chatham 45900 +--- negative offsets before the epoch +Africa/Abidjan -968 +Africa/Accra -52 +Africa/Addis_Ababa 9320 +Europe/Moscow 9017 +--- parseDateTime agrees with toDateTime on an affected zone +1 +1 +1 +1 +1 +1 +--- other consumers of the offset ++1400 +2025-06-14 22:00:00 2025-06-16 02:00:00 +2025-06-14 22:00:00.500 2025-06-16 02:00:00.500 +--- consumers that reduce the offset modulo a day must be unaffected +12:00:00 12:00:00.500 +1970-01-02 12:00:00 2025-06-15 00:00:00 12 2025-06-15 +--- daylight saving transitions keep their sub-day offset +-18000 -14400 -18000 +--- inside and outside the lookup table window report the same offset +1 +--- every zone agrees with rendering the instant as local text and reading it back as UTC +0 diff --git a/tests/queries/0_stateless/01252_weird_time_zone.sql b/tests/queries/0_stateless/01252_weird_time_zone.sql index c4919ca4fe01..729eea83216d 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.sql +++ b/tests/queries/0_stateless/01252_weird_time_zone.sql @@ -13,3 +13,56 @@ SELECT 'Pacific/Kwajalein', rand() as r, toHour(toDateTime(r, 'Pacific/Kwajalein SELECT 'Pacific/Apia', rand() as r, toHour(toDateTime(r, 'Pacific/Apia') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Enderbury', rand() as r, toHour(toDateTime(r, 'Pacific/Enderbury') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Fakaofo', rand() as r, toHour(toDateTime(r, 'Pacific/Fakaofo') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; + +-- timezoneOffset must report the true UTC offset, including its whole-day component (issue #115281). +SELECT '--- offset of zones that crossed the international date line'; +SELECT 'Pacific/Kiritimati', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Enderbury', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Enderbury')); +SELECT 'Pacific/Kanton', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kanton')); +SELECT 'Pacific/Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kwajalein')); +SELECT 'Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Kwajalein')); + +SELECT '--- the same zones before their jump, and a +13:45 zone, must not move'; +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Chatham')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Chatham')); + +SELECT '--- negative offsets before the epoch'; +SELECT 'Africa/Abidjan', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Abidjan')); +SELECT 'Africa/Accra', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Accra')); +SELECT 'Africa/Addis_Ababa', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Addis_Ababa')); +SELECT 'Europe/Moscow', timeZoneOffset(toDateTime64(-1900000000, 0, 'Europe/Moscow')); + +SELECT '--- parseDateTime agrees with toDateTime on an affected zone'; +SELECT toUnixTimestamp(parseDateTime('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeOrNull('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTime64('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00', 'yyyy-MM-dd HH:mm:ss', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeBestEffort('2025-06-15 12:00:00', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00 Pacific/Kiritimati', 'yyyy-MM-dd HH:mm:ss z')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- other consumers of the offset'; +SELECT formatDateTime(toDateTime64(1750000000, 0, 'UTC'), '%z', 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'); + +SELECT '--- consumers that reduce the offset modulo a day must be unaffected'; +SELECT CAST(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati') AS Time), CAST(toDateTime64('2025-06-15 12:00:00.5', 3, 'Pacific/Kiritimati') AS Time64(3)); +SELECT toTime(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toStartOfDay(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toHour(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toDate(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- daylight saving transitions keep their sub-day offset'; +SELECT timeZoneOffset(toDateTime('2025-03-09 01:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-03-09 03:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-11-02 03:00:00', 'America/New_York')); + +SELECT '--- inside and outside the lookup table window report the same offset'; +SELECT timeZoneOffset(toDateTime64(1750000000, 0, 'Pacific/Kiritimati')) = timeZoneOffset(toDateTime64(90000000000, 0, 'Pacific/Kiritimati')); + +SELECT '--- every zone agrees with rendering the instant as local text and reading it back as UTC'; +WITH + arrayJoin([toDateTime64(1262347200, 0, 'UTC'), toDateTime64(1750000000, 0, 'UTC'), toDateTime64(2000000000, 0, 'UTC')]) AS ts, + formatDateTime(ts, '%z', time_zone) AS z, + (toInt64(substring(z, 2, 2)) * 3600 + toInt64(substring(z, 4, 2)) * 60) * multiIf(substring(z, 1, 1) = '-', -1, 1) AS reported, + toInt64(toDateTime(formatDateTime(ts, '%Y-%m-%d %H:%i:%S', time_zone), 'UTC')) - toInt64(ts) AS expected +SELECT count() FROM system.time_zones WHERE reported != expected; diff --git a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference index d771371b2644..0eb78aef3648 100644 --- a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference +++ b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference @@ -1 +1 @@ -0bedc9eaf0b07ce14f59ffd25e1a6df6 - +75b5b0cbd2734c37f4f02bd726c4ea60 - diff --git a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh index a44ae6f1e95a..960f2f03174f 100755 --- a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh +++ b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash -# Tags: distributed +# Tags: distributed, no-llvm-coverage +# no-llvm-coverage: the test needs the shard accumulating `repeat('a', 100000)` per row to hit +# `max_memory_usage=1G` and emit `Query memory limit exceeded` before the other shard cancels. +# LLVM source-based coverage instrumentation perturbs this memory-tracking cadence, so the +# expected exception sometimes does not surface on `127.3` before cancellation, leaving an empty +# `grep` match and a flaky FAIL. CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -9,7 +14,11 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # 1 on 127.2 # 2 on 127.3 # max_block_size to fail faster -# max_memory_usage/_shard_num/repeat() will allow failure on the first shard earlier. +# `groupArrayIf` on `_shard_num` makes `127.3` the only shard that can run out of memory: on +# `127.2` the condition is false for every row, so its aggregate states never grow and it just +# streams `system.numbers` until the initiator cancels it. Before this, `127.2` accumulated +# one-byte strings and reached the same `max_memory_usage` only about 20% later than `127.3`, so +# which shard failed first was a race. opts=( "--max_memory_usage=1G" "--max_block_size=50" @@ -17,9 +26,30 @@ opts=( "--max_distributed_connections=2" "--max_bytes_before_external_group_by=0" "--max_bytes_ratio_before_external_group_by=0" + # The query reads `system.numbers` until a shard runs out of memory, so `max_memory_usage` + # has to be the only limit that can stop it. The test profile of the CI configuration + # (tests/config/users.d/limits.yaml) sets `max_rows_to_read = 20000000`, which `127.2` and + # the initiator reach at about the same time as `127.3` reaches `max_memory_usage`; the query + # then fails with `TOO_MANY_ROWS` instead of `MEMORY_LIMIT_EXCEEDED` and the `grep` below + # finds nothing. + "--max_rows_to_read=0" + # `127.2` now never fails on its own, so if the cancellation this test is about ever breaks, + # the query would stream forever and the test would be killed by the runner's timeout with no + # output. Fail it with `TIMEOUT_EXCEEDED` instead, far above the ~1s the expected exception + # needs. + "--max_execution_time=100" ) -${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArray(repeat('a', if(_shard_num == 2, 100000, 1))), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" |& { - # the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. - grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" - # while if this will not correctly then it will got the exception from the 127.2:9000 and fail -} +LOG="$CLICKHOUSE_TMP/err-$CLICKHOUSE_DATABASE" +trap 'rm -f "$LOG"' EXIT + +${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArrayIf(repeat('a', 100000), _shard_num == 2), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" > "$LOG" 2>&1 +CODE=$? + +# the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. +# while if this will not correctly then it will got the exception from the 127.2:9000 and fail +if ! grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" "$LOG"; then + # stderr only on the failing path: a test that writes there and exits 0 is a FAIL for the runner. + echo "Fail, Code: $CODE, client output:" >&2 + cat "$LOG" >&2 + exit 1 +fi diff --git a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 index 2b1dc6c1c781..89f267e614a3 100644 --- a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 +++ b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 @@ -1,4 +1,8 @@ --- Tags: long +-- Tags: long, no-msan +-- no-msan: 5 join algorithms x ~78 statements, several of them deliberately spilling, average +-- ~183s under MSan against ~4s in a release build; the p99 is 73% of the 600s per-test budget, so +-- a run that gets killed on the timeout is an ordinary tail event. Join implicit-cast semantics +-- get no MSan-specific coverage, and the test still runs under ASan, UBSan and TSan. SET enable_analyzer = 1; DROP TABLE IF EXISTS t1; diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference index 9942759a9480..2d3bd2d2ebfd 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference @@ -1,3 +1,5 @@ 1 10 42 53 1 10 42 53 1 10 42 53 +1 +1 0 0 0 diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql index c49bf392895b..31bf6c5e6524 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql @@ -6,3 +6,13 @@ insert into function file(currentDatabase() || '_data_02302.orc') select 1 as x, select * from file(currentDatabase() || '_data_02302.orc', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_orc_allow_missing_columns=1; insert into function file(currentDatabase() || '_data_02302.arrow') select 1 as x, null::Nullable(UInt8) as xx settings engine_file_truncate_on_insert=1; select * from file(currentDatabase() || '_data_02302.arrow', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_arrow_allow_missing_columns=1; + +-- The next two queries test the native Parquet reader, so they pin it (some release branches still randomize it off). +-- A count-only read reads just the single smallest declared column, so `d` must stay strictly +-- narrower than every other column for this to exercise a defaulted one. The count cache would +-- answer before a reader exists, and the two count-only optimizations are randomized off in some runs, so all three are pinned. +-- Missing columns are rejected so that a read which is not count-only fails here instead of +-- synthesizing `d` into a correctly sized mask and returning the same count with no guard in place. +select count() from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt64, d UInt8 default 10') settings use_cache_for_count_from_files = 0, optimize_count_from_files = 1, optimize_trivial_count_query = 1, input_format_parquet_allow_missing_columns = 0, input_format_parquet_use_native_reader_v3 = 1; +-- With the setting off no `default` expression is applied, so the columns keep their type defaults. +select * from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_parquet_allow_missing_columns=1, input_format_defaults_for_omitted_fields=0, input_format_parquet_use_native_reader_v3=1; diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference new file mode 100644 index 000000000000..0f9d2713f87d --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference @@ -0,0 +1 @@ +idx text diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql new file mode 100644 index 000000000000..a629b362ee8e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql @@ -0,0 +1,24 @@ +-- An `ALTER` that adds an index is authorized against the schema the whole statement produces. +-- That must not skip the validation of its other commands and run into an exception. + +SET enable_full_text_index = 1; + +DROP TABLE IF EXISTS tab; +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab + RENAME COLUMN missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 1; -- { serverError NOT_FOUND_COLUMN_IN_BLOCK } + +ALTER TABLE tab + RENAME COLUMN val TO a, + RENAME COLUMN a TO b, + ADD INDEX idx(id) TYPE minmax GRANULARITY 1; -- { serverError NOT_IMPLEMENTED } + +ALTER TABLE tab + RENAME COLUMN IF EXISTS missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1; + +SELECT name, type FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab'; + +DROP TABLE tab; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.reference b/tests/queries/0_stateless/02346_text_index_transform_access.reference new file mode 100644 index 000000000000..1c382f1ae6da --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.reference @@ -0,0 +1,19 @@ +1. Direct call denied. +2. Denied in a preprocessor. +3. Denied when nested under a String result. +4. Denied via ALTER ADD INDEX. +5. Unprivileged expression unaffected. +1 +6. Accepted with the privilege, so not a blocklist. +1 +7. Existing index stays readable without the privilege. +1 +8. Unrelated ALTER does not re-authorize. +1 +9. Neither does DETACH/ATTACH. +1 +10. Redeclaring with a privileged function is denied. +11. The transform preflight does not reject what a plain ALTER accepts. +idx_pre +12. A statement without a transform is not analyzed at all. +idx_minmax diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.sql b/tests/queries/0_stateless/02346_text_index_transform_access.sql new file mode 100644 index 000000000000..62903e79d44b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.sql @@ -0,0 +1,124 @@ +-- Text index `preprocessor` expressions must only use functions the user declaring +-- the index is permitted to run. +-- +-- The test needs a function the current user may not run. Introspection functions fit: they are +-- refused both without the grant and, as here, with `allow_introspection_functions = 0`. Using the +-- setting keeps the test in plain SQL, with no second user to create. + +DROP TABLE IF EXISTS tab; + +-- The test configuration sets this to 1. +SET allow_introspection_functions = 0; + +SELECT '1. Direct call denied.'; + +SELECT demangle('_ZNK2DB7Context9getAccessEv'); -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. Denied in a preprocessor.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Denied when nested under a String result.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, demangle(val))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '4. Denied via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)); -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '5. Unprivileged expression unaffected.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'Hello World'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; + +SELECT '6. Accepted with the privilege, so not a blocklist.'; + +SET allow_introspection_functions = 1; + +-- `demangle` returns a non-mangled argument unchanged. +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'hello world'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '7. Existing index stays readable without the privilege.'; + +SET allow_introspection_functions = 0; + +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '8. Unrelated ALTER does not re-authorize.'; + +ALTER TABLE tab ADD COLUMN extra UInt8 DEFAULT 0; +ALTER TABLE tab RENAME COLUMN val TO val2; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '9. Neither does DETACH/ATTACH.'; + +DETACH TABLE tab; +ATTACH TABLE tab; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '10. Redeclaring with a privileged function is denied.'; + +ALTER TABLE tab DROP INDEX idx, + ADD INDEX idx(val2) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val2)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '11. The transform preflight does not reject what a plain ALTER accepts.'; + +CREATE TABLE tab_preflight (id UInt64, val String, num UInt64) +ENGINE = MergeTree ORDER BY id SETTINGS auto_statistics_types = 'minmax'; + +-- The preflight must drop implicit statistics too, or `ADD STATISTICS` looks like a duplicate. +ALTER TABLE tab_preflight ADD INDEX idx_pre(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1, + ADD STATISTICS num TYPE minmax; + +SELECT name FROM system.data_skipping_indices +WHERE database = currentDatabase() AND table = 'tab_preflight' ORDER BY name; + +DROP TABLE tab_preflight; + +SELECT '12. A statement without a transform is not analyzed at all.'; + +SET allow_statistics = 1; +CREATE TABLE tab_plain (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS auto_statistics_types = 'minmax'; + +ALTER TABLE tab_plain ADD INDEX idx_minmax(x) TYPE minmax GRANULARITY 1, ADD STATISTICS x TYPE minmax; + +SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab_plain'; + +DROP TABLE tab_plain; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference new file mode 100644 index 000000000000..8a97bd9c341e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference @@ -0,0 +1,3 @@ +1. ALTER ADD INDEX is denied. +2. CREATE TABLE is denied. +3. Accepted with the privilege. diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql new file mode 100644 index 000000000000..67ca0d15dcdc --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql @@ -0,0 +1,40 @@ +-- Tags: zookeeper, no-replicated-database +-- no-replicated-database: the test creates its own Replicated database + +-- A Replicated database hands the DDL to replicas that apply it without the submitting user, so the +-- permission check happens on the node it was submitted to. See 02346_text_index_transform_access +-- for the checks themselves, and 02346_text_index_transform_on_cluster for `ON CLUSTER`. + +SET allow_introspection_functions = 0; + +-- {CLICKHOUSE_DATABASE_1} may be left over from a previous run, hence the DROP. +DROP DATABASE IF EXISTS {CLICKHOUSE_DATABASE_1:Identifier}; +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} +ENGINE = Replicated('/clickhouse/02346_text_index_transform_access/{database}', 'shard1', 'replica1') FORMAT Null; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab (id UInt64, val String) +ENGINE = MergeTree ORDER BY id FORMAT Null; + +SELECT '1. ALTER ADD INDEX is denied.'; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. CREATE TABLE is denied.'; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab_denied +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Accepted with the privilege.'; + +SET allow_introspection_functions = 1; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1 FORMAT Null; + +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} FORMAT Null; diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.reference b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference new file mode 100644 index 000000000000..3954d852fafa --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference @@ -0,0 +1,6 @@ +1. A set from a table. +2. A subquery. +3. A dictionary lookup. +4. The same via ALTER ADD INDEX. +5. A literal set is still accepted. +1 diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.sql b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql new file mode 100644 index 000000000000..9d785850ee83 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql @@ -0,0 +1,68 @@ +-- Text index transforms are analysed under the global context, so anything that reads a table or a +-- dictionary while being analysed would do it with full access, and constant folding could reveal +-- what it read. A transform must be a pure function of the indexed value, so these are rejected +-- before any analysis. See 02346_text_index_transform_access for the function permission checks. + +DROP TABLE IF EXISTS tab; +DROP TABLE IF EXISTS set_source; +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dict_source; + +CREATE TABLE set_source (x String) ENGINE = Set; +INSERT INTO set_source VALUES ('secret'); + +CREATE TABLE dict_source (id UInt64, value String) ENGINE = MergeTree ORDER BY id; +INSERT INTO dict_source VALUES (1, 'secret'); +CREATE DICTIONARY dict (id UInt64, value String) PRIMARY KEY id +SOURCE(CLICKHOUSE(TABLE 'dict_source')) LAYOUT(FLAT()) LIFETIME(0); + +SELECT '1. A set from a table.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '2. A subquery.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, (SELECT any(value) FROM dict_source))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '3. A dictionary lookup.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '4. The same via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN (SELECT x FROM set_source), val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))); -- { serverError INCORRECT_QUERY } + +SELECT '5. A literal set is still accepted.'; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN ('hello', 'world'), val, val)); +INSERT INTO tab VALUES (1, 'hello there'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; +DROP DICTIONARY dict; +DROP TABLE dict_source; +DROP TABLE set_source; diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference new file mode 100644 index 000000000000..91fa6db49214 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference @@ -0,0 +1,14 @@ +1. ALTER ADD INDEX with a transform is refused. +1 +2. CREATE with a transform is refused. +1 +3. Refused on the legacy entry-format path too, which normalizes on the host. +1 +4. Indices inherited by CREATE AS on the legacy path are refused. +1 +5. An index without a transform is unaffected. +idx_plain +6. CREATE AS with an explicit engine and no privilege on the source. +SHOW COLUMNS ON default.tab +7. The same for a source that does not exist. +SHOW COLUMNS ON default.missing diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh new file mode 100755 index 000000000000..15b49c8bf03b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database +# no-replicated-database: ON CLUSTER is not allowed for a Replicated database + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The hosts of an `ON CLUSTER` query resolve a text index transform against their own schema and +# without the submitting user, so it is refused unless they run as that user. + +USER="user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER IF EXISTS $USER; + CREATE TABLE tab (id UInt64, val String, lowered String ALIAS lower(val)) ENGINE = MergeTree ORDER BY id; +" + +echo '1. ALTER ADD INDEX with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lowered) +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '2. CREATE with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_transform ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '3. Refused on the legacy entry-format path too, which normalizes on the host.' +$CLICKHOUSE_CLIENT --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_legacy ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '4. Indices inherited by CREATE AS on the legacy path are refused.' +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.src_transform (id UInt64, val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val))) ENGINE = MergeTree ORDER BY id" +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_inherited ON CLUSTER test_shard_localhost + AS ${CLICKHOUSE_DATABASE}.src_transform ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '5. An index without a transform is unaffected.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx_plain(val) TYPE text(tokenizer = 'splitByNonAlpha') +" +$CLICKHOUSE_CLIENT -q "SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab' ORDER BY name" + +# With an explicit engine `setEngine` does not look at `AS src`, and the inherited indices are inspected +# on the initiator, so describing the source has to be authorized first. +$CLICKHOUSE_CLIENT -n -q " + CREATE USER $USER; + GRANT CREATE TABLE ON ${CLICKHOUSE_DATABASE}.dst TO $USER; + GRANT TABLE ENGINE ON MergeTree TO $USER; +" + +echo '6. CREATE AS with an explicit engine and no privilege on the source.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.tab ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.tab" + +echo '7. The same for a source that does not exist.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.missing ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.missing" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER $USER; + DROP TABLE tab; + DROP TABLE src_transform; +" diff --git a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 index 45c6b5fe5f3f..d05007d356e4 100644 --- a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 +++ b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 @@ -1,4 +1,4 @@ --- Tags: long +-- Tags: long, no-msan SET enable_analyzer = 1; SET single_join_prefer_left_table = 0; diff --git a/tests/queries/0_stateless/02426_orc_bug.reference b/tests/queries/0_stateless/02426_orc_bug.reference index 4f76072e70d1..d5f93b43aa8d 100644 --- a/tests/queries/0_stateless/02426_orc_bug.reference +++ b/tests/queries/0_stateless/02426_orc_bug.reference @@ -1 +1 @@ -64a50db9526e0e3aa8c969939922658d - +f8d66b83061a9b0ce960c0b9ce32a64c - diff --git a/tests/queries/0_stateless/02884_authentication_quota.reference b/tests/queries/0_stateless/02884_authentication_quota.reference index d8ed6d97b505..c41269381185 100644 --- a/tests/queries/0_stateless/02884_authentication_quota.reference +++ b/tests/queries/0_stateless/02884_authentication_quota.reference @@ -6,7 +6,7 @@ > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -18,9 +18,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login @@ -32,7 +32,7 @@ QUOTA_EXCEEDED > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -44,9 +44,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login diff --git a/tests/queries/0_stateless/02884_authentication_quota.sh b/tests/queries/0_stateless/02884_authentication_quota.sh index bca24bf6cc27..b092e0b35359 100755 --- a/tests/queries/0_stateless/02884_authentication_quota.sh +++ b/tests/queries/0_stateless/02884_authentication_quota.sh @@ -18,7 +18,7 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Quota is exceeded 1 >= 1. Login with correct password should fail." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" @@ -37,10 +37,10 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' - ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Also try to login with correct password. Quota should stay exceeded." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference new file mode 100644 index 000000000000..8c21354a38e1 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference @@ -0,0 +1,6 @@ +1 +0 +0 +1 +0 +0 diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh new file mode 100755 index 000000000000..bc088b046271 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel, no-replicated-database, no-shared-merge-tree +# no-parallel: uses a global failpoint and two replicas with stopped replication queues. +# no-fasttest: a test that arms a global failpoint must run alone, and such tests are kept out of the fast test. +# no-replicated-database: the test controls replication queues of individual tables. +# no-shared-merge-tree: the failpoint is in the `ReplicatedMergeTree` block allocation path. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -e + +function cleanup_tables() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R2" 2>/dev/null || true + wait || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R2 SYNC" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R1 SYNC" 2>/dev/null || true +} + +function cleanup() +{ + cleanup_tables +} +trap cleanup EXIT + +# Runs a lightweight update of partition 2 whose rows arrive from the other replica while the update +# waits for committing inserts, and checks that the update has patched all of them. +function run_case() +{ + local name=$1 + local assignment=$2 + R1=t_lwu_prune_empty_03100_58_${name}_r1 + R2=t_lwu_prune_empty_03100_58_${name}_r2 + + $CLICKHOUSE_CLIENT --query " + SET insert_keeper_fault_injection_probability = 0.0; + + DROP TABLE IF EXISTS $R2 SYNC; + DROP TABLE IF EXISTS $R1 SYNC; + + CREATE TABLE $R1 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r1') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + CREATE TABLE $R2 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r2') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + INSERT INTO $R1 SELECT 1, number, 1 FROM numbers(50); + INSERT INTO $R1 SELECT 2, number, 1 FROM numbers(50); + SYSTEM SYNC REPLICA $R2; + + ALTER TABLE $R1 DELETE WHERE p = 2 SETTINGS mutations_sync = 2; + + SYSTEM STOP REPLICATION QUEUES $R1; + + SELECT count() FROM system.parts + WHERE database = currentDatabase() AND table = '$R1' AND partition_id = '2' AND active AND rows = 0; + " + + $CLICKHOUSE_CLIENT --query "INSERT INTO $R2 SELECT 2, 1000000 + number, 1 FROM numbers(30)" + + block_numbers_path="/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name/block_numbers/2" + block_count_before=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + + $CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" + + $CLICKHOUSE_CLIENT --query "UPDATE $R1 SET v = $assignment WHERE p = 2 SETTINGS enable_lightweight_update = 1, enable_shared_storage_snapshot_in_query = 1" & + + for _ in {0..300}; do + sleep 0.3 + block_count_after=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + if [[ "$block_count_after" -gt "$block_count_before" ]]; then + break + fi + done + + if [[ "$block_count_after" -le "$block_count_before" ]]; then + echo "Failed to observe a new block allocation for lightweight update at $block_numbers_path" >&2 + exit 2 + fi + + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" + + wait + + + result=$($CLICKHOUSE_CLIENT --query " + SYSTEM SYNC REPLICA $R1; + SYSTEM SYNC REPLICA $R2; + + SELECT count() FROM $R1 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1; + SELECT count() FROM $R2 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1") + + if [[ "$result" != $'0\n0' ]]; then + echo "Unexpected unpatched-row counts in case $name:" >&2 + echo "$result" >&2 + $CLICKHOUSE_CLIENT --query " + SELECT 'patch parts', name, rows FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND startsWith(name, 'patch') + ORDER BY table, name; + SELECT 'partition 2 parts', table, name, rows, min_block_number, max_block_number FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND partition_id = '2' + ORDER BY table, name; + SELECT 'frozen mutation version', table, mutation_id, block_numbers.partition_id, block_numbers.number + FROM system.mutations + WHERE database = currentDatabase() AND table = '$R1' + ORDER BY create_time DESC;" >&2 + exit 1 + fi + + echo "$result" + + cleanup_tables +} + +run_case plain 999 +# The `IN` operand names the updated table, so validating it in `InterpreterUpdateQuery` takes a storage +# snapshot of the table before the update waits for committing inserts. +run_case in_assignment "if((p, x, v) IN t_lwu_prune_empty_03100_58_in_assignment_r1, 999, 998)" diff --git a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh index 6819deea1fc1..35498f567da2 100755 --- a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh +++ b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh @@ -15,7 +15,7 @@ ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} SYNC" ${CLICKHOUSE_CLIENT} --query "CREATE TABLE ${TABLE_NAME} (c0 Int) ENGINE = File(ORC, '${USER_FILES_PATH}/${TEST_FILE}')" ${CLICKHOUSE_CLIENT} --query "INSERT INTO TABLE ${TABLE_NAME} (c0) VALUES (1),(2),(3),(5.4)" -${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx SETTINGS input_format_orc_use_fast_decoder = 0" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} sync" diff --git a/tests/queries/0_stateless/03784_bad_base_backup.sh b/tests/queries/0_stateless/03784_bad_base_backup.sh index ef0cdd18a110..6ac1401f2fea 100755 --- a/tests/queries/0_stateless/03784_bad_base_backup.sh +++ b/tests/queries/0_stateless/03784_bad_base_backup.sh @@ -48,3 +48,15 @@ thread & thread & wait + +# The databases are created outside of the test database, so they must be dropped here: +# leftover `Replicated` databases break tests that enumerate all `Replicated` databases of the server, +# such as `05061_system_drop_database_replica_access`. Wait for the `ASYNC` backups to finish first. +for _ in $(seq 1 600) +do + [[ $($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.backups WHERE status = 'CREATING_BACKUP' AND name LIKE '%${CLICKHOUSE_DATABASE}%'") == 0 ]] && break + sleep 0.1 +done + +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d1_$CLICKHOUSE_DATABASE SYNC" +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d2_$CLICKHOUSE_DATABASE SYNC" diff --git a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh index 6db574849a79..6548e86729d7 100755 --- a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh +++ b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh @@ -16,7 +16,7 @@ EOF (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; -${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user"; +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE, CREATE TEMPORARY TABLE ON *.* TO $user"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "FILE_DOESNT_EXIST") >= 1 )) && echo "FILE_DOESNT_EXIST" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "CANNOT_STAT") >= 1 )) && echo "CANNOT_STAT" || echo "UNEXPECTED"; diff --git a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh index 3e4c623ee8e6..8caf9b22b41b 100755 --- a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh +++ b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh @@ -30,7 +30,7 @@ $CLICKHOUSE_CLIENT --allow_experimental_kafka_offsets_storage_in_keeper 1 -q " kafka_format = 'JSONEachRow', kafka_max_block_size = 100, kafka_keeper_path = '$KEEPER_PATH', - kafka_replica_name = 'r1'; + kafka_replica_name = '{replica}'; " # Create destination table diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference index 491b7765b057..7d4cda3c2395 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference @@ -16,7 +16,7 @@ 1 1 1 --- Optimization also works with basic (non-bucketed) serialization +-- No optimization with basic (non-bucketed) serialization 1 -- Correctness: results with optimization 7 7 70 diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql index c9eaddb60218..e161a47a3cfa 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql @@ -150,20 +150,19 @@ SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHE -- ========================================== -- Section 8: basic serialization (not with_buckets) --- The optimization still applies because DataTypeMap exposes dynamic subcolumns --- regardless of serialization version. With basic serialization, the whole map is --- read and the key is extracted; with_buckets reads only the relevant bucket. +-- The rewrite is not applied: with basic serialization the key subcolumn reads the whole map anyway. -- ========================================== DROP TABLE t_map_subcolumns; CREATE TABLE t_map_subcolumns (id UInt64, m Map(String, UInt64)) -ENGINE = MergeTree ORDER BY id; +ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; INSERT INTO t_map_subcolumns SELECT number, map('key1', number) FROM numbers(10); -SELECT '-- Optimization also works with basic (non-bucketed) serialization'; -SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; +SELECT '-- No optimization with basic (non-bucketed) serialization'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; -- ========================================== -- Section 9: Correctness - verify actual query results after optimization diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference index 89024e17dd7f..a108bf0eea76 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference @@ -54,7 +54,7 @@ 98 98 2 99 99 1 -- Section 4: PREWHERE with basic serialization --- Optimization still rewrites to subcolumn +-- No rewrite to subcolumn 1 -- Correctness: PREWHERE with basic serialization 96 96 960 diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql index a3594aff2a1b..db0474ce8c2a 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql @@ -133,7 +133,7 @@ DROP TABLE t_map_prewhere; -- ========================================== -- Section 4: PREWHERE with basic serialization (non-bucketed) --- Optimization still applies, but reads the whole map internally. +-- No rewrite to the key subcolumn, it would read the whole map anyway. -- ========================================== DROP TABLE IF EXISTS t_map_prewhere; @@ -141,14 +141,15 @@ CREATE TABLE t_map_prewhere (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'basic', + map_serialization_version_for_zero_level_parts = 'basic', min_bytes_for_wide_part = 1, min_rows_for_wide_part = 1; INSERT INTO t_map_prewhere SELECT number, map('key1', number, 'key2', number * 10) FROM numbers(100); SELECT '-- Section 4: PREWHERE with basic serialization'; -SELECT '-- Optimization still rewrites to subcolumn'; -SELECT count() > 0 FROM ( +SELECT '-- No rewrite to subcolumn'; +SELECT count() = 0 FROM ( EXPLAIN actions = 1 SELECT id, m FROM t_map_prewhere PREWHERE m['key1'] > 95 ) WHERE explain LIKE '%m.key_key1%'; diff --git a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql index 05fe94c220e0..d0a35aacb003 100644 --- a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql +++ b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql @@ -1,7 +1,7 @@ -- Tags: no-random-settings -- Tests that text indexes built on mapValues(m) work correctly when the analyzer --- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form. +-- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form, which it does only for bucketed Maps. SET enable_analyzer = 1; @@ -16,7 +16,8 @@ CREATE TABLE tab ) ENGINE = MergeTree ORDER BY id -SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0; +SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; INSERT INTO tab VALUES (0, {'service':'web-api'}), (1, {'service':'backend'}), (2, {'service':'frontend'}); diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference new file mode 100644 index 000000000000..e99e8dbc05e4 --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference @@ -0,0 +1,8 @@ +1 +0 +1 +0 +1 +0 +1 +0 diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql new file mode 100644 index 000000000000..0965065b3bbe --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql @@ -0,0 +1,9 @@ +SELECT hasSubsequenceUTF8('', ''); +SELECT hasSubsequenceUTF8('', 'a'); +SELECT hasSubsequenceCaseInsensitiveUTF8('', ''); +SELECT hasSubsequenceCaseInsensitiveUTF8('', 'A'); + +SELECT hasSubsequenceUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceUTF8(materialize(''), materialize('a')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('A')); diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference new file mode 100644 index 000000000000..382c328e0874 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference @@ -0,0 +1,3 @@ +2 20 +2 20 +2099-01-01 00:00:00 20 diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql new file mode 100644 index 000000000000..06a0cd88ef07 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql @@ -0,0 +1,34 @@ +SET mutations_sync = 1; + +-- Test that TTL expressions referencing subcolumns work correctly. +-- Previously, executeExpressionAndGetColumn used getByName which failed +-- for subcolumns not present as top-level columns in the block. +-- We test both INSERT (updateTTL in MergeTreeDataWriter) and merge +-- (TTL algorithms in the merge pipeline) paths. + +-- Case 1: Tuple subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol; +CREATE TABLE t_ttl_subcol (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL t.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol VALUES ((1, '2000-01-01'), 10); +INSERT INTO t_ttl_subcol VALUES ((2, '2099-01-01'), 20); +OPTIMIZE TABLE t_ttl_subcol FINAL; +SELECT t.a, val FROM t_ttl_subcol ORDER BY val; +DROP TABLE t_ttl_subcol; + +-- Case 2: Tuple subcolumn with function in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol_func; +CREATE TABLE t_ttl_subcol_func (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL toDate(t.d) + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol_func VALUES ((1, '2000-01-01 12:00:00'), 10); +INSERT INTO t_ttl_subcol_func VALUES ((2, '2099-01-01 12:00:00'), 20); +OPTIMIZE TABLE t_ttl_subcol_func FINAL; +SELECT t.a, val FROM t_ttl_subcol_func ORDER BY val; +DROP TABLE t_ttl_subcol_func; + +-- Case 3: JSON subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_json_subcol; +CREATE TABLE t_ttl_json_subcol (json JSON(d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL json.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2000-01-01"}', 10); +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2099-01-01"}', 20); +OPTIMIZE TABLE t_ttl_json_subcol FINAL; +SELECT json.d, val FROM t_ttl_json_subcol ORDER BY val; +DROP TABLE t_ttl_json_subcol; diff --git a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh index 6dfb8038211b..1639da5845ab 100755 --- a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh +++ b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh @@ -7,10 +7,9 @@ # grind (and could overflow the native stack), uncancellable. It must now be rejected as # TOO_DEEP_RECURSION once the nesting exceeds max_parser_depth. # -# 2. The Apache ORC C++ library (convertType) builds its own orc::Type tree by recursing over the -# file footer before any ClickHouse code runs. A pathologically deep file used to overflow the -# native stack there (crashing the process / triggering the OOM killer). The library now bounds -# the nesting depth and rejects such a file instead of crashing. +# 2. The ORC reader builds its type tree by recursing over the file footer before the schema +# inference runs. A pathologically deep file must not overflow the native stack there: the +# reader bounds the nesting depth and rejects such a file. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -55,18 +54,24 @@ orc.write_table(pa.table({'x': pa.array([], type=t)}), '$2') " } -# (1) A moderate file (200 levels) that the ORC library builds fine, with max_parser_depth lowered +# (1) A moderate file (200 levels) that the ORC reader builds fine, with max_parser_depth lowered # below the nesting so parseORCType rejects it deterministically and build-independently. gen_orc 200 "${TMP_DIR}/moderate.orc" $CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/moderate.orc', ORC) SETTINGS max_parser_depth = 100" 2>&1 \ | expect_contains parser_depth_limit TOO_DEEP_RECURSION -# (2) A file nested past the ORC library's own limit. Even with max_parser_depth raised so high that -# parseORCType would accept it, the library must reject it (without crashing). The library throws +# (2) A file nested past the ORC reader's own limit. Even with max_parser_depth raised so high that +# parseORCType would accept it, the reader must reject it (without crashing). The reader throws # before recursing past its limit, so this is safe to run. gen_orc 3000 "${TMP_DIR}/deep.orc" -$CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1 \ - | expect_contains orc_library_depth_limit "nesting depth exceeds the limit" +# Under TSan the stack size check allows only 5% of the stack, so it can reject the file before the depth limit. +out=$($CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1) +if printf '%s\n' "$out" | grep -qF -e "nesting depth exceeds the limit" -e "TOO_DEEP_RECURSION"; then + echo "orc_library_depth_limit: nesting depth exceeds the limit" +else + echo "orc_library_depth_limit: expected 'nesting depth exceeds the limit', got:" + printf '%s\n' "$out" | head -3 +fi # (3) max_parser_depth=0 means unlimited (matching the SQL parser), so a moderately nested file must # still be inferred normally rather than rejected by the explicit limit. diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.reference b/tests/queries/0_stateless/04338_async_insert_current_user.reference new file mode 100644 index 000000000000..161fe963e5bf --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.reference @@ -0,0 +1,6 @@ +1 1 1 +2 1 1 +1 1 1 +2 1 1 +10 1 1 +20 1 1 diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.sql b/tests/queries/0_stateless/04338_async_insert_current_user.sql new file mode 100644 index 000000000000..5a04881f9670 --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.sql @@ -0,0 +1,43 @@ +-- Regression test for issue #107530: context-dependent functions such as currentUser() +-- must evaluate to the inserting user (not an empty string) on the async_insert flush path, +-- both in DEFAULT/MATERIALIZED column expressions and in materialized views. + +DROP TABLE IF EXISTS t_async_user; +DROP TABLE IF EXISTS t_async_user_src; +DROP TABLE IF EXISTS t_async_user_dst; +DROP VIEW IF EXISTS t_async_user_mv; + +-- DEFAULT / MATERIALIZED column expressions calling currentUser(). +CREATE TABLE t_async_user +( + x Int32, + u_default String DEFAULT currentUser(), + u_materialized String MATERIALIZED currentUser() +) +ENGINE = MergeTree ORDER BY x; + +INSERT INTO t_async_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1); +INSERT INTO t_async_user (x) SETTINGS async_insert = 0 VALUES (2); + +-- The async row (x=1) and the sync row (x=2) must both record the inserting user. +-- Before the fix the async row recorded an empty string. +SELECT x, u_default = currentUser() AS default_matches, length(u_default) > 0 AS default_non_empty +FROM t_async_user ORDER BY x; +SELECT x, u_materialized = currentUser() AS materialized_matches, length(u_materialized) > 0 AS materialized_non_empty +FROM t_async_user ORDER BY x; + +-- Materialized view selecting currentUser(). +CREATE TABLE t_async_user_src (x Int32) ENGINE = MergeTree ORDER BY x; +CREATE TABLE t_async_user_dst (x Int32, u String) ENGINE = MergeTree ORDER BY x; +CREATE MATERIALIZED VIEW t_async_user_mv TO t_async_user_dst AS SELECT x, currentUser() AS u FROM t_async_user_src; + +INSERT INTO t_async_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10); +INSERT INTO t_async_user_src SETTINGS async_insert = 0 VALUES (20); + +SELECT x, u = currentUser() AS mv_matches, length(u) > 0 AS mv_non_empty +FROM t_async_user_dst ORDER BY x; + +DROP VIEW t_async_user_mv; +DROP TABLE t_async_user_dst; +DROP TABLE t_async_user_src; +DROP TABLE t_async_user; diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference new file mode 100644 index 000000000000..697f9b3fa30a --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference @@ -0,0 +1,3 @@ +1 1 1 1 +2 1 1 1 +10 1 1 1 diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh new file mode 100755 index 000000000000..b457807b3384 --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Regression test for issue #107530: authenticatedUser() must evaluate to the +# originally authenticated user (not an empty string, and not currentUser()) on the +# async_insert flush path. Uses EXECUTE AS so currentUser() and authenticatedUser() +# diverge: the test then fails if setAuthenticatedUserName is removed (au becomes empty) +# or wired to the wrong value (au becomes the impersonated user). + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +AUTH_USER="auth_user_${CLICKHOUSE_DATABASE}" +APP_USER="app_user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${APP_USER}" +$CLICKHOUSE_CLIENT --query "CREATE USER ${AUTH_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "CREATE USER ${APP_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "GRANT IMPERSONATE ON ${APP_USER} TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${APP_USER}" + +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP VIEW IF EXISTS t_auth_user_mv" + +# DEFAULT columns: currentUser() = impersonated user, authenticatedUser() = original user. +$CLICKHOUSE_CLIENT --query " +CREATE TABLE t_auth_user +( + x Int32, + cu String DEFAULT currentUser(), + au String DEFAULT authenticatedUser() +) +ENGINE = MergeTree ORDER BY x" + +# Async insert (x=1) and sync insert (x=2), both under EXECUTE AS the impersonated user. +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1)" +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 0 VALUES (2)" + +# The async row (x=1) and the sync row (x=2) must both record currentUser()=impersonated +# and authenticatedUser()=originally authenticated. Before the fix the async row recorded +# an empty authenticatedUser(). cu_ne_au proves the two ClientInfo fields are restored +# independently (it would be false if authenticatedUser were mis-wired to currentUser). +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user ORDER BY x" + +# Materialized view selecting authenticatedUser() under EXECUTE AS on the async path. +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_src (x Int32) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_dst (x Int32, cu String, au String) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE MATERIALIZED VIEW t_auth_user_mv TO t_auth_user_dst AS SELECT x, currentUser() AS cu, authenticatedUser() AS au FROM t_auth_user_src" + +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10)" + +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user_dst ORDER BY x" + +$CLICKHOUSE_CLIENT --query "DROP VIEW t_auth_user_mv" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP USER ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER ${APP_USER}" diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference new file mode 100644 index 000000000000..f693c2c0ae49 --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference @@ -0,0 +1,9 @@ +345 +11400 +168 5800 +[0,1,2,3,4,5,6,7,8,9,10,11,12] +3 3 +10 10 +17 4 +24 11 +1152 71944 diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql new file mode 100644 index 000000000000..4ce81b48033e --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql @@ -0,0 +1,23 @@ +-- Multi-step PREWHERE must keep columns needed to evaluate `DEFAULT`s of columns missing in the part. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default; + +CREATE TABLE t_multistep_prewhere_default (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple(); +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default ADD COLUMN v Int64 DEFAULT k % 13; +ALTER TABLE t_multistep_prewhere_default ADD COLUMN w Int64 DEFAULT k + length(s); + +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +SELECT sum(v) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3' AND k % 2 = 1; +SELECT arraySort(groupUniqArray(v)) FROM (SELECT DISTINCT v FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'); +SELECT k, v FROM t_multistep_prewhere_default WHERE k <= 30 AND s = '3' ORDER BY k; + +-- Parts written after the ALTER store v and w physically. +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7), 42, 43 FROM numbers(1000, 100); +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 1050 AND s = '3'; + +DROP TABLE t_multistep_prewhere_default; diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference new file mode 100644 index 000000000000..22b6a5ac9c04 --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference @@ -0,0 +1,6 @@ +350 +350 +4 4 +11 11 +18 5 +25 12 diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql new file mode 100644 index 000000000000..46e95b8cd3dd --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql @@ -0,0 +1,25 @@ +-- Multi-step PREWHERE must see patched values of the columns it carries over to evaluate `DEFAULT`s. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default_patch; + +SET enable_lightweight_update = 1, apply_patch_parts = 1; +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +CREATE TABLE t_multistep_prewhere_default_patch (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple() +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1; + +SYSTEM STOP MERGES t_multistep_prewhere_default_patch; + +INSERT INTO t_multistep_prewhere_default_patch SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default_patch ADD COLUMN v Int64 DEFAULT k % 13; + +UPDATE t_multistep_prewhere_default_patch SET k = k + 1 WHERE 1; + +-- Both queries must agree: `v` is missing in the part, so it is evaluated from the patched `k`. +SELECT sum((k % 13)::Int64) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; +SELECT sum(v) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; + +SELECT k, v FROM t_multistep_prewhere_default_patch WHERE k <= 30 AND s = '3' ORDER BY k; + +DROP TABLE t_multistep_prewhere_default_patch; diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference new file mode 100644 index 000000000000..7bed391e68f3 --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference @@ -0,0 +1,4 @@ +INCORRECT_DATA +0 0 +1 1 +2 2 diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh new file mode 100755 index 000000000000..57a8727696be --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The stripe footer of this blob is truncated, so reading it must fail with a regular +# INCORRECT_DATA exception. +BLOB='4f52431100000a061204080150005500000a280a06000000000000121e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc1550000f0000780039604d293e0b00006e0007dda36300f00a0608061000180b0a0608061001182d0a0608011001180a0a060805100118081204080010001204080210001a03474d545100000a260a04080150000a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc155000b500000803107e1a0a08031038181220342801220f080c1201011a0263302000280030002208080920002800300030013a04080150003a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc15500040904e48016200085d1005188080102202000c282b300682f403034f524317' + +# The fixture must stay pure even-length lowercase hex: unhex's result for a non-hex character is +# implementation-defined, so one invalid character makes the corrupt footer decoder-dependent and +# this test silently stops asserting anything. +if [[ ! $BLOB =~ ^[0-9a-f]+$ ]] || (( ${#BLOB} % 2 )); then + echo "BLOB must be an even-length string of [0-9a-f]" >&2 + exit 1 +fi + +$CLICKHOUSE_LOCAL -q "SELECT c0 FROM format(ORC, 'c0 DateTime64(3)', unhex('$BLOB'));" 2>&1 \ + | grep -oE "INCORRECT_DATA" \ + | sort -u + +# Well-formed ORC must still read back unchanged. +DATA_FILE="$CLICKHOUSE_TMP/04856_orc_control_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_LOCAL -q "SELECT number AS a, toString(number) AS b FROM numbers(3) FORMAT ORC" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT a, b FROM file('$DATA_FILE', ORC) ORDER BY a" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference new file mode 100644 index 000000000000..1f714f4b2082 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference @@ -0,0 +1,14 @@ +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +1 +2 diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh new file mode 100755 index 000000000000..dd54288e64f9 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Truncating this fixture to 289 bytes leaves byte 6 in the postscript's compression field. Codec 6 +# is BROTLI, which the ORC format declares but this reader does not implement. The reader rejects it +# with a NOT_IMPLEMENTED exception; it must never be a logical error, which aborts in debug and +# sanitizer builds. +DATA_FILE="$CLICKHOUSE_TMP/05036_orc_codec6_${CLICKHOUSE_DATABASE}.orc" +head -c 289 "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$DATA_FILE" + +# Both the schema-inference path and the explicit-structure path reach the reader, so both are +# asserted here. Match on the error text, never on the exit status: ClickHouse exits with the error +# code truncated to a byte, so 636 and 124 are the same outcome. +for query in \ + "SELECT * FROM file('$DATA_FILE', ORC) FORMAT Null" \ + "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" \ + "SELECT count() FROM file('$DATA_FILE', ORC, 'x Int32')" \ + "DESCRIBE file('$DATA_FILE', ORC)" \ + "SELECT * FROM format(ORC, 'x Int32', (SELECT * FROM file('$DATA_FILE', RawBLOB))) FORMAT Null" +do + # An abort prints nothing at all, so classify explicitly rather than letting the arm go silent: + # a missing line is much harder to read in a diff than a named verdict. + OUT=$($CLICKHOUSE_LOCAL --query "$query" 2>&1) + if [ -z "$OUT" ]; then + echo "no output at all" + else + echo "$OUT" | grep -o -m1 'BROTLI compression in ORC files is not supported\|Logical error' || echo "unexpected: $OUT" + fi +done + +# The message must name the codec, and must not call the file corrupt: a well-formed +# Brotli-compressed ORC file takes this same path. +$CLICKHOUSE_LOCAL --query "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" 2>&1 \ + | grep -o -m1 'BROTLI compression in ORC files is not supported\|CORRUPTED\|INCORRECT_DATA' + +# Neighbouring truncations are genuinely corrupt and must keep reporting corruption rather than the +# codec gap. Schema inference wraps every non-retryable cause in one outer code, so that arm alone +# cannot tell the two apart; the explicit-structure arm bypasses the wrapper and surfaces the inner +# classification, and counting the codec error there pins them apart. +for length in 200 400 +do + NEIGHBOUR="$CLICKHOUSE_TMP/05036_orc_${length}_${CLICKHOUSE_DATABASE}.orc" + head -c $length "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$NEIGHBOUR" + $CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC) FORMAT Null" 2>&1 \ + | grep -o -m1 'CANNOT_EXTRACT_TABLE_STRUCTURE\|Logical error' + EXPLICIT=$($CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC, 'x Int32') FORMAT Null" 2>&1) + echo "$EXPLICIT" | grep -o -m1 'INCORRECT_DATA\|Logical error' || echo "unexpected: $EXPLICIT" + echo "$EXPLICIT" | grep -c 'BROTLI compression' + rm "$NEIGHBOUR" +done + +# Well-formed ORC must still read back unchanged. +$CLICKHOUSE_LOCAL --query "SELECT i FROM file('$CUR_DIR/data_orc/orc_union_type.orc', ORC) ORDER BY i" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference new file mode 100644 index 000000000000..98fb6a686563 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference @@ -0,0 +1,4 @@ +1 +1 +1 +1 diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh new file mode 100755 index 000000000000..0e451abc8151 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: zookeeper, replica, no-shared-merge-tree, no-replicated-database +# no-shared-merge-tree: the setting bounds the ReplicatedMergeTree log, which SharedMergeTree does not have +# no-replicated-database: the ZooKeeper path and the replica name are literal, so they collide between the hosts of the database + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# The oldest kept log record names the threshold that log pointers of inactive replicas are compared +# with, so a window that keeps no records at all has no meaning. +ERR="A setting's value has to be greater than 0" + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs_zero (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# An ATTACH that carries a full definition is user input too, and reaches the same check. +uuid=$($CLICKHOUSE_CLIENT --query "SELECT generateUUIDv4()") +$CLICKHOUSE_CLIENT --query " + ATTACH TABLE max_logs_zero UUID '$uuid' (x UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r2', '1') ORDER BY x; +" +$CLICKHOUSE_CLIENT --query " + ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# A positive value is still accepted and stored. +$CLICKHOUSE_CLIENT --query "ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 1;" +$CLICKHOUSE_CLIENT --query " + SELECT count() FROM system.tables + WHERE database = currentDatabase() AND name = 'max_logs' + AND engine_full LIKE '%max_replicated_logs_to_keep = 1%'; +" + +$CLICKHOUSE_CLIENT --query "DROP TABLE max_logs SYNC" diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference new file mode 100644 index 000000000000..743f61f80a90 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference @@ -0,0 +1,9 @@ +String: batches>1=1 64 2016 1 +Nullable(String): batches>1=1 64 2016 1 +LowCardinality: batches>1=1 64 2016 4 +Array(String): batches>1=1 64 2016 1 +Map: batches>1=1 64 2016 1 +Tuple: batches>1=1 64 2016 1 +FixedString: batches>1=1 64 2016 1 +FixedString fixed-width: batches>1=0 64 2016 1 +UInt64: batches>1=0 64 2016 64 diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh new file mode 100755 index 000000000000..695c740a9cd8 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Arrow offsets its String/Binary/List buffers with 32-bit integers, so a block holding more than that has +# to be written as several record batches. `output_format_arrow_max_record_batch_size_bytes` lowers the +# bound, which exercises the same splitting with kilobytes instead of the 2 GiB a real overflow needs. +# +# Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_split.arrows" +trap 'rm -f "$FILE"' EXIT + +batches() { + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY +} + +run() { + local label="$1" expr="$2" limit="$3" extra="${4:-}" + $CLICKHOUSE_LOCAL --allow_suspicious_fixed_string_types 1 --query " + SELECT number AS n, ${expr} AS v + FROM numbers(64) + SETTINGS max_block_size = 64, + output_format_arrow_compression_method = 'none', + output_format_arrow_max_record_batch_size_bytes = ${limit}${extra} + FORMAT ArrowStream + " > "$FILE" + echo -n "${label}: batches>1=$([ "$(batches)" -gt 1 ] && echo 1 || echo 0) " + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(n), uniqExact(v) FROM file('$FILE', ArrowStream)" +} + +# One block of 64 rows against a small bound, so each shape must split. +run "String" "repeat('x', 64)" 512 +run "Nullable(String)" "if(number % 3 = 0, NULL, repeat('y', 64))::Nullable(String)" 512 +run "LowCardinality" "toLowCardinality(repeat(toString(number % 4), 64))" 512 +run "Array(String)" "[repeat('z', 64)]" 512 +run "Map" "map('k', repeat('m', 64))" 512 +run "Tuple" "(repeat('p', 64), repeat('q', 64))" 512 +# Only the offsets mode gives `FixedString` a buffer the bound applies to; the default maps it to a +# fixed-width Arrow type instead. +run "FixedString" "toFixedString(repeat('f', 64), 64)" 512 ", output_format_arrow_fixed_string_as_fixed_byte_array = 0" + +# A fixed-width column has no offsets buffer to overflow, so the bound leaves it in one batch. +run "FixedString fixed-width" "toFixedString(repeat('f', 64), 64)" 512 +run "UInt64" "number" 64 diff --git a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh index ff237fd5db5b..20fc7c819b31 100755 --- a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh +++ b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh @@ -14,7 +14,7 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) BG_MESSAGE="M_bg_${CLICKHOUSE_DATABASE}" FG_MESSAGE="M_fg_${CLICKHOUSE_DATABASE}" -START=$(${CLICKHOUSE_CLIENT} --query "SELECT toString(now64(6))") +START=$(${CLICKHOUSE_CLIENT} --query "SELECT toUnixTimestamp64Micro(now64(6))") ${CLICKHOUSE_CLIENT} --query " CREATE TABLE dest_bg (s String) ENGINE = File(ProtobufSingle) @@ -33,10 +33,11 @@ do ${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS text_log" # The logger is checked too because this query is itself written to the text log, so otherwise # an iteration would match the previous one instead of the background exception. + # `event_date` is in the server time zone, and the session one is randomized. refused=$(${CLICKHOUSE_CLIENT} --query " SELECT count() > 0 FROM system.text_log - WHERE event_date >= toDate('${START}') - AND event_time_microseconds >= toDateTime64('${START}', 6) + WHERE event_date >= yesterday() + AND event_time_microseconds >= fromUnixTimestamp64Micro(${START}) AND logger_name LIKE '%StorageBuffer%' AND message LIKE '%can only be executed on behalf of a user%'") [ "$refused" = "1" ] && break diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference new file mode 100644 index 000000000000..5567708ffa73 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference @@ -0,0 +1,2 @@ +HTTP status code: 409 +requests: 1 diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh new file mode 100755 index 000000000000..1a260ca3f719 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +# `409 Conflict` reports a state mismatch on the server, so resending the same bytes cannot succeed. +# Retrying it only postpones the error the caller has to act on: an Iceberg REST catalog commit +# refused with `409` was resent `http_max_tries` times with backoff, adding ~32 seconds per conflict. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HTTP_PORT=$(python3 -c " +import socket +s = socket.socket() +s.bind(('127.0.0.1', 0)) +print(s.getsockname()[1]) +s.close() +") + +python3 -c " +import threading +from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + +requests = 0 +lock = threading.Lock() + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + global requests + if self.path == '/requests': + with lock: + body = str(requests).encode() + self.send_response(200) + else: + with lock: + requests += 1 + body = b'{\"error\": \"conflict\"}' + self.send_response(409) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + +ThreadingHTTPServer(('127.0.0.1', $HTTP_PORT), Handler).serve_forever() +" & +HTTP_PID=$! + +trap 'kill $HTTP_PID 2>/dev/null' EXIT + +for _ in {1..100}; do + if [ "$(${CLICKHOUSE_CURL} -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${HTTP_PORT}/requests")" = "200" ]; then + break + fi + sleep 0.1 +done + +${CLICKHOUSE_CLIENT} --query "SELECT * FROM url('http://127.0.0.1:${HTTP_PORT}/data', JSONEachRow, 'x Int32')" 2>&1 | grep -o "HTTP status code: 409" | head -n 1 + +echo "requests: $(${CLICKHOUSE_CURL} -s "http://127.0.0.1:${HTTP_PORT}/requests")" diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference new file mode 100644 index 000000000000..fe1489a7d47e --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference @@ -0,0 +1,4 @@ +low_cardinality_as_dictionary=0 record batches for 3 blocks: 3 +6 15 +low_cardinality_as_dictionary=1 record batches for 3 blocks: 3 +6 15 diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh new file mode 100755 index 000000000000..bff3fc53e4fa --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The writer splits a chunk across record batches only when it exceeds the 32-bit offsets of the Arrow +# buffers, so a small result must give exactly one batch per block for every type shape. A wrong row +# count from the split logic shows up only here: the data reads back correctly either way. +# +# `FORMAT ArrowStream` into a file rather than `INSERT INTO FUNCTION file`, whose path squashes the +# blocks into one. Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +GEN="SELECT + toString(number) AS s, + if(number % 3 = 0, NULL, toString(number))::Nullable(String) AS ns, + toLowCardinality(toString(number % 2)) AS lc, + arrayMap(x -> toString(x), range(number % 3)) AS arr, + arrayMap(y -> arrayMap(x -> toString(x), range(y)), range(number % 3)) AS arr2, + map(toString(number), toString(number % 2)) AS m, + (toString(number), toString(number % 2)) AS t, + toFixedString(toString(number), 3) AS fs, + number AS u +FROM numbers(6)" + +for lc_as_dict in 0 1; do + $CLICKHOUSE_LOCAL --query "${GEN} SETTINGS + max_block_size = 2, + output_format_arrow_compression_method = 'none', + output_format_arrow_fixed_string_as_fixed_byte_array = 0, + output_format_arrow_low_cardinality_as_dictionary = ${lc_as_dict} + FORMAT ArrowStream" > "$FILE" + + echo -n "low_cardinality_as_dictionary=${lc_as_dict} record batches for 3 blocks: " + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY + + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(u) FROM file('$FILE', ArrowStream)" +done diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference new file mode 100644 index 000000000000..15e7d3a0e939 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference @@ -0,0 +1,22 @@ +-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs +3 +-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs +3 +-- a nested unknown setting still throws +1 +-- a nested value the setting cannot take still throws +1 +-- a nested clause forwarded to the shards carries the clamped value +1 +-- the same query for an unconstrained user reads both shards +6 +-- a view with an invalid nested setting in its stored body fails on a direct read +1 +-- and on a remote shard through Distributed +1 +-- a parameterized view with an invalid nested setting fails on a direct read +1 +-- and on a remote shard +1 +-- the session settings are untouched +false diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh new file mode 100755 index 000000000000..f05616c8d829 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer +# (the clamp is analyzer-path behaviour; the legacy interpreter throws on such a nested clause) +# A nested `SETTINGS` clause is clamped to the session's settings constraints, and the clamped clause is +# what the query node keeps. So a shard receives the clamped clause, and an +# unknown name or an uncastable value in a nested clause throws, as it does in a top-level clause - also +# when the clause sits in a view's stored body and the view is read on a remote shard. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Users and settings profiles are server-global, so their names carry the test database to keep this +# test safe against a concurrent copy of itself - which is how the flaky check runs it. +SUFFIX="05141_${CLICKHOUSE_DATABASE}" +CONST_USER="user_const_${SUFFIX}" +CONST_PROFILE="profile_const_${SUFFIX}" +RO_USER="user_ro_${SUFFIX}" +RO_PROFILE="profile_ro_${SUFFIX}" +FREE_USER="user_free_${SUFFIX}" +DIST_USER="user_dist_${SUFFIX}" +DIST_PROFILE="profile_dist_${SUFFIX}" +TABLE="t_05141" +DIST_TABLE="dist_05141" +VIEW="v_05141" +DIST_VIEW="dist_v_05141" +PARAM_VIEW="pv_05141" + +${CLICKHOUSE_CLIENT} --query " +DROP USER IF EXISTS ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE IF EXISTS ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; + +CREATE TABLE ${CLICKHOUSE_DATABASE}.${TABLE} (id UInt32, s String) ENGINE = MergeTree ORDER BY id; +INSERT INTO ${CLICKHOUSE_DATABASE}.${TABLE} VALUES (1, 'a'), (2, 'b'), (3, 'c'); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE} AS ${CLICKHOUSE_DATABASE}.${TABLE} + ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${TABLE}); + +CREATE SETTINGS PROFILE ${CONST_PROFILE} SETTINGS use_query_cache = 0 CONST; +CREATE SETTINGS PROFILE ${RO_PROFILE} SETTINGS readonly = 1 CONST; +CREATE SETTINGS PROFILE ${DIST_PROFILE} SETTINGS max_rows_to_read MAX 2; +CREATE USER ${CONST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${CONST_PROFILE}; +CREATE USER ${RO_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${RO_PROFILE}; +CREATE USER ${FREE_USER} IDENTIFIED WITH no_password; +CREATE USER ${DIST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${DIST_PROFILE}; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.* TO ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +" + +# `CREATE` does not analyze the body of a view with an explicit column list nor of a parameterized view, so +# such definitions can carry an invalid nested setting. +${CLICKHOUSE_CLIENT} --query " +CREATE VIEW ${CLICKHOUSE_DATABASE}.${VIEW} (x UInt8) AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW} (x UInt8) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${VIEW}); +CREATE VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW} AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1) WHERE x = {p:UInt8}; +" + +# The bare binary, not ${CLICKHOUSE_CLIENT}: the harness's randomized settings would be rejected for the readonly user. +RESTRICTED_CLIENT="${CLICKHOUSE_CLIENT_BINARY} --host=${CLICKHOUSE_HOST} --port=${CLICKHOUSE_PORT_TCP} --database=${CLICKHOUSE_DATABASE}" +CONST="${RESTRICTED_CLIENT} --user=${CONST_USER}" +RO="${RESTRICTED_CLIENT} --user=${RO_USER}" +FREE="${RESTRICTED_CLIENT} --user=${FREE_USER}" +DIST="${RESTRICTED_CLIENT} --user=${DIST_USER}" + +echo "-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs" +${RO} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- a nested unknown setting still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threds = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a nested value the setting cannot take still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threads = 'abc')" 2>&1 | grep -c -F "CANNOT_PARSE_INPUT_ASSERTION_FAILED" + +# The IN subquery runs on the shards, whose user has no constraints. It must arrive with the value the +# initiator clamped (2, so reading 3 rows fails there), not with the value as written. +echo "-- a nested clause forwarded to the shards carries the clamped value" +${DIST} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" 2>&1 | grep -c -F "TOO_MANY_ROWS" + +echo "-- the same query for an unconstrained user reads both shards" +${FREE} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" + +# The bare binary again: `${CLICKHOUSE_CLIENT}` adds `--send_logs_level`, so the server's error log line would +# be printed too and `grep -c` would count two lines. +echo "-- a view with an invalid nested setting in its stored body fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${VIEW}" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# `prefer_localhost_replica = 0` is explicit: the local shard is analyzed under the initiator's query kind +# and already throws, so only the remote path exercises the fix, and the harness randomizes this setting. +echo "-- and on a remote shard through Distributed" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${DIST_VIEW} SETTINGS prefer_localhost_replica = 0" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a parameterized view with an invalid nested setting fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${PARAM_VIEW}(p = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# 127.0.0.2 is the non-local shard of `test_cluster_two_shards`; the port is explicit so the test runs on +# a non-default port; the database is qualified because the remote session does not inherit the test database. +echo "-- and on a remote shard" +${RESTRICTED_CLIENT} --query "SELECT * FROM remote('127.0.0.2:${CLICKHOUSE_PORT_TCP}', view(SELECT * FROM ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}(p = 1)))" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- the session settings are untouched" +${CONST} --query "SELECT getSetting('use_query_cache')" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; +DROP USER ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +" diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference new file mode 100644 index 000000000000..6ee89cf48413 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference @@ -0,0 +1,18 @@ +-- control: the setting is not changed in the session +0 1 +-- control: compatibility = '26.1' in a nested clause moves the setting to its old default +1 0 +-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level +1 1 +-- and stays on the query node +1 +-- same clause: an equal assignment before compatibility keeps the current value +1 1 +-- same clause: an equal assignment before a profile that carries compatibility keeps the current value +1 1 +-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one +1 +-- child scope: the same with a profile that carries compatibility in the inner one +1 +-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery +1 diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh new file mode 100755 index 000000000000..03ce5a1eebc0 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer + +# A nested `SETTINGS` change equal to the current value is applied and marks the setting as changed +# in the subquery's context, as at the top level. That flag is what `compatibility` respects +# ("changed manually" settings are left alone), also when `compatibility` sits in a profile or in +# a nested query, so the flag must not be dropped as a "no-op". + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Settings profiles are server-global, so the name carries the test database. +PROFILE="p_compat_05175_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE IF EXISTS ${PROFILE}" +${CLICKHOUSE_CLIENT} --query "CREATE SETTINGS PROFILE ${PROFILE} SETTINGS compatibility = '26.1'" + +Q="SELECT changed, value FROM system.settings WHERE name = 'ignore_format_null_for_explain'" + +echo "-- control: the setting is not changed in the session" +${CLICKHOUSE_CLIENT} --query "${Q}" + +echo "-- control: compatibility = '26.1' in a nested clause moves the setting to its old default" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS compatibility = '26.1')" + +echo "-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- and stays on the query node" +${CLICKHOUSE_CLIENT} --query "EXPLAIN QUERY TREE SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" | grep -c "SETTINGS ignore_format_null_for_explain=" + +echo "-- same clause: an equal assignment before compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, compatibility = '26.1')" + +echo "-- same clause: an equal assignment before a profile that carries compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, profile = '${PROFILE}')" + +echo "-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- child scope: the same with a profile that carries compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS profile = '${PROFILE}') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery" +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "SELECT value FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE ${PROFILE}" diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference new file mode 100644 index 000000000000..06604339ef49 --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference @@ -0,0 +1,7 @@ +ACCESS_DENIED: necessary to have the grant READ, WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +ACCESS_DENIED: Missing permissions: WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +424242 diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh new file mode 100755 index 000000000000..1fa58284b9aa --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Tags: no-object-storage, no-replicated-database +# no-object-storage: the query attaches a directory on the local disk, and there the table data lives on +# object storage. +# no-replicated-database: a Replicated database enqueues the query before the path is resolved against +# `user_files`, and the DDL worker then rejects the path as outside of `user_files`. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the data of the new table and moves it to +# the data path of the table, so it needs `READ ON FILE` like the `file` function and `WRITE ON FILE` like +# renaming files after processing. Without that check `CREATE TABLE` on a table of their own is enough for a +# user to read and consume data that somebody else staged in `user_files`. + +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +staged_root="${CLICKHOUSE_TEST_UNIQUE_NAME}_staged" +staged_table_dir="${staged_root}/data/staging/protected" + +# Stage a MergeTree table directory in `user_files` with clickhouse-local, as an admin or a migration +# workflow would do. An Ordinary database keeps the table directory at a known place. +${CLICKHOUSE_LOCAL} --path "${USER_FILES_PATH}/${staged_root}" --allow_deprecated_database_ordinary=1 --query " + CREATE DATABASE staging ENGINE = Ordinary; + CREATE TABLE staging.protected (id UInt64, secret UInt64) ENGINE = MergeTree ORDER BY id; + INSERT INTO staging.protected VALUES (1, 424242); +" + +${CLICKHOUSE_CLIENT} <&1 | grep -qF "$1"; then + echo "ACCESS_DENIED: $1" + else + echo "UNEXPECTED: the attach was not denied with: $1" + fi + ${CLICKHOUSE_CLIENT} --query "SELECT 'tables named stolen:', count() FROM system.tables WHERE database = currentDatabase() AND name = 'stolen'" + if [ -d "${USER_FILES_PATH}/${staged_table_dir}" ]; then + echo "staged directory is still in place" + else + echo "UNEXPECTED: the staged directory is gone" + fi +} +check_denied_and_untouched "necessary to have the grant READ, WRITE ON FILE" +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user" +check_denied_and_untouched "Missing permissions: WRITE ON FILE" + +# With both grants the same query attaches the data. +${CLICKHOUSE_CLIENT} --query "GRANT WRITE ON FILE TO $user" +${CLICKHOUSE_CLIENT} --user "$user" --query "$attach_query" +${CLICKHOUSE_CLIENT} --user "$user" --query "SELECT secret FROM stolen" + +${CLICKHOUSE_CLIENT} <&1 \ + | tr '\t' ' ' | grep -oE "QUOTA_REQUIRES_CLIENT_KEY|^[[:alnum:]_]+ [[:digit:]]+$" +} + +echo "1. warm two cached quota contexts of the same user, without and with a quota key" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "2. a tightening that keeps the key type reaches the warm context" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} FOR INTERVAL 100 YEAR MAX queries = 900" +usage --user "${user}" + +echo "3. switching the key type to client_key must reach both warm contexts" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY client_key FOR INTERVAL 100 YEAR MAX queries = 800" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "4. a user whose context was never cached is rejected the same way" +usage --user "${control_user}" + +echo "5. reverting the key type lets the never-detached context resume" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY user_name FOR INTERVAL 100 YEAR MAX queries = 700" +usage --user "${user}" + +${CLICKHOUSE_CLIENT} -q "DROP QUOTA ${quota}" +${CLICKHOUSE_CLIENT} -q "DROP USER ${user}, ${control_user}" diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference new file mode 100644 index 000000000000..c9a233584ace --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference @@ -0,0 +1,5 @@ +t_05291 (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE v = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE _row_exists = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291_replicated (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +0 diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql new file mode 100644 index 000000000000..58aa5021b160 --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql @@ -0,0 +1,47 @@ +-- Tags: no-fasttest +-- no-fasttest: the `s3` table function is not in the fast test build. + +-- A mutation entry keeps the real text of its commands, because the mutation is executed from it (on every +-- replica, for replicated tables). `system.mutations.command` must still hide the credentials of the table +-- functions in the mutation subqueries, the way the query log does. + +SET mutations_sync = 0; +SET lightweight_deletes_sync = 0; +SET allow_nondeterministic_mutations = 1; + +DROP TABLE IF EXISTS t_05291; +DROP TABLE IF EXISTS t_05291_replicated; + +CREATE TABLE t_05291 (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id; +CREATE TABLE t_05291_replicated (id UInt64, v UInt64) +ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/t_05291_replicated', 'r1') ORDER BY id; + +INSERT INTO t_05291 SELECT number, number FROM numbers(10); +INSERT INTO t_05291_replicated SELECT number, number FROM numbers(10); + +-- Keep the mutations pending, so that they stay in `system.mutations`. +SYSTEM STOP MERGES t_05291; +SYSTEM STOP MERGES t_05291_replicated; + +ALTER TABLE t_05291 DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291DELETE', 'CSV', 'c1 String')); +ALTER TABLE t_05291 UPDATE v = 0 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291UPDATE', 'CSV', 'c1 String')); +DELETE FROM t_05291 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291LIGHTWEIGHT', 'CSV', 'c1 String')); +ALTER TABLE t_05291_replicated DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291REPLICATED', 'CSV', 'c1 String')); + +-- The replica loads the mutations from ZooKeeper asynchronously; `PULL` fetches them synchronously. +SYSTEM SYNC REPLICA t_05291_replicated PULL; + +SELECT table, command FROM system.mutations WHERE database = currentDatabase() ORDER BY table, mutation_id; + +-- A secret cannot be probed with a filter on the column either. +SELECT count() FROM system.mutations WHERE database = currentDatabase() AND position(command, 'SECRET05291') > 0; + +-- `KILL MUTATION` parses the command that it reads from `system.mutations` to check the access rights. +KILL MUTATION WHERE database = currentDatabase() AND table = 't_05291' FORMAT Null; + +DROP TABLE t_05291; +DROP TABLE t_05291_replicated; diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference new file mode 100644 index 000000000000..a685fc6d0653 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference @@ -0,0 +1,6 @@ +-- baseline: the policy confines the user to its single tenant (1) +1 +-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards) +8 +-- and the shards consumed it through an explicit __getScalar reference (1) +1 diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh new file mode 100755 index 000000000000..add1062cda49 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# A row policy whose USING expression contains a scalar subquery (here `has((SELECT [2]), tenant_id)`) +# is resolved through the analyzer's scalar-subquery cache, which lives in the same `Context::scalars` +# map that a client can write to with a `Scalar` packet (the `clickhouse-client --external ... --scalar` +# feature). A restricted user could therefore name a client scalar with the policy subquery's query-tree +# hash and forge its result, replacing `(SELECT [2])` with an attacker-chosen array and reading every +# tenant's rows. On 26.3 `clickhouse-client` cannot send scalars (no `--external ... --scalar`), so the +# forged-scalar cases are left out and this test only pins the policy baseline and that scalars shipped +# to shards in distributed queries still resolve. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# User and policy names are server-global, so suffix them with the (unique) test database. +user="u_scalar_rlp_${CLICKHOUSE_DATABASE}" +policy="rp_scalar_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE IF EXISTS docs; +CREATE TABLE docs (id UInt64, tenant_id UInt8, secret String) ENGINE = MergeTree ORDER BY id; +INSERT INTO docs SELECT number, number, 'secret-' || toString(number) FROM numbers(1, 8); + +CREATE USER ${user} NOT IDENTIFIED; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.docs TO ${user}; +-- The policy confines ${user} to tenant 2 only, via a scalar subquery. +CREATE ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING has((SELECT [2]), tenant_id) TO ${user}; +-- Once a table has any policy, \`throw_on_unmatched_row_policies\` (on in the test config) rejects +-- reads by users no policy matches, so the default user needs a permissive one of its own. +CREATE ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING 1 TO ALL EXCEPT ${user}; +" + +echo "-- baseline: the policy confines the user to its single tenant (1)" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SELECT count() FROM ${CLICKHOUSE_DATABASE}.docs SETTINGS enable_scalar_subquery_optimization = 1" + +# Marking wire scalars as client-supplied must not disturb distributed queries: the initiator computes +# an array-returning scalar subquery once and ships the result to the shards in the same `Scalar` packet, +# where it arrives through `addClientScalar`. The shard consumes it through the explicit `__getScalar` +# reader, which still reads client-supplied entries, rather than through the narrowed subquery cache. +log_comment="scalar_rlp_dist_${CLICKHOUSE_DATABASE}" + +echo "-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards)" +${CLICKHOUSE_CLIENT} --log_comment "${log_comment}" --query " +SELECT count() FROM cluster('test_cluster_two_shards', '${CLICKHOUSE_DATABASE}', docs) +WHERE has((SELECT [2, 3, 4, 5]), tenant_id) +SETTINGS prefer_localhost_replica = 0, enable_scalar_subquery_optimization = 1" + +echo "-- and the shards consumed it through an explicit __getScalar reference (1)" +# The secondary queries log `current_database = 'default'` rather than the test database, so they are +# selected by the id of the initial query, which does carry it. +${CLICKHOUSE_CLIENT} --query " +SYSTEM FLUSH LOGS query_log; +SELECT count() > 0 FROM system.query_log +WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 0 + AND query LIKE '%__getScalar%' + AND initial_query_id IN ( + SELECT query_id FROM system.query_log + WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 1 + AND current_database = currentDatabase() AND log_comment = '${log_comment}')" + +${CLICKHOUSE_CLIENT} --query " +DROP ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs; +DROP ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs; +DROP TABLE docs; +" +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference new file mode 100644 index 000000000000..88b9566a6b12 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference @@ -0,0 +1,3 @@ +column 20 is out of range, the file has 5 columns +column 20 is out of range, the file has 5 columns +100 4950 diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh new file mode 100755 index 000000000000..27b41467be72 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: Depends on S3 + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A 569-byte ORC file (id Int64, name String, v Float64, part Int32) with one row, whose stripe footer declares a +# row index stream for column 20, but the file has 5 columns. Two readers indexed the selected-column mask with +# that id and aborted the server; both must report a malformed file instead: +# - remote reads prebuffer stripes (`ORC::Reader::preBuffer`), so the file is read through s3; +# - predicate pushdown loads the row indexes (`ORC::RowReader::loadStripeIndex`), also for local files. The +# predicate must keep the stripe (`id >= 0`; the row has id 1), or the stripe statistics skip it first. +ORC_B64=$(tr -d '\n' <<'B64' +T1JDEQAACgYSBAgBUAArAAAKEwoDAAAAEgwIARIGCAIQAhgCUAAzAAAKFwoFAAAAAAASDggBIggKAWESAWEYAlAAUwAACicKAgAA +EiEIARobCQAAAAAAAPg/EQAAAAAAAPg/GQAAAAAAAPg/UAArAAAKEwoDAAAAEgwIARIGCAAQABgAUAAHAABCAIADAABhBwAAQACA +EQAAAAAAAAAA+D8HAABAAACuAAAotS/9IGR1AgCEAwoGCAYQABgLCgYIBhABGBgCGBwDGCwUARABGAYCGAQKBggCEAIDARAEGAYS +AggAEgIIAgASAggCCAB7/hAam+nkirydJ0AbQIZdZQm6AAAotS/9IF+lAgBEBApdCgQIAVAACg4IARIGCAIQAhgCUABYBgoQCAEi +CAoBYRIBYQoKIwgBGhsJAPg/EQD4PxkA+D9QAFgLABAAGABQAFgGBQBKyAIaAUJwd1jtfAJ4AQAotS/9IOydBQBCyiYskLc5//// +///w6acgxiIELbemIDUZs4IjVzcRUBwT/pE0KZF9o02pZZNSphSQJ3okw0BbBghYiEDLlRuOvFiuU8aKKePElHHiyPYGVW7/bcVn +e6TQcm1Ni83htzOUa/ujDT2c/5Sg/4wO/hPqp6rnKrCqiyUKQ5//PDC42JMILQmsez1JVU0+1/o9wp3ZDoEFo2mF6HyRLSE6DwgA +SsgCGgFCcHdas32g06DT47p5Bgi/ARAFGICAECICAAwoYDAJgvQDA09SQxg= +B64 +) +FILE="05317_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$FILE', format='RawBLOB') SELECT base64Decode('$ORC_B64')" + +# Stripes are prebuffered only with `remote_filesystem_read_prefetch`, which CI randomizes. +$CLICKHOUSE_CLIENT --remote_filesystem_read_prefetch 1 \ + --query "SELECT * FROM s3(s3_conn, filename='$FILE', format='ORC') FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' + +# Predicate pushdown (on by default) on a local file, which is never prebuffered. +LOCAL_FILE="05317_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --engine_file_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION file('$LOCAL_FILE', 'RawBLOB') SELECT base64Decode('$ORC_B64')" +$CLICKHOUSE_CLIENT --input_format_orc_filter_push_down 1 \ + --query "SELECT * FROM file('$LOCAL_FILE', 'ORC') WHERE id >= 0 FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' +rm -f "${USER_FILES_PATH:?}/$LOCAL_FILE" + +# The server is still alive, and a valid ORC file is still read through the same path. +VALID="05317_valid_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$VALID', format='ORC') SELECT number AS id, toString(number) AS s FROM numbers(100)" +$CLICKHOUSE_CLIENT --query "SELECT count(), sum(id) FROM s3(s3_conn, filename='$VALID', format='ORC')" diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference new file mode 100644 index 000000000000..21113e5c614b --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference @@ -0,0 +1,18 @@ +-- Q-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded LF +contains CR, LF or NUL +400 +-- B-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded NUL +contains CR, LF or NUL +400 +-- Encoded word in the middle of the value +contains CR, LF or NUL +400 +-- Other encoded words are still decoded +café au lait +café diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh new file mode 100755 index 000000000000..ef96f960e4b3 --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# An RFC 2047 encoded word must not decode into CR, LF or NUL inside a header value: +# such a value could split the header when it is forwarded (e.g. to an HTTP authentication server). + +function check_rejected() +{ + local header="$1" + ${CLICKHOUSE_CURL} -sS -H "$header" -w '%{http_code}\n' "${CLICKHOUSE_URL}&query=SELECT+1" | grep -o -F -e 'contains CR, LF or NUL' -e '400' +} + +echo "-- Q-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?Q?x=0D=0AInjected:_1?=' +echo "-- Q-encoded LF" +check_rejected 'X-Test: =?UTF-8?Q?x=0AInjected:_1?=' +echo "-- B-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?B?eA0KSW5qZWN0ZWQ6IDE=?=' +echo "-- Q-encoded NUL" +check_rejected 'X-Test: =?UTF-8?Q?x=00y?=' +echo "-- Encoded word in the middle of the value" +check_rejected 'X-Test: prefix =?UTF-8?Q?=0D=0A?= suffix' + +echo "-- Other encoded words are still decoded" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?Q?caf=C3=A9_au_lait?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?B?Y2Fmw6k=?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference new file mode 100644 index 000000000000..7a770acba3a2 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference @@ -0,0 +1,7 @@ +json_whole 1 +json_whole_prewhere 1 +json_other_path 1 +tuple_whole 1 +map_size_and_key 1 +maps_other_map 1 +map_key_and_whole 1 diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql new file mode 100644 index 000000000000..a87623566a81 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql @@ -0,0 +1,79 @@ +-- Tags: no-parallel-replicas +-- no-parallel-replicas: read_bytes in the initiator's query_log does not include the replicas' reads. + +-- A condition on a cheap subcolumn gets its own PREWHERE read step, so the column it is combined with is read +-- only for the rows it keeps. No row passes the first condition, so a case reads about the bytes of that one alone. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; +SET optimize_move_to_prewhere = 1; +SET query_plan_optimize_prewhere = 1; +SET move_all_conditions_to_prewhere = 1; +SET enable_multiple_prewhere_read_steps = 1; +SET use_query_condition_cache = 0; + +DROP TABLE IF EXISTS t_json; +DROP TABLE IF EXISTS t_tuple; +DROP TABLE IF EXISTS t_map; +DROP TABLE IF EXISTS t_maps; + +CREATE TABLE t_json (id UInt64, j JSON) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_tuple (id UInt64, t Tuple(kind String, payload String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +-- Bucketed, with as many buckets as keys, so that `m['k1']` reads one bucket and not the whole Map. +CREATE TABLE t_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', + map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0; +CREATE TABLE t_maps (id UInt64, c Tuple(left Map(String, String), right Map(String, String))) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +-- Random values, so that the size of a column on disk, by which the conditions are ordered, reflects the cost of reading it. +INSERT INTO t_json SELECT number, concat('{"kind":"a","payload":"', hex(randomString(500)), '"}') FROM numbers(20000); +INSERT INTO t_tuple SELECT number, tuple('a', hex(randomString(500))) FROM numbers(20000); +INSERT INTO t_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> hex(randomString(30)), range(16))) FROM numbers(20000); +INSERT INTO t_maps SELECT number, tuple(map('k', 'a'), map('k', hex(randomString(500)))) FROM numbers(20000); + +SELECT count() FROM t_json WHERE j.kind = 'b' FORMAT Null SETTINGS log_comment = 'json_cheap'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' FORMAT Null SETTINGS log_comment = 'tuple_cheap'; +SELECT count() FROM t_map WHERE length(m) = 3 FORMAT Null SETTINGS log_comment = 'map_cheap'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' FORMAT Null SETTINGS log_comment = 'map_key_cheap'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' FORMAT Null SETTINGS log_comment = 'maps_cheap'; + +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole'; +SELECT count() FROM t_json PREWHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole_prewhere'; +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 FORMAT Null SETTINGS log_comment = 'json_other_path'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' AND length(toString(t)) > 10 FORMAT Null SETTINGS log_comment = 'tuple_whole'; +-- PREWHERE keeps the written order, which the WHERE optimizer may change based on the column sizes. +SELECT count() FROM t_map PREWHERE length(m) = 3 AND m['k1'] != '' FORMAT Null SETTINGS log_comment = 'map_size_and_key'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' AND c.right['k'] != '' FORMAT Null SETTINGS log_comment = 'maps_other_map'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 FORMAT Null SETTINGS log_comment = 'map_key_and_whole'; + +SYSTEM FLUSH LOGS query_log; + +SELECT c.case_name, q.bytes < 2 * base.bytes +FROM VALUES('idx UInt8, case_name String, base_name String', + (1, 'json_whole', 'json_cheap'), + (2, 'json_whole_prewhere', 'json_cheap'), + (3, 'json_other_path', 'json_cheap'), + (4, 'tuple_whole', 'tuple_cheap'), + (5, 'map_size_and_key', 'map_cheap'), + (6, 'maps_other_map', 'maps_cheap'), + (7, 'map_key_and_whole', 'map_key_cheap')) AS c +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS q ON q.log_comment = c.case_name +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS base ON base.log_comment = c.base_name +ORDER BY c.idx; + +DROP TABLE t_json; +DROP TABLE t_tuple; +DROP TABLE t_map; +DROP TABLE t_maps; diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference new file mode 100644 index 000000000000..fcc2c16d9ebd --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference @@ -0,0 +1,30 @@ +bucketed MergeTree +1 +MergeTree with bucketed zero-level parts +1 +basic MergeTree +1 +Memory +1 +explicit key subcolumn of a basic Map +8 8 +9 9 +results +8 8 +9 9 +8 8 +9 9 +8 8 +9 9 +Merge over a bucketed table +1 +MaterializedView with a bucketed target +1 +Buffer with a bucketed destination +1 +Merge over a bucketed and a basic table +1 +8 8 +8 8 +9 9 +9 9 diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql new file mode 100644 index 000000000000..cd62f633bf69 --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql @@ -0,0 +1,75 @@ +-- `m['key']` is rewritten to the Map key subcolumn `m.key_` only when the table serializes Maps +-- with buckets, because only then can a single key be read without the whole Map. +-- Both serialization settings are named in every table, clickhouse-test randomizes them. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; + +DROP TABLE IF EXISTS t_map_buffer; +DROP TABLE IF EXISTS t_map_mv; +DROP TABLE IF EXISTS t_map_merge; +DROP TABLE IF EXISTS t_map_memory; +DROP TABLE IF EXISTS t_map_basic; +DROP TABLE IF EXISTS t_map_zero_level_bucketed; +DROP TABLE IF EXISTS t_map_bucketed; + +CREATE TABLE t_map_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_zero_level_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_basic (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; +CREATE TABLE t_map_memory (id UInt64, m Map(String, UInt64)) ENGINE = Memory; + +INSERT INTO t_map_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_zero_level_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_basic SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_memory SELECT number, map('k', number) FROM numbers(10); + +SELECT 'bucketed MergeTree'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MergeTree with bucketed zero-level parts'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_zero_level_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'basic MergeTree'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_basic WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Memory'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_memory WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +SELECT 'explicit key subcolumn of a basic Map'; +SELECT id, m.key_k FROM t_map_basic WHERE m.key_k > 7 ORDER BY id; + +SELECT 'results'; +SELECT id, m['k'] FROM t_map_bucketed WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_basic WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_memory WHERE m['k'] > 7 ORDER BY id; + +-- Engines that pass the analyzed query to other tables answer for those tables. +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_bucketed$'); +CREATE MATERIALIZED VIEW t_map_mv (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets' +AS SELECT id, m FROM t_map_bucketed; +CREATE TABLE t_map_buffer (id UInt64, m Map(String, UInt64)) +ENGINE = Buffer(currentDatabase(), t_map_bucketed, 1, 10, 100, 10000, 1000000, 10000000, 100000000); + +SELECT 'Merge over a bucketed table'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MaterializedView with a bucketed target'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_mv WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Buffer with a bucketed destination'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_buffer WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +-- The query is sent to every table of a Merge, so all of them must be bucketed. +DROP TABLE t_map_merge; +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_(bucketed|basic)$'); + +SELECT 'Merge over a bucketed and a basic table'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT id, m['k'] FROM t_map_merge WHERE m['k'] > 7 ORDER BY id; + +DROP TABLE t_map_buffer; +DROP TABLE t_map_mv; +DROP TABLE t_map_merge; +DROP TABLE t_map_memory; +DROP TABLE t_map_basic; +DROP TABLE t_map_zero_level_bucketed; +DROP TABLE t_map_bucketed; diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference new file mode 100644 index 000000000000..dfd940ddad71 --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference @@ -0,0 +1,3 @@ +3000 30 +3000 4501500 +1000 499500 diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh new file mode 100755 index 000000000000..f36ec224287c --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires `IcebergLocal` (USE_AVRO build option) + +# Each finished Iceberg data file used to keep its Parquet encoder threads until the commit, so writing +# 30 partitions with `max_threads = 16` needed 480 threads of the 300-thread global pool. +# https://github.com/ClickHouse/ClickHouse/issues/126508 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 16); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 16); do printf ', number * %d' "$i"; done) +SETTINGS="SET allow_insert_into_iceberg = 1, max_insert_threads = 1, max_threads = 16, output_format_parquet_parallel_encoding = 1" + +# INSERT, then ALTER TABLE ... UPDATE, which writes one position delete file and one data file per partition. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32 ${COLS}) ENGINE = IcebergLocal('${TABLE_DIR}/update/') PARTITION BY p; + INSERT INTO t SELECT number % 30 ${EXPRS} FROM numbers(3000); + SELECT count(), uniqExact(_path) FROM t; + ALTER TABLE t UPDATE c1 = c1 + 1 WHERE 1; + SELECT count(), sum(c1) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 + +# ALTER TABLE ... DELETE writes two-column position delete files, so it needs more partitions to fill the pool. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32, x Int64) ENGINE = IcebergLocal('${TABLE_DIR}/delete/') PARTITION BY p; + INSERT INTO t SELECT number % 80, number FROM numbers(2000); + ALTER TABLE t DELETE WHERE x >= 1000; + SELECT count(), sum(x) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference new file mode 100644 index 000000000000..636bda45df5e --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference @@ -0,0 +1,4 @@ +[[[[NULL]]],[[[NULL]]]] +[NULL,NULL] +4 2 +server is alive diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh new file mode 100755 index 000000000000..81d6382e1910 --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# The fast-test build is unoptimized and re-runs a new test several times under a 60s cap, while +# materializing a deeply nested Dynamic value whose operation does not trip the recursion guard takes +# superlinear time. The optimized stateless configurations run it within budget. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Each repetition of 1E2B0801 is a value of type Array(Dynamic(max_types=8)) with one element, so the +# nesting depth of the Dynamic value comes from the data, not from the declared type. The second row is NULL. +nested_value() { echo "format(RowBinary, 'd Dynamic', unhex(concat(repeat('1E2B0801', $1), '0000')))"; } + +$CLICKHOUSE_CLIENT -q "SELECT arraySort([d, d]) FROM $(nested_value 3)" + +# Depending on the build and the stack size, a deep value is either processed or rejected with +# TOO_DEEP_RECURSION, but it must never crash the server or use memory quadratic in the depth. +# Parsing a value takes time quadratic in its depth (every level has a longer type name), so the deepest value, +# which exhausts the stack in the release build, is only used for the operations that recurse into the nested +# columns: `index`, `compareAt`, and `filter`. +check_query() { + out=$($CLICKHOUSE_CLIENT -q "$1 FORMAT Null" 2>&1) + [[ -z "$out" || "$out" == *TOO_DEEP_RECURSION* ]] || echo "$1: $out" +} +table=$(nested_value 1000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d, arrayJoin([1, 2]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done +table=$(nested_value 9000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done + +# Writing a part and merging parts go through the dynamic structure helpers of the column. +# Writing a part takes time quadratic in the nesting depth (every level adds substreams with longer names), +# so a depth that exhausts the stack takes tens of seconds; use a small depth that checks the normal path +# and stays far from the stack limit in sanitizer builds, where depth 300 already hits it. +# The substream names of a deep value exceed the file name length limit of the filesystem in a wide part, +# so they must be replaced with hashes regardless of the randomized MergeTree settings. +$CLICKHOUSE_CLIENT -q "CREATE TABLE deep_dynamic (d Dynamic) ENGINE = MergeTree ORDER BY tuple() SETTINGS replace_long_file_name_to_hash = 1, max_file_name_length = 127" +table=$(nested_value 64) +for query in "INSERT INTO deep_dynamic SELECT d FROM $table" "INSERT INTO deep_dynamic SELECT d FROM $table" "OPTIMIZE TABLE deep_dynamic FINAL"; do + out=$($CLICKHOUSE_CLIENT -q "$query" 2>&1) + [[ -z "$out" ]] || echo "$query: $out" +done +$CLICKHOUSE_CLIENT -q "SELECT count(), countIf(d IS NULL) FROM deep_dynamic" +$CLICKHOUSE_CLIENT -q "DROP TABLE deep_dynamic" + +$CLICKHOUSE_CLIENT -q "SELECT 'server is alive'" diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference new file mode 100644 index 000000000000..fcc653eab3e4 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference @@ -0,0 +1,5 @@ +writer: time zone is rejected +reader: time zone is rejected +reader file: time zone is rejected +--- stateless server is still alive --- +1 diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh new file mode 100755 index 000000000000..f8e04add8d56 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e + +# A malformed ORC timezone name used to reach an empty TZif file outside TZDIR and abort +# inside libc++. The time zones are now resolved only from the embedded time zone database, +# so such a name must be rejected without touching the file system. Keep each attempt in a child clickhouse-local process and disable core dumps. +ulimit -c 0 + +WORK_DIR="${CLICKHOUSE_TMP}/orc_timezone_traversal_${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${WORK_DIR}" +mkdir -p "${WORK_DIR}" +trap 'rm -rf "${WORK_DIR}"' EXIT + +regression_status=0 +python3 - "${WORK_DIR}" <<'PY' || regression_status=$? +import os +import pathlib +import shlex +import shutil +import subprocess +import sys + +work_dir = pathlib.Path(sys.argv[1]) +tz_dir = work_dir / "zoneinfo" / "a" / "b" +tz_dir.mkdir(parents=True) + +# Use real, minimal zone files so the valid setup and the ORC fixture can be loaded while +# TZDIR points at this private directory. The traversal resolves to this test's empty file. +system_zoneinfo = pathlib.Path("/usr/share/zoneinfo") +for zone in ("UTC", "America/Vancouver"): + source = system_zoneinfo / zone + if not source.is_file(): + raise SystemExit(f"required time zone file not found: {source}") + target = tz_dir / zone + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + +(work_dir / "outside").write_bytes(b"") +if (tz_dir / "../../../outside").resolve() != (work_dir / "outside").resolve(): + raise SystemExit("private timezone traversal fixture is misconfigured") +(work_dir / "dev").mkdir() +(work_dir / "dev" / "null").write_bytes(b"") +if (tz_dir / "../../../dev/null").resolve() != (work_dir / "dev" / "null").resolve(): + raise SystemExit("private ORC metadata traversal fixture is misconfigured") + +env = os.environ.copy() +env["TZDIR"] = str(tz_dir) +env["TZ"] = "UTC" +local_command = shlex.split(env["CLICKHOUSE_LOCAL"]) + + +def run_local(path, *args, query=None, input_data=None): + path.mkdir(parents=True, exist_ok=True) + command = local_command + ["--path", str(path), *args] + if query is not None: + command += ["--query", query] + return subprocess.run( + command, + input=input_data, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + + +safe_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='America/Vancouver', " + "output_format_orc_compression_method='none'" +) +fixture = run_local(work_dir / "safe", query=safe_query) +if fixture.returncode != 0 or not fixture.stdout.startswith(b"ORC"): + diagnostic = (fixture.stderr + fixture.stdout).decode(errors="replace") + raise SystemExit(f"could not create valid ORC fixture: {diagnostic[:1000]}") + +# Preserve the ORC file's byte lengths while replacing its writer timezone metadata +# with the path from the customer reproducer. This exercises a file supplied by a +# reader, without requiring a malicious query setting. +safe_name = b"America/Vancouver" +unsafe_name = b"../../../dev/null" +if len(safe_name) != len(unsafe_name) or fixture.stdout.count(safe_name) != 1: + raise SystemExit("valid ORC fixture has unexpected timezone metadata") +malicious_file = fixture.stdout.replace(safe_name, unsafe_name, 1) + +malicious_writer_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='../../../outside', " + "output_format_orc_compression_method='none'" +) +writer = run_local(work_dir / "writer", query=malicious_writer_query) +reader = run_local( + work_dir / "reader", + "--input-format=ORC", + "--input_format_orc_reader_time_zone_name=../../../outside", + query="SELECT * FROM table", + input_data=fixture.stdout, +) +reader_file = run_local( + work_dir / "reader_file", + "--input-format=ORC", + query="SELECT * FROM table", + input_data=malicious_file, +) + +failed = False +for label, result in (("writer", writer), ("reader", reader), ("reader file", reader_file)): + if result.returncode < 0: + print(f"{label}: terminated by signal {-result.returncode}") + failed = True + elif result.returncode == 0: + print(f"{label}: malformed timezone unexpectedly succeeded") + failed = True + elif any( + message in result.stdout + result.stderr + for message in (b"is not supported. Use a name from `system.time_zones`", b"Cannot load time zone ../../../") + ): + print(f"{label}: time zone is rejected") + else: + diagnostic = (result.stderr + result.stdout).decode(errors="replace") + first_line = next((line for line in diagnostic.splitlines() if line), "no diagnostic") + print(f"{label}: unexpected error: {first_line[:300]}") + failed = True + +if failed: + raise SystemExit(1) +PY + +echo '--- stateless server is still alive ---' +${CLICKHOUSE_CLIENT} --query "SELECT 1" +exit "${regression_status}" diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference b/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql new file mode 100644 index 000000000000..329dfc62bcda --- /dev/null +++ b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql @@ -0,0 +1,9 @@ +-- Tags: no-fasttest +-- no-fasttest: needs Azure Blob Storage support, which is not built in the fast test. + +-- The (url, sas_token) form of the Azure table functions parses a URL that ends right after the host like the same URL +-- with a trailing slash (both then fail at format detection), and rejects a malformed abfss URL with BAD_ARGUMENTS. +SELECT * FROM azureBlobStorage('https://acc.blob.core.windows.net', 'sv=2022'); -- { serverError CANNOT_DETECT_FORMAT } +SELECT * FROM azureBlobStorage('abfss://foo.net', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://foo.net/c/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://c.x@acc.dfs.core.windows.net/p/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference new file mode 100644 index 000000000000..e838531bffe0 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference @@ -0,0 +1,51 @@ +LIKE `t0` +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(KEY `k` (`x`)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +LIKE `t0` +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(KEY `k` (`x`)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(`x` int, `y` varchar(10)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh new file mode 100755 index 000000000000..ab7e6079e829 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `CREATE TABLE` in a MySQL dump without column definitions (`CREATE TABLE ... LIKE`, or only indexes or constraints) +# gives no structure, so the structure is inferred from the data of the `INSERT`. + +function dump() +{ + printf 'CREATE TABLE `t1` %s;\n/*!40101 SET character_set_client = @saved_cs_client */;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB'; do + echo "$create" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "DESCRIBE TABLE table" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" +done + +# The `INSERT` immediately following the `CREATE TABLE` must not be skipped. + +function dump_single_insert() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +function dump_multiple_inserts() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"');\nINSERT INTO `t1` VALUES (2,'"'"'b'"'"');\nINSERT INTO `t1` VALUES (3,'"'"'c'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB' '(`x` int, `y` varchar(10)) ENGINE=InnoDB'; do + echo "$create" + dump_single_insert "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --structure 'x UInt32, y String' --query "SELECT * FROM table" +done diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference new file mode 100644 index 000000000000..5453565c8dd8 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference @@ -0,0 +1,3 @@ +BAD_ARGUMENTS +x UInt32 +supported_values Map(String, UInt32) diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh new file mode 100755 index 000000000000..e551cdbc6837 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `map` whose value type is unsupported is skipped in schema inference with +# `input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1`. + +SCHEMADIR="$CUR_DIR/format_schemas" +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 0" 2>&1 | grep -o -m1 -F 'BAD_ARGUMENTS' +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1" diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference new file mode 100644 index 000000000000..739d1f2b1342 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference @@ -0,0 +1,4 @@ +Map(Int64, Nullable(Int64)) {1:1} +Map(Int64, Nullable(Int64)) {0:1} +Map(Int64, Nullable(Int64)) {2:3} +Map(Int64, Int64) {0:1} diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql new file mode 100644 index 000000000000..fb99be351299 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest +-- no-fasttest: MsgPack format is not available in the fasttest environment + +-- A MsgPack map whose first key has no inferable type (nil, empty array, empty map, nested map with a nil key) +-- must be reported as "cannot determine type", not dereferenced. + +SET input_format_msgpack_number_of_columns = 1; + +-- {1: 1} +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\x01\x01'); + +-- {nil: 1}, {[]: 1}, {{}: 1}, {{nil: 1}: 1} +DESC format(MsgPack, '\x81\xc0\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x90\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x80\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x81\xc0\x01\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- {nil: 1}, {2: 3}: the type is taken from the second row. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01\x81\x02\x03'); + +-- {nil: 1} with schema_inference_hints, which the error message suggests. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01') SETTINGS schema_inference_hints = 'c1 Map(Int64, Int64)'; diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference new file mode 100644 index 000000000000..98c80be8e58b --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference @@ -0,0 +1,5 @@ +0300000000000000 +c9b15b7fd5143f1d8f677be3dc4daab9 - +c9b15b7fd5143f1d8f677be3dc4daab9 - +9038957ba26f89fe09ee1964aad98576 - +9038957ba26f89fe09ee1964aad98576 - diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh new file mode 100755 index 000000000000..d6493c3c6808 --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# `RawBLOB` must write the serialized state of an aggregate function, the same as its conversion to `String`, +# not the pointer to the state in memory. + +$CLICKHOUSE_CLIENT -q "SELECT sumState(number) FROM numbers(3) FORMAT RawBLOB" | od -An -tx1 | tr -d ' \n' +echo + +$CLICKHOUSE_CLIENT -q "SELECT quantileState(number) FROM numbers(100000) FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(quantileState(number) AS String) FROM numbers(100000) FORMAT RawBLOB" | md5sum + +$CLICKHOUSE_CLIENT -q "SELECT uniqExactState(number) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(uniqExactState(number) AS String) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference new file mode 100644 index 000000000000..e5046dab0a10 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -0,0 +1,35 @@ +table created +-- ALTER with only ALTER SETTINGS +settings that are not a destination: allowed +-- ALTER with SELECT on the table, but no WRITE on S3 +-- ALTER ON CLUSTER is rejected by the initiator +-- ALTER ON CLUSTER of a table that does not exist on the initiator +-- ALTER with WRITE on S3 limited by a URL filter +-- ALTER with WRITE on S3 +destination with WRITE on S3: allowed +empty destination without WRITE on S3: allowed +-- ALTER with WRITE on S3, restricted by a row policy +empty destination with a row policy: allowed +-- ALTER through an Alias +settings that are not a destination through an alias: allowed +-- CREATE without WRITE on S3 or AZURE +table without a destination: created +-- CREATE AS with a destination, without WRITE on S3 +-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3 +-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3 +-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3 +-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3 +-- ATTACH with a full definition and a destination, without WRITE on S3 +-- RESTORE of a queue with a destination, without WRITE on S3 +0 +0 +0 +-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 +CREATE AS with WRITE on S3: created +materialized view with WRITE on S3: created +RESTORE with WRITE on S3: restored +RESTORE ON CLUSTER with WRITE on S3: restored +CREATE ON CLUSTER with WRITE on S3: created +CREATE AS ON CLUSTER with WRITE on S3: created +ATTACH with WRITE on S3: attached +RESTORE TEMPORARY with WRITE on S3: restored 1 diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh new file mode 100755 index 000000000000..5699f7262195 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -0,0 +1,377 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, zookeeper, no-replicated-database +# Tag no-fasttest: the `S3Queue` and `AzureQueue` engines are not built into the fast test build. +# Tag zookeeper: `S3Queue` keeps its state in Keeper, and `ON CLUSTER` queries use the distributed DDL queue. +# Tag no-replicated-database: with `access_control_improvements.enable_read_write_grants` disabled (the default), +# a replicated access storage round-trips the user through serialized SQL, which rewrites `WRITE ON S3('')` +# into the old-style whole-source `S3` grant without the filter. + +# The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +# `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads the processed files with its +# own credentials and writes them to the destination. So setting `after_processing_move_uri`, +# `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) +# source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. +# `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +db="${CLICKHOUSE_DATABASE}" +user_alter="s3queue_move_alter_${db}" +user_create="s3queue_move_create_${db}" +keeper_path="/s3queue_move_destination_access_${db}" +src="http://localhost:11111/test/${db}_move_src/" +dst="http://localhost:11111/test/${db}_move_dst/" +backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" +backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" +attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") +azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}', after_processing = 'keep' +" +echo "table created" + +$CLICKHOUSE_CLIENT -q " + CREATE USER ${user_alter}; + GRANT ALTER SETTINGS ON ${db}.t TO ${user_alter}; + CREATE USER ${user_create}; + GRANT CREATE TABLE ON ${db}.* TO ${user_create}; + GRANT TABLE ENGINE ON S3Queue TO ${user_create}; + GRANT TABLE ENGINE ON AzureQueue TO ${user_create}; +" + +echo "-- ALTER with only ALTER SETTINGS" + +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container redirects the move to another container of the same account. +# The check reads only the query, so it fails before the storage is involved, although `t` is an `S3Queue`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# Settings that do not choose a destination need only ALTER SETTINGS. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING polling_max_timeout_ms = 20000, after_processing_move_prefix = 'prefix_${db}' +" && echo "settings that are not a destination: allowed" + +echo "-- ALTER with SELECT on the table, but no WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${db}.t TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container is a destination change that needs `WRITE` on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER is rejected by the initiator" + +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" + +# The grants come from the settings in the query, not from the table, so the initiator checks them without the table. +# With the grant, the query reaches the host and fails there. +$CLICKHOUSE_CLIENT -q "GRANT ALTER SETTINGS, SELECT ON ${db}.t_missing TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError UNKNOWN_TABLE } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3 limited by a URL filter" + +# The move writes keys built from the prefix and the source keys, so a URL filter cannot authorize them. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3('${dst}.*') TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3('${dst}.*') FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} +" && echo "destination with WRITE on S3: allowed" + +# Resetting the destination disables the move, so it needs no grant for a destination. +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination without WRITE on S3: allowed" + +echo "-- ALTER with WRITE on S3, restricted by a row policy" + +# The move copies whole files, so a user whose row policy hides rows of the table cannot set a destination. +$CLICKHOUSE_CLIENT -q " + GRANT WRITE ON S3 TO ${user_alter}; + CREATE ROW POLICY p_${db} ON ${db}.t USING x = 1 TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +# Turning the move off needs no check. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination with a row policy: allowed" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY p_${db} ON ${db}.t; + REVOKE WRITE ON S3 FROM ${user_alter}; +" + +echo "-- ALTER through an Alias" + +# The export checks see only the name in the query, which is the alias, so the change is refused for every user. +$CLICKHOUSE_CLIENT --allow_experimental_alias_table_engine 1 -q "CREATE TABLE ${db}.t_alias ENGINE = Alias('${db}', 't')" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError NOT_IMPLEMENTED } +" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 +" && echo "settings that are not a destination through an alias: allowed" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_alias SYNC" + +echo "-- CREATE without WRITE on S3 or AZURE" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# The same CREATE without a destination, or with an empty one, needs no grant for it. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'keep', + after_processing_move_uri = '' +" && echo "table without a destination: created" + +echo "-- CREATE AS with a destination, without WRITE on S3" + +# The engine and the settings of `AS` are inherited after the query is parsed, so the check has to see the final definition. +# `AS` inherits the definition only when the query has no storage clause (with `SETTINGS`, the engine is +# `default_table_engine`), so the destination comes from the source table. +# The source has no `keeper_path`, so each copy gets its own default path from its `UUID`. +# `SELECT` is required because the definition of the source has secret parts. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_as_src (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', after_processing = 'move', after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "GRANT SHOW COLUMNS, SELECT ON ${db}.t_as_src TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3" + +# The engine is an inner engine of the view, and the inner table is created as an internal query, which checks nothing. +$CLICKHOUSE_CLIENT -q "GRANT CREATE VIEW ON ${db}.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3" + +# This format ships the query as written and the workers resolve `AS` with no user. +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_entry_format_version 2 -q " + CREATE TABLE ${db}.t_as_cluster ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3" + +# This format builds the definition on the initiator. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ATTACH with a full definition and a destination, without WRITE on S3" + +# A full definition in `ATTACH` is a new definition, like `CREATE`. An `Atomic` database needs a `UUID` for it. +# The server warns that a full definition in `ATTACH` is not recommended, so only errors are sent to the client. +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- RESTORE of a queue with a destination, without WRITE on S3" + +# The restored definition comes from the backup, and the table is created by an internal query, +# so the restore has to authorize the destination before it creates anything. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "BACKUP TABLE ${db}.t_backup TO ${backup} FORMAT Null" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_backup SYNC" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup'" + +# The hosts create the tables with no user, so the initiator must authorize the destination. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup_cluster'" + +# A temporary table keeps its engine, even with `restore_replace_external_engines_to_null`, so the same check applies. +# Temporary tables live in a session, so the table is created and backed up in one client. +$CLICKHOUSE_CLIENT -m -q " + CREATE TEMPORARY TABLE t_tmp_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_tmp_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys}; + BACKUP TEMPORARY TABLE t_tmp_backup TO ${backup_tmp} FORMAT Null; +" +$CLICKHOUSE_CLIENT -q "GRANT CREATE TEMPORARY TABLE ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} + SETTINGS structure_only = 1, restore_replace_external_engines_to_null = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" + +# The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src +" && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x +" && echo "materialized view with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE ON CLUSTER with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "CREATE ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src +" && echo "CREATE AS ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "ATTACH with WRITE on S3: attached" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; + SELECT 'RESTORE TEMPORARY with WRITE on S3: restored', count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference new file mode 100644 index 000000000000..1ee31d8b5520 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference @@ -0,0 +1,3 @@ +src 0 1 +src 1 2 +tgt 0 1 diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql new file mode 100644 index 000000000000..71c125e9ef63 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql @@ -0,0 +1,39 @@ +-- Two async inserts with the same `insert_deduplication_token` but different data are coalesced +-- into one batch. In the materialized view target, the rows of the two tokens land in different +-- partitions. For the partition of the second (duplicate) token, self-deduplication removes all +-- rows, and the recalculated block for that partition is empty. The empty block used to reach +-- `MergeTreeDataWriter::mergeBlock` and trigger the "Required source after the first merge is +-- not 0" logical error with `optimize_on_insert` enabled and a `ReplacingMergeTree` target. + +DROP TABLE IF EXISTS mv_dedup_empty; +DROP TABLE IF EXISTS tgt_dedup_empty; +DROP TABLE IF EXISTS src_dedup_empty; + +CREATE TABLE src_dedup_empty (p UInt64, v UInt64) ENGINE = MergeTree ORDER BY v; +CREATE TABLE tgt_dedup_empty (p UInt64, v UInt64) ENGINE = ReplacingMergeTree PARTITION BY p ORDER BY v + SETTINGS non_replicated_deduplication_window = 100; +CREATE MATERIALIZED VIEW mv_dedup_empty TO tgt_dedup_empty AS SELECT p, v FROM src_dedup_empty; + +SET async_insert = 1; +SET wait_for_async_insert = 0; +SET async_insert_deduplicate = 1; +SET deduplicate_blocks_in_dependent_materialized_views = 1; +SET optimize_on_insert = 1; +-- Prevent an automatic flush between the two inserts; the flush below is explicit. +SET async_insert_busy_timeout_min_ms = 600000; +SET async_insert_busy_timeout_max_ms = 600000; +SET async_insert_use_adaptive_busy_timeout = 0; + +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (0, 1); +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (1, 2); + +SYSTEM FLUSH ASYNC INSERT QUEUE src_dedup_empty; + +-- The source table has no deduplication window, so it keeps both rows. In the target table the +-- second insert is a duplicate of the first by token, so only the first row survives. +SELECT 'src', p, v FROM src_dedup_empty ORDER BY v; +SELECT 'tgt', p, v FROM tgt_dedup_empty ORDER BY v; + +DROP TABLE mv_dedup_empty; +DROP TABLE tgt_dedup_empty; +DROP TABLE src_dedup_empty; diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference new file mode 100644 index 000000000000..f7068f2917b6 --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference @@ -0,0 +1,7 @@ +parallel_distributed_insert_select=0 ACCESS_DENIED +parallel_distributed_insert_select=1 ACCESS_DENIED +parallel_distributed_insert_select=2 ACCESS_DENIED +0 +1 +row policy on source FALLBACK +additional_table_filters 0 diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh new file mode 100755 index 000000000000..1c39f64182cf --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="user_$CLICKHOUSE_DATABASE" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE secret_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + CREATE TABLE copy_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + INSERT INTO secret_local VALUES (1, 'secret'); + + CREATE TABLE src_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), secret_local, id); + CREATE TABLE dst_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), copy_local, id); + + DROP USER IF EXISTS $user; + CREATE USER $user IDENTIFIED WITH no_password; + GRANT SELECT, INSERT ON $CLICKHOUSE_DATABASE.dst_dist TO $user; +" + +# The cluster has no interserver secret, so the shard runs the forwarded query under the credentials +# from the cluster configuration rather than as the caller. +client=($CLICKHOUSE_CLIENT --user "$user" --prefer_localhost_replica 0) + +for setting in 0 1 2; do + echo -n "parallel_distributed_insert_select=$setting " + "${client[@]}" --parallel_distributed_insert_select "$setting" -q "INSERT INTO dst_dist SELECT * FROM src_dist" |& + grep -o -m1 'ACCESS_DENIED' || echo 'NOT DENIED' +done + +# Read the destination directly: resolving `dst_dist` also authorizes `copy_local` once the shard +# query is planned on the initiator, which depends on the distributed plan settings. +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# With the grant in place the optimized path must still work. +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON $CLICKHOUSE_DATABASE.src_dist TO $user" +"${client[@]}" --parallel_distributed_insert_select 2 -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# A row policy on the source table cannot be applied by the optimized rewrite (it ships the query +# to the shards, where the policy on the Distributed table never applies), so it must fall back to +# the regular path. The regular path reads `src_dist` with a `SELECT` sent to the shard, while the +# optimized rewrite sends only an `INSERT ... SELECT` there, so the fallback is detected by the +# kind of the secondary queries in `system.query_log`. (The regular path of this branch does not +# enforce a row policy on a Distributed table, so the result of the copy itself is not checked.) +# +# The two fallback cases below pin serialize_query_plan = 0: with plan serialization the initiator +# plans the read of the underlying table itself and requires the caller's own SELECT on it, which +# these cases do not grant. +$CLICKHOUSE_CLIENT -q "CREATE ROW POLICY policy_05443 ON src_dist USING id != 1 TO $user" +query_id="05443_row_policy_${CLICKHOUSE_DATABASE}_$RANDOM" +"${client[@]}" --parallel_distributed_insert_select 2 --enable_analyzer 1 --enable_parallel_replicas 0 \ + --serialize_query_plan 0 --query_id "$query_id" \ + -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY policy_05443 ON src_dist; + SYSTEM FLUSH DISTRIBUTED dst_dist; + TRUNCATE TABLE copy_local; + SYSTEM FLUSH LOGS query_log; + SELECT + 'row policy on source', + if(countIf(query_kind = 'Select') > 0 AND countIf(query_kind = 'Insert' AND query ILIKE '%SELECT%') = 0, + 'FALLBACK', 'OPTIMIZED') + FROM system.query_log + WHERE event_date >= yesterday() AND initial_query_id = '$query_id' AND NOT is_initial_query AND type = 'QueryFinish' +" + +# additional_table_filters is keyed by the source table name, which the optimized rewrite would +# drop, so it must fall back to the regular path, which applies the filter: the only row has +# id = 1, nothing is copied and the destination stays empty. +echo -n "additional_table_filters " +"${client[@]}" --parallel_distributed_insert_select 2 --enable_parallel_replicas 0 --serialize_query_plan 0 \ + --additional_table_filters "{'src_dist' : 'id != 1'}" -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH DISTRIBUTED dst_dist; SELECT count() FROM copy_local" + +$CLICKHOUSE_CLIENT -q "DROP USER $user" diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference new file mode 100644 index 000000000000..aca8188dbcd7 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference @@ -0,0 +1,13 @@ +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +0 1900-01-01 00:00:00.145224192 Nullable(DateTime64(9, \'UTC\')) +1 1900-01-01 00:00:00.000000000 Nullable(DateTime64(9, \'UTC\')) +2 2020-05-17 10:20:30.123456000 Nullable(DateTime64(9, \'UTC\')) +3 2262-04-11 23:47:16.854775807 Nullable(DateTime64(9, \'UTC\')) +4 \N Nullable(DateTime64(9, \'UTC\')) +0 1900-01-01 00:00:00.145225 Nullable(DateTime64(6, \'UTC\')) +1 1900-01-01 00:00:00.000000 Nullable(DateTime64(6, \'UTC\')) +2 2020-05-17 10:20:30.123456 Nullable(DateTime64(6, \'UTC\')) +3 2262-04-11 23:47:16.854775 Nullable(DateTime64(6, \'UTC\')) +4 \N Nullable(DateTime64(6, \'UTC\')) +2 diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh new file mode 100755 index 000000000000..184859b09430 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# INT96 timestamps 0001-01-01, 1800-01-01 12:30, 2020-05-17 10:20:30.123456, 9999-12-31 23:59:59 and NULL, written by +# pyarrow with `use_deprecated_int96_timestamps=True`. The first and the fourth do not fit into Int64 nanoseconds. +DATA_FILE="${CUR_DIR}/data_parquet/05443_int96_out_of_range.parquet" + +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'throw'" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet, 'id Int32, ts Nullable(DateTime64(6, \'UTC\'))') ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT count() FROM file('${DATA_FILE}', Parquet) WHERE ts > '2000-01-01' SETTINGS date_time_overflow_behavior = 'saturate';" diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference new file mode 100644 index 000000000000..0b775a99cb4f --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference @@ -0,0 +1,2 @@ +0 1900-01-01 00:00:00.000000000 -9223329600000000000 +0 1900-01-01 00:00:00.000000000 -9223329600000000000 diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh new file mode 100755 index 000000000000..39e02424f38a --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A single INT96 timestamp 1677-09-21 12:00:00 (julian day 2333836, time of day 43200000000000 ns), written by pyarrow +# with `use_deprecated_int96_timestamps=True`. Midnight of that day does not fit into Int64 nanoseconds, but the full value +# -9223329600000000000 does, so it must be read exactly instead of being saturated to the Int64 minimum or rejected. +DATA_FILE="${CUR_DIR}/data_parquet/05444_int96_lower_boundary.parquet" + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'throw';" diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference new file mode 100644 index 000000000000..aa20b4a60886 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference @@ -0,0 +1 @@ +ACCESS_DENIED diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh new file mode 100755 index 000000000000..71282f1c8437 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tags: distributed, no-fasttest +# Tag no-fasttest: the interserver `` requires SSL, which the fast test build does not have. + +# Queued `Distributed` inserts of different users must not be sent in one batch: the batch is sent with +# the `ClientInfo` of its first file, and over a cluster with an interserver `` the shard +# authenticates the whole batch as that file's `initial_user`. Before the fix, rows of a user without +# the remote `INSERT` grant were delivered under the identity of a user that had it. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Flushing the rejected file (also when the table is dropped) logs the error on the server. +CLICKHOUSE_CLIENT=$(echo "$CLICKHOUSE_CLIENT" | sed "s/--send_logs_level=${CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL:-none}/--send_logs_level=none/g") + +WRITER="writer_${CLICKHOUSE_DATABASE}" +TENANT="tenant_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${WRITER}, ${TENANT}; + CREATE TABLE target (key Int) ENGINE = MergeTree ORDER BY key; + CREATE TABLE dist (key Int) ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), target, 0) + SETTINGS background_insert_batch = 1; + SYSTEM STOP DISTRIBUTED SENDS dist; + CREATE USER ${WRITER} IDENTIFIED WITH no_password; + CREATE USER ${TENANT} IDENTIFIED WITH no_password; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.dist TO ${WRITER}, ${TENANT}; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.target TO ${WRITER}; +" + +${CLICKHOUSE_CLIENT} --user "${WRITER}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (1)" +${CLICKHOUSE_CLIENT} --user "${TENANT}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (2)" + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH DISTRIBUTED dist" 2>&1 | grep -o -m1 "ACCESS_DENIED" +${CLICKHOUSE_CLIENT} -q "SELECT key FROM target WHERE key = 2" + +${CLICKHOUSE_CLIENT} -m -q " + DROP TABLE dist; + DROP USER ${WRITER}, ${TENANT}; +" diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference new file mode 100644 index 000000000000..65bc13dc12ac --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference @@ -0,0 +1,13 @@ +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', '[HIDDEN]', 'container', 'blob') +SELECT * FROM icebergAzure('[HIDDEN]', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = '[HIDDEN]', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +HIDDEN +0 1 +0 1 diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh new file mode 100755 index 000000000000..8ef143807a79 --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no `azureBlobStorage` table function + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A storage account url carrying a credential of its own (a SAS `?sig=...`, `user:key@`), or a value that is +# not a plain string literal, is hidden whole in the Azure table functions, positional or as a named-collection +# override, as the `AzureBlobStorage` engine and the backup destination already do. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('https://user:plain_password@account.blob.core.windows.net', 'container', 'blob') +SELECT * FROM azureBlobStorage(concat('https://account.blob.core.windows.net/?sig=', 'plain_sas_signature'), 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +EOF + +# `SELECT` on a view implies `SHOW COLUMNS`, so a user granted only that sees the view definition through +# `SHOW CREATE TABLE` and `system.tables`, but not the SAS in it. +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +$CLICKHOUSE_CLIENT -q "DROP USER IF EXISTS ${user}" +$CLICKHOUSE_CLIENT -q "CREATE VIEW ${CLICKHOUSE_DATABASE}.v_sas AS SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'file.csv', 'CSV', 'none', 'id UInt8')" +$CLICKHOUSE_CLIENT -q "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'hello'" +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.v_sas TO ${user}" + +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SHOW CREATE TABLE ${CLICKHOUSE_DATABASE}.v_sas" | grep -o -e 'plain_sas_signature' -e 'HIDDEN' +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SELECT countIf(create_table_query LIKE '%plain_sas_signature%'), countIf(create_table_query LIKE '%[HIDDEN]%') FROM system.tables WHERE database = '${CLICKHOUSE_DATABASE}' AND name = 'v_sas'" + +# `EXPLAIN AST optimize = 1` expands the view, which executes the table function and needs more than `SELECT` +# on the view, so it is run as the default user, who sees no secrets either without +# `format_display_secrets_in_show_and_select`. +$CLICKHOUSE_CLIENT --format_display_secrets_in_show_and_select 0 -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN AST optimize = 1 SELECT * FROM ${CLICKHOUSE_DATABASE}.v_sas)" + +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.reference b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference new file mode 100644 index 000000000000..a46fd0469968 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference @@ -0,0 +1,14 @@ +1900-06-01 00:01:41.000007000 -2195942298999993 +1900-06-01 00:01:41.000000000 -2195942299000000 +1960-06-01 00:01:41.000007000 -302486298999993 +2000-06-01 00:01:41.000007000 959817701000007 +none 25000 609103159500350648 +zstd 25000 609103159500350648 +lz4 25000 609103159500350648 +snappy 25000 609103159500350648 +zlib 25000 609103159500350648 +expected 25000 609103159500350648 +1001 4500 5500 +1923 +['a','b','a','b'] +['a','b','a','b'] Array(LowCardinality(String)) diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.sh b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh new file mode 100755 index 000000000000..bee99fd05840 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The Arrow ORC adapter stores negative nanoseconds for the timestamps before the epoch, +# and the reader must decode them as the reference implementation does. +$CLICKHOUSE_LOCAL -q "SELECT t, toUnixTimestamp64Micro(t) FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_arrow.orc', ORC) SETTINGS session_timezone = 'UTC'" + +DATA_FILE="$CLICKHOUSE_TMP/05447_${CLICKHOUSE_DATABASE}.orc" + +# Dictionary encoding of strings (with the row index and several row groups), a non-GMT writer time +# zone, and the values that need all integer encodings: repeats, deltas, outliers. +QUERY="SELECT number AS n, + toString(number % 13) AS low_cardinality, + if(number % 5 = 0, NULL, concat('value_', toString(number))) AS high_cardinality, + toDateTime64(1700000000 + number * 37, 3, 'UTC') AS ts, + if(number % 1000 = 0, 1000000000000, number % 7) AS outliers, + intDiv(number, 100) AS runs, + toDecimal128(number, 10) * -3 AS dec +FROM numbers(25000)" + +for compression in none zstd lz4 snappy zlib +do + $CLICKHOUSE_LOCAL -q "$QUERY FORMAT ORC SETTINGS output_format_orc_compression_method = '$compression', + output_format_orc_dictionary_key_size_threshold = 0.5, output_format_orc_row_index_stride = 1000, + output_format_orc_writer_time_zone_name = 'America/Los_Angeles'" > "$DATA_FILE" + $CLICKHOUSE_LOCAL -q "SELECT '$compression', count(), sum(cityHash64(*)) FROM file('$DATA_FILE', ORC, + 'n UInt64, low_cardinality String, high_cardinality Nullable(String), ts DateTime64(3, \'UTC\'), outliers UInt64, runs UInt64, dec Decimal(38, 10)') + SETTINGS input_format_orc_reader_time_zone_name = 'America/Los_Angeles'" +done +$CLICKHOUSE_LOCAL -q "SELECT 'expected', count(), sum(cityHash64(*)) FROM ($QUERY)" + +# Filter pushdown skips the row groups by the statistics in the row index. +$CLICKHOUSE_LOCAL -q "SELECT count(), min(n), max(n) FROM file('$DATA_FILE', ORC) WHERE n BETWEEN 4500 AND 5500 SETTINGS input_format_orc_filter_push_down = 1" +$CLICKHOUSE_LOCAL -q "SELECT count() FROM file('$DATA_FILE', ORC) WHERE low_cardinality = '12' SETTINGS input_format_orc_filter_push_down = 1" + +# The dictionary of a string column nested in an array can have more entries than the stripe has rows. +$CLICKHOUSE_LOCAL -q "SELECT ['a', 'b', 'a', 'b'] AS arr FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 0.5" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT arr FROM file('$DATA_FILE', ORC, 'arr Array(String)')" +$CLICKHOUSE_LOCAL -q "SELECT arr, toTypeName(arr) FROM file('$DATA_FILE', ORC, 'arr Array(LowCardinality(String))')" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.reference b/tests/queries/0_stateless/05448_orc_date_after_2059.reference new file mode 100644 index 000000000000..62cea6b447e4 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.reference @@ -0,0 +1,12 @@ +0 1970-01-01 Nullable(Date32) +1 2059-09-17 Nullable(Date32) +2 2059-09-18 Nullable(Date32) +3 2100-01-01 Nullable(Date32) +4 2149-06-06 Nullable(Date32) +0 1970-01-01 +1 2059-09-17 +2 2059-09-18 +3 2100-01-01 +4 2149-06-06 +3 +4 diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.sh b/tests/queries/0_stateless/05448_orc_date_after_2059.sh new file mode 100755 index 000000000000..8cc480ff4b24 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `Date` is the unsigned number of days, and the dates after 2059-09-18 (more than 32767 days) used +# to be written to ORC as negative numbers, which read back as the dates before 1970. +DATA_FILE="$CLICKHOUSE_TMP/05448_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q "SELECT number AS n, toDate(d) AS d FROM values('number UInt64, d String', (0, '1970-01-01'), (1, '2059-09-17'), (2, '2059-09-18'), (3, '2100-01-01'), (4, '2149-06-06')) FORMAT ORC" > "$DATA_FILE" + +$CLICKHOUSE_LOCAL -q "SELECT n, d, toTypeName(d) FROM file('$DATA_FILE', ORC) ORDER BY n" +$CLICKHOUSE_LOCAL -q "SELECT n, d FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') ORDER BY n" + +# The statistics are correct as well, so the filter pushdown keeps the rows. +$CLICKHOUSE_LOCAL -q "SELECT n FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') WHERE d > '2060-01-01' ORDER BY n SETTINGS input_format_orc_filter_push_down = 1" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference new file mode 100644 index 000000000000..d5d2e9dad4f1 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference @@ -0,0 +1,5 @@ +-- page cache, prefetching read +0 0 +1 10 +2 20 +1 diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh new file mode 100755 index 000000000000..8b52986339b5 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: S3 (MinIO) is not available in the fast test. + +# Parsing a short CSV object through the userspace page cache with a prefetching read must not read past the end of the +# page cache cell that holds it. A sanitizer build aborts on such a read. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}/data.csv" + +CONFIG_FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_page_cache.yaml" +echo "page_cache_max_size: 134217728" > "${CONFIG_FILE}" + +# A 14-byte object: "0,0\n1,10\n2,20\n". +${CLICKHOUSE_CLIENT} --query " + INSERT INTO FUNCTION s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a UInt32, b UInt32') + SELECT number, number * 10 FROM numbers(3) SETTINGS s3_truncate_on_insert = 1" + +echo "-- page cache, prefetching read" +${CLICKHOUSE_LOCAL} --config-file "${CONFIG_FILE}" --query " + SELECT * FROM s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a String, b UInt32') ORDER BY b + SETTINGS input_format_parallel_parsing = 0, use_page_cache_for_object_storage = 1, + remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1; + SELECT value > 0 FROM system.metrics WHERE metric = 'PageCacheBytes'" + +rm "${CONFIG_FILE}" diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference new file mode 100644 index 000000000000..a4a9c43f01b2 --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference @@ -0,0 +1,8 @@ +1.6.0 0 18000000000 Mike +1.6.0 0 1 +1.6.0 1 18000000000 Mike +1.6.0 1 1 +1.6.11 0 18000000000 Mike +1.6.11 0 1 +1.6.11 1 18000000000 Mike +1.6.11 1 1 diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh new file mode 100755 index 000000000000..30badff1fa0d --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# The bloom filters written by the C++ writer of ORC 1.6.0 - 1.6.11 and 1.7.0 use incorrect hashing (ORC-1024) +# and must be ignored, otherwise the filter pushdown skips the matching rows. +for version in 1.6.0 1.6.11 +do + for push_down in 0 1 + do + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, id, name + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id = 18000000000 + SETTINGS input_format_orc_filter_push_down = $push_down" + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, count() + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id IN (18000000000, 18000000001) + SETTINGS input_format_orc_filter_push_down = $push_down" + done +done diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference new file mode 100644 index 000000000000..cf669808c66d --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference @@ -0,0 +1,39 @@ +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +SELECT * FROM azureBlobStorage('[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('[HIDDEN]', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=[HIDDEN]', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = '[HIDDEN]', storage_account_url = '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', connection_string = '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('[HIDDEN]', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]' +0 1 +0 1 +0 1 +0 1 +0 1 diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh new file mode 100755 index 000000000000..6246ea1d8cb3 --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Azure table functions and engines, whose arguments it then hides whole + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `clickhouse-format` hides the credentials in the arguments of the Azure table functions and engines and in the +# `SETTINGS` clause of `AzureQueue`, wherever the parser reads them from. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id', tenant_id = 'tid'), 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id'), extra_credentials(tenant_id = 'tid'), 'plain_account_key', 'CSV') +SELECT * FROM azureBlobStorageCluster(extra_credentials(client_id = 'id'), 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')) +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;SharedAccessSignature=sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=https://account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('HTTPS://user:plain_password=x@account.blob.core.windows.net/', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, client_secret = 'plain_client_secret', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = headers('Authorization' = 'plain_header_secret'), blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', storage_account_url = 'AccountName=account;AccountKey=plain_account_key_2') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = concat('AccountName=account;AccountKey=', 'plain_account_key'), connection_string = 'AccountName=account;AccountKey=plain_account_key_2') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage(azure_conf, sas_token = 'plain_sas_signature') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', 'plain_account_key' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'HTTPS://account.blob.core.windows.net/?sig=plain_sas_signature' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'https://user:plain_password=x@account.blob.core.windows.net/' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2' +EOF + +# The query tree hides an argument masked whole, not only the right side of a comparison. +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x'))" +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage(azure_conf, 'sp=r&sig=plain_sas_signature' = 'x'))" + +# Nothing inside an Azure `extra_credentials(...)` is dumped, keys included. +for explain in "AST" "QUERY TREE run_passes = 0"; do + $CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_client_%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN $explain SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')))" +done + +# The statement is logged with the credential hidden. +$CLICKHOUSE_CLIENT -q "EXPLAIN AST SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_logged')" > /dev/null +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS query_log" +$CLICKHOUSE_CLIENT -q "SELECT countIf(query LIKE '%plain_sas_logged%'), countIf(query LIKE '%[HIDDEN]%') FROM system.query_log WHERE current_database = currentDatabase() AND query LIKE 'EXPLAIN AST%azureBlobStorage%' AND type = 'QueryFinish' AND is_initial_query" diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.reference b/tests/queries/0_stateless/05473_orc_footer_content_length.reference new file mode 100644 index 000000000000..ae5399ce4997 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.reference @@ -0,0 +1,2 @@ +1 True True +1 True True diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.sh b/tests/queries/0_stateless/05473_orc_footer_content_length.sh new file mode 100755 index 000000000000..78921273f950 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. +# The `content_length` in the ORC footer covers only the stripes, not the metadata section with the stripe statistics. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +check() +{ + $CLICKHOUSE_LOCAL --query "$1" | python3 -c ' +import sys + +data = sys.stdin.buffer.read() + +def varint(buf, pos): + result = shift = 0 + while True: + byte = buf[pos] + pos += 1 + result |= (byte & 0x7f) << shift + shift += 7 + if byte < 0x80: + return result, pos + +def fields(buf): + pos = 0 + while pos < len(buf): + key, pos = varint(buf, pos) + if key & 7 == 0: + value, pos = varint(buf, pos) + elif key & 7 == 2: + length, pos = varint(buf, pos) + value = buf[pos:pos + length] + pos += length + else: + raise Exception("unexpected wire type") + yield key >> 3, value + +postscript_length = data[-1] +postscript = dict(fields(data[-1 - postscript_length:-1])) +footer_length = postscript[1] +footer = list(fields(data[-1 - postscript_length - footer_length:-1 - postscript_length])) +content_length = next(v for f, v in footer if f == 2) +stripes = [dict(fields(v)) for f, v in footer if f == 3] +stripes_length = sum(s.get(2, 0) + s.get(3, 0) + s.get(4, 0) for s in stripes) +print(len(stripes), content_length == stripes_length, postscript[5] > 0) +' +} + +check "SELECT number FROM numbers(3) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" +check "SELECT number, toString(number) FROM numbers(100000) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.reference b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference new file mode 100644 index 000000000000..754cd5dae768 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference @@ -0,0 +1,20 @@ +a Nullable(Int64) +b Nullable(Decimal(12, 0)) +c Nullable(Decimal(20, 2)) +d Nullable(Decimal(12, 2)) +e Nullable(Decimal(2, 2)) +17292380420 24 36164.16 0.03 0.01 +17292380421 38 63351.7 0.08 0.01 +17292380421 28 42673.96 0.09 0.06 +17292380421 40 76677.6 0.05 0.04 +17292380421 2 2096.48 0.07 0.07 +17292380421 42 45284.82 0.07 0.05 +17292380421 10 18572.9 0.01 0.08 +17292380422 12 14836.8 0.09 0.06 +17292380422 41 82152.52 0.07 0.02 +17292380422 38 47240.84 0.1 0 +38 0.08 +40 0.05 +42 0.07 +41 0.07 +38 0.1 diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.sh b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh new file mode 100755 index 000000000000..94e31bf56154 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `decimal64_v2.orc` from the examples of apache/orc has the format version 1.9999 (`UNSTABLE_PRE_2_0`), +# where the DECIMAL columns with the precision up to 18 are signed RLEv2 integers without the SECONDARY stream. +$CLICKHOUSE_LOCAL -q "DESCRIBE file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT * FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT b, d FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC) WHERE b > 30 SETTINGS input_format_orc_filter_push_down = 1" diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference new file mode 100644 index 000000000000..8588a3ce6bb6 --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference @@ -0,0 +1,4 @@ +400 79800 0 399 +58 11571 +INCORRECT_DATA +1 diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh new file mode 100755 index 000000000000..b0ebdedb176d --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: needs MinIO + +# A source of an object storage reads the Parquet footer of its next file in the background, while it reads the current one. +# One stream (`max_threads = 1`) reads all files, so every file but the first one is read through a prefetched footer. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +DIR="${CLICKHOUSE_TEST_UNIQUE_NAME}" +Q="${CLICKHOUSE_TEST_UNIQUE_NAME}_" + +for i in 0 1 2 3; do + ${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/good/${i}.parquet', format = Parquet) SELECT number + ${i} * 100 AS x FROM numbers(100)" +done +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/0.parquet', format = Parquet) SELECT number AS x FROM numbers(100)" +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/1.parquet', format = RawBLOB) SELECT 'not a parquet file'" + +# The footer is read in advance only by the native Parquet reader, which CI randomizes on this branch. +SETTINGS="--max_threads 1 --use_parquet_metadata_cache 1 --input_format_parquet_use_native_reader_v3 1" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}1" --query "SELECT count(x), sum(x), min(x), max(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet')" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}2" --query "SELECT count(x), sum(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet') WHERE x % 7 = 0" + +# The file that is not Parquet fails the query as it did before the footer was read in advance. +${CLICKHOUSE_CLIENT} $SETTINGS --query "SELECT sum(x) FROM s3(s3_conn, filename = '${DIR}/bad/*.parquet')" 2>&1 | grep -o -m1 "INCORRECT_DATA" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" + +# The second query finds all footers in the Parquet metadata cache. +# With parallel replicas, `s3` is rewritten to `s3Cluster` and the files are read by secondary queries, +# which run with `current_database = 'default'`, so the hits are summed over `initial_query_id`. +${CLICKHOUSE_CLIENT} --query " + SELECT sum(ProfileEvents['ParquetMetadataCacheHits']) >= 4 + FROM system.query_log + WHERE initial_query_id = '${Q}2' AND type = 'QueryFinish' + AND (current_database = currentDatabase() OR NOT is_initial_query) +" diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference new file mode 100644 index 000000000000..f23520f0dbfc --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference @@ -0,0 +1,2 @@ +batches: 4096 row counts: [64] +262144 1000 16777216 diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh new file mode 100755 index 000000000000..e71fb6e12721 --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# ^ pyarrow is not available in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One large block split by a small `output_format_arrow_max_record_batch_size_bytes` into thousands of +# record batches. The `LowCardinality` column never needs a split itself, but measuring it is linear in +# the rows given, so this is the shape where measuring the whole remainder of the block +# for every batch would be quadratic. Every batch is bounded by the `String` column: 64 rows of 64 bytes. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_many_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +$CLICKHOUSE_LOCAL --query " + SELECT + toLowCardinality(toString(number % 1000)) AS lc, + repeat('x', 64) AS s + FROM numbers(262144) + SETTINGS + max_block_size = 262144, + output_format_arrow_max_record_batch_size_bytes = 4096, + output_format_arrow_compression_method = 'none' + FORMAT ArrowStream" > "$FILE" + +python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + batches = list(ipc.open_stream(src)) +print("batches:", len(batches), "row counts:", sorted({batch.num_rows for batch in batches})) +PY + +$CLICKHOUSE_LOCAL --query " + SELECT count(), uniqExact(lc), sum(length(s)) + FROM file('$FILE', ArrowStream)" diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference new file mode 100644 index 000000000000..d00491fd7e5b --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference @@ -0,0 +1 @@ +1 diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh new file mode 100755 index 000000000000..eec443dcca49 --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Tags: zookeeper + +# `SYSTEM RESTORE DATABASE REPLICA` stops and replaces the DDL worker of a `Replicated` database. +# A DDL query that was concurrently waiting in the worker used to keep a raw pointer to it +# and dereference the destroyed worker (segmentation fault). Now such a query either succeeds +# or fails with an exception, and the server stays alive. + +# The racing queries fail with various errors by design; they are not interesting. +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=none + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +TIMEOUT=10 + +function ddl_thread() +{ + local i=0 + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + i=$((i + 1)) + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_${1}_${i} (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS ${DB}.t_${1}_${i} SYNC" >/dev/null 2>&1 + done +} + +function sync_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +function restore_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +ddl_thread 1 & +ddl_thread 2 & +ddl_thread 3 & +sync_thread & +restore_thread & +restore_thread & +wait + +# The server is alive and the database still accepts DDL. +for _ in $(seq 1 60); do + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_final (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 && break + sleep 1 +done +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t_final" + +$CLICKHOUSE_CLIENT --query "DROP DATABASE ${DB} SYNC" diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference new file mode 100644 index 000000000000..587aee15552b --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference @@ -0,0 +1,5 @@ +restore is waiting 1 +create succeeded +restore finished +1 +0 diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh new file mode 100755 index 000000000000..6ef139d50d2d --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# An initial DDL query of a `Replicated` database executes and commits on the submitting thread. +# `SYSTEM RESTORE DATABASE REPLICA` must wait for such a query that was already admitted by the old +# DDL worker before the new worker recovers the replica. Otherwise the query could commit its metadata +# while the recovery compares the Keeper snapshot with the local tables, and the recovery would move +# the just created table to the `_broken_replicated_tables` database. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +# Hold the initial `CREATE TABLE` after the DDL worker has admitted it, before it executes and commits. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = MergeTree ORDER BY x" & +create_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore stops the old DDL worker and then has to wait for the paused `CREATE TABLE`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $create_pid && echo "create succeeded" +# The restore proceeds only after the query has committed. The replica is not lost then (its digest is not empty), +# so the restore may refuse with `REPLICA_ALREADY_EXISTS`; either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +# The table created by the successful query is still there after the recovery of the replica. +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference new file mode 100644 index 000000000000..799f581f2dea --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference @@ -0,0 +1,6 @@ +d_complex LOADED +d_simple LOADED +1 1 +alive +4 +0 diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh new file mode 100755 index 000000000000..aa8ddefa8372 --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-llvm-coverage +# no-fasttest: waits 7 s for the update backoff; no-llvm-coverage: the file size limit below would also cut the coverage profile. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ssd_cache` dictionaries whose cache file cannot grow for the next partition stay usable after the failed update, +# and the next update fails the same way. The file size limit lets the first 64 KiB of each cache file be allocated, +# but not the next 64 KiB, while 100 values of 1.2 KB need more than that. + +dir="${CLICKHOUSE_USER_FILES_UNIQUE:?}" +rm -rf "${dir:?}" +mkdir -p "$dir" +trap 'rm -rf "${dir:?}"' EXIT + +query=" +CREATE TABLE src (k UInt64, v String) ENGINE = Memory; +INSERT INTO src SELECT number, toString(number) || ':' || repeat('x', 1200) FROM numbers(100); + +CREATE DICTIONARY d_simple (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_simple')); + +CREATE DICTIONARY d_complex (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(COMPLEX_KEY_SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_complex')); + +-- Both updates fail, because the cache files cannot grow. +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +-- Wait for the 5-6 s backoff after a failed update, so that the next lookups update the dictionaries again. +SELECT sleep(3) FORMAT Null; +SELECT sleep(3) FORMAT Null; +SELECT sleep(1) FORMAT Null; + +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +SELECT name, status FROM system.dictionaries ORDER BY name; +SELECT dictGet('d_simple', 'v', toUInt64(0)) = '0:' || repeat('x', 1200), dictGet('d_complex', 'v', tuple(toUInt64(0))) = '0:' || repeat('x', 1200); +SELECT 'alive'; +" + +( + cd "$dir" || exit 1 + ulimit -c 0 + trap '' XFSZ + ulimit -f 100 + $CLICKHOUSE_LOCAL --ignore-error --send_logs_level=error --query "$query" 2>"$dir/stderr" +) + +# Each of the four failed updates reports the failed allocation, and none of them was refused by the backoff. +grep -o -F 'Cannot preallocate space' "$dir/stderr" | wc -l +grep -o -F 'nearest update is scheduled' "$dir/stderr" | wc -l diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference new file mode 100644 index 000000000000..350939450c19 --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference @@ -0,0 +1,25 @@ +--- readonly_1 +READONLY +READONLY +READONLY +READONLY +READONLY +OK +--- readonly_2 +OK +OK +OK +OK +OK +--- readonly_0 +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +OK +--- requests to the endpoint +readonly_2_cluster 1 +readonly_2_describe 1 +readonly_2_remote 1 +readonly_2_select 1 diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh new file mode 100755 index 000000000000..621fcc5b8a8b --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Resolving the structure of a table function (`DESCRIBE TABLE url(...)`, or a table function nested in +# `cluster`) must require the same `CREATE TEMPORARY TABLE` grant as reading from it, and must be refused +# before the source is contacted. Otherwise a user who cannot run `url` (e.g. under `readonly = 1`) can make +# the server request an arbitrary endpoint and read the response from the schema inference error. + +USER_READONLY_1="readonly_1_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_2="readonly_2_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_0="readonly_0_${CLICKHOUSE_TEST_UNIQUE_NAME}" +TEMP_CREDENTIALS="unknown" + +# Create users with different readonly settings. +function create_users() { + ${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + CREATE USER ${USER_READONLY_1} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 1; + CREATE USER ${USER_READONLY_2} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 2; + -- \`readonly = 0\`, but without the \`CREATE TEMPORARY TABLE\` grant. + CREATE USER ${USER_READONLY_0} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}'; + GRANT SELECT ON *.*, READ ON URL, READ ON REMOTE TO ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${USER_READONLY_1}, ${USER_READONLY_2}; + " +} + +function drop_users() { + ${CLICKHOUSE_CLIENT} -q "DROP USER ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}" +} + +# Instead of a mock server, use this server's HTTP interface: every request to it is logged in `system.query_log` +# with the marker given as the argument, so `check_endpoint_requests` can tell whether the source was contacted. +# It always responds in `JSONEachRow`, like the JSON metadata service in the original report: the format passed +# to `url` is how the response is parsed, so `Values` fails to parse it and would echo the body in the error. +function endpoint() { + local marker="$1" + echo "${CLICKHOUSE_PORT_HTTP_PROTO}://${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?database=${CLICKHOUSE_DATABASE}&query=SELECT+1+AS+x,+%27marker_${marker}%27+AS+m+FORMAT+JSONEachRow" +} + +# Run a query as the given user and print `READONLY`, `ACCESS_DENIED`, `OK`, or the full unexpected error. +# `CLICKHOUSE_CLIENT` passes randomized settings, which a `readonly = 1` user is not allowed to change. +function run() { + local user="$1" + local query="$2" + local output + output=$(${CLICKHOUSE_CLIENT_BINARY} --host "${CLICKHOUSE_HOST}" --port "${CLICKHOUSE_PORT_TCP}" \ + --user "${user}" --password "${TEMP_CREDENTIALS}" -q "${query}" 2>&1) + if [[ "${output}" =~ \((READONLY|ACCESS_DENIED)\) ]]; then + echo "${BASH_REMATCH[1]}" + elif [[ "${output}" == *Exception* ]]; then + echo "${output}" + else + echo "OK" + fi +} + +# Run all the queries as one user. The user name without the unique suffix (e.g. `readonly_1`) +# labels the output and the endpoint markers. +function check_user() { + local user="$1" + local label="${user%_"${CLICKHOUSE_TEST_UNIQUE_NAME}"}" + echo "--- ${label}" + run "${user}" "SELECT * FROM url('$(endpoint "${label}_select")', 'JSONEachRow')" + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_describe")', 'JSONEachRow')" + # With a format that fails to parse the response, the schema inference error would contain the response body. + # It is skipped for `readonly_2`, which is allowed to read the URL: its error text depends on the server version. + if [[ "${label}" != "readonly_2" ]]; then + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_values")', 'Values')" + fi + + # `remote` is not allowed in readonly mode, so it is refused before the nested `url` is resolved. + run "${user}" "DESCRIBE TABLE remote('127.0.0.1', url('$(endpoint "${label}_remote")', 'JSONEachRow'))" + # `cluster` is allowed in readonly mode, but it resolves the structure of the nested `url` on the local shard. + run "${user}" "DESCRIBE TABLE cluster('test_shard_localhost', url('$(endpoint "${label}_cluster")', 'JSONEachRow'))" + + # Table functions allowed in readonly mode stay available without the grant. + run "${user}" "DESCRIBE TABLE numbers(1)" +} + +# Print the markers of the requests that reached the endpoint, i.e. which queries contacted the source. +# Only the queries of the `readonly = 2` user may appear: a marker without requests has no row. +function check_endpoint_requests() { + echo "--- requests to the endpoint" + ${CLICKHOUSE_CLIENT} -m -q " + SYSTEM FLUSH LOGS query_log; + SELECT extract(query, 'marker_([a-z0-9_]+)') AS marker, count() > 0 + FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE 'SELECT 1 AS x, %marker_%' + GROUP BY marker + ORDER BY marker; + " +} + +create_users +for user in "${USER_READONLY_1}" "${USER_READONLY_2}" "${USER_READONLY_0}"; do + check_user "${user}" +done +check_endpoint_requests +drop_users diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference new file mode 100644 index 000000000000..2e0aea006e63 --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference @@ -0,0 +1,6 @@ +1 +2 +3 +4 +1 [1,2,3] +1 [1,2,3] diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh new file mode 100755 index 000000000000..19aeaf05141f --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: MsgPack format is not available in the fasttest environment + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One async insert batch reuses one MsgPack input format for all its entries. Each case queues an +# invalid entry followed by a valid one: the valid entry must be parsed from a clean state. + +url="${CLICKHOUSE_URL}&async_insert=1&wait_for_async_insert=0&async_insert_use_adaptive_busy_timeout=0&async_insert_busy_timeout_min_ms=100000&async_insert_busy_timeout_max_ms=100000" + +function insert_pair() +{ + local table=$1 bad=$2 good=$3 + printf '%b' "$bad" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + printf '%b' "$good" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + ${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH ASYNC INSERT QUEUE ${table}" + ${CLICKHOUSE_CLIENT} -q "SELECT * FROM ${table} ORDER BY ALL" +} + +${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_scalar (x UInt64) ENGINE = MergeTree ORDER BY x; + CREATE TABLE t_exception (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; + CREATE TABLE t_array (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; +" + +# A uint32 with 1 of its 4 bytes; the valid entry is four rows 1, 2, 3, 4. +insert_pair t_scalar '\xce\x00' '\x01\x02\x03\x04' +# A string inside Array(UInt8) is rejected in the middle of the array. +insert_pair t_exception '\x07\x92\x01\xa1x' '\x01\x93\x01\x02\x03' +# An array of 3 elements with only 1 present. +insert_pair t_array '\x07\x93\x01' '\x01\x93\x01\x02\x03' + +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_scalar; DROP TABLE t_exception; DROP TABLE t_array" diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference new file mode 100644 index 000000000000..60ef3fadf28c --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference @@ -0,0 +1,13 @@ +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string +which the MySQL client library would read as a list of hosts +which the MySQL client library would read as a connection plugin URL +which the MySQL client library would read as the end of the host +connection failed +port 0: rejected +dictionary 127.0.0.1 port 0: rejected +dictionary localhost port 0: unix socket +dictionary localhost port 0: rejected +localhost: tcp +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh new file mode 100755 index 000000000000..bc24f80c9622 --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MySQL client library is not built in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The MySQL client library reinterprets some host strings: a connection string (which can set a socket, a plugin +# directory, TLS files), a connection plugin URL, a list of hosts, or a host cut at a NUL. They must be rejected +# before any connection attempt. + +# Prints how the host was rejected, or "connection failed" for an ordinary connection failure. +function check() +{ + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "$1" 2>&1 | tr -d '\000') + if grep -q -F "which the MySQL client library would read as" <<< "$output"; then + grep -o -m1 "which the MySQL client library would read as [a-zA-Z ]*" <<< "$output" + elif grep -q -F "ALL_CONNECTION_TRIES_FAILED" <<< "$output"; then + echo "connection failed" + else + echo "unexpected output: $output" + fi +} + +check "SELECT * FROM mysql('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('host=localhost;socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1,localhost:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('[replication://127.0.0.1]:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1\\0.example.com:1', 'db', 't', 'u', 'p')" + +# A plain host is passed through and fails to connect as usual. +check "SELECT * FROM mysql('127.0.0.1:1', 'db', 't', 'u', 'p')" + +# Port 0 would be replaced by the client library's default port. +$CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('127.0.0.1:0', 'db', 't', 'u', 'p')" 2>&1 \ + | grep -q -F "MySQL port 0" && echo "port 0: rejected" || echo "port 0: connection failed" + +# A dictionary socket is used only for `localhost`; for another host it is ignored and port 0 is rejected. +function check_dictionary() +{ + $CLICKHOUSE_CLIENT --send_logs_level=fatal -q " + CREATE DICTIONARY ${CLICKHOUSE_DATABASE}.d_mysql (x UInt64, y String) PRIMARY KEY x + SOURCE(MYSQL(HOST '$1' PORT 0 SOCKET '$2' USER 'u' PASSWORD 'p' DB 'db' TABLE 't')) + LAYOUT(FLAT()) LIFETIME(0)" + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM ${CLICKHOUSE_DATABASE}.d_mysql" 2>&1) + if grep -q -E "MySQL port 0|MySQL socket" <<< "$output"; then + echo "dictionary $1 port 0: rejected" + elif grep -q -F "through socket" <<< "$output"; then + echo "dictionary $1 port 0: unix socket" + else + echo "unexpected output: $output" + fi + $CLICKHOUSE_CLIENT -q "DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" +} +check_dictionary "127.0.0.1" "/nonexistent/mysqld.sock" +check_dictionary "localhost" "/nonexistent/mysqld.sock" +# The client library would read a socket starting with NUL as no socket and connect over TCP. +check_dictionary "localhost" "\\0" + +# `localhost` uses TCP to the given port, not the client library's default Unix socket. +output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('localhost:1', 'db', 't', 'u', 'p')" 2>&1) +if grep -q -F "Can't connect to server on 'localhost'" <<< "$output"; then + echo "localhost: tcp" +elif grep -q -F "through socket" <<< "$output"; then + echo "localhost: unix socket" +else + echo "unexpected output: $output" +fi + +# The `MySQL` database engine and table engine use the same connection pool. +check "CREATE DATABASE ${CLICKHOUSE_DATABASE}_mysql ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 'u', 'p')" +check "CREATE TABLE ${CLICKHOUSE_DATABASE}.t_mysql (x UInt32) ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p'); SELECT * FROM ${CLICKHOUSE_DATABASE}.t_mysql" + +$CLICKHOUSE_CLIENT -q "DROP DATABASE IF EXISTS ${CLICKHOUSE_DATABASE}_mysql; DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.t_mysql; DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference new file mode 100644 index 000000000000..6ccddfe23c73 --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference @@ -0,0 +1,4 @@ +after_processing_move_access_key_id key_id_05493 +after_processing_move_connection_string [HIDDEN] +after_processing_move_secret_access_key [HIDDEN] +mode unordered diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql new file mode 100644 index 000000000000..63571197469e --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` engine is not built in the fast test. + +-- `system.s3_queue_settings` hides the secrets that `SHOW CREATE TABLE` hides. + +DROP TABLE IF EXISTS t_secrets; + +CREATE TABLE t_secrets (a String) +ENGINE = S3Queue('http://whatever-we-dont-care:9001/root/t_secrets/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', + after_processing_move_access_key_id = 'key_id_05493', + after_processing_move_secret_access_key = 'SEKRIT_05493_1', + after_processing_move_connection_string = 'DefaultEndpointsProtocol=https;AccountName=a;AccountKey=SEKRIT_05493_2;'; + +SELECT name, value +FROM system.s3_queue_settings +WHERE database = currentDatabase() AND table = 't_secrets' + AND name IN ('after_processing_move_access_key_id', 'after_processing_move_secret_access_key', + 'after_processing_move_connection_string', 'mode') +ORDER BY name; + +DROP TABLE t_secrets; diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference new file mode 100644 index 000000000000..573541ac9702 --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference @@ -0,0 +1 @@ +0 diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql new file mode 100644 index 000000000000..1247bc62fb1f --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql @@ -0,0 +1,31 @@ +-- Tags: no-fasttest +-- no-fasttest: needs S3 support in the build. + +-- An SSE-C key that is not the base64 of a 256-bit key is rejected when the S3 client is created, before any request. + +-- Non-ASCII bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'éAAA'); -- { serverError BAD_ARGUMENTS } + +-- Valid base64 of 3 bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'AAAA'); -- { serverError BAD_ARGUMENTS } + +-- An invalid character in a key of the right length. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAx!jM0NTY3ODkwMTIzNDU2Nzg5MDE='); -- { serverError BAD_ARGUMENTS } + +-- A valid key followed by more characters. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=!'); -- { serverError BAD_ARGUMENTS } + +-- A valid key with surrounding whitespace. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = ' MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE= '); -- { serverError BAD_ARGUMENTS } + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name = 't_sse_c'; diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference new file mode 100644 index 000000000000..573a680fbe86 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference @@ -0,0 +1,16 @@ +nanoseconds local push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=1: (INCORRECT_DATA) +statistics local push_down=0 lazy=0: 3 +statistics local push_down=0 lazy=1: 3 +statistics local push_down=1 lazy=0: 3 +statistics local push_down=1 lazy=1: 3 +statistics remote push_down=0 lazy=0: 3 +statistics remote push_down=0 lazy=1: 3 +statistics remote push_down=1 lazy=0: 3 +statistics remote push_down=1 lazy=1: 3 diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh new file mode 100755 index 000000000000..53eae4b38eb0 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The nanoseconds of a timestamp with the 7 removed trailing zeros overflow `Int64`. +orc_check nanoseconds "$DATA/malformed_timestamp_nanoseconds.orc" 't Nullable(DateTime64(9))' "SELECT count(), max(t) FROM SOURCE" \ + 'Invalid timestamp in ORC column 1: seconds=[0-9]+, encoded nanoseconds=-?[0-9]+' + +# The minimum nanoseconds in the statistics is 0x80000000: such statistics must not be used by the filter pushdown. +orc_check statistics "$DATA/malformed_timestamp_statistics_nanoseconds.orc" 't DateTime64(9)' \ + "SELECT count() FROM SOURCE WHERE t > toDateTime64('2000-01-01 00:00:00', 9, 'UTC')" diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference new file mode 100644 index 000000000000..17ac0b58ed17 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference @@ -0,0 +1,7 @@ +1e308 ['0','1','2','0','1','2','0','1','2','0'] +-1e308 ['0','1','2','0','1','2','0','1','2','0'] +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +9223372036854775807 +-9223372036854775808 diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh new file mode 100755 index 000000000000..6da24b0909d7 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A dictionary threshold that does not fit in `size_t` when multiplied by the number of values. +for threshold in 1e308 -1e308; do + $CLICKHOUSE_LOCAL -q "SELECT toString(number % 3) AS s FROM numbers(10) FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = $threshold" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT '$threshold', groupArray(s) FROM table" +done + +# The extreme `DateTime64` values that cannot be stored in ORC with their statistics in milliseconds. +for value in 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(-9223372036854775808), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(1)'"'"')'; do + $CLICKHOUSE_LOCAL -q "SELECT $value AS t FORMAT ORC" 2>&1 >/dev/null | grep -oE '\(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE\)' | head -n1 | grep . || echo "$value: no error" +done + +# The extreme values with the nanoseconds can be stored. +for value in 9223372036854775807 -9223372036854775808; do + $CLICKHOUSE_LOCAL -q "SELECT reinterpret(toInt64($value), 'DateTime64(9, \'UTC\')') AS t FORMAT ORC" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT reinterpret(t, 'Int64') FROM table" +done diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference new file mode 100644 index 000000000000..2d165fb8a6c0 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference @@ -0,0 +1,16 @@ +empty local push_down=0 lazy=0: (INCORRECT_DATA) +empty local push_down=0 lazy=1: (INCORRECT_DATA) +empty local push_down=1 lazy=0: (INCORRECT_DATA) +empty local push_down=1 lazy=1: (INCORRECT_DATA) +empty remote push_down=0 lazy=0: (INCORRECT_DATA) +empty remote push_down=0 lazy=1: (INCORRECT_DATA) +empty remote push_down=1 lazy=0: (INCORRECT_DATA) +empty remote push_down=1 lazy=1: (INCORRECT_DATA) +nulls local push_down=0 lazy=0: 5 5 +nulls local push_down=0 lazy=1: 5 5 +nulls local push_down=1 lazy=0: 5 5 +nulls local push_down=1 lazy=1: 5 5 +nulls remote push_down=0 lazy=0: 5 5 +nulls remote push_down=0 lazy=1: 5 5 +nulls remote push_down=1 lazy=0: 5 5 +nulls remote push_down=1 lazy=1: 5 5 diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh new file mode 100755 index 000000000000..437d071ce5a5 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# A dictionary without entries referenced by the non-null values. +orc_check empty "$DATA/malformed_dictionary_empty.orc" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" \ + 'ORC dictionary index 0 at row 0 is out of range \[0, 0\)' + +# A valid empty dictionary of a column with only nulls. +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_nulls.orc" +trap 'rm -f "$FILE"' EXIT +$CLICKHOUSE_LOCAL -q "SELECT CAST(NULL, 'Nullable(String)') AS s FROM numbers(5) INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 1" +orc_check nulls "$FILE" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.reference b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference new file mode 100644 index 000000000000..1e94a8329c54 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference @@ -0,0 +1,32 @@ +compression_block local push_down=0 lazy=0: 1 10000 +compression_block local push_down=0 lazy=1: 1 10000 +compression_block local push_down=1 lazy=0: 1 10000 +compression_block local push_down=1 lazy=1: 1 10000 +compression_block remote push_down=0 lazy=0: 1 10000 +compression_block remote push_down=0 lazy=1: 1 10000 +compression_block remote push_down=1 lazy=0: 1 10000 +compression_block remote push_down=1 lazy=1: 1 10000 +dictionary_size local push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.sh b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh new file mode 100755 index 000000000000..bc5685ba3187 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The memory must be allocated by the size of the data, not by the sizes declared in the file. +LIMIT='max_memory_usage = 100000000' + +# The declared compression block size is 1 GiB, the chunks are small. The schema inference reads the compressed footer. +orc_check compression_block "$DATA/malformed_compression_block_1g.orc" '' "SELECT count(), sum(length(s)) FROM SOURCE" '' "$LIMIT" + +# The declared dictionary size is 2^32 - 1, the stream has a few entries. +orc_check dictionary_size "$DATA/malformed_dictionary_size_max.orc" 's Nullable(String)' "SELECT count(), sum(length(s)) FROM SOURCE" \ + 'Unexpected end of ORC stream column 1 kind 2' "$LIMIT" + +# The sizes stored in the snappy and zstd chunks are 1 GiB, the chunks have a few bytes. +orc_check snappy_chunk_size "$DATA/malformed_snappy_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'snappy-compressed chunk of ORC file decompresses to 1073741824 bytes' "$LIMIT" +orc_check zstd_chunk_size "$DATA/malformed_zstd_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'Malformed zstd-compressed data in ORC file' "$LIMIT" diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference new file mode 100644 index 000000000000..3c50f86ded0e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference @@ -0,0 +1,16 @@ +stripe local push_down=0 lazy=0: (INCORRECT_DATA) +stripe local push_down=0 lazy=1: (INCORRECT_DATA) +stripe local push_down=1 lazy=0: (INCORRECT_DATA) +stripe local push_down=1 lazy=1: (INCORRECT_DATA) +stripe remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe remote push_down=1 lazy=1: (INCORRECT_DATA) +stream local push_down=0 lazy=0: (INCORRECT_DATA) +stream local push_down=0 lazy=1: (INCORRECT_DATA) +stream local push_down=1 lazy=0: (INCORRECT_DATA) +stream local push_down=1 lazy=1: (INCORRECT_DATA) +stream remote push_down=0 lazy=0: (INCORRECT_DATA) +stream remote push_down=0 lazy=1: (INCORRECT_DATA) +stream remote push_down=1 lazy=0: (INCORRECT_DATA) +stream remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh new file mode 100755 index 000000000000..2d3b50f7f31e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The sum of the offset and the lengths of the stripe overflows `UInt64`. +orc_check stripe "$DATA/malformed_stripe_offset_overflow.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stripe information at stripe index 0' + +# The length of a stream of a column that is not read is 2^64 - 1, the offsets of the next streams wrap around. +orc_check stream "$DATA/malformed_stream_offset_overflow.orc" 'b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stream.*11.*18446744073709551615' diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference new file mode 100644 index 000000000000..1fafd3d526a4 --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference @@ -0,0 +1,32 @@ +row_groups local push_down=1 lazy=0: (INCORRECT_DATA) +row_groups local push_down=1 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=1: (INCORRECT_DATA) +row_groups local push_down=0 lazy=0: (INCORRECT_DATA) +row_groups local push_down=0 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=0 lazy=0: (INCORRECT_DATA) +patched_base local push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=1 lazy=0: (INCORRECT_DATA) +patched_base local push_down=1 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek local push_down=0 lazy=0: 1 +row_index_seek local push_down=0 lazy=1: 1 +row_index_seek local push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek local push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek remote push_down=0 lazy=0: 1 +row_index_seek remote push_down=0 lazy=1: 1 +row_index_seek remote push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_control local push_down=0 lazy=0: 1 +row_index_control local push_down=0 lazy=1: 1 +row_index_control local push_down=1 lazy=0: 1 +row_index_control local push_down=1 lazy=1: 1 +row_index_control remote push_down=0 lazy=0: 1 +row_index_control remote push_down=0 lazy=1: 1 +row_index_control remote push_down=1 lazy=0: 1 +row_index_control remote push_down=1 lazy=1: 1 diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh new file mode 100755 index 000000000000..163a644dea9f --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The stripe has 2^64 - 1 rows: rounding up the number of row groups overflows. +ORC_PUSH_DOWN_VALUES=1 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'The row index of ORC column 1 has 2 entries, less than the [0-9]+ row groups of stripe 0' +ORC_PUSH_DOWN_VALUES=0 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Unexpected end of ORC stream column 1 kind 1' + +# A PATCHED_BASE run whose last patch is a continuation (gap 255, patch 0). +orc_check patched_base "$DATA/malformed_patched_base_terminal_continuation.orc" 'x Int64' "SELECT count(), sum(x) FROM SOURCE" \ + 'Corrupt PATCHED_BASE encoded data in ORC stream column 1 kind 1 in stripe 0 \(unterminated gap\)' + +# A row index position beyond the end of the stream, and the same file with the valid position. +orc_check row_index_seek "$DATA/malformed_row_index_seek_past_stream.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Seek position 127 is beyond the end of ORC stream column 1 kind 1 in stripe 0 of size 3' +orc_check row_index_control "$DATA/row_index_seek_control.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference new file mode 100644 index 000000000000..bac3e0b9f016 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference @@ -0,0 +1,16 @@ +footer_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh new file mode 100755 index 000000000000..9c0fb713fb91 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The number of the repeated objects in the metadata is limited by the numbers of the columns and the stripes. +orc_check footer_statistics "$DATA/malformed_footer_too_many_statistics.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many column statistics in ORC footer: 13, the file has 3 columns' +orc_check stripe_statistics "$DATA/malformed_metadata_too_many_stripes.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many stripe statistics in ORC metadata, at most 1 expected' diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference new file mode 100644 index 000000000000..7f41d79fbe44 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference @@ -0,0 +1,21 @@ +t < fromUnixTimestamp64Nano(-500000001, 'UTC') +500 +500 0 499 +500 0 499 +t <= fromUnixTimestamp64Nano(-500000001, 'UTC') +600 +501 0 500 +501 0 500 +t = fromUnixTimestamp64Nano(-950000001, 'UTC') +100 +1 50 50 +1 50 50 +t = fromUnixTimestamp64Nano(-999500000, 'UTC') +1 +1 1 1 +1 1 1 +-2000000000 1 +-1 1 +-999500000 1 +-1500000 1 +1000000000 1 diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh new file mode 100755 index 000000000000..21a4b8bb4428 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Prints the number of rows that are not pruned, and the result with and without the filter pushdown. +function check() +{ + local condition=$1 + echo "$condition" + $CLICKHOUSE_LOCAL -q " + SELECT count() FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE indexHint($condition); + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition; + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition + SETTINGS input_format_orc_filter_push_down = 0" +} + +# The timestamps before the epoch with a negative sub-millisecond part, from -1.000000001 to -0.001000001 seconds, +# in row groups of 100 rows. Their statistics must allow the pruning. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano(toInt64(number) * 1000000 - 1000000001, 'UTC') AS t FROM numbers(1000) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 100" +check "t < fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t <= fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t = fromUnixTimestamp64Nano(-950000001, 'UTC')" + +# A timestamp in the millisecond after -1 second, in its own row group: the pruning must keep it. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano([-2000000000, -999500000, -500000000][number + 1], 'UTC') AS t FROM numbers(3) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 1" +check "t = fromUnixTimestamp64Nano(-999500000, 'UTC')" + +# A file from PyArrow (the C++ writer of ORC) with a bloom filter, which rounds the negative milliseconds toward zero, +# and one row in each row group: the bloom filter must keep the matching rows. +for value in -2000000000 -1 -999500000 -1500000 1000000000; do + $CLICKHOUSE_LOCAL -q " + SELECT $value, count() FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc', 'ORC', 't Nullable(DateTime64(9))') + WHERE t = fromUnixTimestamp64Nano($value)" +done diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.reference b/tests/queries/0_stateless/05515_orc_nullable_floats.reference new file mode 100644 index 000000000000..4aae050a32fc --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.reference @@ -0,0 +1,2 @@ +1 +1086 1410 5000 10000 0 diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.sh b/tests/queries/0_stateless/05515_orc_nullable_floats.sh new file mode 100755 index 000000000000..c7eba0810a43 --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Nullable floats with different patterns of nulls, and special values, at the top level and nested. +QUERY=" + SELECT + number, + multiIf(k = 0, NULL, k = 1, nan, k = 2, inf, k = 3, -inf, k = 4, -0., k = 5, toFloat32(1e-42), toFloat32(number) / 7)::Nullable(Float32) AS f32, + multiIf(k2 = 0, NULL, k2 = 1, nan, k2 = 2, -inf, k2 = 3, 5e-324, k2 = 4, -0., number / 3.)::Nullable(Float64) AS f64, + if(intDiv(number, 1000) % 2 = 0, NULL, number / 2.)::Nullable(Float64) AS runs, + NULL::Nullable(Float32) AS all_null, + (number * 1.5)::Nullable(Float64) AS no_null, + arrayMap(x -> if(x % 3 = 0, NULL, toFloat32(x) / 4), range(number % 5))::Array(Nullable(Float32)) AS arr + FROM (SELECT number, cityHash64(number) % 9 AS k, cityHash64(number, 1) % 7 AS k2 FROM numbers(10000))" +STRUCTURE='number UInt64, f32 Nullable(Float32), f64 Nullable(Float64), runs Nullable(Float64), all_null Nullable(Float32), no_null Nullable(Float64), arr Array(Nullable(Float32))' +DIGEST="sum(cityHash64(number, isNull(f32), reinterpretAsUInt32(ifNull(f32, 0)), isNull(f64), reinterpretAsUInt64(ifNull(f64, 0)), + isNull(runs), ifNull(runs, 0), isNull(all_null), no_null, arrayMap(x -> (isNull(x), reinterpretAsUInt32(ifNull(x, 0))), arr)))" + +$CLICKHOUSE_LOCAL -q "$QUERY INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q " + SELECT (SELECT $DIGEST FROM ($QUERY)) = (SELECT $DIGEST FROM file('$FILE', 'ORC', '$STRUCTURE')); + SELECT countIf(f32 IS NULL), countIf(f64 IS NULL), countIf(runs IS NULL), countIf(all_null IS NULL), countIf(no_null IS NULL) FROM file('$FILE', 'ORC', '$STRUCTURE')" diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference new file mode 100644 index 000000000000..36b34a909261 --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference @@ -0,0 +1,6 @@ +restore is waiting 1 +alter succeeded +restore finished +x +y +0 diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh new file mode 100755 index 000000000000..4083ae7715ff --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# `SYSTEM RESTORE DATABASE REPLICA` waits for the initial DDL queries that the DDL worker has already admitted. +# An `ALTER` of a `ReplicatedMergeTree` table with `alter_sync = 1` waits until the table executes its +# `ALTER_METADATA` entry, which requires an active DDL worker of the database (`canExecuteReplicatedMetadataAlter`). +# The restore must not stop the worker before such a query finishes, otherwise both queries wait for each other. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = ReplicatedMergeTree ORDER BY x" + +# Hold the initial `ALTER` after the DDL worker has admitted it, before it executes. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --alter_sync 1 --distributed_ddl_output_mode=none --query "ALTER TABLE ${DB}.t ADD COLUMN y UInt64" & +alter_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore has to wait for the paused `ALTER`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +# The `ALTER` finishes, including the wait for its `ALTER_METADATA` entry, and then the restore proceeds. +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $alter_pid && echo "alter succeeded" +# The replica is not lost (its digest is not empty), so the restore may refuse with `REPLICA_ALREADY_EXISTS`; +# either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "SELECT name FROM system.columns WHERE database = '${DB}' AND table = 't' ORDER BY name" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference new file mode 100644 index 000000000000..4e3dc3cd1a09 --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference @@ -0,0 +1 @@ +4800 552844800 24 diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh new file mode 100755 index 000000000000..b33d61ad599f --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires the Parquet format (USE_PARQUET build option) + +# Every Parquet writer had its own pool of `max_threads` encoder threads, so many open writers with `max_threads = 32` +# did not fit in a 500-thread global pool: the 24 partitions of one stream. +# https://github.com/ClickHouse/ClickHouse/issues/129864 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 48); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 48); do printf ', number * %d' "$i"; done) +SETTINGS="SET max_threads = 32, + output_format_parquet_parallel_encoding = 1, output_format_parquet_row_group_size = 200, + max_block_size = 1000, min_insert_block_size_rows = 1000, min_insert_block_size_bytes = 0" + +# Small row groups make every writer encode while the INSERT runs, not only when its file is finalized. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}, max_insert_threads = 1; + INSERT INTO FUNCTION file('${TABLE_DIR}/file/{_partition_id}.parquet', 'Parquet', 'p UInt8 ${COLS}') PARTITION BY p + SELECT number % 24 ${EXPRS} FROM numbers(4800); + SELECT count(), sum(c48), uniqExact(_path) FROM file('${TABLE_DIR}/file/*.parquet'); +" -- --max_thread_pool_size=500 --thread_pool_queue_size=500 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference new file mode 100644 index 000000000000..ec1c393fef3a --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference @@ -0,0 +1,3 @@ +1 +1 +still alive diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql new file mode 100644 index 000000000000..36af86696314 --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql @@ -0,0 +1,28 @@ +-- A deserialized `groupArraySample` state may carry an arbitrary `total_values` counter. +-- Merging must not wrap it around to zero, which led to a division by zero. + +-- Valid states merge fine. +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')])); +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')])); + +-- total_values = UINT64_MAX, merged with a state with one value. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('010141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +-- Both states have more values than the sample size, and their counters sum to 2^64. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +SELECT 'still alive'; diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.reference b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference new file mode 100644 index 000000000000..d509bf4d85ea --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference @@ -0,0 +1,21 @@ +Mechanisms that take the credentials from the server, and a client certificate file +refused +refused +refused +refused +refused +refused +refused +refused +Credentials in the connection string +connects +connects +connects +A MongoDB table is checked when it is read +refused +refused +So is a table created with CREATE TABLE ... AS mongodb(...) +x UInt8 +refused +And the table function with a named collection +refused diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.sh b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh new file mode 100755 index 000000000000..e563e94de006 --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB table function and table engine need USE_MONGODB + +# A query that reads with the `mongodb` table function or from a `MongoDB` table is refused with `ACCESS_DENIED` if the +# connection string makes the server authenticate with credentials of the server process. Nothing listens on +# 127.0.0.1:1, so a query that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +NC="nc_05567_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +check() +{ + $CLICKHOUSE_CLIENT -q "$1" 2>&1 | classify +} + +read_uri() +{ + check "SELECT count() FROM mongodb('mongodb://${HOST}/db?${TIMEOUTS}&$1', 'c', 'x UInt8')" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP TABLE IF EXISTS t_engine; + DROP TABLE IF EXISTS t_as_function; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Mechanisms that take the credentials from the server, and a client certificate file' +read_uri 'authMechanism=MONGODB-OIDC' +read_uri 'authmechanism=mongodb-oidc&authMechanismProperties=ENVIRONMENT:test' +read_uri 'authMechanism=MONGODB-AWS' +read_uri 'authMechanism=MONGODB-X509' +check "SELECT count() FROM mongodb('mongodb://user@${HOST}/db?${TIMEOUTS}&authMechanism=GSSAPI', 'c', 'x UInt8')" +read_uri 'tls=true&tlsCertificateKeyFile=/nonexistent.pem' +read_uri 'ssl=true&sslClientCertificateKeyFile=/nonexistent.pem' +check "SELECT count() FROM mongodb('${HOST}', 'db', 'c', '', '', 'x UInt8', '${TIMEOUTS}&authMechanism=MONGODB-OIDC')" + +echo 'Credentials in the connection string' +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=plain', 'c', 'x UInt8')" + + +echo 'A MongoDB table is checked when it is read' +$CLICKHOUSE_CLIENT -q "CREATE TABLE t_engine (x UInt8) ENGINE = MongoDB('${OIDC_URI}', 'c')" +check "SELECT count() FROM t_engine" +$CLICKHOUSE_CLIENT -m -q "DETACH TABLE t_engine; ATTACH TABLE t_engine;" +check "SELECT count() FROM t_engine" + +echo 'So is a table created with CREATE TABLE ... AS mongodb(...)' +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE t_as_function AS mongodb('${OIDC_URI}', 'c', 'x UInt8'); + DETACH TABLE t_as_function; + ATTACH TABLE t_as_function; + DESCRIBE t_as_function SETTINGS describe_compact_output = 1; +" +check "SELECT count() FROM t_as_function" + +echo 'And the table function with a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS uri = '${OIDC_URI}', collection = 'c', structure = 'x UInt8'" +check "SELECT count() FROM mongodb(${NC})" diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference new file mode 100644 index 000000000000..f0b81f6f43ed --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference @@ -0,0 +1,12 @@ +Refused +refused +refused +Credentials in the connection string +connects +The options that a dictionary adds to a named collection +refused +A named collection that changes after the dictionary is created +connects +refused +clickhouse-local is not restricted +connects diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh new file mode 100755 index 000000000000..354ecf0acbb7 --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB dictionary source needs USE_MONGODB + +# A MongoDB dictionary created with a DDL query may never make the server authenticate with credentials of the server +# process: the source is built when the server loads the dictionary, also after the named collection it refers to +# has changed. The dictionaries are loaded by `dictGet`. +# Nothing listens on 127.0.0.1:1, so a dictionary that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +SCRAM_URI="mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256" +NC="nc_05568_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +# Runs the queries $1. +check() +{ + $CLICKHOUSE_CLIENT -m -q "$1" 2>&1 | classify +} + +# Creates the dictionary $1 with the source $2 and prints whether reading it is refused. +check_source() +{ + $CLICKHOUSE_CLIENT -q "CREATE DICTIONARY $1 (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB($2 COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" + check "SELECT dictGet('$1', 'v', tuple('k'))" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP DICTIONARY IF EXISTS d_uri; + DROP DICTIONARY IF EXISTS d_options; + DROP DICTIONARY IF EXISTS d_scram; + DROP DICTIONARY IF EXISTS d_named_options; + DROP DICTIONARY IF EXISTS d_named_altered; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Refused' +check_source d_uri "URI '${OIDC_URI}'" +check_source d_options "HOST '127.0.0.1' PORT 1 DB 'db' USER '' PASSWORD '' OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" + +echo 'Credentials in the connection string' +check_source d_scram "URI '${SCRAM_URI}'" + +echo 'The options that a dictionary adds to a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS host = '127.0.0.1', port = '1', db = 'db', user = '', password = ''" +check_source d_named_options "NAME ${NC} OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +$CLICKHOUSE_CLIENT -q "DROP DICTIONARY d_named_options" + +echo 'A named collection that changes after the dictionary is created' +$CLICKHOUSE_CLIENT -q "CREATE DICTIONARY d_named_altered (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB(NAME ${NC} COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" +check "SELECT dictGet('d_named_altered', 'v', tuple('k'))" +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${NC} SET options = '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +check "SYSTEM RELOAD DICTIONARY d_named_altered; SELECT dictGet('d_named_altered', 'v', tuple('k'))" + +echo 'clickhouse-local is not restricted' +$CLICKHOUSE_LOCAL -m -q " + CREATE DICTIONARY d (_id String, v String) PRIMARY KEY _id + SOURCE(MONGODB(URI '${OIDC_URI}' COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT()); + SELECT dictGet('d', 'v', tuple('k')); +" 2>&1 | classify diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference new file mode 100644 index 000000000000..338bce460b79 --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference @@ -0,0 +1,18 @@ +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `l` from type Array(String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `s` from type Tuple(value String) to type Map(String, String) +Code: 53 while converting column `s` from type Tuple(value String) to type Array(String) +Code: 53 while converting column `lm` from type Array(Map(String, String)) to type Array(Tuple(value String)) +Code: 53 while converting column `sl` from type Tuple(a Array(String)) to type Tuple(a Map(String, String)) +2 {\'key\':\'profile\'} +2 [('key','profile')] +2 {'k':'(\'v\')'} +['(\'v\')'] +2 {'key':'profile'} ['profile'] ('profile') {'k':('v')} [{'k':'v'}] (['x']) +('profile',0) +2 +Code: 53 while converting column `m` from type Map(LowCardinality(String), LowCardinality(Nullable(String))) to type Tuple(value Nullable(String)) +Code: 53 while converting column `lm` from type Array(Map(LowCardinality(String), LowCardinality(Nullable(String)))) to type Array(Tuple(value String)) +{\'key\':\'profile\'} +{'key':'profile'} [{'k':'v'}] diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh new file mode 100755 index 000000000000..f503b6d888fa --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +# An ORC list, map or struct requested as a type of another kind is cast to it, not read as default values. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Prints the error code and the conversion of a query that has to fail. +function error() +{ + $CLICKHOUSE_LOCAL -q "$1" 2>&1 | tr '\n' ' ' | grep -o -E 'Code: [0-9]+|while converting column [^:]* to type [^:]*' | head -n 2 | paste -sd ' ' +} + +FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +$CLICKHOUSE_LOCAL -q "SELECT 2::Int64 AS id, map('key', 'profile') AS m, ['profile'] AS l, + CAST(tuple('profile'), 'Tuple(value String)') AS s, map('k', CAST(tuple('v'), 'Tuple(value String)')) AS ms, + [map('k', 'v')] AS lm, CAST(tuple(['x']), 'Tuple(a Array(String))') AS sl FORMAT ORC" > "$FILE" +F="file('$FILE', ORC" + +# Conversions the cast cannot do. +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))') SETTINGS input_format_orc_allow_missing_columns = 0" +error "SELECT * FROM $F, 'id Int64, l Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, s Map(String, String)')" +error "SELECT * FROM $F, 'id Int64, s Array(String)')" +error "SELECT * FROM $F, 'id Int64, lm Array(Tuple(value String))')" +error "SELECT * FROM $F, 'id Int64, sl Tuple(a Map(String, String))')" + +# Conversions the cast does, also of a map value. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m String')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Array(Tuple(String, String))')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, ms Map(String, String)')" +$CLICKHOUSE_LOCAL -q "SELECT ms.values FROM $F, 'id Int64, ms Map(String, String)')" + +# Matching kinds, a Tuple naming only some of the fields, and the other columns of a mismatched structure. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Map(String, String), l Array(String), s Tuple(value String), + ms Map(String, Tuple(value String)), lm Array(Map(String, String)), sl Tuple(a Array(String))')" +$CLICKHOUSE_LOCAL -q "SELECT s FROM $F, 's Tuple(value String, other Int32)')" +$CLICKHOUSE_LOCAL -q "SELECT id FROM $F, 'id Int64, m Tuple(value Nullable(String))')" + +DICT_FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}_dict.orc" +$CLICKHOUSE_LOCAL --output_format_orc_dictionary_key_size_threshold=1 -q "SELECT map('key', 'profile') AS m, [map('k', 'v')] AS lm FORMAT ORC" > "$DICT_FILE" +D="file('$DICT_FILE', ORC" +S="SETTINGS input_format_orc_dictionary_as_low_cardinality = 1" + +# A dictionary-encoded map key. +error "SELECT * FROM $D, 'm Tuple(value Nullable(String))') $S" +error "SELECT * FROM $D, 'lm Array(Tuple(value String))') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm String') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm Map(String, String), lm Array(Map(String, String))') $S" + +rm -f "$FILE" +rm -f "$DICT_FILE" diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference new file mode 100644 index 000000000000..d0fcfd538e17 --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference @@ -0,0 +1,6 @@ +MEMORY_LIMIT_EXCEEDED +PrettyCompactMonoBlock 241 +MEMORY_LIMIT_EXCEEDED +PrettyCompact 241 +MEMORY_LIMIT_EXCEEDED +JSONColumns 241 diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh new file mode 100755 index 000000000000..551f08b3f82c --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Every stored block is larger than the memory limit, so the format that accumulates the result fails to copy it +# when the next block arrives: the query must fail with an error, not crash. +for format in PrettyCompactMonoBlock PrettyCompact JSONColumns; do + $CLICKHOUSE_LOCAL --query " + CREATE TABLE t (x UInt64) ENGINE = Memory; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + SELECT * FROM t FORMAT $format SETTINGS max_threads = 1, max_memory_usage = '20Mi', + output_format_pretty_squash_consecutive_ms = 1000000, output_format_pretty_squash_max_wait_ms = 1000000; + " 2>&1 >/dev/null | grep -o -m1 'MEMORY_LIMIT_EXCEEDED' | head -n1 + echo "$format ${PIPESTATUS[0]}" +done diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference new file mode 100644 index 000000000000..8e054e883dc4 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference @@ -0,0 +1,9 @@ +1900-05-31 16:00:00 +1900-07-06 03:13:13 +1949-12-31 16:00:00 +1900-06-01 08:00:00 +1900-06-01 00:36:45 +1960-01-15 00:00:00 +0 1900-06-01 08:00:00.000000000 +1 1900-06-01 08:00:00.000000000 +1900-06-01 08:00:00.000000000 diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh new file mode 100755 index 000000000000..61cb9f7a7221 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no ORC format + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Before the first transition of a time zone, the wall clock is kept with the oldest standard offset +# (Asia/Shanghai +08:00 until 1901), not with the local mean time, as in other ORC readers. +# `DateTime64` starts at 1900 on this branch. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q " + SELECT arrayJoin([toDateTime64('1900-06-01 00:00:00', 0, 'UTC'), toDateTime64('1900-07-06 11:13:13', 0, 'UTC'), toDateTime64('1950-01-01 00:00:00', 0, 'UTC')]) AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Asia/Shanghai'" + +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# Europe/Lisbon starts with a no-op transition record in 1884 that keeps the local mean time (-00:36:45). +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Europe/Lisbon'" + +# Europe/London had +01:00 in 1970 and +00:00 in 1960, a lower offset before the epoch must not shift the day. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1960-01-15 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Europe/London'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# The timestamp statistics must agree with the values that are read, or the filter pushdown drops the row. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 9, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +for push_down in 0 1; do + $CLICKHOUSE_LOCAL -q " + SELECT $push_down, ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') + WHERE ts = toDateTime64('1900-06-01 08:00:00', 9, 'UTC') SETTINGS input_format_orc_filter_push_down = $push_down" +done + +# A time zone that `DateLUT` loads without an embedded file. +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'libc:UTC'" + +rm -f "$FILE" diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc new file mode 100644 index 0000000000000000000000000000000000000000..6c52f4f0f98b40dec581f1b02ec3936d34d62796 GIT binary patch literal 709 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo mQfoMv*fgJAnSmomfKj5Mfklalfk(r{fUW5ZGqZn?vp4|E0T8hO literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc new file mode 100644 index 0000000000000000000000000000000000000000..fc3ffef8f18c17dc95f532108f94846c6cb9b894 GIT binary patch literal 717 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo vQfoMv*fgI#S!njcc{ArNRAk^N5nz;PXkbxdV&Ks*F<@)@!p!U+JFZE-iyIBTGB(h%cBfX4BGjAJ&?Gn8U6&@(d& zz$y=vGO&;Wsxk>+P+(wKo$%nn**QlR@+j>TaZurBkYr%+<23NG2w({jkqGi}XJ9z6 zYbW!qRlXhHI#@oOiG6Td^2pN_EKS$M7W4_Nc>Rj~#nl5W{0t0koK8+IN-kjSYyv`D ze0)qod?H{j6B7>yAC~|R3qu>wgGrAQgcBw_c*b{mZuY+kFmEzQ>GXvtHD{W zWs;4rS`L~_X0e}<#`Zdy^-@fN9e2o_(5Co~&Su7rnHMtH82$lGnRVvG(L)DC4;)ZE zeNa{9)WwY{H(#^4HOd*NetdLvKd-FANsdH4L0}-t>A5j0stGG=rYRQ(FVL``E)@{c z*M0ZIflEH;k2rN4K6K*36_4{*Ji0C)IdSR0m4Neim{y!?@a9?3$G>FuO^5RVT}K_x zpW#^}ug521v|$3%saXw27$-3@JWde%aZ=^z*@HR-4S|as4*E8Gdp0$@cTAnwIkPpi z%P_FZ(6h@hvdhr5%P_RFv)Q$?x7ok>cmtzPw}gS?Pk~t{8%{Qy?rLq;ZaC;Qt=ZdS z%Hrgco38WrFxe(}Jv!Q5FKyK@N$^mZl1z-7O-v7)laHEP&>6R9%Nzphv`rVRkP+WK zv2p3ld7Z5S?X43RuADe;;?|1sEk78U&P>8TXu+-id_MC9Fa-<` z?lW*QFhnuTafo1Gc%1Y&K{#Q;gJ(<^dxYv@a%6g#dW4FAv=5MebWNDr~+4;VnvT^!awPNw&jholK~7@| z!qQ)f-`+hkxUucGmEX^Ib+-3k9pAk34oO3dhvpw=li&Ht=fd(`*2q-Zz@MuUHur+;QX7&$q76$-W;u-w_ literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc b/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc new file mode 100644 index 0000000000000000000000000000000000000000..27d3a7a5694c836382a434b145463145bc7e4969 GIT binary patch literal 174 zcmeYdaz2pEz)<19(7?sU!6?8e!2+b2fixqKW&+a8LQEVCLL5M`|3JVm#q91I!X?hd z!jTfdz{SszqQuF?SRuq%A#s8+fB~q=Sc(fsGDvVJXltY>ad7YmF)~Uq7ArAvup6XU xfwftoYja@mU`*n2&dE&9_Q)?SPUUb18qm-npv1($qakU)*7Sv$*+0lx8~}Ex9uxoo literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc b/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc new file mode 100644 index 0000000000000000000000000000000000000000..00ab37f164451f7d41fdd9918d3a60e6eb3fb9e1 GIT binary patch literal 353 zcmb7!55@c<-_od@Ma)J`I4HxfN+mPlz%p40|nh@xK=W-?pJwH%K)jX%p}<3F&Fh@rNx z?t8Y(IS+(X;JUy~Nt{KsDqAPB`oye0GaG+COmQR4^X~C!`ttU={aZS&{tbFtXANNv_gqUE3}AonBeEZn8f9rlbM|DkzZPz$`J=lJ`D{5 WN=ytq8jF|>*qXjDGy4ZQO8@|~r#gH9 literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc b/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc new file mode 100644 index 0000000000000000000000000000000000000000..43552b05c31d975806e7b28bf0348ac911b93320 GIT binary patch literal 83 zcmeYda_(bbf5@QqpMi^wgHeD{fZBafx-+D4Gk42F|jIl^(saf&@Ul}_i@Q96kobdi?g;4J`i%|p7O zHQHy4J^a)g0`Qj6YX%1aWcQxocSeo^^{~g%Xx3tINijrGbQqKXl}3-r5QS%EZ#Tnm$hsO_t_nvG%Tof%Rfa2K6BY3f#1KM=U?J&`Kze_YKPs*0 zx=Eu0j}P9!do!~|CB`MJ=O9i9z@@C6VX*Am!Mha&!ECV3S+H<8^mY#W1gIGH9|rxw zXpDOxF>EY&jzr&%B;N@{i#~~@xF<_qJ7Nf;voiJcyp((SJL0nbs+X1h!K@W3q*{Nxeoi)D+c$m>ztpwO3DRD- MFyFsQ%@$SX1Y@lyc>n+a literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc b/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc new file mode 100644 index 0000000000000000000000000000000000000000..ab57ba54f6cb5f35ce2f2225cedead3e3c24d9e6 GIT binary patch literal 238 zcmeYdaz4P>@V{v>Ba?moe+amFYzD)Ut4a(EH!q|}F!G&RDZuEwo9hH)g+~tq6u9SsRejxb{KXpyLT!00RfJK%^8GkYtdsQIOT(QsUs?5n^PNVk}W&;@~vk yvI3i7h1U!R1`oz0F6W%gPb;1ObElwvGVV&dR5V73CA xVnx6dhY5Zjj7eP1Iho1X9{HuksT|=zmo_vAC^0ecXlNL)HGN@b_78Fv2LL-3L?-|M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc b/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc new file mode 100644 index 0000000000000000000000000000000000000000..4f30ed6c7f1acfc4f1587ecd851ca828b38d2f80 GIT binary patch literal 38 scmeYda+Y9V(AcW~cL4(fg99T20|&nVt3(43uxKzeePL$y4{{a;0H`qt$^ZZW literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc b/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..ed3597a70455f3319174fea0ea64f41d446cd797 GIT binary patch literal 666 zcmaix&q~8U5XNU_lXYBHS=Webywo6)Qz;&EDiqX}}d=Fp4 ztKzsxN?H%yzWek=6A!rcN(PZ|1U)2|F+f zWWX+C!3O6Z=i#sQ%pmv^#{76&%5v;*uMLjcUdixCsKY(M%hOn5oHKSQO2pknd z7L|gHsv1oio`%E7btpyAVMwAg?1CC}C6^^LhR zwLh!Q)l7zn1(v%$tsAu28&>Xva+&X5G332>ELE}3))P`rPmei1_n?FU6wIoLEbn+y zx|=2Gzb@vjC2M*Is*1l}t*q0qxQr`v&RGZfszKyT&K0WWt$Db%~yI3Rzfh`{f M`sGWh$!rvU0o^4u?*IS* literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_union_type.orc b/tests/queries/0_stateless/data_orc/orc_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..08c73c83fd428e64b0f74df501b573b0d8eb7b8d GIT binary patch literal 398 zcmeYdau#G@;9?VE;b012kOnfjxtJLk7$AIYAYT~5=iy)!V&e!A2$2X0U@%}{cr5fh zDV2dy(T>kel~3;&m*O!l&Sea23@BQdfLfRYSR~j27}yyY{xL8DNk4`VAnCx+0JNq8 z$Z}&;X<=ZnJ$aD#fB^@y0~3eqm*!uaW)*I7+WlY4H&#<#{+Oh#SHY8X=RnpKi2>>P z+5D?QuKz1<{`|h<^6n{bLhf1XSHJtolmc|qrUyw66Sxu@CfUgJIOWJFGARlvIv655 zae|Z_pV|VQ$qd~r(G1KCFMyg7#4OHf96fqaXM&pI;s>h^E>SshQ2EG_6G}%Tw2sbL zd0@f8gaZqX96qRh@VGj1mnEEJ{oaJQ}73 NY)xO7nf-&D#Q~MRda3{b literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/row_index_seek_control.orc b/tests/queries/0_stateless/data_orc/row_index_seek_control.orc new file mode 100644 index 0000000000000000000000000000000000000000..ede347aa81181c970ec5d83161d8595eef07a424 GIT binary patch literal 213 zcmY+7F$=;#426?iIYPMMI7E+5r66?dD4oO#c9E9SA0Uc@C^(4VSp3cY0MA1Nhvb8o z_g>n*7VQ$o4t{h(0M0Nv&0xVpxP3JIYGlb%2P@1(vknFuiM|L#i(WZm2t%pbYzLW0 z!oe?wDK^G5E4xc2?1fj^yr7)fIK&hmIdM`_6*JXeW{C~%rM{dF=jM999eEv|kE6{A OOffC>^QBbV*RwZ`5EX0y literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc new file mode 100644 index 0000000000000000000000000000000000000000..d6e0144685e7e91cbc4e2f76aba78db27c503b4f GIT binary patch literal 294 zcmeYda^_+aV&Py3VBnJHVqpLRA#n~CFF}d-S0A;$tXG(DYv0WG<_0&-0vIZo8Q1fF zHU<%<3}+*pj2X=Co-wUs{tp7J@2o(YK>&?!#l^uMlK_Jhv%7By$R%JG;c^KFv%n-qDJ~$TDPf^tsKKJd$H61S$SB2FqQIcR zV8Ecn!NCb(8L(J^&9cH}mcs-;55^=`BRwGGhyc2?p@Bt-iGfE$(SWV#3p2BSkh3@d Dw(m#M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc new file mode 100644 index 0000000000000000000000000000000000000000..2afd747824ec0515a92db943df384c0a15d9573e GIT binary patch literal 517 zcmah_F-XHu5WUM!;u%X*Gw3%hG-L`zN_4CaLP4z{m7=SIgM;WMjv~5taS^)MxuUCE zXQx6PTq+J-6>$+1LF@hef*^>uyn8P%clTelR(5R9BwT}kal$cy%S#ikkZk6IWVM&3+yxPgX3uK-?@cBI7ut#aQ69Ap@RG z2HVjWORMWDLb5o9G+8=Y{U{Qd6XB0B)D1Zo%tuz3rj&>1G`*BQ+>fo1s*rPY z<~tIo>C52xd@=P*T`HPO=fa~AC5KX$QO)2}nRh1jyG=~AvjcuNo8b}B*Y_dmqTM+s z%Sgh-{5jA?(yFE`wR{4hIO~K=Wjl7=B}Xf}W{@pajjY)=+iq##pbu_Q=h(2_ti3>u z9J)?2=+GRx-X5s=SumAbf+5?n4%qkartR%4)<&I(Tt*DJ7X=wHr|d<1%^YzzE3xM> z-%7E|JP?a`XAz0(J?42JA3%DAus`Z&$y9Xaij(78A=2Oj@9du!#a=!NEc0aI_oNwy zL6aGK>2?l~?dJ7(AxI8I0lE`VGY3E}E@o%dTVTviD!?e2g#g2kAR) empty_values = 2; + map recursive_values = 3; + map big_enum_values = 4; + map supported_values = 5; +} diff --git a/tests/queries/0_stateless/orc_malformed.lib b/tests/queries/0_stateless/orc_malformed.lib new file mode 100644 index 000000000000..64f884cc4498 --- /dev/null +++ b/tests/queries/0_stateless/orc_malformed.lib @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2154 + +# Helpers to read (possibly malformed) ORC files from the tests: locally with `file` in clickhouse-local, and remotely +# with `s3` in the server, with the filter pushdown and the lazy dictionaries both enabled and disabled. + +ORC_S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}" +# The values of `input_format_orc_filter_push_down` to check. +ORC_PUSH_DOWN_VALUES="0 1" + +# Prints the result in one line, or the name of the error code (with the message if it does not match `expected_error`). +function orc_result() +{ + local output=$1 status=$2 expected_error=$3 + if [ "$status" -eq 0 ]; then + echo "$output" | tr '\n' ' ' | sed 's/ $//' + return + fi + local code + code=$(echo "$output" | grep -oE '\([A-Z_]{3,}\)' | tail -n1) + if [ -z "$code" ]; then + echo "unexpected failure with status $status: $(echo "$output" | head -n3)" + elif [ -z "$expected_error" ] || echo "$output" | grep -qE "$expected_error"; then + echo "$code" + else + echo "$code with an unexpected message: $(echo "$output" | head -n1 | cut -c1-300)" + fi +} + +# orc_check
`, so it requires the `WRITE` grant on the `S3` source. A grant limited by a URL filter is not enough, because the move writes keys that are built from `after_processing_move_prefix` and the source keys, not from the URI. `ALTER TABLE ... MODIFY SETTING` also requires `SELECT` on the table. The destination must be allowed by `remote_url_allow_hosts`. + Possible values: - String. diff --git a/docs/en/operations/settings/settings-users.md b/docs/en/operations/settings/settings-users.md index d7d61ff6ee9c..d029b4cca3ad 100644 --- a/docs/en/operations/settings/settings-users.md +++ b/docs/en/operations/settings/settings-users.md @@ -110,6 +110,7 @@ It's not yet supported in SQL-driven Access Control. To authenticate using TOTP, users must provide a primary password along with a one-time password generated by their TOTP application via the `--one-time-password` command line option or concatenated to main password together with a '+' character. For example if the primary password is `some_password` and the generated TOTP code is `345123`, user may specify `--password some_password+345123` or `--password some_password --one-time-password 345123` when connecting to ClickHouse. If no password specified `clickhouse-client` will prompt for it interactively. +When no code is supplied for an account with TOTP, the server replies with the error `REQUIRED_SECOND_FACTOR` whether or not the password is correct, and `clickhouse-client` prompts for the code; the password is verified only together with the code. Each code is accepted at most once, as required by [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238#section-5.2), so a user can successfully authenticate at most once per `period`. Keep this in mind for clients that authenticate on every request or connection (for example, scripts using the HTTP interface): each authentication needs a fresh code. diff --git a/programs/client/Client.cpp b/programs/client/Client.cpp index d37218c596e4..e7d0ad5281c8 100644 --- a/programs/client/Client.cpp +++ b/programs/client/Client.cpp @@ -408,6 +408,16 @@ try if (should_ask_2fa) { + /// The server asks for the second factor before it checks the password, so the first attempt + /// without any password ends here too. Ask for the password alone first: it may already contain + /// the code (`password+code`); otherwise the server asks again and the code is prompted. + if (!asked_password && !config().has("password") && !config().getBool("ask-password", false)) + { + asked_password = true; + config().setBool("ask-password", true); + continue; + } + asked_2fa = true; if (!connection_parameters.password.empty()) config().setString("password", connection_parameters.password); @@ -567,7 +577,8 @@ void Client::connect() catch (Exception & e) { /// This problem can't be fixed with reconnection so it is not attempted - if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD) + if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD + || e.code() == ErrorCodes::REQUIRED_SECOND_FACTOR) throw; if (attempted_address_index == hosts_and_ports.size() - 1) diff --git a/src/Access/AccessBackup.cpp b/src/Access/AccessBackup.cpp index d22edd007e2f..6af476b88b1b 100644 --- a/src/Access/AccessBackup.cpp +++ b/src/Access/AccessBackup.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -176,6 +177,23 @@ namespace } } }; + + AccessRights getRequiredAccessToRestoreGrants(const AccessRights & access) + { + AccessRights required_access; + for (const auto & element : access.getElements()) + { + /// Restoring a grant requires `GRANT OPTION` even if the backed-up entity does not have it. + if (element.is_partial_revoke && element.grant_option) + continue; + + if (element.is_partial_revoke) + required_access.revoke(element); + else + required_access.grantWithGrantOption(element); + } + return required_access; + } } @@ -338,12 +356,14 @@ void AccessRestorerFromBackup::loadFromBackup() } -AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const +AccessRights AccessRestorerFromBackup::getRequiredAccess() const { if (!loaded) throw Exception(ErrorCodes::LOGICAL_ERROR, "Access entities not loaded"); - AccessRightsElements res; + AccessRights res; + /// Like `CREATE ... OR REPLACE`, replacement requires `DROP` even if the entity does not exist. + const bool replace = (creation_mode == RestoreAccessCreationMode::kReplace); for (const auto & [id, entity_info] : entity_infos) { if (!entity_info.restore) @@ -355,57 +375,56 @@ AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const case User::TYPE: { const auto & user = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_USER, user.getName()); + AccessFlags flags = AccessType::CREATE_USER; + if (replace) + flags |= AccessType::DROP_USER; + res.grant(flags, user.getName()); if (!restore_with_current_grants) - { - auto elements = user.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(user.access)); if (!user.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case Role::TYPE: { const auto & role = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROLE, role.getName()); + AccessFlags flags = AccessType::CREATE_ROLE; + if (replace) + flags |= AccessType::DROP_ROLE; + res.grant(flags, role.getName()); if (!restore_with_current_grants) - { - auto elements = role.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(role.access)); if (!role.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case SettingsProfile::TYPE: { - res.emplace_back(AccessType::CREATE_SETTINGS_PROFILE); + AccessFlags flags = AccessType::CREATE_SETTINGS_PROFILE; + if (replace) + flags |= AccessType::DROP_SETTINGS_PROFILE; + res.grant(flags); break; } case RowPolicy::TYPE: { const auto & policy = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROW_POLICY, policy.getDatabase(), policy.getTableName()); + AccessFlags flags = AccessType::CREATE_ROW_POLICY; + if (replace) + flags |= AccessType::DROP_ROW_POLICY; + res.grant(flags, policy.getDatabase(), policy.getTableName()); break; } case Quota::TYPE: { - res.emplace_back(AccessType::CREATE_QUOTA); + AccessFlags flags = AccessType::CREATE_QUOTA; + if (replace) + flags |= AccessType::DROP_QUOTA; + res.grant(flags); break; } diff --git a/src/Access/AccessBackup.h b/src/Access/AccessBackup.h index 8219d1051035..da0f3088a033 100644 --- a/src/Access/AccessBackup.h +++ b/src/Access/AccessBackup.h @@ -11,7 +11,7 @@ class AccessControl; enum class AccessEntityType : uint8_t; struct IAccessEntity; using AccessEntityPtr = std::shared_ptr; -class AccessRightsElements; +class AccessRights; class IAccessStorage; class IBackup; using BackupPtr = std::shared_ptr; @@ -69,9 +69,9 @@ class AccessRestorerFromBackup /// Loads access entities from the backup. void loadFromBackup(); - /// Checks that the current user can do restoring. - /// Function loadFromBackup() must be called before that. - AccessRightsElements getRequiredAccess() const; + /// Returns the access required to restore the loaded entities. + /// `loadFromBackup` must be called first. + AccessRights getRequiredAccess() const; /// Generates random IDs for access entities we're restoring to insert them into an access storage; /// and finds IDs of existing access entities which are used as dependencies. diff --git a/src/Access/AccessControl.cpp b/src/Access/AccessControl.cpp index 03e25e9c513f..92f938920279 100644 --- a/src/Access/AccessControl.cpp +++ b/src/Access/AccessControl.cpp @@ -602,22 +602,25 @@ AuthResult AccessControl::authenticate(const Credentials & credentials, const Po // NOTE: In the case where the user has never been logged in using LDAP, // Then user_id is not generated, and the authentication quota will always be nullptr. auto authentication_quota = getAuthenticationQuota(credentials.getUserName(), address, client_info.getLastForwardedForHost()); - if (authentication_quota) - { - /// Reserve a single try from the quota to check whether we have another authentication try. - /// This is required for correct behavior in this situation: - /// User has 1 login failures quota. - /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. - /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. - /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED - /// and don't let the user authenticate. - /// - /// The authentication failures counter will be reset after successful authentication. - authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); - } try { + if (authentication_quota) + { + /// Reserve a single try from the quota to check whether we have another authentication try. + /// This is required for correct behavior in this situation: + /// User has 1 login failures quota. + /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. + /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. + /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED + /// and don't let the user authenticate. + /// + /// The authentication failures counter will be reset after successful authentication. + /// Inside the try block, so that an exceeded quota is reported like any other authentication failure + /// and doesn't reveal whether the user exists. + authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); + } + const auto auth_result = MultipleAccessStorage::authenticate(credentials, address, *external_authenticators, client_info, allow_no_password, allow_plaintext_password); if (authentication_quota) @@ -859,7 +862,7 @@ std::shared_ptr AccessControl::getEnabledQuota( const String & forwarded_address, const String & custom_quota_key) const { - return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key, true); + return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key); } std::shared_ptr AccessControl::getAuthenticationQuota( @@ -872,18 +875,13 @@ std::shared_ptr AccessControl::getAuthenticationQuota( const auto new_current_roles = user->granted_roles.findGranted(user->default_roles); const auto roles_info = getEnabledRolesInfo(new_current_roles, {}); - // client_key is not received at the moment of authentication during TCP connection - // if key type is set to QuotaKeyType::CLIENT_KEY - // QuotaCache::QuotaInfo::calculateKey will throw exception without throw_if_client_key_empty = false String quota_key; - bool throw_if_client_key_empty = false; return quota_cache->getEnabledQuota(*user_id, user->getName(), roles_info->enabled_roles, std::make_shared(address), forwarded_address, - quota_key, - throw_if_client_key_empty); + quota_key); } return nullptr; } diff --git a/src/Access/Authentication.cpp b/src/Access/Authentication.cpp index 055109dc596b..7745947d0fd2 100644 --- a/src/Access/Authentication.cpp +++ b/src/Access/Authentication.cpp @@ -183,80 +183,60 @@ namespace return {password_with_otp.substr(0, separator_pos), password_with_otp.substr(separator_pos + 1)}; } - Authentication::CredentialsCheckResult checkBasicAuthentication( - const BasicCredentials * basic_credentials, + /// Verifies the primary credential: the password without the one-time password part. + bool checkPrimaryCredential( + std::string_view password, + const BasicCredentials & basic_credentials, const AuthenticationData & authentication_method, const ExternalAuthenticators & external_authenticators, const ClientInfo & client_info, SettingsChanges & settings) { - const auto & provided_password = basic_credentials->getPassword(); - const auto & otp_secret = authentication_method.getOneTimePassword(); - auto [password, one_time_password] = splitOneTimePasswordAndPassword(provided_password, authentication_method); - Authentication::CredentialsCheckResult on_success = Authentication::CredentialsCheckResult::Success; - if (otp_secret) - { - /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after - /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. - if (one_time_password.empty()) - on_success = Authentication::CredentialsCheckResult::NeedSecondFactor; - else if (!checkOneTimePassword(one_time_password, *otp_secret)) - return Authentication::CredentialsCheckResult::Fail; - } - switch (authentication_method.getType()) { case AuthenticationType::NO_PASSWORD: { - return on_success; // N.B. even if the password is not empty! + return true; // N.B. even if the password is not empty! } case AuthenticationType::PLAINTEXT_PASSWORD: { const auto & password_plaintext = authentication_method.getPasswordHashBinary(); - return constantTimeEquals(Util::stringToDigest(password), password_plaintext) ? on_success : Authentication::CredentialsCheckResult::Fail; + return constantTimeEquals(Util::stringToDigest(password), password_plaintext); } case AuthenticationType::SHA256_PASSWORD: { const auto & password_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); String salted_password = String(password).append(salt); - return Util::encodeSHA256(salted_password) == password_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeSHA256(salted_password) == password_sha256; } case AuthenticationType::SCRAM_SHA256_PASSWORD: { const auto & password_scram_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); auto digest = Util::encodeScramSHA256(password, salt); - return digest == password_scram_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return digest == password_scram_sha256; } case AuthenticationType::DOUBLE_SHA1_PASSWORD: { const auto & password_double_sha1 = authentication_method.getPasswordHashBinary(); - return Util::encodeDoubleSHA1(password) == password_double_sha1 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeDoubleSHA1(password) == password_double_sha1; } case AuthenticationType::LDAP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; - return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), *basic_credentials) ? - on_success : Authentication::CredentialsCheckResult::Fail; + return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), basic_credentials); } case AuthenticationType::BCRYPT_PASSWORD: { const auto & password_bcrypt = authentication_method.getPasswordHashBinary(); - return Util::checkPasswordBcrypt(password, password_bcrypt) ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::checkPasswordBcrypt(password, password_bcrypt); } case AuthenticationType::HTTP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; if (authentication_method.getHTTPAuthenticationScheme() == HTTPAuthenticationScheme::BASIC) { return external_authenticators.checkHTTPBasicCredentials( - authentication_method.getHTTPAuthenticationServerName(), *basic_credentials, client_info, settings) ? - on_success : Authentication::CredentialsCheckResult::Fail; + authentication_method.getHTTPAuthenticationServerName(), basic_credentials, client_info, settings); } break; } @@ -264,7 +244,38 @@ namespace break; } - return Authentication::CredentialsCheckResult::Fail; + return false; + } + + Authentication::CredentialsCheckResult checkBasicAuthentication( + const BasicCredentials * basic_credentials, + const AuthenticationData & authentication_method, + const ExternalAuthenticators & external_authenticators, + const ClientInfo & client_info, + SettingsChanges & settings) + { + const auto & otp_secret = authentication_method.getOneTimePassword(); + auto [password, one_time_password] = splitOneTimePasswordAndPassword(basic_credentials->getPassword(), authentication_method); + + const auto auth_type = authentication_method.getType(); + if (otp_secret && (auth_type == AuthenticationType::LDAP || auth_type == AuthenticationType::HTTP)) + /// One-time password supported only with password-based authentication methods. + return Authentication::CredentialsCheckResult::Fail; + + /// Decided before the primary credential is looked at, so that the response (and its timing) is the same + /// for a right and a wrong password: otherwise an attacker could confirm a guessed password without the code. + if (otp_secret && one_time_password.empty()) + return Authentication::CredentialsCheckResult::NeedSecondFactor; + + const bool primary_ok = checkPrimaryCredential(password, *basic_credentials, authentication_method, external_authenticators, client_info, settings); + if (!otp_secret) + return primary_ok ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; + + /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after + /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. + /// Both factors are evaluated unconditionally, so that the timing does not tell which one failed. + const bool otp_ok = checkOneTimePassword(one_time_password, *otp_secret); + return (primary_ok && otp_ok) ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; } #if USE_SSL diff --git a/src/Access/ContextAccess.cpp b/src/Access/ContextAccess.cpp index 98cd4af879ed..080eab0c7fa1 100644 --- a/src/Access/ContextAccess.cpp +++ b/src/Access/ContextAccess.cpp @@ -586,6 +586,10 @@ std::shared_ptr ContextAccess::getQuota() const } } + /// Outside the branch above on purpose: `QuotaCache` refreshes the quota set in place, so an already + /// memoised object has to be re-checked on every call. + enabled_quota->checkClientKeySupplied(); + return enabled_quota; } @@ -779,15 +783,16 @@ bool ContextAccess::checkAccessImplHelper(const ContextPtr & context, AccessFlag const AccessFlags function_ddl = AccessType::CREATE_FUNCTION | AccessType::DROP_FUNCTION; const AccessFlags workload_ddl = AccessType::CREATE_WORKLOAD | AccessType::DROP_WORKLOAD; const AccessFlags resource_ddl = AccessType::CREATE_RESOURCE | AccessType::DROP_RESOURCE; + const AccessFlags named_collection_ddl = AccessType::CREATE_NAMED_COLLECTION | AccessType::DROP_NAMED_COLLECTION | AccessType::ALTER_NAMED_COLLECTION; const AccessFlags table_and_dictionary_ddl = table_ddl | dictionary_ddl; const AccessFlags table_and_dictionary_and_function_ddl = table_ddl | dictionary_ddl | function_ddl; const AccessFlags write_table_access = AccessType::INSERT | AccessType::OPTIMIZE; const AccessFlags write_dcl_access = AccessType::ACCESS_MANAGEMENT - AccessType::SHOW_ACCESS; - const AccessFlags not_readonly_flags = write_table_access | table_and_dictionary_and_function_ddl | workload_ddl | resource_ddl | write_dcl_access | AccessType::SYSTEM | AccessType::KILL_QUERY; + const AccessFlags not_readonly_flags = write_table_access | table_and_dictionary_and_function_ddl | workload_ddl | resource_ddl | named_collection_ddl | write_dcl_access | AccessType::SYSTEM | AccessType::KILL_QUERY; const AccessFlags not_readonly_1_flags = AccessType::CREATE_TEMPORARY_TABLE; - const AccessFlags ddl_flags = table_ddl | dictionary_ddl | function_ddl | workload_ddl | resource_ddl; + const AccessFlags ddl_flags = table_ddl | dictionary_ddl | function_ddl | workload_ddl | resource_ddl | named_collection_ddl; const AccessFlags introspection_flags = AccessType::INTROSPECTION; }; static const PrecalculatedFlags precalc; diff --git a/src/Access/EnabledQuota.cpp b/src/Access/EnabledQuota.cpp index 92518d5506ea..c5333af77e4d 100644 --- a/src/Access/EnabledQuota.cpp +++ b/src/Access/EnabledQuota.cpp @@ -14,6 +14,7 @@ namespace DB namespace ErrorCodes { extern const int QUOTA_EXCEEDED; + extern const int QUOTA_REQUIRES_CLIENT_KEY; } @@ -307,6 +308,18 @@ void EnabledQuota::checkExceeded(QuotaType quota_type) const } +void EnabledQuota::checkClientKeySupplied() const +{ + if (!requires_client_key) + return; + throw Exception( + ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, + "Quota {} (for user {}) requires a client supplied key.", + intervals.load()->quota_name, + getUserName()); +} + + void EnabledQuota::reset(QuotaType quota_type) const { const auto loaded = intervals.load(); diff --git a/src/Access/EnabledQuota.h b/src/Access/EnabledQuota.h index 2513bed9622c..587c97f108f4 100644 --- a/src/Access/EnabledQuota.h +++ b/src/Access/EnabledQuota.h @@ -52,6 +52,10 @@ class EnabledQuota : public boost::noncopyable void checkExceeded() const; void checkExceeded(QuotaType quota_type) const; + /// Throws if a governing quota is keyed by `client_key` and this context supplied none. Authentication + /// is metered before a client key can exist, so only the query path calls this. + void checkClientKeySupplied() const; + void reset(QuotaType quota_type) const; /// Returns the information about quota consumption. @@ -97,6 +101,9 @@ class EnabledQuota : public boost::noncopyable const Params params; boost::atomic_shared_ptr intervals; /// atomically changed by QuotaUsageManager std::atomic empty = false; /// Use a separate flag to avoid loading intervals, which is way more expensive than an atomic bool + /// The chosen quota is keyed by `client_key` and this context supplied none, so it cannot be metered. + /// Refreshed in place by `QuotaCache` together with `intervals`; see `checkClientKeySupplied`. + std::atomic requires_client_key = false; }; } diff --git a/src/Access/HTTPAuthClient.h b/src/Access/HTTPAuthClient.h index 27e0d5dc507b..2768639cb709 100644 --- a/src/Access/HTTPAuthClient.h +++ b/src/Access/HTTPAuthClient.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -12,6 +13,11 @@ namespace DB { +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + struct HTTPAuthClientParams { Poco::URI uri; @@ -95,8 +101,13 @@ class HTTPBasicAuthClient : private HTTPAuthClient for (const auto & k : headers) { - if (this->getForwardHeaders().contains(k.first)) - request.add(k.first, k.second); + if (!this->getForwardHeaders().contains(k.first)) + continue; + /// Poco writes header values verbatim, so a line break would let the value inject extra headers + /// (e.g. an `Authorization` placed before ours) into the request to the authentication server. + if (k.second.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Forwarded HTTP header \"{}\" contains CR, LF or NUL", k.first); + request.add(k.first, k.second); } Poco::Net::HTTPBasicCredentials basic_credentials{user_name, password}; diff --git a/src/Access/IAccessStorage.cpp b/src/Access/IAccessStorage.cpp index 2beb46691b4b..7c2ed52f88e7 100644 --- a/src/Access/IAccessStorage.cpp +++ b/src/Access/IAccessStorage.cpp @@ -598,6 +598,8 @@ std::optional IAccessStorage::authenticateImpl( "check allow_no_password and allow_plaintext_password settings in the server configuration"); } + /// Reported for a missing code before the password is checked (see `checkBasicAuthentication`), + /// so this error does not confirm the password. if (need_second_factor) throw Exception(ErrorCodes::REQUIRED_SECOND_FACTOR, "Authentication requires second factor"); throw Exception(ErrorCodes::WRONG_PASSWORD, "Invalid credentials"); diff --git a/src/Access/QuotaCache.cpp b/src/Access/QuotaCache.cpp index d5a019639a2f..338b09a34e73 100644 --- a/src/Access/QuotaCache.cpp +++ b/src/Access/QuotaCache.cpp @@ -26,7 +26,6 @@ namespace DB { namespace ErrorCodes { - extern const int QUOTA_REQUIRES_CLIENT_KEY; extern const int LOGICAL_ERROR; } @@ -40,7 +39,7 @@ void QuotaCache::QuotaInfo::setQuota(const QuotaPtr & quota_, const UUID & quota } -String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool throw_if_client_key_empty) const +String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled) const { const auto & params = enabled.params; switch (quota->key_type) @@ -65,14 +64,9 @@ String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool th { if (!params.client_key.empty()) return params.client_key; - - if (throw_if_client_key_empty) - throw Exception( - ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, - "Quota {} (for user {}) requires a client supplied key.", - quota->getName(), - params.user_name); - return ""; // Authentication quota has no client key at time of authentication. + /// An empty key is a legitimate state: at the time of authentication no client key exists yet. + /// The requirement is published as `EnabledQuota::requires_client_key` and enforced on the query path. + return ""; } case QuotaKeyType::CLIENT_KEY_OR_USER_NAME: { @@ -187,8 +181,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( const boost::container::flat_set & enabled_roles, const std::shared_ptr & client_address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty) + const String & client_key) { std::lock_guard lock{mutex}; ensureAllQuotasRead(); @@ -211,7 +204,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( auto res = std::shared_ptr(new EnabledQuota(params)); enabled_quotas.emplace(std::move(params), res); - chooseQuotaToConsumeFor(*res, throw_if_client_key_empty); + chooseQuotaToConsumeFor(*res); return res; } @@ -294,7 +287,7 @@ void QuotaCache::chooseQuotaToConsume() i = enabled_quotas.erase(i); else { - chooseQuotaToConsumeFor(*elem, true); + chooseQuotaToConsumeFor(*elem); ++i; } } @@ -308,16 +301,18 @@ void QuotaCache::chooseQuotaToConsume() LOG_DEBUG(getLogger("QuotaCache"), "Re-chose quotas for {} enabled set(s) over {} quotas in {} ms", enabled_quotas.size(), all_quotas.size(), elapsed_ms); } -void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_client_key_empty) +void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled) { /// `mutex` is already locked. boost::shared_ptr intervals; + bool requires_client_key = false; for (auto & info : all_quotas | boost::adaptors::map_values) { if (info.roles->match(enabled.params.user_id, enabled.params.enabled_roles)) { - String key = info.calculateKey(enabled, throw_if_client_key_empty); + String key = info.calculateKey(enabled); intervals = info.getOrBuildIntervals(key); + requires_client_key = (info.quota->key_type == QuotaKeyType::CLIENT_KEY) && enabled.params.client_key.empty(); break; } } @@ -332,6 +327,7 @@ void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_c enabled.intervals.store(intervals); enabled.empty = false; } + enabled.requires_client_key = requires_client_key; } diff --git a/src/Access/QuotaCache.h b/src/Access/QuotaCache.h index 4c4cd955bac1..29df5ebe50b6 100644 --- a/src/Access/QuotaCache.h +++ b/src/Access/QuotaCache.h @@ -28,8 +28,7 @@ class QuotaCache const boost::container::flat_set & enabled_roles, const std::shared_ptr & address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty); + const String & client_key); std::vector getAllQuotasUsage() const; @@ -42,7 +41,7 @@ class QuotaCache QuotaInfo(const QuotaPtr & quota_, const UUID & quota_id_) { setQuota(quota_, quota_id_); } void setQuota(const QuotaPtr & quota_, const UUID & quota_id_); - String calculateKey(const EnabledQuota & enabled_quota, bool throw_if_client_key_empty) const; + String calculateKey(const EnabledQuota & enabled_quota) const; boost::shared_ptr getOrBuildIntervals(const String & key); boost::shared_ptr rebuildIntervals(const String & key, std::chrono::system_clock::time_point current_time); void rebuildAllIntervals(); @@ -58,7 +57,7 @@ class QuotaCache void quotaRemoved(const UUID & quota_id); void chooseQuotaToConsume(); void chooseQuotaToConsumeIfNeeded(); - void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota, bool throw_if_client_key_empty); + void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota); const AccessControl & access_control; mutable std::mutex mutex; diff --git a/src/Access/SettingsConstraints.cpp b/src/Access/SettingsConstraints.cpp index bb47d78c603f..dcf8d39879f0 100644 --- a/src/Access/SettingsConstraints.cpp +++ b/src/Access/SettingsConstraints.cpp @@ -287,6 +287,18 @@ void SettingsConstraints::clamp(const Settings & current_settings, SettingsChang }); } +void SettingsConstraints::clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const +{ + /// The surviving list is stored on the query node as the settings set explicitly on that node, + /// so a change equal to the current value must stay in the list. + std::erase_if( + changes, + [&](SettingChange & change) -> bool + { + return !checkImpl(current_settings, change, CLAMP_ON_VIOLATION_THROW_ON_INVALID, source, /*ignore_unchanged_settings=*/ true); + }); +} + /// The value a setting holds now. /// /// `Settings` keeps a `merge_tree_`-prefixed name as a custom setting, under the exact name that wrote it. @@ -321,13 +333,13 @@ Field castValueOfSetting(const String & name, const Field & value) } template -bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool throw_on_failure) +bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool ignore_unchanged_settings, bool throw_on_failure) { Field current_value; bool has_current_value = getCurrentValueOfSetting(current_settings, change.name, current_value); /// Setting isn't checked if value has not changed. - if (has_current_value && change.value == current_value) + if (!ignore_unchanged_settings && has_current_value && change.value == current_value) return false; /// Put the value into the type of the setting. This throws when the value does not fit, as @@ -358,7 +370,7 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan /// stores a Bool, the same 1 in a query arrives as a UInt64, and comparing them as they are would /// make a change that keeps the value look like a real one. Field cast_current_value; - if (has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) + if (!ignore_unchanged_settings && has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) return false; return true; @@ -367,14 +379,18 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan bool SettingsConstraints::checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const + SettingSource source, + bool ignore_unchanged_settings) const { std::string_view setting_name = Settings::resolveName(change.name); if (setting_name == "profile") return true; - if (reaction == THROW_ON_VIOLATION) + /// Invalid changes (an unknown or disallowed name, an uncastable value) throw in every mode but `CLAMP_ON_VIOLATION`. + const bool throw_on_invalid_change = reaction != CLAMP_ON_VIOLATION; + + if (throw_on_invalid_change) { try { @@ -396,7 +412,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, return false; Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, ignore_unchanged_settings, /*throw_on_failure=*/ throw_on_invalid_change)) return false; return getChecker(current_settings, setting_name).check(change, new_value, reaction, source); @@ -405,7 +421,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, bool SettingsConstraints::checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const { Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, /*ignore_unchanged_settings=*/ false, reaction == THROW_ON_VIOLATION)) return false; if (isAnyTierRestricted()) @@ -422,9 +438,12 @@ bool SettingsConstraints::Checker::check(SettingChange & change, ReactionOnViolation reaction, SettingSource source) const { + /// Every reaction other than `THROW_ON_VIOLATION` clamps or drops a violating change. + const bool throw_on_violation = reaction == THROW_ON_VIOLATION; + if (!explain.text.empty()) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(explain, code); return false; } @@ -433,7 +452,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto less_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateLess(left, right); try { @@ -447,7 +466,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto equals_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateEquals(left, right); try { @@ -462,7 +481,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (constraint.writability == SettingConstraintWritability::CONST) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} should not be changed", setting_name); return false; } @@ -473,7 +492,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && !max_value.isNull() && less_or_cannot_compare(max_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception( ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "The maximum ({}) value is less than the minimum ({}) value for setting {}", @@ -485,7 +504,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && less_or_cannot_compare(new_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be less than {}", setting_name, applyVisitor(FieldVisitorToString(), min_value)); @@ -495,7 +514,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!max_value.isNull() && less_or_cannot_compare(max_value, new_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be greater than {}", setting_name, applyVisitor(FieldVisitorToString(), max_value)); @@ -513,7 +532,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!getSettingSourceRestrictions(setting_name).isSourceAllowed(source)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::READONLY, "Setting {} is not allowed to be set by {}", setting_name, toString(source)); return false; } diff --git a/src/Access/SettingsConstraints.h b/src/Access/SettingsConstraints.h index dc87368a62e2..2231cda9cfd6 100644 --- a/src/Access/SettingsConstraints.h +++ b/src/Access/SettingsConstraints.h @@ -95,8 +95,13 @@ class SettingsConstraints void check(const MergeTreeSettings & current_settings, const SettingsChanges & changes) const; /// Checks whether `change` violates these and clamps the `change` if so. + /// A change equal to the current value is dropped from `changes`. void clamp(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + /// Same as `clamp`, but an unknown or disallowed setting name and an uncastable value throw, as in `check`, + /// and a change equal to the current value is kept in `changes`. + void clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + friend bool operator ==(const SettingsConstraints & left, const SettingsConstraints & right); friend bool operator !=(const SettingsConstraints & left, const SettingsConstraints & right) { return !(left == right); } @@ -104,8 +109,12 @@ class SettingsConstraints private: enum ReactionOnViolation { + /// Any violation, an unknown name or an uncastable value throws. THROW_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value is dropped. CLAMP_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value throws. + CLAMP_ON_VIOLATION_THROW_ON_INVALID, }; struct Constraint @@ -165,7 +174,8 @@ class SettingsConstraints bool checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const; + SettingSource source, + bool ignore_unchanged_settings = false) const; bool checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const; diff --git a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp index b1bf4f7edb96..7df726a74610 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp @@ -24,6 +24,8 @@ #include +#include + #include constexpr size_t AGGREGATE_FUNCTION_GROUP_ARRAY_MAX_ELEMENT_SIZE = 0xFFFFFF; @@ -90,6 +92,17 @@ struct GroupArraySamplerData size_t total_values = 0; pcg32_fast rng; + /// The counter may come from a deserialized state, so it can be arbitrarily large, + /// and wrapping it around would make `genRandom` divide by zero. + void addTotalValues(UInt64 count) + { + UInt64 new_total_values = 0; + if (common::addOverflow(static_cast(total_values), count, new_total_values)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The number of values in groupArraySample state overflows: {} + {}", total_values, count); + total_values = new_total_values; + } + UInt64 genRandom(size_t lim) { chassert(lim != 0); @@ -160,7 +173,7 @@ class GroupArrayNumericImpl final void insertWithSampler(Data & a, const T & v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v, arena); else @@ -183,7 +196,10 @@ class GroupArrayNumericImpl final const auto & row_value = assert_cast &>(*columns[0]).getData()[row_num]; auto & cur_elems = this->data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -275,8 +291,8 @@ class GroupArrayNumericImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); @@ -525,7 +541,7 @@ class GroupArrayGeneralImpl final void insertWithSampler(Data & a, const Node * v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v->clone(arena), arena); else @@ -547,7 +563,10 @@ class GroupArrayGeneralImpl final { auto & cur_elems = data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -642,8 +661,8 @@ class GroupArrayGeneralImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp index 8c61d13923ca..610937b52f5f 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp @@ -61,8 +61,14 @@ void forEachSecretArgumentNode( continue; } + if (const auto masked = secret_arguments.masked_arguments.find(n); masked != secret_arguments.masked_arguments.end()) + { + on_secret(n, masked->second ? secretValueSlot(arguments[n]) : arguments[n]); + continue; + } + const bool in_span = secret_arguments.start <= n && n < secret_arguments.start + secret_arguments.count; - if (in_span || secret_arguments.masked_arguments.contains(n) || secret_arguments.replaced_arguments.contains(n)) + if (in_span || secret_arguments.replaced_arguments.contains(n)) on_secret(n, secretValueSlot(arguments[n])); } } diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h index 6afdd5d3a952..ecd7322afc29 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h @@ -122,7 +122,8 @@ using FunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeN using TableFunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeNodeImpl; /// Visits the secret value slots selected by a finder result in a resolved argument list, for the -/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members and the arguments +/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members, the individually +/// masked arguments (whole, unless masked as a named `key = value`) and the arguments /// with a partial replacement (for a `key = value` argument, its value; a tree dump cannot represent /// partial masking, so the whole value is masked: fail closed), and the values of the nested secret /// maps (`headers(..)` / `extra_credentials(..)`; a malformed child is visited whole). The callback diff --git a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp index 44c9ee3df51b..b95cc0fd9410 100644 --- a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp +++ b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp @@ -550,6 +550,10 @@ std::tuple getTypedNodesForOptimizati if (!storage->supportsOptimizationToSubcolumns() || storage->isVirtualColumn(column.name, storage_snapshot->metadata)) return {}; + /// Without buckets the key subcolumn `m.key_` reads the whole Map, so `m['key']` is not rewritten to it. + if (function_node->getFunctionName() == "arrayElement" && isMap(column.type) && !storage->hasBucketedMapSerialization()) + return {}; + auto column_in_table = storage_snapshot->tryGetColumn(GetColumnsOptions(GetColumnsOptions::All).withSubcolumns(), column.name); if (!column_in_table || !column_in_table->type->equals(*column.type)) return {}; diff --git a/src/Analyzer/QueryTreeBuilder.cpp b/src/Analyzer/QueryTreeBuilder.cpp index 285edf278e72..16cab878c838 100644 --- a/src/Analyzer/QueryTreeBuilder.cpp +++ b/src/Analyzer/QueryTreeBuilder.cpp @@ -302,22 +302,28 @@ QueryTreeNodePtr QueryTreeBuilder::buildSelectExpression( set_query.changes.removeSetting("offset"); } - /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) used to be applied to - /// the per-node context unchecked, letting a user override `readonly`, `CONST` and `MIN`/`MAX` - /// constraints - e.g. `additional_table_filters`, which the Planner reads from this context. - /// Clamp it instead of throwing, as done for other settings crossing execution contexts - /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are - /// dropped, out-of-bounds values are clamped, so a view whose inner clause violates the - /// reader's constraints keeps working. A top-level clause still throws - /// (`applySettingsFromQuery`). Clamp a copy: the `QueryNode` keeps the clause as written, so - /// the tree's AST and hash are unchanged, and every node executing the subquery clamps it - /// against its own constraints. `SETTINGS name = DEFAULT` stays ignored here - see #115415. + /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) is clamped to the session's + /// settings constraints, as done for other settings crossing execution contexts + /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are dropped, + /// out-of-bounds values are clamped, so a view whose inner clause violates the reader's constraints + /// keeps working. A top-level clause still throws (`applySettingsFromQuery`). An unknown name or an + /// uncastable value throws as for a top-level clause, on every server that executes the query. The + /// node records the effective `changes`: the ones that survive, with their clamped values and the + /// literals as written, so `toAST`, the tree hash, the `Planner` and the shards receiving the + /// subquery see what was applied. `SETTINGS name = DEFAULT` stays ignored here - see #115415. if (!set_query.changes.empty()) { - auto checked_changes = set_query.changes; - updated_context->clampToSettingsConstraints(checked_changes, SettingSource::QUERY); - updated_context->applySettingsChanges(checked_changes); - settings_changes = set_query.changes; + /// One change at a time, so that each is clamped against the context as the preceding changes + /// left it. Clamping the whole clause as a batch checks every change against the context as it + /// was before the clause - so `SETTINGS use_query_cache = 1, use_query_cache = 0` could resolve + /// differently from the last-wins reading the clause has everywhere else. + for (const auto & change : set_query.changes) + { + SettingsChanges single_change{change}; + updated_context->clampToSettingsConstraintsRejectingInvalidChanges(single_change, SettingSource::QUERY); + updated_context->applySettingsChanges(single_change); + settings_changes.insert(settings_changes.end(), single_change.begin(), single_change.end()); + } } } diff --git a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp index e5ec3cc7c4e1..56109118b128 100644 --- a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp +++ b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp @@ -114,7 +114,7 @@ void QueryAnalyzer::evaluateScalarSubqueryIfNeeded(QueryTreeNodePtr & node, Iden scalar_block = scalars_cache.at(node_with_hash); } - else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasScalar(str_hash)) + else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasComputedScalar(str_hash)) { scalar_block = context->getQueryContext()->getScalar(str_hash); scalar_subquery_to_scalar_value_global.emplace(node_with_hash, scalar_block); diff --git a/src/Backups/BackupIO_AzureBlobStorage.cpp b/src/Backups/BackupIO_AzureBlobStorage.cpp index eb2126f1dd9f..cd08f6e339e3 100644 --- a/src/Backups/BackupIO_AzureBlobStorage.cpp +++ b/src/Backups/BackupIO_AzureBlobStorage.cpp @@ -2,6 +2,7 @@ #include #if USE_AZURE_BLOB_STORAGE +#include #include #include #include @@ -29,6 +30,17 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +namespace +{ + /// An Azure disk configured with `connection_string` is described by that whole string. + String maskedDescription(const DataSourceDescription & description) + { + String result = description.description; + maskAzureConnectionStringSecrets(result); + return result; + } +} + BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const AzureBlobStorage::ConnectionParams & connection_params_, const String & blob_path_, @@ -37,7 +49,7 @@ BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const WriteSettings & write_settings_, const ContextPtr & context_) : BackupReaderDefault(read_settings_, write_settings_, getLogger("BackupReaderAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -85,7 +97,7 @@ void BackupReaderAzureBlobStorage::copyFileToDisk(const String & path_in_backup, DiskPtr destination_disk, const String & destination_path, WriteMode write_mode) { auto destination_data_source_description = destination_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, destination_data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, maskedDescription(destination_data_source_description)); if (destination_data_source_description.object_storage_type == ObjectStorageType::Azure && destination_data_source_description.is_encrypted == encrypted_in_backup) { @@ -132,7 +144,7 @@ BackupWriterAzureBlobStorage::BackupWriterAzureBlobStorage( const ContextPtr & context_, bool attempt_to_create_container) : BackupWriterDefault(read_settings_, write_settings_, getLogger("BackupWriterAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -162,7 +174,7 @@ void BackupWriterAzureBlobStorage::copyFileFromDisk( { /// Use the native copy as a more optimal way to copy a file from AzureBlobStorage to AzureBlobStorage if it's possible. auto source_data_source_description = src_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", source_data_source_description.description, data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", maskedDescription(source_data_source_description), data_source_description.description); if (source_data_source_description.object_storage_type == ObjectStorageType::Azure && source_data_source_description.is_encrypted == copy_encrypted) { diff --git a/src/Backups/BackupMetadataFinder.cpp b/src/Backups/BackupMetadataFinder.cpp index 46115481a708..4b3534b9b24b 100644 --- a/src/Backups/BackupMetadataFinder.cpp +++ b/src/Backups/BackupMetadataFinder.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -287,6 +288,16 @@ void BackupMetadataFinder::findTableInBackupImpl( ParserCreateQuery create_parser; ASTPtr create_table_query = parseQuery(create_parser, create_query_str, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + /// `BACKUP` writes the full definition, without `AS` (see `cleanupObjectDefinitionFromTemporaryFlags`). A definition that + /// inherits its engine with `AS` would let the access check of the restore see no engine, so it is rejected. + if (const auto & create = create_table_query->as(); !create.as_table.empty()) + throw Exception( + ErrorCodes::CANNOT_RESTORE_TABLE, + "The definition of {} in the backup uses AS {}, which BACKUP never writes", + tableNameWithTypeToString(table_name_in_backup.database, table_name_in_backup.table, false), + backQuoteIfNeed(create.as_table)); + applyCustomStoragePolicy(create_table_query); renameDatabaseAndTableNameInCreateQuery(create_table_query, renaming_map, context->getGlobalContext()); String create_table_query_str = create_table_query->formatWithSecretsOneLine(); diff --git a/src/Backups/RestorerFromBackup.cpp b/src/Backups/RestorerFromBackup.cpp index b1cfe0451a94..5c47fd9cea18 100644 --- a/src/Backups/RestorerFromBackup.cpp +++ b/src/Backups/RestorerFromBackup.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ namespace Setting extern const SettingsUInt64 backup_restore_keeper_max_retries; extern const SettingsSeconds lock_acquire_timeout; extern const SettingsBool restore_replicated_merge_tree_to_shared_merge_tree; + extern const SettingsBool restore_replace_external_engines_to_null; } namespace ErrorCodes @@ -276,6 +278,7 @@ void RestorerFromBackup::loadSystemAccessTables() void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const { AccessRightsElements required_access; + AccessRights required_access_rights; { std::lock_guard lock{mutex}; @@ -310,7 +313,17 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const continue; } - if (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE) + const ASTCreateQuery & create = table_info.create_table_query->as(); + const bool is_temporary = (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE); + + /// The definition comes from the backup, and the table is created by an internal query that checks + /// nothing, so settings that send the data elsewhere are authorized here, as for `CREATE`. + /// An external engine replaced by `Null` sends nothing, but temporary tables keep their engine. + if (restore_settings.create_table != RestoreTableCreationMode::kMustExist + && (is_temporary || !context->getSettingsRef()[Setting::restore_replace_external_engines_to_null])) + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + + if (is_temporary) { if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) required_access.emplace_back(AccessType::CREATE_TEMPORARY_TABLE); @@ -318,7 +331,6 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const } AccessFlags flags; - const ASTCreateQuery & create = table_info.create_table_query->as(); if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) { @@ -346,15 +358,12 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const required_access.emplace_back(flags, table_name.database, table_name.table); } + required_access_rights = AccessRights{required_access}; + /// Partial revokes in restored grants must not remove the rights required to restore other objects. if (access_restorer) - insertAtEnd(required_access, access_restorer->getRequiredAccess()); + required_access_rights.makeUnion(access_restorer->getRequiredAccess()); } - /// We convert to AccessRights to check if we have the rights contained in our current access. - /// This handles the situation when restoring partial revoked grants: - /// GRANT SELECT ON *.* - /// REVOKE SELECT FROM systems.* - const auto & required_access_rights = AccessRights{required_access}; const auto & current_user_access_rights = context->getAccess()->getAccessRightsWithImplicit(); if (current_user_access_rights->contains(required_access_rights)) return; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 88dcaa1fa6ab..469b3b3ad16f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -359,6 +359,10 @@ if (USE_PARQUET) add_object_library(clickhouse_processors_formats_impl_parquet Processors/Formats/Impl/Parquet) endif() +if (USE_ORC) + add_object_library(clickhouse_processors_formats_impl_orc Processors/Formats/Impl/ORC) +endif() + if (TARGET ch_contrib::nuraft) add_object_library(clickhouse_coordination Coordination) endif() @@ -642,11 +646,6 @@ endif() target_link_libraries (clickhouse_common_io PUBLIC ch_contrib::fast_float) -if (USE_ORC) - target_link_libraries(dbms PUBLIC ${ORC_LIBRARIES}) - target_include_directories(dbms SYSTEM BEFORE PUBLIC ${ORC_INCLUDE_DIR} "${PROJECT_BINARY_DIR}/contrib/orc/c++/include") -endif () - if (TARGET ch_contrib::rocksdb) target_link_libraries(dbms PUBLIC ch_contrib::rocksdb) endif() @@ -773,6 +772,10 @@ if (ENABLE_TESTS) clickhouse_common_config clickhouse_common_zookeeper) + if (TARGET ch_contrib::brotli) + target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::brotli) + endif() + if (TARGET ch_contrib::simdjson) target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::simdjson) endif() diff --git a/src/Client/ClientBase.cpp b/src/Client/ClientBase.cpp index dfa4234f2042..aa2e00344b73 100644 --- a/src/Client/ClientBase.cpp +++ b/src/Client/ClientBase.cpp @@ -3582,13 +3582,13 @@ void ClientBase::runInteractive() #if USE_REPLXX - replxx::Replxx::highlighter_callback_with_pos_t highlight_callback{}; + ReplxxLineReader::Highlighter highlight_callback{}; if (getClientConfiguration().getBool("highlight", true)) { - highlight_callback = [this](const String & query, std::vector & colors, int pos) + highlight_callback = [this](const String & query, std::vector & colors, int pos, bool & last_is_delimiter) { - highlight(query, colors, *client_context, pos); + highlight(query, colors, *client_context, pos, &last_is_delimiter); }; } diff --git a/src/Client/ClientBaseHelpers.cpp b/src/Client/ClientBaseHelpers.cpp index 3955d1d8edf2..28e01896beb4 100644 --- a/src/Client/ClientBaseHelpers.cpp +++ b/src/Client/ClientBaseHelpers.cpp @@ -155,7 +155,7 @@ static size_t countCodePointsWithSeqLength(const String & query, const char * en return code_points; } -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position) +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter) { using namespace replxx; @@ -512,14 +512,16 @@ void highlight(const String & query, std::vector & colors } /// This is a callback for the client/local app to better find query end. Note: this is a kludge, remove it. + if (!last_is_delimiter) + return; if (last_token.type == TokenType::Semicolon || last_token.type == TokenType::VerticalDelimiter || query.ends_with(';') || query.ends_with("\\G")) /// This is for raw data in INSERT queries, which is not necessarily tokenized. { - ReplxxLineReader::setLastIsDelimiter(true); + *last_is_delimiter = true; } else if (last_token.type != TokenType::Whitespace) { - ReplxxLineReader::setLastIsDelimiter(false); + *last_is_delimiter = false; } } @@ -528,7 +530,7 @@ String highlighted(const String & query, const Context & context) const size_t num_code_points = countCodePointsWithSeqLength(query, query.data() + query.size()); std::vector colors(num_code_points, replxx::Replxx::Color::DEFAULT); - highlight(query, colors, context, 0); + highlight(query, colors, context, 0, nullptr); String res; size_t query_size = query.size(); diff --git a/src/Client/ClientBaseHelpers.h b/src/Client/ClientBaseHelpers.h index 4e41e605f3f7..ad02976550df 100644 --- a/src/Client/ClientBaseHelpers.h +++ b/src/Client/ClientBaseHelpers.h @@ -24,7 +24,9 @@ std::string getChineseZodiac(); bool isCloudEndpoint(const std::string & host); #if USE_REPLXX -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position); +/// If `last_is_delimiter` is not null, it is set to whether the query ends with a delimiter (and left +/// intact if the query ends with whitespace). +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter); String highlighted(const String & query, const Context & context); #endif diff --git a/src/Client/ReplxxLineReader.cpp b/src/Client/ReplxxLineReader.cpp index 14842dbfd77e..c909f14beb44 100644 --- a/src/Client/ReplxxLineReader.cpp +++ b/src/Client/ReplxxLineReader.cpp @@ -286,12 +286,6 @@ void convertHistoryFile(const std::string & path, replxx::Replxx & rx) namespace DB { -static bool replxx_last_is_delimiter = false; -void ReplxxLineReader::setLastIsDelimiter(bool flag) -{ - replxx_last_is_delimiter = flag; -} - ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) : LineReader ( @@ -360,7 +354,12 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) rx.set_indent_multiline(false); if (highlighter) - rx.set_highlighter_callback(highlighter); + { + rx.set_highlighter_callback([this](const String & query, std::vector & colors, int cursor_position) + { + highlighter(query, colors, cursor_position, last_is_delimiter); + }); + } /// By default C-p/C-n bound to COMPLETE_NEXT/COMPLETE_PREV, /// bind C-p/C-n to history-previous/history-next like readline. @@ -376,9 +375,9 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) { /// If we allow multiline and there is already something in the input, start a newline. /// NOTE: Lexer is only available if we use highlighter. - if (highlighter && multiline && !replxx_last_is_delimiter) + if (highlighter && multiline && !last_is_delimiter) return rx.invoke(Replxx::ACTION::NEW_LINE, code); - replxx_last_is_delimiter = false; + last_is_delimiter = false; return rx.invoke(Replxx::ACTION::COMMIT_LINE, code); }; /// bind C-j to ENTER action. diff --git a/src/Client/ReplxxLineReader.h b/src/Client/ReplxxLineReader.h index cdaa5cab6be1..0dae383f8d53 100644 --- a/src/Client/ReplxxLineReader.h +++ b/src/Client/ReplxxLineReader.h @@ -12,6 +12,11 @@ namespace DB class ReplxxLineReader : public LineReader { public: + /// The highlighter callback of replxx, which also reports whether the last token of the + /// query is a delimiter: it sets `last_is_delimiter` to true or false, or leaves it intact + /// when this cannot be determined (e.g. the query ends with whitespace). + using Highlighter = std::function & colors, int cursor_position, bool & last_is_delimiter)>; + struct Options { Suggest & suggest; @@ -24,7 +29,7 @@ class ReplxxLineReader : public LineReader Patterns extenders; Patterns delimiters; std::span word_break_characters; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; std::istream & input_stream = std::cin; std::ostream & output_stream = std::cout; int in_fd = STDIN_FILENO; @@ -38,10 +43,6 @@ class ReplxxLineReader : public LineReader void enableBracketedPaste() override; void disableBracketedPaste() override; - /// If highlight is on, we will set a flag to denote whether the last token is a delimiter. - /// This is useful to determine the behavior of key when multiline is enabled. - static void setLastIsDelimiter(bool flag); - /// Set text to be prepopulated in the next readLine call void setInitialText(const String & text) override; private: @@ -51,7 +52,13 @@ class ReplxxLineReader : public LineReader void openEditor(bool format_query); replxx::Replxx rx; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; + + /// If highlight is on, the highlighter reports whether the last token is a delimiter. + /// This is used to determine the behavior of key when multiline is enabled. + /// It is a member rather than a global, because several readers can work concurrently + /// in one process (client sessions embedded into the server). + bool last_is_delimiter = false; const char * word_break_characters; diff --git a/src/Columns/ColumnArray.cpp b/src/Columns/ColumnArray.cpp index d572873dca0b..b1bc0921a153 100644 --- a/src/Columns/ColumnArray.cpp +++ b/src/Columns/ColumnArray.cpp @@ -978,17 +978,17 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi memset(&nested_filt[offsetAt(i)], 0, sizeAt(i)); } - auto res = ColumnArray::create(data->cloneEmpty()); - ssize_t nested_result_size_hint = 0; if (result_size_hint < 0) nested_result_size_hint = result_size_hint; else if (result_size_hint && result_size_hint < 1000000000 && data->size() < 1000000000) /// Avoid overflow. nested_result_size_hint = result_size_hint * data->size() / size; - res->data = data->filter(nested_filt, nested_result_size_hint); + /// See the comment in `indexImpl` about building the nested result first. + ColumnPtr res_data = data->filter(nested_filt, nested_result_size_hint); - Offsets & res_offsets = res->getOffsets(); + auto res_offsets_column = ColumnOffsets::create(); + Offsets & res_offsets = res_offsets_column->getData(); if (result_size_hint) res_offsets.reserve_exact(result_size_hint > 0 ? result_size_hint : size); @@ -1002,7 +1002,7 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi } } - return res; + return ColumnArray::create(res_data, std::move(res_offsets_column)); } ColumnPtr ColumnArray::filterNullable(const Filter & filt, ssize_t result_size_hint) const @@ -1236,10 +1236,8 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit PaddedPODArray & nested_indexes = nested_indexes_column->getData(); nested_indexes.reserve_exact(getOffsets().back()); - auto res = ColumnArray::create(data->cloneEmpty()); - - Offsets & res_offsets = res->getOffsets(); - res_offsets.resize_exact(limit); + auto res_offsets_column = ColumnOffsets::create(limit); + Offsets & res_offsets = res_offsets_column->getData(); size_t current_offset = 0; for (size_t i = 0; i < limit; ++i) @@ -1250,10 +1248,10 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit res_offsets[i] = current_offset; } - if (current_offset != 0) - res->data = data->index(*nested_indexes_column, current_offset); - - return res; + /// Build the nested result first: an empty clone of `data` copies its whole nested structure, which for + /// `Dynamic` is as deep as the data, and every level of this recursion would hold one. + ColumnPtr res_data = current_offset != 0 ? data->index(*nested_indexes_column, current_offset) : data->cloneEmpty(); + return ColumnArray::create(res_data, std::move(res_offsets_column)); } INSTANTIATE_INDEX_IMPL(ColumnArray) diff --git a/src/Columns/ColumnDynamic.cpp b/src/Columns/ColumnDynamic.cpp index 59ed075737df..446f5c38042e 100644 --- a/src/Columns/ColumnDynamic.cpp +++ b/src/Columns/ColumnDynamic.cpp @@ -314,6 +314,8 @@ void ColumnDynamic::get(size_t n, Field & res) const void ColumnDynamic::getValueNameImpl(WriteBufferFromOwnString & name_buf, size_t n, const Options & options) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); /// Check if value is not in shared variant. if (variant_col.globalDiscriminatorAt(n) != getSharedVariantDiscriminator()) @@ -338,6 +340,8 @@ void ColumnDynamic::insertFrom(const IColumn & src_, size_t n) void ColumnDynamic::doInsertFrom(const IColumn & src_, size_t n) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); /// Same variants: copy the Variant column directly. Skip this fast path when the source has values in @@ -417,6 +421,8 @@ void ColumnDynamic::insertRangeFrom(const IColumn & src_, size_t start, size_t l void ColumnDynamic::doInsertRangeFrom(const IColumn & src_, size_t start, size_t length) #endif { + checkStackSize(); + if (start + length > src_.size()) throw Exception(ErrorCodes::PARAMETER_OUT_OF_BOUND, "Parameter out of bound in ColumnDynamic::insertRangeFrom method. " "[start({}) + length({}) > src.size()({})]", start, length, src_.size()); @@ -649,6 +655,8 @@ void ColumnDynamic::insertManyFrom(const IColumn & src_, size_t position, size_t void ColumnDynamic::doInsertManyFrom(const IColumn & src_, size_t position, size_t length) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); auto & variant_col = getVariantColumn(); @@ -862,6 +870,8 @@ void ColumnDynamic::skipSerializedInArena(ReadBuffer & in) const void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); auto discr = variant_col.globalDiscriminatorAt(n); if (discr == ColumnVariant::NULL_DISCRIMINATOR) @@ -892,6 +902,7 @@ void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const void ColumnDynamic::updateHashWithValueRange(size_t begin, size_t end, SipHash & hash) const { + checkStackSize(); variant_column_ptr->updateHashWithValueRange(begin, end, hash); } @@ -901,6 +912,8 @@ int ColumnDynamic::compareAt(size_t n, size_t m, const IColumn & rhs, int nan_di int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_direction_hint) const #endif { + checkStackSize(); + const auto & left_variant = getVariantColumn(); const auto & right_dynamic = assert_cast(rhs); const auto & right_variant = right_dynamic.getVariantColumn(); @@ -1050,6 +1063,7 @@ void ColumnDynamic::updatePermutation(IColumn::PermutationSortDirection directio ColumnPtr ColumnDynamic::compress(bool force_compression) const { + checkStackSize(); ColumnPtr variant_compressed = variant_column_ptr->compress(force_compression); size_t byte_size = variant_compressed->byteSize(); return ColumnCompressed::create(size(), byte_size, @@ -1061,6 +1075,7 @@ ColumnPtr ColumnDynamic::compress(bool force_compression) const ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const { + checkStackSize(); std::unordered_map variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) variants_checkpoints[name] = variant_column_ptr->getVariantByGlobalDiscriminator(discr).getCheckpoint(); @@ -1069,6 +1084,7 @@ ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const { + checkStackSize(); auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) @@ -1086,6 +1102,7 @@ void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const void ColumnDynamic::rollback(const ColumnCheckpoint & checkpoint) { + checkStackSize(); const auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; /// Manually rollback internals of Variant column @@ -1158,6 +1175,7 @@ void ColumnDynamic::getAllTypeNamesInto(UnorderedSetWithMemoryTracking & void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); if (source_columns.empty()) return; @@ -1181,6 +1199,7 @@ void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t f void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); /// Internal variants of source dynamic columns may differ. /// We want to preallocate memory for all variants we will have after squashing. /// It may happen that the total number of variants in source columns will @@ -1288,6 +1307,8 @@ void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const { + checkStackSize(); + if (const auto * rhs_concrete = typeid_cast(&rhs)) return max_dynamic_types == rhs_concrete->max_dynamic_types && global_max_dynamic_types == rhs_concrete->global_max_dynamic_types && variant_info.variant_name == rhs_concrete->variant_info.variant_name @@ -1297,6 +1318,8 @@ bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_columns, std::optional max_dynamic_subcolumns) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "chooseDynamicStructureForMerge should be called only on empty Dynamic column"); @@ -1431,6 +1454,8 @@ void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_column void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "takeExactDynamicStructureFrom should be called only on empty Dynamic column"); @@ -1453,6 +1478,8 @@ void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) void ColumnDynamic::fixDynamicStructure() { + checkStackSize(); + /// Reduce max_dynamic_types to the number of selected variants, so there will be no possibility /// to extend selected variants on inserts into this column. /// -1 because we don't count shared variant in the limit. @@ -1487,6 +1514,8 @@ ColumnDynamic::StatisticsPtr ColumnDynamic::getOrCalculateStatistics() const void ColumnDynamic::takeOrCalculateStatisticsFrom(const Columns & source_columns) { + checkStackSize(); + /// Assumes dynamic structure has already been set by `takeExactDynamicStructureFrom` or `chooseDynamicStructureForMerge`. Statistics new_statistics; /// Collect total sizes for variants that are not in our structure (candidates for shared variant statistics). diff --git a/src/Columns/ColumnDynamic.h b/src/Columns/ColumnDynamic.h index cac25ec194e5..594512677430 100644 --- a/src/Columns/ColumnDynamic.h +++ b/src/Columns/ColumnDynamic.h @@ -7,6 +7,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,10 @@ namespace DB * When the limit on number of dynamic types is exceeded, all values * with new types are inserted into special shared variant with type String * that contains values and their types in binary format. + * + * Values nest into each other through variants like Array(Dynamic) to a depth that comes + * from the data, not from the declared type, so methods that recurse into the Variant + * column call checkStackSize. */ class ColumnDynamic final : public COWHelper, ColumnDynamic> { @@ -116,12 +121,14 @@ class ColumnDynamic final : public COWHelper, Colum MutableColumnPtr cloneEmpty() const override { + checkStackSize(); /// Keep current dynamic structure return Base::create(variant_column->cloneEmpty(), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumnPtr cloneResized(size_t size) const override { + checkStackSize(); return Base::create(variant_column->cloneResized(size), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } @@ -181,6 +188,7 @@ class ColumnDynamic final : public COWHelper, Colum void popBack(size_t n) override { + checkStackSize(); variant_column_ptr->popBack(n); } @@ -204,42 +212,50 @@ class ColumnDynamic final : public COWHelper, Colum void updateHashFast(SipHash & hash) const override { + checkStackSize(); variant_column_ptr->updateHashFast(hash); } ColumnPtr filter(const Filter & filt, ssize_t result_size_hint) const override { + checkStackSize(); return create(variant_column_ptr->filter(filt, result_size_hint), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } void filter(const Filter & filt) override { + checkStackSize(); variant_column_ptr->filter(filt); statistics.reset(); } void expand(const Filter & mask, bool inverted) override { + checkStackSize(); variant_column_ptr->expand(mask, inverted); } ColumnPtr permute(const Permutation & perm, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->permute(perm, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr index(const IColumn & indexes, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->index(indexes, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr replicate(const Offsets & replicate_offsets) const override { + checkStackSize(); return create(variant_column_ptr->replicate(replicate_offsets), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumns scatter(size_t num_columns, const Selector & selector) const override { + checkStackSize(); MutableColumns scattered_variant_columns = variant_column_ptr->scatter(num_columns, selector); MutableColumns scattered_columns; scattered_columns.reserve(num_columns); @@ -257,6 +273,7 @@ class ColumnDynamic final : public COWHelper, Colum bool hasEqualValues() const override { + checkStackSize(); return variant_column_ptr->hasEqualValues(); } @@ -287,31 +304,37 @@ class ColumnDynamic final : public COWHelper, Colum void shrinkToFit() override { + checkStackSize(); variant_column_ptr->shrinkToFit(); } void ensureOwnership() override { + checkStackSize(); variant_column_ptr->ensureOwnership(); } size_t byteSize() const override { + checkStackSize(); return variant_column_ptr->byteSize(); } size_t byteSizeAt(size_t n) const override { + checkStackSize(); return variant_column_ptr->byteSizeAt(n); } size_t allocatedBytes() const override { + checkStackSize(); return variant_column_ptr->allocatedBytes(); } void protect() override { + checkStackSize(); variant_column_ptr->protect(); } @@ -323,11 +346,17 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumn(MutableColumnCallback callback) override { + /// Callers like IColumn::mutate recurse into the subcolumns through this method. + checkStackSize(); callback(variant_column); variant_column_ptr = assert_cast(variant_column.get()); } - void forEachSubcolumn(ColumnCallback callback) const override { callback(variant_column); } + void forEachSubcolumn(ColumnCallback callback) const override + { + checkStackSize(); + callback(variant_column); + } /// Dynamic columns manage their own variant_info type metadata. /// The default convertToFullIfNeeded recurses into subcolumns and strips LowCardinality @@ -337,6 +366,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumnRecursively(RecursiveMutableColumnCallback callback) override { + checkStackSize(); callback(*variant_column); variant_column_ptr = assert_cast(variant_column.get()); variant_column->forEachMutableSubcolumnRecursively(callback); @@ -344,6 +374,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachSubcolumnRecursively(RecursiveColumnCallback callback) const override { + checkStackSize(); callback(*variant_column); variant_column->forEachSubcolumnRecursively(callback); } @@ -374,11 +405,13 @@ class ColumnDynamic final : public COWHelper, Colum void finalize() override { + checkStackSize(); variant_column_ptr->finalize(); } bool isFinalized() const override { + checkStackSize(); return variant_column_ptr->isFinalized(); } diff --git a/src/Columns/ColumnLowCardinality.cpp b/src/Columns/ColumnLowCardinality.cpp index 9a76fde596b9..a6540dbf60c3 100644 --- a/src/Columns/ColumnLowCardinality.cpp +++ b/src/Columns/ColumnLowCardinality.cpp @@ -234,7 +234,7 @@ void ColumnLowCardinality::insertRangeFromFullColumn(const IColumn & src, size_t idx.insertIndexesRange(*inserted_indexes, 0, length); } -static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) +void ColumnLowCardinality::checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) { auto check_for_type = [&](auto type) { @@ -248,14 +248,14 @@ static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) size_t num_rows = data.size(); if (num_rows == 0) return true; - UInt64 max_position = 0; + ColumnType max_position = 0; for (size_t i = 0; i < num_rows; ++i) - max_position = std::max(max_position, data[i]); + max_position = std::max(max_position, data[i]); - if (max_position >= limit) + if (static_cast(max_position) >= limit) throw Exception(ErrorCodes::INCORRECT_DATA, "Index for LowCardinality is out of range. Dictionary size is {}, " - "but found index with value {}", limit, max_position); + "but found index with value {}", limit, static_cast(max_position)); return true; }; diff --git a/src/Columns/ColumnLowCardinality.h b/src/Columns/ColumnLowCardinality.h index 8538b4cededf..d03921bef1fe 100644 --- a/src/Columns/ColumnLowCardinality.h +++ b/src/Columns/ColumnLowCardinality.h @@ -94,6 +94,7 @@ class ColumnLowCardinality final : public COWHelper +#include #include #include #include @@ -16,6 +17,12 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace FailPoints +{ + extern const char reverse_index_build_index_throw[]; } template @@ -432,17 +439,25 @@ void ReverseIndex::buildIndex() if (!column) throw Exception(ErrorCodes::LOGICAL_ERROR, "ReverseIndex can't build index because index column wasn't set."); + /// Build everything into local variables and publish them only at the end, so that an exception + /// thrown midway (for example, `MEMORY_LIMIT_EXCEEDED` from an allocation in `calcHashes`) does not + /// leave a half-built index behind: a non-null `index` with a null `saved_hash` would make the next + /// `insert` dereference a null pointer. auto size = column->size(); - index = std::make_unique(size); + auto new_index = std::make_unique(size); + fiu_do_on(FailPoints::reverse_index_build_index_throw, + throw Exception(ErrorCodes::MEMORY_LIMIT_EXCEEDED, "Injected failure while building ReverseIndex");); + + ColumnUInt64::MutablePtr new_saved_hash; if constexpr (use_saved_hash) - saved_hash = calcHashes(); + new_saved_hash = calcHashes(); - auto & state = index->getState(); + auto & state = new_index->getState(); state.index_column = column; state.base_index = base_index; if constexpr (use_saved_hash) - state.saved_hash_column = &saved_hash->getData(); + state.saved_hash_column = &new_saved_hash->getData(); using IteratorType = typename IndexMapType::iterator; IteratorType iterator; @@ -452,15 +467,18 @@ void ReverseIndex::buildIndex() { UInt64 hash; if constexpr (use_saved_hash) - hash = saved_hash->getElement(row); + hash = new_saved_hash->getElement(row); else hash = getHash(column->getDataAt(row)); - index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); + new_index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); if (!inserted) throw Exception(ErrorCodes::LOGICAL_ERROR, "Duplicating keys found in ReverseIndex."); } + + index = std::move(new_index); + saved_hash = std::move(new_saved_hash); } template @@ -484,37 +502,58 @@ UInt64 ReverseIndex::insert(std::string_view data) if (!index) buildIndex(); - using IteratorType = typename IndexMapType::iterator; - IteratorType iterator; - bool inserted; - - auto hash = getHash(data); - UInt64 num_rows = size(); - - if constexpr (use_saved_hash) + try { - auto & column_data = saved_hash->getData(); - if (column_data.size() <= num_rows) - column_data.resize(num_rows + 1); - column_data[num_rows] = hash; - } - else - column->insertData(data.data(), data.size()); + using IteratorType = typename IndexMapType::iterator; + IteratorType iterator; + bool inserted = false; - index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + auto hash = getHash(data); + UInt64 num_rows = size(); - if constexpr (use_saved_hash) - { - if (inserted) + if constexpr (use_saved_hash) + { + auto & column_data = saved_hash->getData(); + if (column_data.size() <= num_rows) + column_data.resize(num_rows + 1); + column_data[num_rows] = hash; + } + else column->insertData(data.data(), data.size()); + + index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + + if constexpr (use_saved_hash) + { + if (inserted) + column->insertData(data.data(), data.size()); + } + else + { + if (!inserted) + column->popBack(1); + } + + return iterator->getValue(); } - else + catch (...) { - if (!inserted) - column->popBack(1); - } + /// The hash table may now disagree with the column: for example, the key was already added to the + /// hash table, but `insertData` failed, so the key refers to a row that does not exist. Drop the index, + /// it is rebuilt from the column on the next use. + index = nullptr; + saved_hash = nullptr; - return iterator->getValue(); + if constexpr (std::is_same_v) + { + /// `ColumnString::insertData` appends to `chars` before it grows `offsets`. If the latter failed, the bytes + /// of the row that was never added are still there and would become a prefix of the next inserted value. + const auto & offsets = column->getOffsets(); + column->getChars().resize_assume_reserved(offsets.empty() ? 0 : offsets.back()); + } + + throw; + } } template diff --git a/src/Columns/tests/gtest_reverse_index_exception_safety.cpp b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp new file mode 100644 index 000000000000..f0826e7359d1 --- /dev/null +++ b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace DB::FailPoints +{ + extern const char reverse_index_build_index_throw[]; +} + +using namespace DB; + +/// Mimics what happens during an asynchronous insert flush under memory pressure: the first insert into a +/// `LowCardinality` dictionary throws `MEMORY_LIMIT_EXCEEDED` while the reverse index is being built, the error +/// is handled by the caller, and the same dictionary is reused for the next entry. The index must either be +/// fully built or absent, never a non-null hash table paired with a null saved-hash array. +TEST(ReverseIndex, ExceptionWhileBuildingIndexLeavesNoHalfBuiltIndex) +{ + auto column = ColumnUnique::create(DataTypeString()); + + FailPointInjection::enableFailPoint(FailPoints::reverse_index_build_index_throw); + try + { + column->uniqueInsertData("a", 1); + FAIL() << "Expected an exception from the failpoint"; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::MEMORY_LIMIT_EXCEEDED); + } + FailPointInjection::disableFailPoint(FailPoints::reverse_index_build_index_throw); + + /// Index 0 is the default value (empty string). + EXPECT_EQ(column->size(), 1u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("b", 1), 2u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("", 0), 0u); + EXPECT_EQ(column->size(), 3u); + EXPECT_EQ(column->getDataAt(1), "a"); + EXPECT_EQ(column->getDataAt(2), "b"); +} + +/// The same reuse after a failure inside `insert` itself: the key is already in the hash table and the string bytes are +/// already appended to `chars` when growing `offsets` fails. The dictionary must come back to the state before the +/// insert, so that the next inserted value does not get the failed one as a prefix and lookups stay correct. +TEST(ReverseIndex, ExceptionWhileInsertingDataKeepsDictionaryConsistent) +{ + MainThreadStatus::getInstance(); + auto & thread_tracker = CurrentThread::get().memory_tracker; + + auto column = ColumnUnique::create(DataTypeString()); + ASSERT_EQ(column->uniqueInsertData("a", 1), 1u); + + /// Leave `offsets` without spare capacity and `chars` with plenty, so that growing `offsets` is the only + /// allocation of the next insert. + auto & nested = assert_cast(column->getNestedColumn()->assumeMutableRef()); + nested.getOffsets().shrink_to_fit(); + nested.getChars().reserve(nested.getChars().size() + 1024); + + const Int64 saved_untracked_limit = CurrentThread::get().untracked_memory_limit; + const Int64 saved_thread_hard_limit = thread_tracker.getHardLimit(); + const Int64 saved_total_hard_limit = total_memory_tracker.getHardLimit(); + + auto lift_limits = [&] + { + total_memory_tracker.setHardLimit(saved_total_hard_limit); + thread_tracker.setHardLimit(saved_thread_hard_limit); + CurrentThread::get().untracked_memory_limit = saved_untracked_limit; + }; + SCOPE_EXIT_SAFE(lift_limits()); + + /// Make even a tiny allocation reach the trackers and fail: no per-thread untracked buffer, limits of one byte. + CurrentThread::get().untracked_memory_limit = 0; + CurrentThread::flushUntrackedMemory(); + total_memory_tracker.resetCounters(); + thread_tracker.resetCounters(); + total_memory_tracker.setHardLimit(1); + thread_tracker.setHardLimit(1); + + bool thrown = false; + int code = 0; + try + { + column->uniqueInsertData("bb", 2); + } + catch (const Exception & e) + { + thrown = true; + code = e.code(); + } + + /// Lift the limits before anything else, the assertions allocate. + lift_limits(); + + ASSERT_TRUE(thrown) << "the insert was expected to fail under the memory limit"; + EXPECT_EQ(code, ErrorCodes::MEMORY_LIMIT_EXCEEDED); + + EXPECT_EQ(column->size(), 2u); + EXPECT_EQ(nested.getChars().size(), nested.getOffsets().back()); + + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->getDataAt(2), "c"); + EXPECT_EQ(column->uniqueInsertData("bb", 2), 3u); + EXPECT_EQ(column->getDataAt(3), "bb"); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->size(), 4u); +} diff --git a/src/Common/CurrentMetrics.cpp b/src/Common/CurrentMetrics.cpp index 84d3b3c5bd0e..c88478725f6e 100644 --- a/src/Common/CurrentMetrics.cpp +++ b/src/Common/CurrentMetrics.cpp @@ -323,6 +323,8 @@ M(AsyncInsertCacheSize, "Number of async insert hash id in cache") \ M(IcebergMetadataFilesCacheBytes, "Size of the Iceberg metadata cache in bytes") \ M(IcebergMetadataFilesCacheFiles, "Number of cached files in the Iceberg metadata cache") \ + M(GlueCatalogSchemaCacheBytes, "Size of the cache of current Iceberg schema field types in Glue catalogs in bytes") \ + M(GlueCatalogSchemaCacheEntries, "Number of entries in the cache of current Iceberg schema field types in Glue catalogs") \ M(ParquetMetadataCacheBytes, "Size of the Parquet metadata cache in bytes") \ M(ParquetMetadataCacheFiles, "Number of cached files in the Parquet metadata cache") \ M(AvroSchemaCacheBytes, "Size of the Avro schema cache in bytes") \ diff --git a/src/Common/DateLUTImpl.h b/src/Common/DateLUTImpl.h index 4ac32f91a97e..690a6496ab53 100644 --- a/src/Common/DateLUTImpl.h +++ b/src/Common/DateLUTImpl.h @@ -561,21 +561,15 @@ class DateLUTImpl { const LUTIndex index = findIndex(t); - /// Calculate daylight saving offset first. - /// Because the "amount_of_offset_change" in LUT entry only exists in the change day, it's costly to scan it from the very begin. - /// but we can figure out all the accumulated offsets from 1970-01-01 to that day just by get the whole difference between lut[].date, - /// and then, we can directly subtract multiple 86400s to get the real DST offsets for the leap seconds is not considered now. - Time res = (lut[index].date - lut[daynum_offset_epoch].date) % 86400; - - /// As so far to know, the maximal DST offset couldn't be more than 2 hours, so after the modulo operation the remainder - /// will sits between [-offset --> 0 --> offset] which respectively corresponds to moving clock forward or backward. - res = res > 43200 ? (86400 - res) : (0 - res); + /// The offset at the start of the day: local midnight is `day_number * 86400` seconds of local + /// time from the epoch, while `date` is the UTC instant of that same midnight. + Time res = (static_cast(index.toUnderType()) - daynum_offset_epoch) * 86400 - lut[index].date; /// Check if has a offset change during this day. Add the change when cross the line if (lut[index].amount_of_offset_change() != 0 && t >= lut[index].date + lut[index].time_at_offset_change()) res += lut[index].amount_of_offset_change(); - return res + offset_at_start_of_epoch; + return res; } diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 875173c92b8b..7dfb2f297886 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -34,6 +34,7 @@ static struct InitFiu #define APPLY_FOR_FAILPOINTS(ONCE, REGULAR, PAUSEABLE_ONCE, PAUSEABLE) \ ONCE(replicated_merge_tree_commit_zk_fail_after_op) \ ONCE(replicated_queue_fail_next_entry) \ + ONCE(reverse_index_build_index_throw) \ REGULAR(replicated_queue_unfail_entries) \ ONCE(replicated_merge_tree_insert_quorum_fail_0) \ REGULAR(replicated_merge_tree_commit_zk_fail_when_recovering_from_hw_fault) \ @@ -96,6 +97,7 @@ static struct InitFiu PAUSEABLE_ONCE(finish_clean_quorum_failed_parts) \ PAUSEABLE_ONCE(smt_wait_next_mutation) \ PAUSEABLE_ONCE(delta_lake_metadata_iterate_pause) \ + PAUSEABLE_ONCE(rmt_restore_replica_pause_before_metadata_version_raise) \ PAUSEABLE(dummy_pausable_failpoint) \ ONCE(execute_query_calling_empty_set_result_func_on_exception) \ ONCE(terminate_with_exception) \ @@ -129,6 +131,7 @@ static struct InitFiu REGULAR(database_replicated_delay_recovery) \ REGULAR(database_replicated_delay_entry_execution) \ PAUSEABLE(database_replicated_stop_entry_execution) \ + PAUSEABLE_ONCE(database_replicated_pause_before_initial_query_execution) \ REGULAR(remove_merge_tree_part_delay) \ REGULAR(plain_object_storage_copy_temp_source_file_fail_on_file_move) \ REGULAR(plain_object_storage_copy_temp_target_file_fail_on_file_move) \ diff --git a/src/Common/RemoteHostFilter.cpp b/src/Common/RemoteHostFilter.cpp index 6f953f48d48b..5b5da5ec7c6b 100644 --- a/src/Common/RemoteHostFilter.cpp +++ b/src/Common/RemoteHostFilter.cpp @@ -110,6 +110,10 @@ bool RemoteHostFilter::checkForDirectEntry(const std::string & str) const /// Allow everything by default. return true; + /// Connectors take the host as a C string and stop at the first NUL, so the checked string must not contain one. + if (str.contains('\0')) + return false; + std::lock_guard guard(hosts_mutex); if (primary_hosts.contains(str)) diff --git a/src/Common/Scheduler/CPUSlotsAllocation.cpp b/src/Common/Scheduler/CPUSlotsAllocation.cpp index a11e4a6feb9a..30d9d735e60d 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.cpp +++ b/src/Common/Scheduler/CPUSlotsAllocation.cpp @@ -7,6 +7,7 @@ #include #include #include +#include namespace ProfileEvents { @@ -72,6 +73,10 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker for (CPUSlotRequest & request : requests) request.allocation = this; + wait_thread_group = CurrentThread::getGroup(); + if (wait_thread_group) + wait_counters = &wait_thread_group->performance_counters; + std::unique_lock lock{schedule_mutex}; while (allocated < total_slots) { @@ -79,7 +84,7 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker { queue->enqueueRequest(current_request); scheduled_slot_increment.emplace(CurrentMetrics::ConcurrencyControlScheduled); - wait_timer.emplace(CurrentThread::getProfileEvents().timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); + wait_timer.emplace(wait_counters->timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); break; } else // noncompeting slot - provide for free diff --git a/src/Common/Scheduler/CPUSlotsAllocation.h b/src/Common/Scheduler/CPUSlotsAllocation.h index d8963f14b8cf..caaf37139b25 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.h +++ b/src/Common/Scheduler/CPUSlotsAllocation.h @@ -17,6 +17,7 @@ namespace DB { class CPUSlotsAllocation; +class ThreadGroup; // Represents a resource request for a cpu slot for a single thread class CPUSlotRequest final : public ResourceRequest @@ -113,6 +114,9 @@ class CPUSlotsAllocation final : public ISlotAllocation std::vector requests; // Requests per every slot CPUSlotRequest * current_request; std::optional scheduled_slot_increment; + /// `wait_timer` may end on another thread after the creating one has exited, so it counts into the query's group, kept alive here. + std::shared_ptr wait_thread_group; + ProfileEvents::Counters * wait_counters = &ProfileEvents::global_counters; std::optional wait_timer; }; diff --git a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp index 0c6ba16e64d4..cdc0b8f1ad07 100644 --- a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp +++ b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -49,6 +51,7 @@ namespace ProfileEvents { extern const Event ConcurrencyControlUpscales; extern const Event ConcurrencyControlDownscales; + extern const Event ConcurrencyControlWaitMicroseconds; } namespace CurrentMetrics @@ -1068,6 +1071,41 @@ TEST(SchedulerWorkloadResourceManager, CPUSchedulingRoundRobin) t.wait(); } +/// The wait for a CPU slot is accounted to the query even when the allocation outlives the thread that created it +/// (here: destroyed on another thread while its request is still queued, like a `KILL QUERY` of a waiting query). +TEST(SchedulerWorkloadResourceManager, CPUSlotsWaitTimerOutlivesCreatingThread) +{ + ResourceTest t; + t.query("CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD)"); + t.query("CREATE WORKLOAD all SETTINGS max_concurrent_threads = 1"); + ClassifierPtr c = t.manager->acquire("all"); + ResourceLink link = c->get("cpu"); + + /// Takes the only slot, so the next allocation keeps its request queued. + auto blocker = std::make_shared(1, 0, link, link); + auto blocker_slot = blocker->acquire(); + + std::weak_ptr weak_group; + SlotAllocationPtr allocation; + std::thread([&] + { + DB::ThreadStatus thread_status; + auto group = std::make_shared(Context::getGlobalContextInstance(), 0); + weak_group = group; + CurrentThread::attachToGroupIfDetached(group); + allocation = std::make_shared(1, 0, link, link); + CurrentThread::detachFromGroupIfNotDetached(); + }).join(); + + ASSERT_TRUE(allocation->isRequesting()); + /// The creating thread is gone, so only the allocation can still own the group. + ThreadGroupPtr group = weak_group.lock(); + ASSERT_NE(group, nullptr); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + allocation.reset(); + EXPECT_GE(group->performance_counters[ProfileEvents::ConcurrencyControlWaitMicroseconds], 10'000); +} + TEST(SchedulerWorkloadResourceManager, CPUSchedulingFairness) { ResourceTest t; diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 15b5d71e193c..3054e98b8259 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -116,7 +116,10 @@ ThreadStatus::ThreadStatus() last_rusage = std::make_unique(); memory_tracker.setDescription("Thread"); - log = getLogger("ThreadStatus"); + /// A `ThreadStatus` is created for every job of a thread pool, and `getLogger` locks the global mutex of the + /// registry of loggers, so all threads of the pools would contend on it. + static const LoggerPtr thread_status_log = getLogger("ThreadStatus"); + log = thread_status_log; current_thread = this; diff --git a/src/Common/ZooKeeper/ZooKeeperConstants.h b/src/Common/ZooKeeper/ZooKeeperConstants.h index d5c5cc119fb5..7e61d02e91c1 100644 --- a/src/Common/ZooKeeper/ZooKeeperConstants.h +++ b/src/Common/ZooKeeper/ZooKeeperConstants.h @@ -92,6 +92,8 @@ static constexpr int32_t PASSWORD_LENGTH = 16; static constexpr int32_t MAX_STRING_OR_ARRAY_SIZE = 1 << 28; /// 256 MiB /// Upper bound on elements reserved up front when reading an array; the declared size is attacker-controlled static constexpr int32_t MAX_ARRAY_PREALLOCATION = 4096; +/// Bytes read per step when reading a string; the declared size is attacker-controlled, so memory grows with the bytes received +static constexpr int32_t MAX_STRING_PREALLOCATION = 1 << 16; /// 64 KiB static constexpr int32_t DEFAULT_SESSION_TIMEOUT_MS = 30000; static constexpr int32_t DEFAULT_MIN_SESSION_TIMEOUT_MS = 10000; static constexpr int32_t DEFAULT_MAX_SESSION_TIMEOUT_MS = 100000; diff --git a/src/Common/ZooKeeper/ZooKeeperIO.cpp b/src/Common/ZooKeeper/ZooKeeperIO.cpp index 88de2b4dc01d..c872bdac795e 100644 --- a/src/Common/ZooKeeper/ZooKeeperIO.cpp +++ b/src/Common/ZooKeeper/ZooKeeperIO.cpp @@ -93,11 +93,24 @@ void read(std::string & s, ReadBuffer & in) if (size > MAX_STRING_OR_ARRAY_SIZE) throw Exception(Error::ZMARSHALLINGERROR,"Too large string size while reading from ZooKeeper {}", size); - s.resize(size); - size_t read_bytes = in.read(s.data(), size); - if (read_bytes != static_cast(size)) - throw Exception( - Error::ZMARSHALLINGERROR, "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", size, read_bytes); + /// Memory must track bytes actually read, not the declared size: + /// do not pre-allocate for an attacker-controlled length. + s.clear(); + size_t remaining = static_cast(size); + while (remaining > 0) + { + const size_t chunk = std::min(remaining, MAX_STRING_PREALLOCATION); + const size_t old_size = s.size(); + s.resize(old_size + chunk); + const size_t read_bytes = in.read(s.data() + old_size, chunk); + if (read_bytes != chunk) + throw Exception( + Error::ZMARSHALLINGERROR, + "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", + size, + old_size + read_bytes); + remaining -= chunk; + } } void read(ACL & acl, ReadBuffer & in) diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index d368e482aa8c..a4f762ec2d57 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -2,14 +2,69 @@ #include +#include #include #include #include +#include namespace DB { +/** Hides the secrets of an Azure connection string as the Azure SDK reads it (`Azure::Storage::_internal::ParseConnectionString`, + * `contrib/azure/sdk/storage/azure-storage-common/src/storage_credential.cpp`): a key runs to '=' and its value to ';', keys + * match exactly, and the last copy of a repeated key wins. Splitting at every ';' first can only hide more than the SDK reads. + * - secret keys: `AccountName=a;AccountKey=K;SharedAccessSignature=S` -> `AccountName=a;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]` + * - repeated keys: `AccountKey=K1;AccountKey=K2` -> `AccountKey=[HIDDEN];AccountKey=[HIDDEN]` + * - an endpoint is a url, so a query in it is a SAS: `BlobEndpoint=https://h/?sig=S` or `BlobEndpoint=https://u@h/` -> `BlobEndpoint=[HIDDEN]` + * - the whole string is hidden when a '?', '#' or '@' is still shown, or when it has one and holds a url outside the pair + * values (':' or '/' in a key or in a part without '='; no key has them): `https://h/?sig=S` or `https://u:p=s@h/` -> `[HIDDEN]` + * Returns whether anything was hidden. + */ +inline bool maskAzureConnectionStringSecrets(std::string & str) +{ + static constexpr std::array secret_keys = {"AccountKey", "SharedAccessSignature"}; + auto is_secret_key = [](std::string_view key) { return std::ranges::find(secret_keys, key) != secret_keys.end(); }; + + const bool has_url_delimiters = str.find_first_of("?#@") != std::string::npos; + bool url_outside_values = false; + std::string result; + size_t copied = 0; + bool masked = false; + for (size_t part_begin = 0; part_begin <= str.length();) + { + const size_t part_end = std::min(str.find(';', part_begin), str.length()); + const std::string_view part = std::string_view(str).substr(part_begin, part_end - part_begin); + const size_t equals = part.find('='); + if (part.substr(0, equals).find_first_of(":/") != std::string_view::npos) + url_outside_values = true; + if (equals != std::string_view::npos + && (is_secret_key(part.substr(0, equals)) || part.substr(equals + 1).find_first_of("?@") != std::string_view::npos)) + { + const size_t value_begin = part_begin + equals + 1; + result.append(str, copied, value_begin - copied); + result.append("[HIDDEN]"); + copied = part_end; + masked = true; + } + part_begin = part_end + 1; + } + + if (masked) + { + result.append(str, copied, std::string::npos); + str = std::move(result); + } + + if (str.find_first_of("?#@") != std::string::npos || (url_outside_values && has_url_delimiters)) + { + str = "[HIDDEN]"; + return true; + } + return masked; +} + inline bool maskURIPassword(std::string * uri) { return RE2::Replace(uri, R"(([^:]+://[^:]*):([^@]*)@(.*))", "\\1:[HIDDEN]@\\3"); diff --git a/src/Common/mysqlxx/Connection.cpp b/src/Common/mysqlxx/Connection.cpp index f9f2d3e5d1aa..8614bed72705 100644 --- a/src/Common/mysqlxx/Connection.cpp +++ b/src/Common/mysqlxx/Connection.cpp @@ -114,6 +114,14 @@ void Connection::connect(const char* db, if (mysql_ssl_set(driver.get(), ifNotEmpty(ssl_key), ifNotEmpty(ssl_cert), ifNotEmpty(ssl_ca), nullptr, nullptr)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// Without an explicit socket, use TCP to the given port: otherwise `localhost` goes to the library's default socket. + if (!ifNotEmpty(socket)) + { + unsigned protocol = MYSQL_PROTOCOL_TCP; + if (mysql_options(driver.get(), MYSQL_OPT_PROTOCOL, &protocol)) + throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + } + if (!mysql_real_connect(driver.get(), server, user, password, db, port, ifNotEmpty(socket), driver->client_flag)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); diff --git a/src/Common/mysqlxx/Pool.cpp b/src/Common/mysqlxx/Pool.cpp index 7173adf3326c..58d54882fa6c 100644 --- a/src/Common/mysqlxx/Pool.cpp +++ b/src/Common/mysqlxx/Pool.cpp @@ -9,11 +9,61 @@ #include #include #include +#include #include #include #include +namespace DB::ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + +namespace +{ + +/// `mysql_real_connect` reinterprets these hosts and port 0; reject them so it dials exactly what `remote_url_allow_hosts` checked. +void checkConnectionTarget(const std::string & server, unsigned port, const std::string & socket) +{ + std::string_view meaning; + if (server.contains('\0')) + meaning = "the end of the host"; + else if (server.find_first_of(";=") != std::string::npos) + meaning = "a connection string"; + else if (server.contains("://")) + meaning = "a connection plugin URL"; + else if (server.contains(',')) + meaning = "a list of hosts"; + + if (!meaning.empty()) + { + std::string printable; + for (const char c : server) + printable += c == '\0' ? std::string_view("\\0") : std::string_view(&c, 1); + + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL host '{}' contains syntax which the MySQL client library would read as {}. " + "Specify a plain host and port, and use the `socket` and `ssl_*` settings instead", + printable, meaning); + } + + if (socket.contains('\0')) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, "MySQL socket for host '{}' contains a NUL byte, where the MySQL client library would end it", server); + + /// The client library uses the socket only for an empty host or `localhost`, otherwise it connects over TCP. + const bool uses_socket = !socket.empty() && (server.empty() || server == "localhost"); + if (port == 0 && !uses_socket) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL port 0 for host '{}' would be replaced by the default port of the MySQL client library. Specify the port explicitly", + server); +} + +} + namespace mysqlxx { @@ -367,6 +417,9 @@ void Pool::initialize() Pool::Connection * Pool::allocConnection(bool dont_throw_if_failed_first_time) { + /// All connections of the pool are created here. + checkConnectionTarget(server, port, socket); + auto conn_ptr = std::make_unique(); try diff --git a/src/Common/tests/gtest_distrusted_certificates.cpp b/src/Common/tests/gtest_distrusted_certificates.cpp new file mode 100644 index 000000000000..5931feea9f6b --- /dev/null +++ b/src/Common/tests/gtest_distrusted_certificates.cpp @@ -0,0 +1,137 @@ +#include "config.h" + +#if USE_SSL + +#include + +#include +#include + +#include +#include +#include + +#include +#include + + +namespace +{ + +/// `emSign ECC Root CA - G3`, distrusted. +constexpr std::string_view emsign_ecc_root_g3 = R"( +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +)"; + +/// `EM DV TLS CA - G3B` cross-signed by `AAA Certificate Services`, distrusted by the key of the certificate issued by `emSign Root TLS CA - G3`. +constexpr std::string_view em_dv_tls_ca_g3b_cross_signed = R"( +-----BEGIN CERTIFICATE----- +MIIDzjCCAragAwIBAgIRAKAk/fS6Zlx4XOSgIEg4WLcwDQYJKoZIhvcNAQELBQAw +ezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV +BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0yNTA1MTQwMDAwMDBaFw0y +ODEyMzEyMzU5NTlaMD8xCzAJBgNVBAYTAk5MMRMwEQYDVQQKDAplTXVkaHJhIEJW +MRswGQYDVQQDDBJFTSBEViBUTFMgQ0EgLSBHM0IwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAATnntnASpdzxHNeUREdqFrCvV5kqzdLgOEsvCA47B5PDjuBL8mFnh5nr7BO +L4vJf3SFumWqkR7opORbYtXMA9Vr5nizw4y03JN8okYOI4RTyJKTXSnUT5HhVga2 +PM7atGijggE1MIIBMTAfBgNVHSMEGDAWgBSgEQojPpbxB+zirynvgqV/0DCktDAd +BgNVHQ4EFgQU4h4v5xwZOQ5VS2LBICRXNSSKJRQwDgYDVR0PAQH/BAQDAgEGMBIG +A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC +MDEGA1UdIAQqMCgwCAYGZ4EMAQIBMA0GCysGAQQBg44hAQABMA0GCysGAQQBg44h +AQJkMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0FB +QUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEF +BQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBCwUAA4IB +AQBzQ1IoqpdotM6gFrR4Q3YrKifOLeaj5XXunldpVE/vZn2TxC2y0s8oYiLR5ICE +wqVXSB7N6BM1Mp+Nif7Jbhb2IswAfSR4Iik8+B0iRmi7lYoNlycCgHjmsjOmZaxM +QkPmjXAJbG5f4V41OsvJZmS7lI3r0IuvEDVX3GAZ13on6IImSs9ybNpHQ7NCqkMQ +7wH4uAO1dtpFycgJSdHaCOhHjrox2BTYGLdpUrYwY3EOAjlZ8UGgsxs7mG+xquMl +bN1LFURwfnkVMP3T/DBIZ/ys2+lNFyxK3FlArrV4/000uTnVB1lO8oGORYdXoT5V +GUyRCEIDhF5TBUuKF4E3kf1h +-----END CERTIFICATE-----)"; + +/// `emSign Root CA - G1`, not affected. +constexpr std::string_view emsign_root_g1 = R"( +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +)"; + +using X509Ptr = std::unique_ptr; + +X509Ptr parseCertificate(std::string_view pem) +{ + std::unique_ptr bio(BIO_new_mem_buf(pem.data(), static_cast(pem.size())), BIO_free); + X509Ptr certificate(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr), X509_free); + EXPECT_NE(certificate, nullptr); + return certificate; +} + +/// Verifies a trusted self-signed certificate the same way a TLS connection of a Poco context does it. +int verifyTrustedRoot(std::string_view pem) +{ + Poco::Net::Context context(Poco::Net::Context::CLIENT_USE, Poco::Net::Context::Params{}); + X509Ptr certificate = parseCertificate(pem); + X509_STORE * store = SSL_CTX_get_cert_store(context.sslContext()); + EXPECT_EQ(X509_STORE_add_cert(store, certificate.get()), 1); + + std::unique_ptr store_ctx(X509_STORE_CTX_new(), X509_STORE_CTX_free); + EXPECT_EQ(X509_STORE_CTX_init(store_ctx.get(), store, certificate.get(), nullptr), 1); + X509_STORE_CTX_set_verify_cb(store_ctx.get(), SSL_CTX_get_verify_callback(context.sslContext())); + + if (X509_verify_cert(store_ctx.get()) == 1) + return X509_V_OK; + return X509_STORE_CTX_get_error(store_ctx.get()); +} + +} + + +TEST(DistrustedCertificates, Check) +{ + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_ecc_root_g3).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(em_dv_tls_ca_g3b_cross_signed).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_root_g1).get()), X509_V_OK); +} + +TEST(DistrustedCertificates, RejectedEvenIfTrusted) +{ + EXPECT_EQ(verifyTrustedRoot(emsign_ecc_root_g3), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(verifyTrustedRoot(emsign_root_g1), X509_V_OK); +} + +#endif diff --git a/src/Common/tests/gtest_file_channel_rotation_failure.cpp b/src/Common/tests/gtest_file_channel_rotation_failure.cpp new file mode 100644 index 000000000000..d4ca3bee239b --- /dev/null +++ b/src/Common/tests/gtest_file_channel_rotation_failure.cpp @@ -0,0 +1,133 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Log rotation must not leave `FileChannel` with a deleted `LogFile` when the process has no free file descriptors. + +namespace +{ + +/// glibc defines `RLIMIT_NOFILE` as a self-referential macro, which trips -Wdisabled-macro-expansion inside gtest macros. +const auto nofile_resource = RLIMIT_NOFILE; + +struct DescriptorTableGuard +{ + struct rlimit original_limit{}; + std::vector descriptors; + + void release() + { + for (int fd : descriptors) + ::close(fd); + descriptors.clear(); + EXPECT_EQ(0, setrlimit(nofile_resource, &original_limit)); + } + + ~DescriptorTableGuard() { release(); } +}; + +int setSoftLimit(rlim_t value, const struct rlimit & original_limit) +{ + struct rlimit limit = original_limit; + limit.rlim_cur = value; + return setrlimit(nofile_resource, &limit); +} + +int fillDescriptorTable(DescriptorTableGuard & guard) +{ + while (true) + { + int fd = ::open("/dev/null", O_RDONLY | O_CLOEXEC); + if (fd < 0) + return errno; + guard.descriptors.push_back(fd); + } +} + +Poco::Message makeMessage(const std::string & text) +{ + return Poco::Message("gtest_file_channel_rotation_failure", text, Poco::Message::PRIO_INFORMATION); +} + +void expectNoFreeDescriptors(Poco::FileChannel & channel, const std::string & text) +{ + try + { + channel.log(makeMessage(text)); + ADD_FAILURE() << "Expected EMFILE while logging: " << text; + } + catch (const Poco::FileException & e) + { + EXPECT_EQ(EMFILE, e.code()) << e.displayText(); + } +} + +std::string readFile(const std::string & path) +{ + std::ifstream in(path); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +} + +TEST(FileChannelRotation, NoFreeDescriptorsDuringRotation) +{ + const auto dir = std::filesystem::temp_directory_path() / ("gtest_file_channel_rotation_" + std::to_string(::getpid())); + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + struct DirectoryGuard + { + std::filesystem::path path; + ~DirectoryGuard() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + } directory_guard{dir}; + const std::string path = (dir / "server.log").string(); + + Poco::AutoPtr channel = new Poco::FileChannel(path); + channel->setProperty(Poco::FileChannel::PROP_ROTATION, "1K"); + channel->setProperty(Poco::FileChannel::PROP_ARCHIVE, "number"); + channel->setProperty(Poco::FileChannel::PROP_COMPRESS, "false"); + + DescriptorTableGuard guard; + ASSERT_EQ(0, getrlimit(nofile_resource, &guard.original_limit)); + const rlim_t limit = std::min({guard.original_limit.rlim_cur, guard.original_limit.rlim_max - 1, 1024}); + + /// The log file gets descriptor `limit`, so closing it in `archive` frees no descriptor below the limit. + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + ASSERT_EQ(EMFILE, fillDescriptorTable(guard)); + ASSERT_EQ(0, setSoftLimit(limit + 1, guard.original_limit)); + ASSERT_NO_THROW(channel->open()); + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + + ASSERT_NO_THROW(channel->log(makeMessage(std::string(2048, 'x')))); + + expectNoFreeDescriptors(*channel, "rotation without free descriptors"); + EXPECT_TRUE(std::filesystem::exists(path + ".0")); + EXPECT_EQ(0u, channel->size()); + expectNoFreeDescriptors(*channel, "still no free descriptors"); + + guard.release(); + + const std::string marker = "logged after descriptors were released"; + ASSERT_NO_THROW(channel->log(makeMessage(marker))); + channel->close(); + EXPECT_NE(std::string::npos, readFile(path).find(marker)); +} diff --git a/src/Coordination/Changelog.cpp b/src/Coordination/Changelog.cpp index 26f8cff05cae..dd4d3a9e8cff 100644 --- a/src/Coordination/Changelog.cpp +++ b/src/Coordination/Changelog.cpp @@ -2568,6 +2568,8 @@ void Changelog::applyEntriesFromBuffer(uint64_t index, nuraft::buffer & buffer) { uint64_t cur_index = index + i; int buf_size = buffer.get_int(); + if (buf_size < 0 || static_cast(buf_size) > buffer.size() - buffer.pos()) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Log entry {} in a log pack has invalid size {}", cur_index, buf_size); nuraft::ptr buf_local = nuraft::buffer::alloc(buf_size); buffer.get(buf_local); diff --git a/src/Coordination/tests/gtest_coordination.cpp b/src/Coordination/tests/gtest_coordination.cpp index 291bc4236055..6f0a8d868f51 100644 --- a/src/Coordination/tests/gtest_coordination.cpp +++ b/src/Coordination/tests/gtest_coordination.cpp @@ -172,6 +172,69 @@ TYPED_TEST(CoordinationTest, CreateRequestDoesNotPreallocateOversizedACLs) } } +TEST(CoordinationSerialization, StringReadDoesNotPreallocateDeclaredSize) +{ + /// Invariant: memory must track bytes actually read, not the declared string length. + const size_t chunk = Coordination::MAX_STRING_PREALLOCATION; + + auto expect_marshalling_error = [](DB::ReadBuffer & rbuf, std::string & s) + { + try + { + Coordination::read(s, rbuf); + FAIL() << "Expected ZMARSHALLINGERROR"; + } + catch (const Coordination::Exception & e) + { + EXPECT_EQ(e.code, Coordination::Error::ZMARSHALLINGERROR); + } + }; + + { + /// The largest allowed length is declared, but no payload bytes follow. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 2 * chunk); + } + + { + /// The input ends after one complete chunk. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + const std::string first_chunk(chunk, 'x'); + wbuf.write(first_chunk.data(), first_chunk.size()); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 4 * chunk); + } + + { + /// A string that needs more than one chunk is read completely, and the next field is aligned. + std::string expected(chunk + 1, '\0'); + for (size_t i = 0; i < expected.size(); ++i) + expected[i] = static_cast(i % 251); + + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(expected, wbuf); + Coordination::write(static_cast(42), wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + int32_t next = 0; + Coordination::read(s, rbuf); + Coordination::read(next, rbuf); + EXPECT_EQ(s, expected); + EXPECT_EQ(next, 42); + EXPECT_TRUE(rbuf.eof()); + } +} + template struct SimpliestRaftServer { diff --git a/src/Coordination/tests/gtest_coordination_changelog.cpp b/src/Coordination/tests/gtest_coordination_changelog.cpp index c0a33caadbdd..fa3ec468e04e 100644 --- a/src/Coordination/tests/gtest_coordination_changelog.cpp +++ b/src/Coordination/tests/gtest_coordination_changelog.cpp @@ -479,6 +479,45 @@ TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsEmpty) changelog_reader.init(5, 0); } +TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsInvalidSize) +{ + ChangelogDirTest test("./logs"); + this->setLogDirectory("./logs"); + + DB::KeeperLogStore changelog( + DB::LogFileSettings{.force_sync = true, .compress_logs = this->enable_compression, .rotate_interval = 100}, + DB::FlushSettings(), + this->keeper_context); + changelog.init(0, 0); + auto entry = getLogEntry("hello_world", 10); + changelog.append(entry); + changelog.end_of_append_batch(0, 0); + waitDurableLogs(changelog); + + /// A pack of one entry holds the entry count, the entry size and the entry itself. A peer controls the size, + /// so only the size is rewritten here. + auto entries = changelog.pack(1, 1); + const auto entry_size = static_cast(entries->size() - 2 * sizeof(int32_t)); + auto apply_with_size = [&](int32_t size) + { + entries->pos(sizeof(int32_t)); + entries->put(size); + changelog.apply_pack(2, *entries); + }; + + /// On master a size past the entry over-reads the pack in `nuraft::buffer::get` and a negative size + /// wraps the allocation size in `nuraft::buffer::alloc`. + EXPECT_THROW(apply_with_size(entry_size + 1), DB::Exception); + EXPECT_THROW(apply_with_size(-1), DB::Exception); + EXPECT_EQ(changelog.next_slot(), 2); + + apply_with_size(entry_size); + changelog.apply_pack(3, *changelog.pack(1, 0)); + changelog.end_of_append_batch(0, 0); + EXPECT_EQ(changelog.next_slot(), 3); + EXPECT_EQ(changelog.entry_at(2)->get_term(), 10); +} + TYPED_TEST(CoordinationChangelogTest, ChangelogTestWriteAtPreviousFile) { diff --git a/src/Core/Field.cpp b/src/Core/Field.cpp index 8afadfc8ac9e..ca0f375ed111 100644 --- a/src/Core/Field.cpp +++ b/src/Core/Field.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -369,6 +370,9 @@ bool Field::operator== (const Field & rhs) const Field getBinaryValue(UInt8 type, ReadBuffer & buf) { + /// Containers are read recursively, and the nesting depth comes from the data. + checkStackSize(); + switch (static_cast(type)) { case Field::Types::Null: diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 0042be8fe8a1..31643b8133cd 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -1408,6 +1408,13 @@ Compression method for Arrow output format. Supported codecs: lz4_frame, zstd, n )", 0) \ DECLARE(Bool, output_format_arrow_date_as_uint16, false, R"( Write Date values as plain 16-bit numbers (read back as UInt16), instead of converting to a 32-bit Arrow DATE32 type (read back as Date32). +)", 0) \ + DECLARE(UInt64, output_format_arrow_max_record_batch_size_bytes, 2147483646, R"( +Upper bound on the `Utf8`, `Binary` and `List` buffers of a single record batch in the `Arrow` and `ArrowStream` output formats. A block whose strings, binary values or list elements exceed this is written as several record batches. + +This is a limit that splits large blocks. The default is the largest value Arrow can address, because it offsets those buffers with 32-bit integers; a larger value has no effect. + +Only the buffers named above are bounded: a column of a fixed-width type has no offsets to overflow and stays in one batch. A single row never splits either, so a row above the limit still produces a batch that exceeds it. )", 0) \ \ DECLARE(Bool, output_format_orc_string_as_string, true, R"( diff --git a/src/Core/PostgreSQLProtocol.h b/src/Core/PostgreSQLProtocol.h index 20349d50560c..74accb0cef73 100644 --- a/src/Core/PostgreSQLProtocol.h +++ b/src/Core/PostgreSQLProtocol.h @@ -55,6 +55,14 @@ namespace PostgreSQLProtocol namespace Messaging { +/** Upper bound for the declared length of a message that is parsed before the client is authenticated. + * The payload of such a message is bounded by its declared length, but that length is chosen by an + * unauthenticated client, so the length itself must be bounded as well. Otherwise a client declares + * the Int32 maximum and makes the server buffer up to 2 GiB of payload before it gives up. + * PostgreSQL uses the same limit for its startup packet. + */ +constexpr Int32 max_unauthenticated_message_size = 10000; + enum class FrontMessageType : Int32 { // first message types @@ -307,14 +315,26 @@ class FrontMessage : public IMessage virtual void deserialize(ReadBuffer & in) = 0; protected: + /** Parses the payload of a message inside a buffer that ends at the declared length. + * `max_size` bounds the declared length itself. Pass it for every message that is parsed before the + * client is authenticated, because that client chooses the length. A frame rejected by `max_size` is + * left unread in the stream, so only a caller whose error closes the connection may pass a limit. + */ template - static void deserializePayload(ReadBuffer & in, std::string_view message_name, F && deserialize_payload) + static void deserializePayload( + ReadBuffer & in, + std::string_view message_name, + F && deserialize_payload, + Int32 max_size = std::numeric_limits::max()) { Int32 size = 0; readBinaryBigEndian(size, in); if (size < 4) throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT, "Wrong message length {} in {}, it must be at least 4", size, message_name); + if (size > max_size) + throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT, + "Wrong message length {} in {}, it must not exceed {}", size, message_name, max_size); const size_t payload_size = static_cast(size - 4); LimitReadBuffer payload_in(in, {.read_no_less = payload_size, .read_no_more = payload_size}); @@ -598,7 +618,7 @@ class SASLInitialResponse : public Messaging::FrontMessage "Wrong SASL mechanism length {} in SASLInitialResponse, it must not be less than -1", size_sasl_mechanism); if (size_sasl_mechanism > 0) readStringOfDeclaredSize(sasl_mechanism, size_sasl_mechanism, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override @@ -646,7 +666,7 @@ class SASLResponse : public Messaging::FrontMessage deserializePayload(in, "SASLResponse message", [this](ReadBuffer & payload_in) { readStringUntilEOF(sasl_mechanism, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override @@ -687,7 +707,7 @@ class PasswordMessage : FrontMessage deserializePayload(in, "PasswordMessage", [this](ReadBuffer & payload_in) { readNullTerminated(password, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index ac119469ccd0..6cbd2e052809 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -1270,6 +1270,10 @@ Possible values: - `2` — `SELECT` and `INSERT` will be executed on each shard from/to the underlying table of the distributed engine. Setting `enable_parallel_replicas = 1` is needed when using this setting. + +:::note +The rewritten query, including every expression of the `SELECT` (subqueries, UDFs, and so on), is executed on the shards under the credentials of the cluster configuration — the same trust model as other shard-side processing, such as the subqueries of a non-`GLOBAL` `IN`. Configure an interserver secret (the `secret` element of the cluster configuration) if shard-side reads must be authorized as the calling user. +::: )", 0) \ DECLARE(UInt64, distributed_group_by_no_merge, 0, R"( Do not merge aggregation states from different servers for distributed query processing, you can use this in case it is for certain that there are different keys on different shards diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 62e4d873e09d..caf53da95654 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -41,6 +41,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() /// Note: please check if the key already exists to prevent duplicate entries. addSettingsChanges(settings_changes_history, "26.3", { + {"output_format_arrow_max_record_batch_size_bytes", 2147483646, 2147483646, "New setting bounding the size of one record batch in `Arrow` and `ArrowStream` output. The default is Arrow's own addressing limit, so it does not change behavior."}, {"variant_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Variant implementation"}, {"dynamic_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Dynamic implementation"}, {"defer_partition_pruning_after_final", false, true, "Gates the FINAL planner's unconditional skipping of partition pruning when the partition-key column is not in the sorting key. The behavior change itself shipped silently in 26.3 via https://github.com/ClickHouse/ClickHouse/pull/98242; this entry retroactively documents it so `compatibility = '26.2'` restores the pre-regression behavior (0 = prune before FINAL, fast; 1 = defer pruning, correctness-safe)."}, diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp index 4b0be9872423..1b1665c4abff 100644 --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp @@ -607,6 +607,13 @@ void SerializationLowCardinality::deserializeBinaryBulkWithMultipleStreams( bool has_additional_keys = low_cardinality_state->index_type.has_additional_keys; bool column_is_empty = low_cardinality_column.empty(); + /// Indexes come from the stream. + if (low_cardinality_state->index_type.need_global_dictionary) + { + const size_t num_additional_keys = additional_keys ? additional_keys->size() : 0; + ColumnLowCardinality::checkIndexesAreLimited(*indexes_column, global_dictionary->size() + num_additional_keys); + } + if (!low_cardinality_state->index_type.need_global_dictionary) { if (additional_keys == nullptr) diff --git a/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp new file mode 100644 index 000000000000..4ea6070e820a --- /dev/null +++ b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp @@ -0,0 +1,179 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int INCORRECT_DATA; +} + +using namespace DB; + +namespace +{ + +/// The MergeTree layout: the dictionary in one stream, the indexes and the additional keys in another. +template +auto makeGetter(Buffer & keys, Buffer & indexes) +{ + return [&keys, &indexes](const ISerialization::SubstreamPath & path) -> BufferPtr + { + if (!path.empty() && path.back().type == ISerialization::Substream::DictionaryKeys) + return &keys; + return &indexes; + }; +} + +struct Streams +{ + std::string keys; + std::string indexes; +}; + +Streams serialize(const DataTypePtr & type, const IColumn & column, size_t max_dictionary_size) +{ + WriteBufferFromOwnString keys; + WriteBufferFromOwnString indexes; + auto serialization = type->getDefaultSerialization(); + ISerialization::SerializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.low_cardinality_max_dictionary_size = max_dictionary_size; + settings.low_cardinality_use_single_dictionary_for_part = false; + ISerialization::SerializeBinaryBulkStatePtr state; + serialization->serializeBinaryBulkStatePrefix(column, settings, state); + serialization->serializeBinaryBulkWithMultipleStreams(column, 0, column.size(), settings, state); + serialization->serializeBinaryBulkStateSuffix(settings, state); + keys.finalize(); + indexes.finalize(); + return {keys.str(), indexes.str()}; +} + +ColumnPtr deserialize(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + ReadBufferFromString keys(streams.keys); + ReadBufferFromString indexes(streams.indexes); + auto serialization = type->getDefaultSerialization(); + ISerialization::DeserializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.native_format = false; + ISerialization::DeserializeBinaryBulkStatePtr state; + serialization->deserializeBinaryBulkStatePrefix(settings, state, nullptr); + ColumnPtr column = type->createColumn(); + serialization->deserializeBinaryBulkWithMultipleStreams(column, 0, rows, settings, state, nullptr); + return column; +} + +void expectIncorrectData(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + try + { + deserialize(type, streams, rows); + FAIL() << "accepted an index past the keys"; + } + catch (const Exception & e) + { + ASSERT_EQ(e.code(), ErrorCodes::INCORRECT_DATA) << e.message(); + } +} + +/// Calls `check` for `LowCardinality(String)` and `LowCardinality(Nullable(UInt64))`, each serialized with a dictionary +/// of 2 keys (so most values become additional keys) and with one large enough for all values (no additional keys). +template +void forEachCase(Check && check) +{ + for (bool nullable : {false, true}) + { + DataTypePtr inner = nullable ? makeNullable(std::make_shared()) : std::make_shared(); + auto type = std::make_shared(inner); + auto column = type->createColumn(); + for (size_t i = 0; i < 20; ++i) + { + if (nullable) + column->insert(i % 6 == 0 ? Field() : Field(UInt64(i % 6))); + else + column->insert(String(1, static_cast('a' + i % 5))); + } + + for (size_t max_dictionary_size : {2, 8192}) + { + SCOPED_TRACE(type->getName() + " with max dictionary size " + std::to_string(max_dictionary_size)); + auto streams = serialize(type, *column, max_dictionary_size); + + constexpr UInt64 need_global_dictionary_bit = 1ULL << 8; + constexpr UInt64 has_additional_keys_bit = 1ULL << 9; + const UInt64 index_type = unalignedLoadLittleEndian(streams.indexes.data()); + const bool has_additional_keys = (index_type & has_additional_keys_bit) != 0; + ASSERT_NE(index_type & need_global_dictionary_bit, 0u); + ASSERT_EQ(has_additional_keys, max_dictionary_size == 2); + ASSERT_LE(index_type & 0xff, 3u); + + /// The keys stream starts with the version, then the number of keys; the indexes stream starts with the index type, + /// then the number of additional keys if there are any. + const UInt64 num_keys = unalignedLoadLittleEndian(streams.keys.data() + 8) + + (has_additional_keys ? unalignedLoadLittleEndian(streams.indexes.data() + 8) : 0); + const size_t index_width = 1ULL << (index_type & 0xff); + + check(type, *column, std::move(streams), num_keys, index_width); + } + } +} + +} + +TEST(SerializationLowCardinality, ValidStreamsRoundTrip) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64, size_t) + { + auto result = deserialize(type, streams, column.size()); + ASSERT_EQ(result->size(), column.size()); + for (size_t i = 0; i < column.size(); ++i) + ASSERT_EQ((*result)[i], column[i]) << "row " << i; + }); +} + +/// The indexes come from the data, so they have to be checked against the keys of the dictionary and the additional keys. +TEST(SerializationLowCardinality, IndexPastTheKeysIsRejected) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64 num_keys, size_t index_width) + { + const size_t rows = column.size(); + const size_t indexes_begin = streams.indexes.size() - rows * index_width; + + /// The same indexes as `UInt64` (index type 3, the low byte of the index type) read back the same values... + Streams wide{streams.keys, streams.indexes.substr(0, indexes_begin)}; + wide.indexes[0] = 3; + for (size_t row = 0; row < rows; ++row) + { + UInt64 index = 0; + for (size_t i = 0; i < index_width; ++i) + index |= UInt64(static_cast(streams.indexes[indexes_begin + row * index_width + i])) << (8 * i); + for (size_t i = 0; i < 8; ++i) + wide.indexes.push_back(static_cast(index >> (8 * i))); + } + auto result = deserialize(type, wide, rows); + ASSERT_EQ(result->size(), rows); + for (size_t row = 0; row < rows; ++row) + ASSERT_EQ((*result)[row], column[row]) << "row " << row; + + /// ...and the largest possible last index is rejected before `mapIndexWithAdditionalKeys` sizes its overflow map by it. + std::fill(wide.indexes.end() - 8, wide.indexes.end(), '\xff'); + expectIncorrectData(type, wide, rows); + + /// The last index of the original stream becomes the first value past the keys. + ASSERT_LE(num_keys, std::numeric_limits::max() >> (64 - 8 * index_width)); + for (size_t i = 0; i < index_width; ++i) + streams.indexes[streams.indexes.size() - index_width + i] = static_cast(num_keys >> (8 * i)); + expectIncorrectData(type, streams, rows); + }); +} diff --git a/src/Databases/DataLake/GlueCatalog.cpp b/src/Databases/DataLake/GlueCatalog.cpp index df08b71baf8a..3ab1c7067a12 100644 --- a/src/Databases/DataLake/GlueCatalog.cpp +++ b/src/Databases/DataLake/GlueCatalog.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -77,8 +78,8 @@ namespace DB::ServerSetting namespace CurrentMetrics { - extern const Metric MarkCacheBytes; - extern const Metric MarkCacheFiles; + extern const Metric GlueCatalogSchemaCacheBytes; + extern const Metric GlueCatalogSchemaCacheEntries; } namespace DataLake @@ -95,7 +96,7 @@ GlueCatalog::GlueCatalog( , region(settings_.region) , settings(settings_) , table_engine_definition(table_engine_definition_) - , metadata_objects(CurrentMetrics::MarkCacheBytes, CurrentMetrics::MarkCacheFiles, 1024) + , current_schema_field_types(CurrentMetrics::GlueCatalogSchemaCacheBytes, CurrentMetrics::GlueCatalogSchemaCacheEntries, 16_MiB) { DB::S3::CredentialsConfiguration creds_config; creds_config.use_environment_credentials = true; @@ -466,7 +467,7 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet const String & metadata_uri = table_specific_properties->iceberg_metadata_file_location; - if (!metadata_objects.get(metadata_uri)) + auto [field_types, _] = current_schema_field_types.getOrSet(metadata_uri, [&] { auto [object_storage, bucket_name, metadata_path] = createObjectStorageForEarlyTableAccess(metadata_uri, table_metadata); const auto & read_settings = getContext()->getReadSettings(); @@ -479,28 +480,42 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(metadata_file_content); auto metadata_object = result.extract(); - metadata_objects.set(metadata_uri, std::make_shared(metadata_object)); - } + return std::make_shared(getCurrentSchemaFieldTypes(metadata_object)); + }); + + auto it = field_types->find(column_name); + return it != field_types->end() && it->second == DB::Iceberg::f_timestamptz; +} - auto metadata_object = *metadata_objects.get(metadata_uri); +GlueCatalog::FieldTypes GlueCatalog::getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object) +{ + FieldTypes result; auto current_schema_id = metadata_object->getValue("current-schema-id"); auto schemas = metadata_object->getArray(DB::Iceberg::f_schemas); for (size_t i = 0; i < schemas->size(); ++i) { auto schema = schemas->getObject(static_cast(i)); - if (schema->getValue("schema-id") == current_schema_id) + if (schema->getValue("schema-id") != current_schema_id) + continue; + + auto fields = schema->getArray(DB::Iceberg::f_fields); + for (size_t j = 0; j < fields->size(); ++j) { - auto fields = schema->getArray(DB::Iceberg::f_fields); - for (size_t j = 0; j < fields->size(); ++j) - { - auto field = fields->getObject(static_cast(j)); - if (field->getValue(DB::Iceberg::f_name) == column_name) - return field->getValue(DB::Iceberg::f_type) == DB::Iceberg::f_timestamptz; - } + auto field = fields->getObject(static_cast(j)); + auto type = field->get(DB::Iceberg::f_type); + if (type.isString()) + result.emplace(field->getValue(DB::Iceberg::f_name), type.extract()); } } + return result; +} - return false; +size_t GlueCatalog::FieldTypesWeightFunction::operator()(const FieldTypes & field_types) const +{ + size_t result = 0; + for (const auto & [name, type] : field_types) + result += sizeof(FieldTypes::value_type) + name.size() + type.size(); + return result; } GlueCatalog::ObjectStorageWithPath GlueCatalog::createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const diff --git a/src/Databases/DataLake/GlueCatalog.h b/src/Databases/DataLake/GlueCatalog.h index c65c69a2a75a..e0485de5e0e0 100644 --- a/src/Databases/DataLake/GlueCatalog.h +++ b/src/Databases/DataLake/GlueCatalog.h @@ -83,9 +83,18 @@ class GlueCatalog final : public ICatalog, private DB::WithContext const String & column_name, const String & glue_column_type); + using FieldTypes = std::unordered_map; + + static FieldTypes getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object); + private: void createNamespaceIfNotExists(const String & namespace_name) const; + struct FieldTypesWeightFunction + { + size_t operator()(const FieldTypes & field_types) const; + }; + std::unique_ptr glue_client; const LoggerPtr log; std::shared_ptr credentials_provider; @@ -112,7 +121,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext ObjectStorageWithPath createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const; - mutable DB::CacheBase metadata_objects; + mutable DB::CacheBase, FieldTypesWeightFunction> current_schema_field_types; }; } diff --git a/src/Databases/DataLake/HiveCatalog.cpp b/src/Databases/DataLake/HiveCatalog.cpp index b86f70dfc4b5..918ed836737e 100644 --- a/src/Databases/DataLake/HiveCatalog.cpp +++ b/src/Databases/DataLake/HiveCatalog.cpp @@ -10,8 +10,10 @@ #include #include #include +#include #include #include +#include #include namespace DB::ErrorCodes @@ -64,11 +66,23 @@ std::pair parseHostPort(const String & url) } } +std::shared_ptr createSocket(const String & base_url, const DB::ContextPtr & context) +{ + auto [host, port] = parseHostPort(base_url); + + /// Also rejects control characters such as NUL, which `getaddrinfo` would truncate the host at. + context->getRemoteHostFilter().checkAndGetCanonicalHostAndPort( + host + ":" + std::to_string(port), static_cast(port), "Hive metastore address"); + + return std::make_shared(host, port); +} + } -HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr) +HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr context_) : ICatalog(warehouse_) - , socket(new apache::thrift::transport::TSocket(parseHostPort(base_url_).first, parseHostPort(base_url_).second)) + , DB::WithContext(context_) + , socket(createSocket(base_url_, context_)) , transport(new apache::thrift::transport::TBufferedTransport(socket)) , protocol(new apache::thrift::protocol::TBinaryProtocol(transport)) , client(protocol) diff --git a/src/Databases/DatabaseReplicated.cpp b/src/Databases/DatabaseReplicated.cpp index 94d0aa46efd8..8428ea1c4c20 100644 --- a/src/Databases/DatabaseReplicated.cpp +++ b/src/Databases/DatabaseReplicated.cpp @@ -63,6 +63,7 @@ #include #include #include +#include #include #include @@ -798,14 +799,14 @@ void DatabaseReplicated::createEmptyLogEntry(const ZooKeeperPtr & current_zookee bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, SyncReplicaMode mode) { chassert(mode == SyncReplicaMode::DEFAULT || mode == SyncReplicaMode::STRICT); - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - return false; - } + /// The worker can be stopped and replaced concurrently (`SYSTEM RESTORE DATABASE REPLICA`, `DROP DATABASE`): + /// the reference keeps it alive, and a stopped worker returns from the wait. + auto worker = tryGetDDLWorker(); + if (!worker) + return false; if (mode == SyncReplicaMode::DEFAULT) - return ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms); + return worker->waitForReplicaToProcessAllEntries(timeout_ms); Stopwatch elapsed; while (true) @@ -814,15 +815,19 @@ bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, Sy if (elapsed_ms > timeout_ms) return false; - if (ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) + if (worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) return true; - UInt32 our_log_ptr = ddl_worker->getLogPointer(); + UInt32 our_log_ptr = worker->getLogPointer(); UInt32 max_log_ptr = parse(getZooKeeper()->get(fs::path(zookeeper_path) / "max_log_ptr")); bool became_synced = our_log_ptr + db_settings[DatabaseReplicatedSetting::max_replication_lag_to_enqueue] >= max_log_ptr; if (became_synced) return true; + /// The worker was stopped (e.g. by `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE`), it will not make progress. + if (worker->isStopped()) + return false; + /// max_log_ptr might be increased while we were waiting - retry until replication lag is below the threshold } } @@ -995,11 +1000,36 @@ void DatabaseReplicated::initDDLWorkerUnlocked() chassert(!is_probably_dropped.load()); chassert(!ddl_worker_initialized.load()); - ddl_worker = std::make_unique(this, getContext()); + replaceDDLWorkerUnlocked(std::make_shared(this, getContext())); ddl_worker->startup(); ddl_worker_initialized = true; } +std::shared_ptr DatabaseReplicated::tryGetDDLWorker() const +{ + std::lock_guard lock{ddl_worker_mutex}; + if (!ddl_worker || is_probably_dropped) + return nullptr; + return ddl_worker; +} + +std::shared_ptr DatabaseReplicated::replaceDDLWorkerUnlocked(std::shared_ptr new_worker) +{ + std::lock_guard lock{ddl_worker_ptr_mutex}; + std::swap(ddl_worker, new_worker); + return new_worker; +} + +bool DatabaseReplicated::isDDLWorkerCurrentlyActive() const +{ + std::shared_ptr worker; + { + std::lock_guard lock{ddl_worker_ptr_mutex}; + worker = ddl_worker; + } + return worker && worker->isCurrentlyActive(); +} + void DatabaseReplicated::restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper) { auto local_context = getContext(); @@ -1058,7 +1088,7 @@ void DatabaseReplicated::reinitializeDDLWorker() ddl_worker->shutdown(); { ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } } @@ -1279,7 +1309,7 @@ bool DatabaseReplicated::checkDigestValid(const ContextPtr & local_context) cons LOG_TEST(log, "Current in-memory metadata digest: {}", tables_metadata_digest); /// Database is probably being dropped - if (!local_context->getZooKeeperMetadataTransaction() && (!ddl_worker || !ddl_worker->isCurrentlyActive())) + if (!local_context->getZooKeeperMetadataTransaction() && !isDDLWorkerCurrentlyActive()) return true; /// SYSTEM RESTART REPLICA temporarily removes a table from the in-memory tables map @@ -1385,13 +1415,12 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex if (is_readonly) throw Exception(ErrorCodes::NO_ZOOKEEPER, "Database is in readonly mode, because it cannot connect to ZooKeeper"); - String host_fqdn_id; - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); - host_fqdn_id = ddl_worker->getCommonHostID(); - } + /// Hold our own reference: `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE` can stop and replace the worker + /// while this query waits in `tryEnqueueAndExecuteEntry`. A stopped worker makes it throw instead of executing. + auto worker = tryGetDDLWorker(); + if (!worker) + throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); + String host_fqdn_id = worker->getCommonHostID(); if (!flags.internal && query_context->isDDLOrOnClusterInternal()) throw Exception(ErrorCodes::INCORRECT_QUERY, "It's not initial query. ON CLUSTER is not allowed for Replicated database."); @@ -1406,7 +1435,7 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex entry.tracing_context = OpenTelemetry::CurrentContext(); entry.initial_query_id = query_context->getClientInfo().initial_query_id; entry.is_backup_restore = flags.distributed_backup_restore; - String node_path = ddl_worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); + String node_path = worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); Strings hosts_to_wait; Strings unfiltered_hosts = getZooKeeper()->getChildren(zookeeper_path + "/replicas"); @@ -2078,10 +2107,63 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) auto component_guard = Coordination::setCurrentComponent("DatabaseReplicated::restoreDatabaseMetadataInKeeper"); waitDatabaseStarted(); + /// Concurrent restores of the same database would stop and re-create the DDL worker under each other + /// and race on the replication state that `initDatabaseReplica` rewrites (e.g. `max_log_ptr_at_creation`). + std::lock_guard restore_lock{restore_in_keeper_mutex}; + auto zookeeper = getZooKeeper(); if (!zookeeper) throw Exception(ErrorCodes::NO_ZOOKEEPER, "No ZooKeeper"); + /// Stop this replica's DDL worker before the calls below re-initialize replication state: + /// its recovery reads `max_log_ptr_at_creation` and compares the Keeper metadata with the + /// local table set, which those calls rewrite, and a recovery running against a half-updated + /// view detaches local tables into `_broken_replicated_tables`. + std::shared_ptr old_worker; + { + std::lock_guard lock{ddl_worker_mutex}; + old_worker = ddl_worker; + } + + /// Initial queries admitted by the worker execute and commit on their own threads, and `shutdown` does not wait + /// for them. Wait for them before rewriting the replication state: otherwise a query could commit its metadata + /// while the recovery of the new worker compares the Keeper snapshot with the local tables, and the recovery + /// would move the just created table to `_broken_replicated_tables` (or drop it). + /// Stop admitting new initial queries, but keep the worker running while waiting: an admitted query may depend + /// on it, e.g. an `ALTER` of a `ReplicatedMergeTree` table with `alter_sync` waits for its `ALTER_METADATA` entry, + /// which the table executes only while `canExecuteReplicatedMetadataAlter` is true. + /// Not under `ddl_worker_mutex`, because these queries may need it. + if (old_worker) + { + LOG_TRACE(log, "Waiting for initial queries before restoring database metadata in Keeper."); + old_worker->stopInitialQueries(); + old_worker->waitForForegroundTasks(); + } + + { + std::lock_guard lock{ddl_worker_mutex}; + /// Only `restoreDatabaseInKeeper` (serialized by `restore_in_keeper_mutex`) creates a new worker after startup, + /// so the worker is either still the same or was removed by a concurrent `DROP DATABASE`. + chassert(!ddl_worker || ddl_worker == old_worker); + if (ddl_worker) + { + LOG_TRACE(log, "Stopping DDL worker before restoring database metadata in Keeper."); + ddl_worker->shutdown(); + ddl_worker_initialized = false; + replaceDDLWorkerUnlocked(nullptr); + } + } + old_worker.reset(); + + /// If the restore fails, reinitialize the DDL worker so the database remains functional. + /// SAFE: the body runs while an exception propagates and can itself throw (thread + /// creation), which must not replace the restore's own error. + bool need_reinitialize_ddl_worker = true; + SCOPE_EXIT_SAFE({ + if (need_reinitialize_ddl_worker) + reinitializeDDLWorker(); + }); + try { restoreDatabaseNodesInKeeper(zookeeper); @@ -2099,6 +2181,8 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) /// Force the database to recover to update the restored metadata auto current_zookeeper = getZooKeeper(); current_zookeeper->set(replica_path + "/digest", DatabaseReplicatedDDLWorker::FORCE_AUTO_RECOVERY_DIGEST); + + need_reinitialize_ddl_worker = false; reinitializeDDLWorker(); } @@ -2173,7 +2257,7 @@ void DatabaseReplicated::shutdown() { std::lock_guard lock{ddl_worker_mutex}; ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } DatabaseAtomic::shutdown(); } @@ -2184,7 +2268,7 @@ void DatabaseReplicated::dropTable(ContextPtr local_context, const String & tabl waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); + assert(txn || !isDDLWorkerCurrentlyActive() || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); @@ -2293,7 +2377,7 @@ void DatabaseReplicated::commitCreateTable(const ASTCreateQuery & query, const S ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); String statement = getObjectDefinitionFromCreateQuery(query.clone()); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) @@ -2321,7 +2405,7 @@ void DatabaseReplicated::commitAlterTable(const StorageID & table_id, const String & statement, ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_id.table_name); @@ -2361,7 +2445,7 @@ void DatabaseReplicated::detachTablePermanently(ContextPtr local_context, const throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Support for DETACH TABLE PERMANENTLY is disabled"); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { /// We have to remove metadata from zookeeper, because we do not distinguish permanently detached tables @@ -2386,7 +2470,7 @@ void DatabaseReplicated::removeDetachedPermanentlyFlag(ContextPtr local_context, waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery() && attach) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); diff --git a/src/Databases/DatabaseReplicated.h b/src/Databases/DatabaseReplicated.h index aa1f030cb971..d0c6e9377560 100644 --- a/src/Databases/DatabaseReplicated.h +++ b/src/Databases/DatabaseReplicated.h @@ -230,6 +230,15 @@ class DatabaseReplicated : public DatabaseAtomic void stopLoading() override; void initDDLWorkerUnlocked() TSA_REQUIRES(ddl_worker_mutex); + /// Returns a reference to the DDL worker taken under `ddl_worker_mutex`, or nullptr if the database + /// is not initialized yet or is being dropped. + std::shared_ptr tryGetDDLWorker() const; + /// Assigns `ddl_worker` and returns the previous worker. Requires both mutexes, see `ddl_worker_ptr_mutex`. + std::shared_ptr replaceDDLWorkerUnlocked(std::shared_ptr new_worker) + TSA_REQUIRES(ddl_worker_mutex); + /// Whether the current DDL worker exists and is active. Does not take `ddl_worker_mutex`, + /// so it is safe to call from the callbacks of DDL queries executed by the worker. + bool isDDLWorkerCurrentlyActive() const; void restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper); void reinitializeDDLWorker(); @@ -257,9 +266,20 @@ class DatabaseReplicated : public DatabaseAtomic std::atomic_bool is_probably_dropped = false; std::atomic_bool is_recovering = false; std::atomic_bool ddl_worker_initialized = false; - std::unique_ptr ddl_worker; + /// Shared, so that a query thread that uses the worker outside of `ddl_worker_mutex` (e.g. waiting in + /// `tryEnqueueAndExecuteEntry`) keeps it alive while `shutdown`, `restoreDatabaseInKeeper` or + /// `reinitializeDDLWorker` concurrently stop and replace it. Such a thread must take its own reference + /// under the mutex with `tryGetDDLWorker` and never dereference this member without the lock. + std::shared_ptr ddl_worker; mutable std::mutex ddl_worker_mutex; + /// Protects only the `ddl_worker` pointer itself: it is assigned under both mutexes and can be read under either. + /// Unlike `ddl_worker_mutex`, it is never held while the worker is shut down (and its threads are joined), + /// so the callbacks of DDL queries (`commitCreateTable`, `dropTable`, ...) can take it with `isDDLWorkerCurrentlyActive` + /// even when they are executed by the worker's threads or concurrently with `SYSTEM RESTORE DATABASE REPLICA`. + mutable std::mutex ddl_worker_ptr_mutex; UInt32 max_log_ptr_at_creation = 0; + /// Serializes `restoreDatabaseInKeeper`. Taken before `ddl_worker_mutex`. + std::mutex restore_in_keeper_mutex; /// Usually operation with metadata are single-threaded because of the way replication works, /// but StorageReplicatedMergeTree may call alterTable outside from DatabaseReplicatedDDLWorker causing race conditions. diff --git a/src/Databases/DatabaseReplicatedWorker.cpp b/src/Databases/DatabaseReplicatedWorker.cpp index 9112adf427d9..b3e7c1edd804 100644 --- a/src/Databases/DatabaseReplicatedWorker.cpp +++ b/src/Databases/DatabaseReplicatedWorker.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -49,6 +50,7 @@ namespace FailPoints extern const char database_replicated_delay_recovery[]; extern const char database_replicated_delay_entry_execution[]; extern const char database_replicated_stop_entry_execution[]; + extern const char database_replicated_pause_before_initial_query_execution[]; } @@ -160,9 +162,35 @@ void DatabaseReplicatedDDLWorker::shutdown() active_node_holder.reset(); active_node_holder_zookeeper.reset(); + /// Waiters in `tryEnqueueAndExecuteEntry` and `waitForReplicaToProcessAllEntries` (which may outlive the + /// shutdown, holding a reference to this worker) check `stop_flag` under `mutex`. Taking it before notifying + /// guarantees that each of them either sees the flag or receives the notification. + { + std::lock_guard lock{mutex}; + for (const auto & event : log_ptr_waiters) + event->set(); + } + wait_current_task_change.notify_all(); +} + +void DatabaseReplicatedDDLWorker::stopInitialQueries() +{ + { + std::lock_guard lock{mutex}; + initial_queries_stopped = true; + } wait_current_task_change.notify_all(); } +void DatabaseReplicatedDDLWorker::waitForForegroundTasks() +{ + std::unique_lock lock{mutex}; + chassert(stop_flag || initial_queries_stopped); + if (foreground_tasks) + LOG_TRACE(log, "Waiting for {} admitted initial queries", foreground_tasks); + foreground_tasks_finished.wait(lock, [&] { return foreground_tasks == 0; }); +} + void DatabaseReplicatedDDLWorker::initializeReplication() { /// Check if we need to recover replica. @@ -357,19 +385,31 @@ bool DatabaseReplicatedDDLWorker::waitForReplicaToProcessAllEntries(UInt64 timeo return zookeeper->expired() || current_task >= max_log || stop_flag; }); - if (!processed) + if (!processed || stop_flag) return false; } - /// Lets now wait for max_log_ptr to be processed - Coordination::Stat stat; + /// Lets now wait for max_log_ptr to be processed. + /// The event is set either by the watch or by `shutdown`, so a stopped worker does not wait for the whole timeout. auto event_ptr = std::make_shared(); + { + std::lock_guard lock{mutex}; + if (stop_flag) + return false; + log_ptr_waiters.insert(event_ptr); + } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + log_ptr_waiters.erase(event_ptr); + }); + + Coordination::Stat stat; auto new_log = zookeeper->get(our_log_ptr_path, &stat, event_ptr); if (new_log == toString(max_log_ptr)) return true; - return event_ptr->tryWait(timeout_ms); + return event_ptr->tryWait(timeout_ms) && !stop_flag; } @@ -473,9 +513,9 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr { assert(zookeeper->expired() || current_task <= entry_name); - if (zookeeper->expired() || stop_flag) + if (zookeeper->expired() || stop_flag || initial_queries_stopped) { - LOG_TRACE(log, "Not enqueueing query: {}", stop_flag ? "replication stopped" : "ZooKeeper session expired"); + LOG_TRACE(log, "Not enqueueing query: {}", zookeeper->expired() ? "ZooKeeper session expired" : "replication stopped"); throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "ZooKeeper session expired or replication stopped, try again"); } @@ -491,8 +531,21 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr if (!processed) throw Exception(ErrorCodes::UNFINISHED, "Timeout: Cannot enqueue query on this replica, " "most likely because replica is busy with previous queue entries"); + + /// The predicate above has checked `stop_flag` and `initial_queries_stopped` under `mutex`, + /// so `waitForForegroundTasks` will wait for this query. + ++foreground_tasks; } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + --foreground_tasks; + if (foreground_tasks == 0) + foreground_tasks_finished.notify_all(); + }); + + FailPointInjection::pauseFailPoint(FailPoints::database_replicated_pause_before_initial_query_execution); + if (entry.parent_table_uuid.has_value() && !checkParentTableExists(entry.parent_table_uuid.value())) throw Exception(ErrorCodes::TABLE_IS_DROPPED, "Parent table doesn't exist"); diff --git a/src/Databases/DatabaseReplicatedWorker.h b/src/Databases/DatabaseReplicatedWorker.h index 5583f112662f..1f03d0722955 100644 --- a/src/Databases/DatabaseReplicatedWorker.h +++ b/src/Databases/DatabaseReplicatedWorker.h @@ -2,6 +2,9 @@ #include #include #include +#include + +#include namespace DB { @@ -31,8 +34,21 @@ class DatabaseReplicatedDDLWorker : public DDLWorker void shutdown() override; + /// Returns false on timeout or if the worker is stopped before or during the wait. bool waitForReplicaToProcessAllEntries(UInt64 timeout_ms); + /// The worker was shut down. A stopped worker is never restarted, the database replaces it with a new one. + bool isStopped() const { return stop_flag; } + + /// Makes `tryEnqueueAndExecuteEntry` reject new initial queries (as if the worker was stopped), + /// while the worker itself keeps running. Irreversible: the database replaces such a worker afterwards. + void stopInitialQueries(); + + /// Waits until the initial queries that `tryEnqueueAndExecuteEntry` admitted for execution finish. + /// They execute and commit on the submitting threads, so `shutdown` (which joins only the worker's + /// own threads) does not wait for them. Requires `stopInitialQueries` or `shutdown` to be called before. + void waitForForegroundTasks(); + static String enqueueQueryImpl(const ZooKeeperPtr & zookeeper, DDLLogEntry & entry, DatabaseReplicated * const database, bool committed = false, Coordination::Requests additional_checks = {}); /// NOLINT @@ -68,6 +84,15 @@ class DatabaseReplicatedDDLWorker : public DDLWorker std::condition_variable wait_current_task_change; String current_task; + /// The number of initial queries being executed by `tryEnqueueAndExecuteEntry` on the submitting threads. + /// Protected by `mutex`, see `waitForForegroundTasks`. + size_t foreground_tasks = 0; + std::condition_variable foreground_tasks_finished; + /// Set by `stopInitialQueries`. Protected by `mutex`. + bool initial_queries_stopped = false; + /// Events of `waitForReplicaToProcessAllEntries` waiting for our `log_ptr` in Keeper to change. + /// `shutdown` sets them, so that the waiters return without waiting for the timeout. + std::unordered_set> log_ptr_waiters; std::atomic logs_to_keep = std::numeric_limits::max(); std::atomic_bool unsynced_after_recovery = false; diff --git a/src/Databases/MySQL/DatabaseMySQL.cpp b/src/Databases/MySQL/DatabaseMySQL.cpp index 1c85c1ef38d7..ce3ca3203f83 100644 --- a/src/Databases/MySQL/DatabaseMySQL.cpp +++ b/src/Databases/MySQL/DatabaseMySQL.cpp @@ -38,6 +38,7 @@ # include # include # include +# include # include #if CLICKHOUSE_CLOUD @@ -643,6 +644,14 @@ void registerDatabaseMySQL(DatabaseFactory & factory) configuration.username = safeGetLiteralValue(arguments[2], engine_name); configuration.password = safeGetLiteralValue(arguments[3], engine_name); } + + /// Skip only the server's own metadata replay. + if (!(args.is_metadata_replay && args.mode >= LoadingStrictnessLevel::ATTACH)) + { + for (const auto & address : configuration.addresses) + args.context->getRemoteHostFilter().checkHostAndPort(address.first, toString(address.second)); + } + mysql_settings->loadFromQueryContext(args.context, *engine_define); if (engine_define->settings) mysql_settings->loadFromQuery(*engine_define); diff --git a/src/Dictionaries/MongoDBDictionarySource.cpp b/src/Dictionaries/MongoDBDictionarySource.cpp index 437dc9639d5b..21fc0088c6ba 100644 --- a/src/Dictionaries/MongoDBDictionarySource.cpp +++ b/src/Dictionaries/MongoDBDictionarySource.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -45,7 +46,7 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) Block & sample_block, ContextPtr context, const std::string & /* default_database */, - bool /* created_from_ddl */) + bool created_from_ddl) { const auto config_prefix = root_config_prefix + ".mongodb"; auto configuration = std::make_shared(); @@ -102,6 +103,10 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) configuration->checkHosts(context); configuration->checkCollection(); + /// A DDL dictionary is loaded by the server with the global context, so no session setting can permit server credentials here. + if (created_from_ddl && context->getApplicationType() != Context::ApplicationType::LOCAL) + configuration->checkServerCredentialsForDictionary(); + return std::make_unique(dict_struct, std::move(configuration), std::make_shared(sample_block)); }; #else diff --git a/src/Dictionaries/SSDCacheDictionaryStorage.h b/src/Dictionaries/SSDCacheDictionaryStorage.h index e6a732ef34a1..afbf9c3170e2 100644 --- a/src/Dictionaries/SSDCacheDictionaryStorage.h +++ b/src/Dictionaries/SSDCacheDictionaryStorage.h @@ -1370,9 +1370,10 @@ class SSDCacheDictionaryStorage final : public ICacheDictionaryStorage if (memory_buffer_partitions.size() < configuration.max_partitions_count) { /// Try tro create next partition without reusing old partitions - ++current_partition_index; file_buffer.allocateSizeForNextPartition(); memory_buffer_partitions.emplace_back(configuration.block_size, configuration.write_buffer_blocks_size); + /// Advance only after both calls succeed, so the index stays valid if one of them throws. + ++current_partition_index; } else { diff --git a/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp b/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp index 7d5849f91375..8c8226001be9 100644 --- a/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp +++ b/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp @@ -256,7 +256,7 @@ void parseMatchList(UInt64 parent_id, UInt64 & id, const YAML::Node & node, Resu { if (!node.IsSequence()) { - throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Configuration {} must be a yaml list of match rules", node.as()); + throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Configuration must be a yaml list of match rules"); } for (const auto & child_node : node) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp index 41e7a8ced5cf..cc7273537fa2 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp @@ -88,6 +88,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int AZURE_BLOB_STORAGE_ERROR; extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; } @@ -227,6 +228,28 @@ String ConnectionParams::getConnectionURL() const return endpoint.storage_account_url; } +String ConnectionParams::getConnectionURLWithoutQuery() const +{ + if (std::holds_alternative(auth_method)) + { + try + { + /// `ParseConnectionString` appends the SAS of the connection string to `BlobServiceUrl` as its query. + auto url = Azure::Storage::_internal::ParseConnectionString(endpoint.storage_account_url).BlobServiceUrl; + const auto query = url.GetQueryParameters(); + for (const auto & [key, value] : query) + url.RemoveQueryParameter(key); + return url.GetAbsoluteUrl(); + } + catch (const std::logic_error & e) + { + translateAzureSdkParseError(e); + } + } + + return endpoint.storage_account_url.substr(0, endpoint.storage_account_url.find_first_of("?#")); +} + std::unique_ptr ConnectionParams::createForService() const { try @@ -359,6 +382,13 @@ std::unique_ptr getContainerClient(const ConnectionParams & par } } +String getETag(const Azure::ETag & etag, const String & blob_path) +{ + if (!etag.HasValue()) + throw Exception(ErrorCodes::AZURE_BLOB_STORAGE_ERROR, "Azure Blob Storage endpoint did not return an ETag for blob {}", blob_path); + return etag.ToString(); +} + AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { if (config.has(config_prefix + ".account_key") && config.has(config_prefix + ".account_name")) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h index b282df96fae8..7387f59df565 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h @@ -146,6 +146,8 @@ struct ConnectionParams String getContainer() const { return endpoint.container_name; } String getConnectionURL() const; + /// Without the query, which can be a SAS, for where the url only names the endpoint (logs, errors, cache keys). + String getConnectionURLWithoutQuery() const; std::unique_ptr createForService() const; std::unique_ptr createForContainer() const; @@ -163,6 +165,10 @@ BlobClientOptions getClientOptions( AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); +/// `ETag` is an optional response header, and `Azure::ETag::ToString` aborts the process when the tag is absent +/// (also in release builds). Use this function instead: it throws an exception when the endpoint did not send the tag. +String getETag(const Azure::ETag & etag, const String & blob_path); + #endif Endpoint processEndpoint(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp index 80d0714c83ab..d59df48d18a7 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp @@ -100,7 +100,7 @@ class AzureIteratorAsync final : public IObjectStorageIteratorAsync .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); @@ -209,7 +209,7 @@ void AzureObjectStorage::listObjects(const std::string & path, RelativePathsWith .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); diff --git a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp index 241e8c8f7550..ec6a692f6fe6 100644 --- a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp +++ b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp @@ -81,6 +81,7 @@ AsynchronousBoundedReadBuffer::AsynchronousBoundedReadBuffer( { use_page_cache = true; buffer_size = read_settings.page_cache_block_size; + padded = false; } LOG_TEST(log, "Using buffer size {} while reading {}", buffer_size, file_name); diff --git a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp index 672d1bfbf8fb..f206567eea2a 100644 --- a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp +++ b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp @@ -431,7 +431,7 @@ void ReadBufferFromAzureBlobStorage::setMetadataFromResponse(const Azure::Storag { ObjectMetadata new_metadata; new_metadata.size_bytes = blob_size; - new_metadata.etag = details.ETag.ToString(); + new_metadata.etag = AzureBlobStorage::getETag(details.ETag, path); new_metadata.last_modified = static_cast(details.LastModified).time_since_epoch().count(); if (!details.Metadata.empty()) { diff --git a/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp new file mode 100644 index 000000000000..161256caba5b --- /dev/null +++ b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp @@ -0,0 +1,106 @@ +#include "config.h" + +#if USE_AZURE_BLOB_STORAGE + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int AZURE_BLOB_STORAGE_ERROR; +} + +namespace +{ + +class OwningBodyStream : public Azure::Core::IO::BodyStream +{ +public: + explicit OwningBodyStream(std::vector data_) : data(std::move(data_)) { } + + int64_t Length() const override { return static_cast(data.size()); } + + void Rewind() override { position = 0; } + +private: + size_t OnRead(uint8_t * buffer, size_t count, const Azure::Core::Context &) override + { + const size_t to_read = std::min(count, data.size() - position); + if (to_read != 0) + memcpy(buffer, data.data() + position, to_read); + position += to_read; + return to_read; + } + + std::vector data; + size_t position = 0; +}; + +/// A fake Azure endpoint that serves a 10-byte blob in a response without the optional `ETag` header. +class EndpointWithoutETag : public Azure::Core::Http::HttpTransport +{ +public: + std::unique_ptr Send(Azure::Core::Http::Request &, const Azure::Core::Context &) override + { + constexpr size_t blob_size = 10; + auto response = std::make_unique( + 1, 1, Azure::Core::Http::HttpStatusCode::PartialContent, "Partial Content"); + response->SetHeader("Content-Length", std::to_string(blob_size)); + response->SetHeader("Content-Range", "bytes 0-" + std::to_string(blob_size - 1) + "/" + std::to_string(blob_size)); + response->SetHeader("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT"); + response->SetHeader("x-ms-blob-type", "BlockBlob"); + response->SetBodyStream(std::make_unique(std::vector(blob_size, 'a'))); + return response; + } +}; + +} + +/// `Azure::ETag::ToString` aborts the process on an absent tag, also in release builds. +/// A download response without `ETag` must fail the read with an exception instead. +TEST(AzureReadBuffer, MissingETagIsAnException) +{ + Azure::Storage::Blobs::BlobClientOptions client_options; + client_options.Retry.MaxRetries = 0; + client_options.Transport.Transport = std::make_shared(); + + auto container_client = std::make_shared( + Azure::Storage::Blobs::BlobContainerClient("http://azure.invalid/container", client_options), /* blob_prefix */ ""); + + DB::ReadBufferFromAzureBlobStorage buffer( + container_client, + "blob", + DB::ReadSettings{}, + /* max_single_read_retries */ 1, + /* max_single_download_retries */ 1); + + std::optional error_code; + try + { + std::string data; + DB::readStringUntilEOF(data, buffer); + } + catch (const DB::Exception & e) + { + error_code = e.code(); + } + ASSERT_EQ(error_code, std::optional(DB::ErrorCodes::AZURE_BLOB_STORAGE_ERROR)); +} + +#endif diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index 807bf03ce4f7..d82cf35bef76 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -313,6 +313,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se format_settings.arrow.output_fixed_string_as_fixed_byte_array = settings[Setting::output_format_arrow_fixed_string_as_fixed_byte_array]; format_settings.arrow.output_compression_method = settings[Setting::output_format_arrow_compression_method]; format_settings.arrow.output_date_as_uint16 = settings[Setting::output_format_arrow_date_as_uint16]; + format_settings.arrow.output_max_record_batch_bytes = settings[Setting::output_format_arrow_max_record_batch_size_bytes]; format_settings.orc.allow_missing_columns = settings[Setting::input_format_orc_allow_missing_columns]; format_settings.orc.row_batch_size = settings[Setting::input_format_orc_row_batch_size]; format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference = settings[Setting::input_format_orc_skip_columns_with_unsupported_types_in_schema_inference]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 8cc2792c21f8..7ad2d29e34f3 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -5,9 +5,15 @@ #include #include +#include + namespace DB { +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, and the Apache Arrow +/// builders additionally reject the last representable value. +constexpr UInt64 MAX_ARROW_BUFFER_SIZE = std::numeric_limits::max() - 1; + /** * Various tweaks for input/output formats. Text serialization/deserialization * of data types also depend on some of these settings. It is different from @@ -166,6 +172,8 @@ struct FormatSettings bool output_fixed_string_as_fixed_byte_array = true; ArrowCompression output_compression_method = ArrowCompression::NONE; bool output_date_as_uint16 = false; + /// Upper bound on one record batch. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; } arrow{}; struct diff --git a/src/Formats/ProtobufSerializer.cpp b/src/Formats/ProtobufSerializer.cpp index 420d951ed7c0..49089ea851d0 100644 --- a/src/Formats/ProtobufSerializer.cpp +++ b/src/Formats/ProtobufSerializer.cpp @@ -4122,6 +4122,9 @@ namespace if (!name_and_type) return std::nullopt; const auto * tuple_type = assert_cast(name_and_type->type.get()); + /// The key or the value of the map entry was skipped as unsupported, so the map is skipped as a whole. + if (tuple_type->getElements().size() != 2) + return std::nullopt; return NameAndTypePair{name_and_type->name, std::make_shared(tuple_type->getElements())}; } diff --git a/src/Functions/HasSubsequenceImpl.h b/src/Functions/HasSubsequenceImpl.h index 30a522ea50a6..17f370e68344 100644 --- a/src/Functions/HasSubsequenceImpl.h +++ b/src/Functions/HasSubsequenceImpl.h @@ -127,6 +127,8 @@ class HasSubsequenceImpl : public IFunction if (!needle_size) return 1; + if (!haystack_size) + return 0; auto haystack_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(haystack_pos), haystack_end - haystack_pos); auto needle_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(needle_pos), needle_end - needle_pos); diff --git a/src/Functions/URL/protocol.h b/src/Functions/URL/protocol.h index 5e90f538ff1e..5542458a75d9 100644 --- a/src/Functions/URL/protocol.h +++ b/src/Functions/URL/protocol.h @@ -10,6 +10,9 @@ namespace DB /// Extracts scheme from given url. inline std::string_view getURLScheme(const char * data, size_t size) { + if (size == 0) + return {}; + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) const char * pos = data; const char * end = data + size; diff --git a/src/IO/CachedInMemoryReadBufferFromFile.cpp b/src/IO/CachedInMemoryReadBufferFromFile.cpp index c3241d65aede..c2489460cad5 100644 --- a/src/IO/CachedInMemoryReadBufferFromFile.cpp +++ b/src/IO/CachedInMemoryReadBufferFromFile.cpp @@ -26,6 +26,8 @@ CachedInMemoryReadBufferFromFile::CachedInMemoryReadBufferFromFile( , inner_read_until_position(read_until_position) { cache_key.offset = 0; + /// The working buffer is a page cache cell, an exact-size allocation: nothing past its end is readable. + padded = false; } String CachedInMemoryReadBufferFromFile::getFileName() const diff --git a/src/IO/ReadWriteBufferFromHTTP.cpp b/src/IO/ReadWriteBufferFromHTTP.cpp index 02834987d538..29d108ac9ca2 100644 --- a/src/IO/ReadWriteBufferFromHTTP.cpp +++ b/src/IO/ReadWriteBufferFromHTTP.cpp @@ -28,7 +28,8 @@ bool isRetriableError(const Poco::Net::HTTPResponse::HTTPStatus http_status) noe Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND, Poco::Net::HTTPResponse::HTTPStatus::HTTP_FORBIDDEN, Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_IMPLEMENTED, - Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED}; + Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED, + Poco::Net::HTTPResponse::HTTPStatus::HTTP_CONFLICT}; return std::all_of( non_retriable_errors.begin(), non_retriable_errors.end(), [&](const auto status) { return http_status != status; }); diff --git a/src/IO/S3/Client.cpp b/src/IO/S3/Client.cpp index 33dd73a0f579..8e09316d4de7 100644 --- a/src/IO/S3/Client.cpp +++ b/src/IO/S3/Client.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -78,6 +79,7 @@ namespace Setting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; extern const int TOO_MANY_REDIRECTS; } @@ -1196,6 +1198,21 @@ std::unique_ptr ClientFactory::create( // NOLINT if (!server_side_encryption_customer_key_base64.empty()) { + /// `base64Decode` throws on characters outside the alphabet but skips whitespace and ignores padding bits, + /// so the round trip below accepts only the canonical base64 of an AES-256 key, the only key SSE-C takes. + String customer_key; + try + { + customer_key = base64Decode(server_side_encryption_customer_key_base64); + } + catch (const Poco::DataFormatException &) + { + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + } + + if (customer_key.size() != AES256_KEY_BYTES || base64Encode(customer_key) != server_side_encryption_customer_key_base64) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + /// See Client::GeneratePresignedUrlWithSSEC(). headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, @@ -1204,10 +1221,8 @@ std::unique_ptr ClientFactory::create( // NOLINT headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, server_side_encryption_customer_key_base64}); - Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode(server_side_encryption_customer_key_base64); - String str_buffer(reinterpret_cast(buffer.GetUnderlyingData()), buffer.GetLength()); headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, - Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(str_buffer))}); + Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(customer_key))}); } // These will be added after request signing diff --git a/src/IO/S3/Client.h b/src/IO/S3/Client.h index 61ee4ead3dc0..ac7fd172617b 100644 --- a/src/IO/S3/Client.h +++ b/src/IO/S3/Client.h @@ -333,6 +333,8 @@ class Client : private Aws::S3::S3Client class ClientFactory { public: + static constexpr size_t AES256_KEY_BYTES = 32; + ~ClientFactory(); static ClientFactory & instance(); diff --git a/src/IO/SharedThreadPools.cpp b/src/IO/SharedThreadPools.cpp index c299fc8175e5..29e65bf483a8 100644 --- a/src/IO/SharedThreadPools.cpp +++ b/src/IO/SharedThreadPools.cpp @@ -43,6 +43,9 @@ namespace CurrentMetrics extern const Metric MergeTreeSnapshotCommitThreads; extern const Metric MergeTreeSnapshotCommitThreadsActive; extern const Metric MergeTreeSnapshotCommitThreadsScheduled; + extern const Metric ParquetEncoderThreads; + extern const Metric ParquetEncoderThreadsActive; + extern const Metric ParquetEncoderThreadsScheduled; } namespace DB @@ -236,4 +239,10 @@ StaticThreadPool & getFormatParsingThreadPool() return instance; } +StaticThreadPool & getParquetEncoderThreadPool() +{ + static StaticThreadPool instance("ParquetEncoderThreadPool", CurrentMetrics::ParquetEncoderThreads, CurrentMetrics::ParquetEncoderThreadsActive, CurrentMetrics::ParquetEncoderThreadsScheduled); + return instance; +} + } diff --git a/src/IO/SharedThreadPools.h b/src/IO/SharedThreadPools.h index 505688083347..2e8d17d2529c 100644 --- a/src/IO/SharedThreadPools.h +++ b/src/IO/SharedThreadPools.h @@ -91,4 +91,6 @@ StaticThreadPool & getMergeTreePrefixesDeserializationThreadPool(); StaticThreadPool & getFormatParsingThreadPool(); +StaticThreadPool & getParquetEncoderThreadPool(); + } diff --git a/src/IO/tests/gtest_brotli_decoder.cpp b/src/IO/tests/gtest_brotli_decoder.cpp new file mode 100644 index 000000000000..d7b8ade6a3f3 --- /dev/null +++ b/src/IO/tests/gtest_brotli_decoder.cpp @@ -0,0 +1,58 @@ +#include "config.h" + +#if USE_BROTLI + +#include +#include + +#include +#include +#include +#include +#include + +TEST(BrotliDecoder, RejectInvalidBlockSwitch) +{ + // A block switch is invalid when the stream declares only one block type. + // From https://github.com/nodejs/node/blob/main/test/parallel/test-zlib-invalid-input.js. + constexpr std::array input = { + 0x20, 0x00, 0x10, 0x41, 0x41, 0x41, 0xfc, 0xff, 0xff, 0x07, 0x00, + 0x22, 0x28, 0xf0, 0x0b, 0x60, 0xf7, 0xf4, 0x1f, 0x00, 0x00, 0x00}; + + for (size_t chunk_size : {input.size(), size_t{1}}) + { + std::unique_ptr state( + BrotliDecoderCreateInstance(nullptr, nullptr, nullptr), &BrotliDecoderDestroyInstance); + ASSERT_NE(state.get(), nullptr); + + std::array output{}; + size_t total_output = 0; + BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + + for (size_t offset = 0; offset < input.size() && result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;) + { + size_t available_input = std::min(chunk_size, input.size() - offset); + const size_t provided_input = available_input; + const uint8_t * next_input = input.data() + offset; + do + { + uint8_t * next_output = output.data(); + size_t available_output = output.size(); + result = BrotliDecoderDecompressStream( + state.get(), &available_input, &next_input, &available_output, &next_output, nullptr); + total_output += output.size() - available_output; + ASSERT_LT(total_output, 64 * 1024 * 1024); + } + while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT); + offset += provided_input - available_input; + if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) + ASSERT_GT(provided_input - available_input, 0); + } + + EXPECT_EQ(result, BROTLI_DECODER_RESULT_ERROR); + // -17 is the `BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH` code added by the fix. + EXPECT_EQ(BrotliDecoderGetErrorCode(state.get()), static_cast(-17)); + } +} + +#endif diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index 8aa24023956f..b5599a2b6ee6 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -124,12 +124,18 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_) : query(query_->clone()) , query_str_with_secrets(query->formatWithSecretsOneLine()) , user_id(user_id_) , current_roles(current_roles_) + , current_user(current_user_) + , initial_user(initial_user_) + , authenticated_user(authenticated_user_) , settings(std::make_unique(settings_)) , data_kind(data_kind_) { @@ -147,6 +153,13 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( } } + /// Length-prefix each field: update(String) streams only bytes and the queue is keyed + /// by hash alone, so otherwise "a"/"a"/"aaa" and "aa"/"aa"/"a" would collide. + for (const String & identity_field : {current_user, initial_user, authenticated_user}) + { + siphash.update(identity_field.size()); + siphash.update(identity_field); + } setting_changes = settings->changes(); for (auto it = setting_changes.begin(); it != setting_changes.end();) @@ -172,6 +185,9 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -187,6 +203,9 @@ AsynchronousInsertQueue::InsertQuery::operator=(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -533,7 +552,16 @@ AsynchronousInsertQueue::PushResult AsynchronousInsertQueue::pushDataChunk(ASTPt if (insert_query.format == "Values") entry->query_parameters = query_context->getQueryParameters(); - InsertQuery key{query, query_context->getUserID(), query_context->getCurrentRoles(), settings, data_kind}; + const auto & client_info = query_context->getClientInfo(); + InsertQuery key{ + query, + query_context->getUserID(), + query_context->getCurrentRoles(), + client_info.current_user, + client_info.initial_user, + client_info.authenticated_user, + settings, + data_kind}; InsertDataPtr data_to_process; std::future progress_future; @@ -980,6 +1008,14 @@ try insert_context->setCurrentRoles(key.current_roles); } + /// Context::setUser only restores the access-control identity, not the ClientInfo user + /// names. Restore them from the originating query so currentUser()/user()/ + /// authenticatedUser() and the materialized views triggered by the flush observe the + /// inserting user instead of an empty string. + insert_context->setCurrentUserName(key.current_user); + insert_context->setInitialUserName(key.initial_user); + insert_context->setAuthenticatedUserName(key.authenticated_user); + insert_context->setSettings(*key.settings); /// Set initial_query_id, because it's used in InterpreterInsertQuery for table lock. diff --git a/src/Interpreters/AsynchronousInsertQueue.h b/src/Interpreters/AsynchronousInsertQueue.h index 81a6fb36ab6f..f9eed199e90a 100644 --- a/src/Interpreters/AsynchronousInsertQueue.h +++ b/src/Interpreters/AsynchronousInsertQueue.h @@ -85,6 +85,14 @@ class AsynchronousInsertQueue : public WithContext String query_str_with_secrets; std::optional user_id; std::vector current_roles; + /// Client identity of the originating INSERT query (ClientInfo user names). + /// Restored on the flush context so currentUser()/user()/authenticatedUser() and + /// the materialized views triggered by the flush observe the inserting user instead + /// of an empty string. Part of the batching key so inserts from different identities + /// (e.g. impersonation, forwarded distributed queries) are never coalesced. + String current_user; + String initial_user; + String authenticated_user; std::unique_ptr settings; AsynchronousInsertQueueDataKind data_kind; @@ -94,6 +102,9 @@ class AsynchronousInsertQueue : public WithContext const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_); @@ -103,7 +114,7 @@ class AsynchronousInsertQueue : public WithContext StorageID getStorageID() const; private: - auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, setting_changes); } + auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, current_user, initial_user, authenticated_user, setting_changes); } std::vector setting_changes; }; diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index aa63ec626fc7..c3f710e251d1 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1192,6 +1192,15 @@ void ContextSharedMutex::lockSharedImpl() ProfileEvents::increment(ProfileEvents::ContextLockWaitMicroseconds, watch.elapsedMicroseconds()); } +/// An entry of `ContextData::scalars`. `from_client` is true when the block arrived from the client +/// over the wire (`Context::addClientScalar`) rather than being computed by the server, so that +/// `Context::hasComputedScalar` can keep such a block out of the analyzer's scalar-subquery cache. +struct ScalarEntry +{ + Block block; + bool from_client = false; +}; + ContextData::ContextData() { settings = std::make_unique(); @@ -2383,7 +2392,10 @@ std::pair Context::setConcurrentThreadsSoftLimit(UInt64 num, UIn Scalars Context::getScalars() const { std::lock_guard lock(mutex); - return scalars; + Scalars res; + for (const auto & [name, entry] : scalars) + res.emplace(name, entry.block); + return res; } @@ -2398,7 +2410,7 @@ Block Context::getScalar(const String & name) const // often, so 'bad arguments' for now. throw Exception(ErrorCodes::BAD_ARGUMENTS, "Scalar {} doesn't exist (internal bug)", backQuoteIfNeed(name)); } - return it->second; + return it->second.block; } std::optional Context::tryGetSpecialScalar(const String & name) const @@ -2528,7 +2540,18 @@ void Context::addScalar(const String & name, const Block & block) throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); std::lock_guard lock(mutex); - scalars[name] = block; + /// A server-computed value overrides any client-supplied one of the same name and is trusted. + scalars[name] = ScalarEntry{block, /*from_client=*/ false}; +} + + +void Context::addClientScalar(const String & name, const Block & block) +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + scalars[name] = ScalarEntry{block, /*from_client=*/ true}; } @@ -2551,6 +2574,16 @@ bool Context::hasScalar(const String & name) const return scalars.contains(name); } +bool Context::hasComputedScalar(const String & name) const +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + auto it = scalars.find(name); + return it != scalars.end() && !it->second.from_client; +} + void Context::addQueryAccessInfo( const StorageID & table_id, const Names & column_names) @@ -3201,6 +3234,13 @@ void Context::clampToSettingsConstraintsWithLock(SettingsChanges & changes, Sett doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); } +void Context::clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source) +{ + getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.clampRejectingInvalidChanges(*settings, changes, source); + if (getApplicationType() == ApplicationType::LOCAL || getApplicationType() == ApplicationType::SERVER) + doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); +} + void Context::checkMergeTreeSettingsConstraintsWithLock(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.check(merge_tree_settings, changes); @@ -3284,6 +3324,21 @@ void Context::clampToSettingsConstraints(SettingsChanges & changes, SettingSourc clampToSettingsConstraintsWithLock(changes, source); } +void Context::clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source) +{ + if (std::ranges::any_of(changes, isProfileChange)) + { + changes = enforceConstraintsAlongProfileChanges(shared_from_this(), changes, [source](Context & context, SettingsChanges & segment) + { + context.clampToSettingsConstraintsRejectingInvalidChanges(segment, source); + }); + return; + } + + SharedLockGuard lock(mutex); + clampToSettingsConstraintsRejectingInvalidChangesWithLock(changes, source); +} + void Context::checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { SharedLockGuard lock(mutex); @@ -6999,6 +7054,12 @@ void Context::setInitialUserName(const String & initial_user_name) need_recalculate_access = true; } +void Context::setAuthenticatedUserName(const String & authenticated_user_name) +{ + client_info.authenticated_user = authenticated_user_name; + need_recalculate_access = true; +} + void Context::setInitialAddress(const Poco::Net::SocketAddress & initial_address) { client_info.initial_address = std::make_shared(initial_address); diff --git a/src/Interpreters/Context.h b/src/Interpreters/Context.h index e2fcb1224695..d732882f83e9 100644 --- a/src/Interpreters/Context.h +++ b/src/Interpreters/Context.h @@ -164,6 +164,10 @@ class DDLWorker; class ITableFunction; using TableFunctionPtr = std::shared_ptr; class Block; +/// An entry of the query scalar map: the scalar block plus whether it came from the client. +/// Defined in Context.cpp, where `Block` is complete; here `std::map` only needs the forward +/// declaration, the same way `Scalars` is a `std::map` over the forward-declared `Block`. +struct ScalarEntry; class ActionLocksManager; using ActionLocksManagerPtr = std::shared_ptr; class ShellCommand; @@ -395,8 +399,13 @@ class ContextData String insert_format; /// Format, used in insert query. TemporaryTablesMapping external_tables_mapping; - /// Query scalars - Scalars scalars; + /// Query scalars. Each entry carries whether it was supplied by the client over the wire (the + /// `Scalar` packet, i.e. the `clickhouse-client --external ... --scalar` feature or an initiator + /// shipping scalars to a shard) rather than computed by the server itself. The origin travels with + /// the block so that the analyzer's scalar-subquery cache (which keys on the query-tree hash) never + /// mistakes a client-supplied block for an already-computed subquery result; without this a client + /// could forge the result of a scalar subquery used in a row policy and bypass the policy. + std::map scalars; /// Used to store constant values which are different on each instance during distributed plan, such as _shard_num. Scalars special_scalars; @@ -942,6 +951,7 @@ class Context: public ContextData, public std::enable_shared_from_this void setCurrentUserName(const String & current_user_name); void setCurrentAddress(const Poco::Net::SocketAddress & current_address); void setInitialUserName(const String & initial_user_name); + void setAuthenticatedUserName(const String & authenticated_user_name); void setInitialAddress(const Poco::Net::SocketAddress & initial_address); void setInitialQueryId(const String & initial_query_id); void setInitialQueryStartTime(std::chrono::time_point initial_query_start_time); @@ -981,6 +991,16 @@ class Context: public ContextData, public std::enable_shared_from_this void addScalar(const String & name, const Block & block); bool hasScalar(const String & name) const; + /// Add a scalar received from the client over the wire (the `Scalar` packet). Unlike `addScalar`, + /// the entry is marked as client-supplied so that `hasComputedScalar` will not report it as a + /// server-computed subquery result. Explicit readers (`__getScalar`, `_shard_num`, forwarding to + /// shards) still see it through `getScalar` / `hasScalar` / `getScalars`. + void addClientScalar(const String & name, const Block & block); + /// Like `hasScalar`, but returns true only for scalars the server computed itself, never for + /// client-supplied ones. The analyzer's scalar-subquery cache must use this so that a forged + /// client scalar cannot stand in for the result of a (e.g. row-policy) scalar subquery. + bool hasComputedScalar(const String & name) const; + std::optional tryGetSpecialScalar(const String & name) const; void addSpecialScalar(const String & name, const Block & block); @@ -1117,6 +1137,7 @@ class Context: public ContextData, public std::enable_shared_from_this /// For the resets of a statement that also changes `profile`: `changes_applied_first` decides their constraints. void checkSettingsConstraintsForSettingsReset(const std::vector & names, const SettingsChanges & changes_applied_first, SettingSource source); void clampToSettingsConstraints(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source); void checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const; /// Reset settings to default value @@ -1810,6 +1831,7 @@ class Context: public ContextData, public std::enable_shared_from_this void checkSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source); void checkSettingsConstraintsWithLock(const AlterSettingsProfileElements & profile_elements, SettingSource source) const; void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source) const; diff --git a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp index dc247f5119e3..bd217badfadf 100644 --- a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp +++ b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp @@ -156,7 +156,7 @@ void ExecuteScalarSubqueriesMatcher::visit(const ASTSubquery & subquery, ASTPtr } else { - if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasScalar(scalar_query_hash_str)) + if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasComputedScalar(scalar_query_hash_str)) { if (!data.getContext()->getViewSource()) { diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index 2ad408df7443..9976d55c6111 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -24,12 +25,17 @@ #include #include #include +#include #include #include +#include #include #include +#include #include +#include #include +#include #include #include #include @@ -62,6 +68,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int LOGICAL_ERROR; extern const int INCORRECT_QUERY; extern const int NOT_IMPLEMENTED; @@ -73,6 +80,83 @@ namespace ErrorCodes extern const int SUPPORT_IS_DISABLED; } +namespace +{ + +/// A setting that sends the table's data elsewhere copies the data as it is stored, so nothing can filter the rows +/// that a row policy hides. It reads only the query and the access entities, +/// not the table, so it runs on the initiator. The database is resolved only for such a setting, so that other queries +/// do not need a current database. +void checkNoRowPolicyForExport(const ASTAlterQuery & alter, const ContextPtr & context) +{ + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::MODIFY_SETTING || !command.settings_changes) + continue; + + const auto & changes = command.settings_changes->as().changes; + if (StorageFactory::instance().getExportAccessOfAnyEngine(changes).empty()) + continue; + + const String database = context->resolveDatabase(alter.getDatabase()); + auto row_policy_filter = context->getRowPolicyFilter(database, alter.getTable(), RowPolicyFilterType::SELECT_FILTER); + if (row_policy_filter && !row_policy_filter->isAlwaysTrue()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "Cannot change the settings of table {}.{} that send its data elsewhere because a row policy applies to it. " + "The data is copied as it is stored, so its rows cannot be filtered", + backQuoteIfNeed(database), backQuoteIfNeed(alter.getTable())); + } +} + +/// A `Replicated`-database host applies the statement without the submitting user. `ON CLUSTER` does +/// not reach this: it is refused unless its hosts run as the initiating user. +void checkAddedIndexPermissions(const ASTAlterQuery & alter, const StoragePtr & table, const ContextPtr & context) +{ + if (!table) + return; + + bool adds_transform = false; + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + + if (const auto * declaration = command.index_decl->as()) + if (hasTextIndexPreOrPostProcessor(*declaration)) + adds_transform = true; + } + + /// Against the schema the whole statement produces: a command of the same statement can change what + /// an alias in a transform expands to. Transforms only, so other statements get no extra analysis. + if (!adds_transform) + return; + + AlterCommands commands; + for (const auto & child : alter.command_list->children) + { + const auto * command_ast = child->as(); + if (command_ast->type == ASTAlterCommand::EXECUTE_COMMAND) + continue; + if (auto command = AlterCommand::parse(command_ast)) + commands.emplace_back(std::move(*command)); + } + + /// The same sequence as `executeToTable`: `apply` relies on the checks before it, and it authorizes + /// the added indices as the user. + StorageInMemoryMetadata metadata = table->getInMemoryMetadata(); + commands.validate(table, context); + commands.prepare(metadata); + table->checkAlterIsPossible(commands, context); + /// As the storages do before `apply`: an explicit `ADD STATISTICS` replaces an implicit one. + removeImplicitStatistics(metadata.columns); + commands.apply(metadata, context); +} + +} + InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, ContextMutablePtr context_) : WithMutableContext(context_), query_ptr(query_ptr_) { } @@ -130,15 +214,37 @@ BlockIO InterpreterAlterQuery::executeToTable(const ASTAlterQuery & alter) DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_alter = captured_query_ptr->as(); + for (const auto & child : captured_alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + if (const auto * declaration = command.index_decl->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + } + }; + /// The hosts run the entry without the user, so the row policy is checked here before the entry is enqueued. + checkNoRowPolicyForExport(alter, getContext()); return executeDDLQueryOnCluster(query_ptr, getContext(), params); } getContext()->checkAccess(getRequiredAccess()); + checkNoRowPolicyForExport(alter, getContext()); if (!table_id) throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(alter.getDatabase())); DatabasePtr database = DatabaseCatalog::instance().getDatabase(table_id.database_name); + + checkAddedIndexPermissions(alter, table, getContext()); + if (database->shouldReplicateQuery(getContext(), query_ptr)) { auto guard = DatabaseCatalog::instance().getDDLGuard(table_id.database_name, table_id.table_name, database.get()); @@ -624,6 +730,20 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand(const AS case ASTAlterCommand::MODIFY_SETTING: { required_access.emplace_back(AccessType::ALTER_SETTINGS, database, table); + + /// A setting that sends the table's data elsewhere, e.g. the move destination of a queue, is the same data flow as + /// `INSERT INTO FUNCTION s3(...) SELECT * FROM
`. The creator of the table supplied its source and credentials, + /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator + /// of `ON CLUSTER` can check them without the table. + if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) + { + auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + if (!export_access.empty()) + { + required_access.append_range(std::move(export_access)); + required_access.emplace_back(AccessType::SELECT, database, table); + } + } break; } case ASTAlterCommand::ATTACH_PARTITION: diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index 715a96ebc0b7..d0a1ce770c76 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -34,10 +34,12 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -146,6 +148,7 @@ namespace Setting namespace ServerSetting { + extern const ServerSettingsBool distributed_ddl_use_initial_user_and_roles; extern const ServerSettingsBool ignore_empty_sql_security_in_create_view_query; extern const ServerSettingsUInt64 max_database_num_to_throw; extern const ServerSettingsUInt64 max_dictionary_num_to_throw; @@ -988,6 +991,14 @@ InterpreterCreateQuery::TableProperties InterpreterCreateQuery::getTableProperti if (!create.columns_list) create.set(create.columns_list, make_intrusive()); + /// Authorize the text index transforms of every definition the user supplies now. A replay of stored + /// metadata is not checked, so such a table still attaches. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + { + for (const auto & index : properties.indices) + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + ASTPtr new_columns = formatColumns(properties.columns); ASTPtr new_indices = formatIndices(properties.indices); ASTPtr new_constraints = formatConstraints(properties.constraints); @@ -1714,6 +1725,11 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) /// Set and retrieve list of columns, indices and constraints. Set table engine if needed. Rewrite query in canonical way. TableProperties properties = getTablePropertiesAndNormalizeCreateQuery(create, mode); + /// Only here is an engine inherited through `AS` known, and nothing is enqueued or created yet. + /// A replay of a stored definition was checked when it was created. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + checkExportAccess(create); + DatabasePtr database; bool need_add_to_database = !create.isTemporary(); // In case of an ON CLUSTER query, the database may not be present on the initiator node @@ -2500,6 +2516,20 @@ BlockIO InterpreterCreateQuery::executeQueryOnCluster(ASTCreateQuery & create) prepareOnClusterQuery(create, getContext(), create.cluster); DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_create = captured_query_ptr->as(); + if (!captured_create.columns_list || !captured_create.columns_list->indices) + return; + + for (const auto & index : captured_create.columns_list->indices->children) + if (const auto * declaration = index->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + }; return executeDDLQueryOnCluster(query_ptr, getContext(), params); } @@ -2539,6 +2569,46 @@ BlockIO InterpreterCreateQuery::execute() if (inherited.storage && inherited.storage->engine) getContext()->checkAccess(AccessType::TABLE_ENGINE, inherited.storage->engine->name); + + /// setEngine copies only the outer engine of a `TimeSeries` source, and the worker copies + /// its inner engines while normalizing, so add the ones this query does not give itself + if (inherited.is_time_series_table) + { + auto as_create_ptr = DatabaseCatalog::instance().getDatabase(inherited.as_database)->getCreateTableQuery(inherited.as_table, getContext()); + const auto & as_create = as_create_ptr->as(); + if (as_create.targets) + for (const auto & target : as_create.targets->targets) + if (target.inner_engine && !inherited.getTargetInnerEngine(target.kind)) + inherited.setTargetInnerEngine(target.kind, target.inner_engine->clone()); + } + + /// the worker inherits the move destination of the source too, and runs with no user + checkExportAccess(inherited); + + /// A worker copies the source's indices with no user, so declare their transforms here. + if (inherited.storage && inherited.storage->engine && endsWith(inherited.storage->engine->name, "MergeTree")) + { + /// Before resolving it: an error below would otherwise disclose a source the user + /// cannot see. + getContext()->checkAccess(AccessType::SHOW_COLUMNS, create.as_database, create.as_table); + StoragePtr as_storage = resolveStorageProxyLoading( + DatabaseCatalog::instance().getTable({create.as_database, create.as_table}, getContext())); + /// The query dispatches `AS src`, so each host materializes its own source, which + /// may define the transform differently from the one authorized here. + const bool workers_use_initiator_user + = getContext()->getServerSettings()[ServerSetting::distributed_ddl_use_initial_user_and_roles] + && on_cluster_version >= DDLLogEntry::INITIATOR_USER_VERSION; + + auto as_storage_metadata = as_storage->getInMemoryMetadataPtr(); + for (const auto & index : as_storage_metadata->getSecondaryIndices()) + { + if (index.isImplicitlyCreated()) + continue; + if (!workers_use_initiator_user) + rejectTextIndexTransformWithoutInitiatorUser(index); + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + } } return executeQueryOnCluster(create); @@ -2623,9 +2693,28 @@ AccessRightsElements InterpreterCreateQuery::getRequiredAccess() const if (create.storage && create.storage->engine) required_access.emplace_back(AccessType::TABLE_ENGINE, create.storage->engine->name); + /// `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the table data and then moves it to the + /// data path of the new table. Reading it needs `READ` on the FILE source like the `file` function does, and + /// taking it away from `user_files` needs `WRITE`, like renaming files after processing does. Without this, + /// `CREATE TABLE` on a table of their own would let a user read or consume any data staged in `user_files`. + if (create.has_attach_from_path) + required_access.emplace_back(AccessType::READ | AccessType::WRITE, toStringSource(AccessTypeObjects::Source::FILE)); + + /// Settings that send the table's data elsewhere, e.g. the move destination of a queue, need the grants of that place. + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + return required_access; } +void InterpreterCreateQuery::checkExportAccess(const ASTCreateQuery & create) const +{ + /// Internal queries (initiated by the server itself) always have access to everything. + if (internal) + return; + + getContext()->checkAccess(StorageFactory::instance().getExportAccess(create)); +} + void InterpreterCreateQuery::extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr &, ContextPtr) const { if (!as_table_saved.empty()) diff --git a/src/Interpreters/InterpreterCreateQuery.h b/src/Interpreters/InterpreterCreateQuery.h index 9692dcdedbb6..674965cc7e00 100644 --- a/src/Interpreters/InterpreterCreateQuery.h +++ b/src/Interpreters/InterpreterCreateQuery.h @@ -112,6 +112,10 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext void setEngine(ASTCreateQuery & create) const; AccessRightsElements getRequiredAccess() const; + /// The part of `getRequiredAccess` for settings that send the table's data elsewhere, checked again once + /// `setEngine` has resolved an engine inherited through `AS`, which `getRequiredAccess` cannot see. + void checkExportAccess(const ASTCreateQuery & create) const; + /// Create IStorage and add it to database. If table already exists and IF NOT EXISTS specified, do nothing and return false. bool doCreateTable(ASTCreateQuery & create, const TableProperties & properties, DDLGuardPtr & ddl_guard, LoadingStrictnessLevel mode); BlockIO doCreateOrReplaceTable(ASTCreateQuery & create, const InterpreterCreateQuery::TableProperties & properties, LoadingStrictnessLevel mode); diff --git a/src/Interpreters/JIT/CHJIT.cpp b/src/Interpreters/JIT/CHJIT.cpp index 67c3068d0e0c..85609a0f5f07 100644 --- a/src/Interpreters/JIT/CHJIT.cpp +++ b/src/Interpreters/JIT/CHJIT.cpp @@ -427,7 +427,12 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function { std::lock_guard lock(jit_lock); - auto module = createModuleForCompilation(); + /// A fresh context per compile: `LLVMContext` never frees the constants it interns, and the optimizer + /// creates new ones for every distinct literal, so a long-lived context grows without bound. + /// Declared before `module`, which must be destroyed first. + auto context = std::make_unique(); + + auto module = createModuleForCompilation(*context); compile_function(*module); auto module_info = compileModule(std::move(module)); @@ -435,7 +440,7 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function return module_info; } -std::unique_ptr CHJIT::createModuleForCompilation() +std::unique_ptr CHJIT::createModuleForCompilation(llvm::LLVMContext & context) { std::unique_ptr module = std::make_unique("jit" + std::to_string(current_module_key), context); module->setDataLayout(layout); diff --git a/src/Interpreters/JIT/CHJIT.h b/src/Interpreters/JIT/CHJIT.h index 89d446fd3b34..04788222136e 100644 --- a/src/Interpreters/JIT/CHJIT.h +++ b/src/Interpreters/JIT/CHJIT.h @@ -89,7 +89,7 @@ class CHJIT private: - std::unique_ptr createModuleForCompilation(); + std::unique_ptr createModuleForCompilation(llvm::LLVMContext & context); CompiledModule compileModule(std::unique_ptr module); @@ -99,7 +99,6 @@ class CHJIT static std::unique_ptr getTargetMachine(); - llvm::LLVMContext context; std::unique_ptr machine; llvm::DataLayout layout; std::unique_ptr compiler; diff --git a/src/Interpreters/executeDDLQueryOnCluster.cpp b/src/Interpreters/executeDDLQueryOnCluster.cpp index 514f390e93ff..b2e6a3880daf 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.cpp +++ b/src/Interpreters/executeDDLQueryOnCluster.cpp @@ -194,6 +194,12 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, ContextPtr context, entry.initiator_user = context->getUserName(); entry.initiator_user_roles = context->getAccessControl().tryReadNames(context->getCurrentRoles()); } + + /// The workers run the query as the initiator's user and roles only if the entry carries them. + const bool workers_use_initiator_user = !entry.initiator_user.empty() && entry.version >= DDLLogEntry::INITIATOR_USER_VERSION; + if (params.additional_access_check) + params.additional_access_check(/* throw_if_unresolved = */ !workers_use_initiator_user); + ddl_worker.updateHostIDs(entry.hosts); String node_path = ddl_worker.enqueueQuery(entry, params.retries_info); diff --git a/src/Interpreters/executeDDLQueryOnCluster.h b/src/Interpreters/executeDDLQueryOnCluster.h index 69e0c38834e6..f98f9bb4aafc 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.h +++ b/src/Interpreters/executeDDLQueryOnCluster.h @@ -7,6 +7,8 @@ #include #include +#include + namespace zkutil { @@ -38,6 +40,12 @@ struct DDLQueryOnClusterParams /// Privileges which the current user should have to execute a query. AccessRightsElements access_to_check; + /// An authorization check which must run after the standard cluster and query checks but before enqueueing. + /// It receives whether the workers run the query without the initiator's user: they run it as that user and + /// roles only when `distributed_ddl_use_initial_user_and_roles` is enabled and `distributed_ddl_entry_format_version` + /// carries the initiator's user. + std::function additional_access_check; + /// Use retries when creating nodes "query-0000000000", "query-0000000001", "query-0000000002" in ZooKeeper. ZooKeeperRetriesInfo retries_info; }; diff --git a/src/Interpreters/tests/gtest_async_insert_key.cpp b/src/Interpreters/tests/gtest_async_insert_key.cpp index 0f4095a05bee..327525b4db5c 100644 --- a/src/Interpreters/tests/gtest_async_insert_key.cpp +++ b/src/Interpreters/tests/gtest_async_insert_key.cpp @@ -37,13 +37,59 @@ TEST(AsyncInsertKey, SettingsChanges) auto kind = AsynchronousInsertQueueDataKind::Parsed; - AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, settings1, kind); - AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, settings2, kind); - AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, settings3, kind); - AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, settings4, kind); + AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, {}, {}, {}, settings1, kind); + AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, {}, {}, {}, settings2, kind); + AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, {}, {}, {}, settings3, kind); + AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, {}, {}, {}, settings4, kind); EXPECT_EQ(key1, key2); EXPECT_NE(key1, key3); EXPECT_NE(key2, key3); EXPECT_NE(key3, key4); } + +TEST(AsyncInsertKey, IdentityHashIsNotAmbiguous) +{ + String query_str = "INSERT INTO test (a, b, c) VALUES (1, 2, 3)"; + ParserInsertQuery parser(query_str.data() + query_str.size(), false); + ASTPtr query = parseQuery(parser, query_str, DBMS_DEFAULT_MAX_QUERY_SIZE, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + Settings settings; + settings.set("async_insert", 1); + + auto kind = AsynchronousInsertQueueDataKind::Parsed; + + auto make_key = [&](const String & current_user, const String & initial_user, const String & authenticated_user) + { + return AsynchronousInsertQueue::InsertQuery( + query, {}, {}, current_user, initial_user, authenticated_user, settings, kind); + }; + + /// The three identity fields are variable-length strings folded into the queue key hash, + /// and the queue is indexed by hash alone. Without a length delimiter "a"/"a"/"aaa" and + /// "aa"/"aa"/"a" stream the same bytes ("aaaaa") and collide, which would route a second + /// user's insert into the first user's pending batch and flush it under the wrong + /// ClientInfo. The keys must differ both by hash and by equality. + auto key_a = make_key("a", "a", "aaa"); + auto key_b = make_key("aa", "aa", "a"); + EXPECT_NE(key_a.hash, key_b.hash); + EXPECT_NE(key_a, key_b); + + /// A field boundary shift across the current/initial split must also be distinguished. + auto key_c = make_key("a", "b", ""); + auto key_d = make_key("a", "", "b"); + EXPECT_NE(key_c.hash, key_d.hash); + EXPECT_NE(key_c, key_d); + + /// Same identity still hashes the same and compares equal (batching preserved). + auto key_e = make_key("alice", "alice", "alice"); + auto key_f = make_key("alice", "alice", "alice"); + EXPECT_EQ(key_e.hash, key_f.hash); + EXPECT_EQ(key_e, key_f); + + /// Distinct identities never coalesce. + auto key_g = make_key("alice", "alice", "alice"); + auto key_h = make_key("bob", "bob", "bob"); + EXPECT_NE(key_g.hash, key_h.hash); + EXPECT_NE(key_g, key_h); +} diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index 8509d3903c38..e2698652f3fc 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -72,6 +73,16 @@ namespace return AzureConnectionValue::PlainStorageAccountURL; } + /// The keys an Azure named collection accepts (`StorageAzureConfiguration`). An override with any + /// other key, which can name any credential, is rejected only after the statement is logged. + bool isAzureCollectionKey(std::string_view key) + { + static const std::unordered_set keys = {"blob_path", "container", "format", "compression", "structure", + "compression_method", "account_name", "account_key", "connection_string", "storage_account_url", "partition_strategy", + "partition_columns_in_data_file", "client_id", "tenant_id"}; + return keys.contains(key); + } + /// The backup engines whose locator names a destination with no credential in it, each with the /// argument count it accepts. `BackupFactory` registers exactly these plus `S3` and `AzureBlobStorage`. std::optional credentialFreeBackupEngineArity(const String & engine_name) @@ -607,43 +618,147 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageFunctionSecretArguments( /// azureBlobStorageCluster('cluster_name', 'conn_string/storage_account_url', ...) has 'conn_string/storage_account_url' as its second argument. size_t url_arg_idx = is_cluster_function ? 1 : 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + + /// The other values are hidden before a connection string is: hiding that replaces its whole argument. if (!is_cluster_function && isNamedCollectionName(0)) { /// azureBlobStorage(named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(1); + maskUnreadAzureCollectionOverrides(1); + findSecretNamedArgument("account_key", 1); if (maskAzureConnectionString(-1, true, 1)) return; - findSecretNamedArgument("account_key", 1); + maskUnshowableAzureConnectionOverrides(1); return; } if (is_cluster_function && isNamedCollectionName(1)) { /// azureBlobStorageCluster(cluster, named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(2); + maskUnreadAzureCollectionOverrides(2); + findSecretNamedArgument("account_key", 2); if (maskAzureConnectionString(-1, true, 2)) return; - findSecretNamedArgument("account_key", 2); + maskUnshowableAzureConnectionOverrides(2); return; } - if (maskAzureConnectionString(url_arg_idx)) + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + + if (const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx)) + markSecretArgument(*credential_arg_idx); + + if (maskAzureConnectionString(arg(url_arg_idx))) return; - /// We should check other arguments first because we don't need to do any replacement in case of - /// azureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - /// azureBlobStorageCluster(cluster, connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) + if (arg(url_arg_idx) < function->arguments->size()) + maskUnshowableAzureConnectionValue(arg(url_arg_idx), *function->arguments->at(arg(url_arg_idx)), /* argument_is_named= */ false); +} + +void FunctionSecretArgumentsFinder::maskAzureExtraCredentials() +{ + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + if (const auto f = function->arguments->at(i)->getFunction(); f && f->name() == "extra_credentials") + markSecretArgument(i); + } +} + +std::optional FunctionSecretArgumentsFinder::tryGetAzureKey(const AbstractFunction & equals) +{ + String key; + if (equals.arguments && equals.arguments->size() == 2 && tryGetStringFromArgument(*equals.arguments->at(0), &key) + && isAzureCollectionKey(key)) + return key; + return {}; +} + +void FunctionSecretArgumentsFinder::maskUnreadAzureCollectionOverrides(size_t start) +{ + std::vector connection_overrides; + for (size_t i = start, size = function->arguments->size(); i < size; ++i) { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) + const auto f = function->arguments->at(i)->getFunction(); + if (!f || f->name() != "equals") + continue; + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if (!(tryGetStringFromArgument(*f->arguments->at(1), nullptr) || f->arguments->at(1)->tryGetLiteralText(nullptr))) + markSecretArgument(i, /* argument_is_named= */ true); + if (key == "connection_string" || key == "storage_account_url") + connection_overrides.push_back(i); + } + + if (connection_overrides.size() > 1) + for (const size_t i : connection_overrides) + markSecretArgument(i, /* argument_is_named= */ true); +} + +std::vector FunctionSecretArgumentsFinder::azureSlotArguments(size_t start) +{ + std::vector slots; + size_t extra_credentials = 0; + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + const auto argument = function->arguments->at(i); + if (argument->isSettings()) + continue; + const auto f = i < start ? nullptr : argument->getFunction(); + if (f && f->name() == "extra_credentials") { - if (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg)) - return; + ++extra_credentials; + continue; + } + if (f && f->name() == "equals" && f->arguments && f->arguments->size() == 2) + { + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if ((key != "partition_strategy" && key != "partition_columns_in_data_file") || !f->arguments->at(1)->tryGetLiteralText(nullptr)) + markSecretArgument(i, /* argument_is_named= */ true); + continue; } + slots.push_back(i); } - /// We're going to replace 'account_key' with '[HIDDEN]' if account_key is used in the signature - if (url_arg_idx + 4 < count) - markSecretArgument(url_arg_idx + 4); + if (extra_credentials > 1) + { + maskEveryArgument(); + return {}; + } + return slots; +} + +std::optional FunctionSecretArgumentsFinder::azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const +{ + const size_t count = slot_arguments.size(); + if (count == url_arg_idx + 2) + return slot_arguments[url_arg_idx + 1]; + if (count <= url_arg_idx + 4) + return {}; + String fourth_arg; + if (count <= url_arg_idx + 7 && tryGetStringFromArgument(slot_arguments[url_arg_idx + 3], &fourth_arg) + && (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg))) + return {}; + return slot_arguments[url_arg_idx + 4]; +} + +void FunctionSecretArgumentsFinder::maskPositionalsAfterAzureCollection(size_t start) +{ + for (size_t i = start, size = function->arguments->size(); i < size; ++i) + { + const auto f = function->arguments->at(i)->getFunction(); + if (!f || (f->name() != "equals" && f->name() != "extra_credentials")) + markSecretArgument(i); + } } bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named, size_t start) @@ -663,32 +778,38 @@ bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_id return false; } - if (!url_arg.starts_with("http")) + if (!url_arg.starts_with("http") && maskAzureConnectionStringSecrets(url_arg)) { - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - if (RE2::Replace(&url_arg, account_key_pattern, "AccountKey=[HIDDEN]\\1")) - { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; - } + chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments + result.start = url_arg_idx; + result.are_named = argument_is_named; + result.count = 1; + result.replacement = url_arg; + return true; + } - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - if (RE2::Replace(&url_arg, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1")) + return false; +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionValue( + size_t index, const AbstractFunction::Argument & value, bool argument_is_named) +{ + String text; + if (!value.tryGetString(&text, /* allow_identifier= */ false) || classifyAzureConnectionValue(text) == AzureConnectionValue::Unmaskable) + markSecretArgument(index, argument_is_named); +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionOverrides(size_t start) +{ + for (const auto * key : {"connection_string", "storage_account_url"}) + { + for (ssize_t i = findNamedArgument(nullptr, key, start); i >= 0; i = findNamedArgument(nullptr, key, static_cast(i) + 1)) { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; + const auto index = static_cast(i); + /// `findNamedArgument` returns only an `equals` function with two arguments. + maskUnshowableAzureConnectionValue(index, *function->arguments->at(index)->getFunction()->arguments->at(1), /* argument_is_named= */ true); } } - - return false; } bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit) @@ -701,8 +822,10 @@ bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t s { /// A key this rule cannot read hides which credential the override carries; a value that is /// no plain literal or identifier can nest one (`headers('Authorization' = '...')`). + String key; if (argument_function->arguments && argument_function->arguments->size() == 2 - && tryGetStringFromArgument(*argument_function->arguments->at(0), nullptr) + && tryGetStringFromArgument(*argument_function->arguments->at(0), &key) + && isAzureCollectionKey(key) && (tryGetStringFromArgument(*argument_function->arguments->at(1), nullptr) || argument_function->arguments->at(1)->tryGetLiteralText(nullptr))) continue; @@ -1043,6 +1166,12 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format, [account_name, account_key, ...]) size_t url_arg_idx = 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + if (isNamedCollectionName(url_arg_idx)) { /// AzureBlobStorage(named_collection, ..., account_key = 'account_key', ...) @@ -1057,28 +1186,15 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - /// We should check other arguments first because we don't need to do any replacement in case of - /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - bool fourth_argument_is_format = false; - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) - { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) - fourth_argument_is_format = fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg); - } - /// Which argument holds a credential: the two-argument shape takes a shared access signature beside - /// the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. - std::optional credential_arg_idx; - if (count == url_arg_idx + 2) - credential_arg_idx = url_arg_idx + 1; - else if (!fourth_argument_is_format && (url_arg_idx + 4 < count)) - credential_arg_idx = url_arg_idx + 4; + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx); /// The engine reads this argument as a connection string or as a plain account url; a value of /// another shape is read by neither rule below, and a hidden connection string replaces it whole. String connection_value; - const auto shape = tryGetStringFromArgument(url_arg_idx, &connection_value) + const auto shape = tryGetStringFromArgument(arg(url_arg_idx), &connection_value) ? classifyAzureConnectionValue(connection_value) : AzureConnectionValue::Unmaskable; if (shape == AzureConnectionValue::Unmaskable || (shape == AzureConnectionValue::ConnectionString && credential_arg_idx)) @@ -1087,7 +1203,7 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - if (maskAzureConnectionString(url_arg_idx)) + if (maskAzureConnectionString(arg(url_arg_idx))) return; if (credential_arg_idx) diff --git a/src/Parsers/FunctionSecretArgumentsFinder.h b/src/Parsers/FunctionSecretArgumentsFinder.h index b2c0f511ebbd..161a9754aa52 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.h +++ b/src/Parsers/FunctionSecretArgumentsFinder.h @@ -28,6 +28,9 @@ class AbstractFunction /// The exact literal text of any scalar literal (`1`, `true`, `1.5`), with strings quoted. /// Lets a reconstructor keep non-string values like `use_environment_credentials = 1` visible. virtual bool tryGetLiteralText(String * res) const = 0; + /// A `SETTINGS` clause among the arguments (`remote(..., SETTINGS ...)`): not a positional + /// argument, and it hides its own secret values when formatted. + virtual bool isSettings() const { return false; } }; class Arguments { @@ -164,12 +167,37 @@ class FunctionSecretArgumentsFinder void findS3FunctionSecretArguments(bool is_cluster_function); void findAzureBlobStorageFunctionSecretArguments(bool is_cluster_function); + /// Hides every `extra_credentials(...)` whole, its keys included: a key can be written as anything, a credential too. + void maskAzureExtraCredentials(); + /// The key of a `key = value` argument if it is one of the keys an Azure named collection accepts. Any other left + /// operand can be the credential itself (`'sp=r&sig=...' = 'x'`), so its argument is hidden whole. + static std::optional tryGetAzureKey(const AbstractFunction & equals); + /// Hides every override from `start` on that this rule cannot read: one whose key an Azure named collection does not + /// accept or whose value is no plain literal (it can nest a credential), and every connection override when there are + /// several: only one is read, and only one can be partly shown. + void maskUnreadAzureCollectionOverrides(size_t start); + /// The raw indexes of the arguments the Azure parser assigns slots to, the ones before `start` (the cluster name) as + /// written: it strips the `SETTINGS` clause and the first `extra_credentials(...)`, and a `key = value` takes no slot. + /// Also hides the value of a key the explicit form does not read (all of an argument whose key is no Azure key), and + /// every argument when a second `extra_credentials(...)` shifts the slots. + std::vector azureSlotArguments(size_t start); + /// The raw index of the argument holding a credential, if any: the two-argument shape takes a shared access signature + /// beside the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. + std::optional azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const; + /// After the collection name every argument must be an override or `extra_credentials(...)`; a positional one is + /// invalid but logged before validation rejects it, and can be a credential. + void maskPositionalsAfterAzureCollection(size_t start); bool maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named = false, size_t start = 0); /// Whether the arguments an `AzureBlobStorage(named_collection, ...)` destination or table takes /// from `start` can be shown: only an argument written here can carry a credential, and each has /// to be readable enough to tell that it does not. `positional_limit` bounds the plain literals /// read beside the overrides: one filename for a backup locator, none for a table engine. bool azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit); + /// Hides a connection value that no rule here can show: a URL carrying a credential of its own + /// (`user:key@`, a SAS `?sig=...`), or a value that is not a plain string literal. + void maskUnshowableAzureConnectionValue(size_t index, const AbstractFunction::Argument & value, bool argument_is_named); + /// The same, for the `connection_string` and `storage_account_url` overrides of a named collection from `start` on. + void maskUnshowableAzureConnectionOverrides(size_t start); /// Masks the secrets of every URL form (`url`/`urlCluster` table functions, the `URL` table /// engine, and their named-collection variants): the userinfo password of the url positional or a /// named `url = ...` override, and the `headers(...)` values at any position. `url` is at diff --git a/src/Parsers/FunctionSecretArgumentsFinderAST.h b/src/Parsers/FunctionSecretArgumentsFinderAST.h index 754411535c8d..6d0c5c050342 100644 --- a/src/Parsers/FunctionSecretArgumentsFinderAST.h +++ b/src/Parsers/FunctionSecretArgumentsFinderAST.h @@ -5,6 +5,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,7 @@ class FunctionAST : public AbstractFunction return nullptr; } bool isIdentifier() const override { return argument->as(); } + bool isSettings() const override { return argument->as(); } bool tryGetString(String * res, bool allow_identifier) const override { if (const auto * literal = argument->as()) diff --git a/src/Parsers/Lexer.cpp b/src/Parsers/Lexer.cpp index 8806ed24492c..abb35a149bc5 100644 --- a/src/Parsers/Lexer.cpp +++ b/src/Parsers/Lexer.cpp @@ -116,7 +116,7 @@ Token quotedHexOrBinString(const char *& pos, const char * const token_begin, co Token Lexer::nextToken() { Token res = nextTokenImpl(); - if (max_query_size && res.end > begin + max_query_size) + if (begin && max_query_size && res.end > begin + max_query_size) res.type = TokenType::ErrorMaxQuerySizeExceeded; if (res.isSignificant()) prev_significant_token_type = res.type; diff --git a/src/Parsers/tests/gtest_Parser.cpp b/src/Parsers/tests/gtest_Parser.cpp index 22f73a45a039..429e65d8d125 100644 --- a/src/Parsers/tests/gtest_Parser.cpp +++ b/src/Parsers/tests/gtest_Parser.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -38,6 +39,13 @@ std::ostream & operator<<(std::ostream & ostr, const ParserTestCase & test_case) return ostr << "ParserTestCase input: " << input_text; } +TEST(Lexer, NullInputWithMaxQuerySize) +{ + Lexer lexer(nullptr, nullptr, 262144); + Token token = lexer.nextToken(); + EXPECT_EQ(TokenType::EndOfStream, token.type); +} + TEST_P(ParserTest, parseQuery) { const auto & parser = std::get<0>(GetParam()); diff --git a/src/Processors/Chunk.cpp b/src/Processors/Chunk.cpp index 0564131c8768..aef99bd3dee0 100644 --- a/src/Processors/Chunk.cpp +++ b/src/Processors/Chunk.cpp @@ -69,13 +69,11 @@ void Chunk::checkNumRowsIsConsistent() MutableColumns Chunk::mutateColumns() { - size_t num_columns = columns.size(); - MutableColumns mutable_columns(num_columns); - for (size_t i = 0; i < num_columns; ++i) - mutable_columns[i] = IColumn::mutate(std::move(columns[i])); - - columns.clear(); - num_rows = 0; + MutableColumns mutable_columns(columns.size()); + /// Detach first: `IColumn::mutate` consumes the column even when it throws, and a chunk never holds a null column. + Columns detached_columns = detachColumns(); + for (size_t i = 0; i < detached_columns.size(); ++i) + mutable_columns[i] = IColumn::mutate(std::move(detached_columns[i])); return mutable_columns; } diff --git a/src/Processors/Formats/IInputFormat.h b/src/Processors/Formats/IInputFormat.h index 2b1eb5a447e8..a2e2f693ef54 100644 --- a/src/Processors/Formats/IInputFormat.h +++ b/src/Processors/Formats/IInputFormat.h @@ -130,6 +130,8 @@ class IInputFormat : public ISource void needOnlyCount() { need_only_count = true; } + virtual void prefetch() {} + protected: ReadBuffer & getReadBuffer() const { chassert(in); return *in; } diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp new file mode 100644 index 000000000000..8f76772b9ef6 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp @@ -0,0 +1,319 @@ +#include + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace DB +{ + +namespace +{ + +/// The largest `n <= end - begin` for which the non-decreasing `offsets` grow by at most `limit` over +/// rows [begin, begin + n). +size_t maxRowsByOffsets(const IColumn::Offsets & offsets, size_t begin, size_t end, UInt64 limit) +{ + const UInt64 base = offsets[static_cast(begin) - 1]; + const auto * first = offsets.data() + begin; + const auto * it = std::upper_bound(first, offsets.data() + end, base + limit); + return static_cast(it - first); +} + +/// A writer either materializes the column or dictionary-encodes it; measuring it as materialized bounds +/// both, since a batch's dictionary holds at most the distinct values of its rows. `canBeInsideLowCardinality` +/// allows only fixed-width types, `String` and `FixedString`, and of those only the two string types reach +/// a 32-bit-offset buffer. +size_t maxRowsForLowCardinality( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const DataTypePtr values_type = removeNullable(removeLowCardinality(type)); + const auto & low_cardinality = assert_cast(column); + const IColumn & values_column = *low_cardinality.getDictionary().getNestedNotNullableColumn(); + + if (isFixedString(values_type)) + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(values_column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + + if (!isString(values_type)) + return num_rows; + + const auto & values = assert_cast(values_column); + const auto & value_offsets = values.getOffsets(); + + /// Scanning the indexes is only needed when the whole dictionary repeated on every row could overflow: + /// no single value is larger than all of them together. This is O(1), unlike finding the largest value, + /// so it does not add work proportional to the dictionary for every batch of a split chunk. + const UInt64 dictionary_bytes = values.empty() ? 0 : value_offsets.back(); + if (dictionary_bytes == 0 || num_rows <= max_batch_bytes / dictionary_bytes) + return num_rows; + + const auto & indexes = low_cardinality.getIndexes(); + UInt64 total = 0; + for (size_t row = begin; row != end; ++row) + { + const auto index = static_cast(indexes.getUInt(row)); + total += value_offsets[index] - value_offsets[index - 1]; + if (total > max_batch_bytes) + return row - begin; + } + return num_rows; +} + +/// A `Variant` becomes an Arrow dense union, whose own buffers are bounded by the row count; only its +/// children, holding one alternative's rows each, can overflow. +size_t maxRowsForVariant( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const auto & variant_column = assert_cast(column); + const auto & variant_type = assert_cast(*type); + const size_t num_variants = variant_column.getNumVariants(); + const auto & local_discriminators = variant_column.getLocalDiscriminators(); + const auto & variant_offsets = variant_column.getOffsets(); + + /// Within a contiguous row range the offsets of each alternative are contiguous too (see + /// `ColumnVariant::updateHashWithValueRange`), so [begin, end) maps to the range + /// [nested_begin, nested_begin + nested_rows) of every alternative. + std::vector nested_begin(num_variants, 0); + std::vector nested_rows(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows[local_discr] == 0) + nested_begin[local_discr] = variant_offsets[row]; + ++nested_rows[local_discr]; + } + + std::vector nested_rows_that_fit(num_variants); + bool all_fit = true; + for (size_t local_discr = 0; local_discr != num_variants; ++local_discr) + { + const auto global_discr + = variant_column.globalDiscriminatorByLocal(static_cast(local_discr)); + nested_rows_that_fit[local_discr] = maxRowsFittingOneArrowBatch( + variant_column.getVariantByLocalDiscriminator(local_discr), + variant_type.getVariant(global_discr), + nested_begin[local_discr], + nested_begin[local_discr] + nested_rows[local_discr], + fixed_string_as_fixed_byte_array, max_batch_bytes); + all_fit &= nested_rows_that_fit[local_discr] == nested_rows[local_discr]; + } + if (all_fit) + return num_rows; + + /// Some alternative cannot take all of its rows: cut at the row where it runs out. + std::vector nested_rows_taken(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows_taken[local_discr] == nested_rows_that_fit[local_discr]) + return row - begin; + ++nested_rows_taken[local_discr]; + } + return num_rows; +} + +} + +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Arrow cannot address more than this however the caller was configured. + max_batch_bytes = std::min(max_batch_bytes, MAX_ARROW_BUFFER_SIZE); + + if (type->lowCardinality()) + return maxRowsForLowCardinality(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + if (isVariant(type)) + return maxRowsForVariant(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + /// A null row is written as a zero-length slot, so measuring the nested column only overestimates. + if (type->isNullable()) + { + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + removeNullable(type), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + + switch (WhichDataType(type).idx) + { + case TypeIndex::String: + { + return maxRowsByOffsets(assert_cast(column).getOffsets(), begin, end, max_batch_bytes); + } + case TypeIndex::FixedString: + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + case TypeIndex::Array: + { + const auto & array = assert_cast(column); + const auto & offsets = array.getOffsets(); + const size_t nested_begin = offsets[static_cast(begin) - 1]; + const size_t nested_rows = maxRowsFittingOneArrowBatch( + array.getData(), + assert_cast(*type).getNestedType(), + nested_begin, + offsets[end - 1], + fixed_string_as_fixed_byte_array, max_batch_bytes); + return maxRowsByOffsets(offsets, begin, end, std::min(nested_rows, max_batch_bytes)); + } + case TypeIndex::Map: + { + /// Both writers encode a Map exactly as its nested `Array(Tuple(key, value))`. + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + assert_cast(*type).getNestedType(), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + case TypeIndex::Tuple: + { + const auto & tuple = assert_cast(column); + const auto & elements = assert_cast(*type).getElements(); + size_t rows = num_rows; + for (size_t i = 0; i != elements.size(); ++i) + { + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + tuple.getColumn(i), elements[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + } + return rows; + } + /// Fixed-width Arrow types: a single values buffer, no offsets, nothing to exceed. + case TypeIndex::UInt8: + case TypeIndex::UInt16: + case TypeIndex::UInt32: + case TypeIndex::UInt64: + case TypeIndex::UInt128: + case TypeIndex::UInt256: + case TypeIndex::Int8: + case TypeIndex::Int16: + case TypeIndex::Int32: + case TypeIndex::Int64: + case TypeIndex::Int128: + case TypeIndex::Int256: + case TypeIndex::Float32: + case TypeIndex::Float64: + case TypeIndex::Enum8: + case TypeIndex::Enum16: + case TypeIndex::Date: + case TypeIndex::Date32: + case TypeIndex::DateTime: + case TypeIndex::DateTime64: + case TypeIndex::Time: + case TypeIndex::Time64: + case TypeIndex::Decimal32: + case TypeIndex::Decimal64: + case TypeIndex::Decimal128: + case TypeIndex::Decimal256: + case TypeIndex::IPv4: + case TypeIndex::IPv6: + case TypeIndex::UUID: + case TypeIndex::Interval: + { + return num_rows; + } + default: + { + /// A type with no Arrow equivalent is written by serializing each value, so bounding its + /// encoded size would mean serializing twice. The encoder rejects a batch that overflows. + return num_rows; + } + } +} + +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + chassert(columns.size() == types.size()); + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Some limits (`Variant`, `LowCardinality`) take time linear in the rows they are given, so measuring + /// the whole remainder of a chunk for each of its batches would be quadratic. The window grows instead: + /// the limit of a prefix is the limit of the whole range capped at the prefix's length, so the first + /// window that does not fit entirely gives the answer, and the work stays proportional to the rows + /// emitted, plus the initial window. + static constexpr size_t initial_window = 8192; + size_t window = std::min(num_rows, initial_window); + while (true) + { + /// Two columns never share an Arrow buffer, so the smallest per-column limit applies. + size_t rows = window; + for (size_t i = 0; i < columns.size() && rows != 0; ++i) + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + *columns[i], types[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + + if (rows < window || window == num_rows) + return rows; + window = std::min(num_rows, window * 2); + } +} + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.h b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h new file mode 100644 index 000000000000..c532138a8da0 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h @@ -0,0 +1,47 @@ +#pragma once + +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include + +namespace DB +{ + +/// The largest `n` such that rows [begin, begin + n) of `column` stay within `max_batch_bytes`; writers +/// split an oversized chunk accordingly. Returns 0 only when the first row does not fit on its own, which +/// the writer then lets Arrow reject. `ColumnConst` and the sparse/replicated representations are not +/// handled; callers materialize first. +/// +/// `LowCardinality` is measured as materialized, which only over-splits when it is written as an Arrow +/// dictionary. A dictionary larger than one buffer is not covered at all: its bytes do not depend on the +/// row count, because `ColumnLowCardinality::insertRangeFrom` keeps a shared source dictionary whole, so +/// every slice re-emits it. Arrow rejects such a chunk. +/// +/// A type with no Arrow equivalent is not covered either, since only serializing its values reveals their +/// encoded size. Both uncovered shapes are rejected by the writer instead of being split. +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes = MAX_ARROW_BUFFER_SIZE); + +/// The largest `n` such that rows [begin, begin + n) of every column stay within `max_batch_bytes`: the +/// number of rows of the next record batch of a chunk. The work is proportional to the returned number of +/// rows rather than to `end - begin`, so splitting a chunk into many batches stays linear. +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes); + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp index 1a71a4a32447..7c0dfb0044ae 100644 --- a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp @@ -64,6 +64,7 @@ void ArrowBlockOutputFormat::consume(Chunk chunk) .use_signed_indexes_for_dictionary = format_settings.arrow.use_signed_indexes_for_dictionary, .use_64_bit_indexes_for_dictionary = format_settings.arrow.use_64_bit_indexes_for_dictionary, .output_date_as_uint16 = format_settings.arrow.output_date_as_uint16, + .output_max_record_batch_bytes = format_settings.arrow.output_max_record_batch_bytes, }); } diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp index 4699b1b2fdf0..7c2d5b54eed9 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp @@ -1,7 +1,7 @@ #pragma clang diagnostic ignored "-Wreserved-identifier" #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include #include diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.h b/src/Processors/Formats/Impl/ArrowBufferedStreams.h index ecb6ef8cb6fe..510e3ee4c26e 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.h +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.h @@ -3,7 +3,7 @@ #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp index ffac42b86605..a9b508893a8f 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp @@ -1,7 +1,7 @@ #include #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h index e06cce04579d..bf0e3ecf828a 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h @@ -5,7 +5,7 @@ #include "config.h" -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp index 60f89e76aeef..f4e991cc1643 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp @@ -21,9 +21,12 @@ #include #include #include +#include #include #include +#include + #include #include #include @@ -66,6 +69,7 @@ namespace DB extern const int LOGICAL_ERROR; extern const int DECIMAL_OVERFLOW; extern const int ILLEGAL_COLUMN; + extern const int TOO_LARGE_ARRAY_SIZE; } static const std::initializer_list>> internal_type_to_arrow_type = @@ -517,6 +521,18 @@ namespace DB throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot fill arrow array {} with {} data", value_type->name(), column_type->getName()); } + /// Arrow's `Utf8`/`Binary` builders take an int32 length and their `Append` skips the copy when it is + /// negative, so a narrowed size would store an empty value instead of failing. + static void checkStringSizeFitsArrowOffsets(size_t size, const String & column_name, const String & format_name) + { + if (size > MAX_ARROW_BUFFER_SIZE) + throw Exception( + ErrorCodes::TOO_LARGE_ARRAY_SIZE, + "Cannot write a value of {} bytes of column {} to {}: `Utf8`/`Binary` offsets are 32-bit, so a single " + "value cannot be larger than {} bytes", + size, column_name, format_name, MAX_ARROW_BUFFER_SIZE); + } + template static void fillArrowArrayWithStringColumnData( ColumnPtr write_column, @@ -541,6 +557,7 @@ namespace DB else { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); } checkStatus(status, write_column->getName(), format_name); @@ -551,6 +568,7 @@ namespace DB for (size_t string_i = start; string_i < end; ++string_i) { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); checkStatus(status, write_column->getName(), format_name); } @@ -1200,37 +1218,72 @@ namespace DB for (const auto & chunk : chunks) { - /// For arrow::Table creation + /// Normalize once per chunk, so that it is not repeated for each row range below. + Columns columns(columns_num); + DataTypes column_types(columns_num); for (size_t column_i = 0; column_i < columns_num; ++column_i) { - const ColumnWithTypeAndName & header_column = header_columns[column_i]; - auto column = chunk.getColumns()[column_i]; - + auto column = chunk.getColumns()[column_i]->convertToFullColumnIfConst()->convertToFullColumnIfReplicated(); + auto column_type = header_columns[column_i].type; if (!settings.low_cardinality_as_dictionary) column = recursiveRemoveLowCardinality(column); - - std::unique_ptr array_builder; - arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); - checkStatus(status, column->getName(), format_name); - - fillArrowArray( - header_column.name, - column, - header_column.type, - nullptr, - array_builder.get(), - format_name, - 0, - column->size(), - settings, - dictionary_values); - - std::shared_ptr arrow_array; - status = array_builder->Finish(&arrow_array); - checkStatus(status, column->getName(), format_name); - - table_data.at(column_i).emplace_back(std::move(arrow_array)); + columns[column_i] = std::move(column); + column_types[column_i] = std::move(column_type); } + + /// The row limit is measured on types matching the columns: without dictionary output the + /// `LowCardinality` columns were materialized above. + DataTypes measured_types = column_types; + if (!settings.low_cardinality_as_dictionary) + for (auto & type : measured_types) + type = recursiveRemoveLowCardinality(type); + + /// A chunk that exceeds the 32-bit Arrow offsets becomes several arrays of the ChunkedArray. + const size_t num_rows = chunk.getNumRows(); + size_t offset = 0; + do + { + size_t rows = maxRowsFittingOneArrowBatch( + columns, + measured_types, + offset, + num_rows, + settings.output_fixed_string_as_fixed_byte_array, + settings.output_max_record_batch_bytes); + /// A row that does not fit on its own cannot be represented at all; the leaf encoders reject it. + rows = std::min(std::max(rows, 1), num_rows - offset); + + /// For arrow::Table creation + for (size_t column_i = 0; column_i < columns_num; ++column_i) + { + const ColumnWithTypeAndName & header_column = header_columns[column_i]; + ColumnPtr column = columns[column_i]; + + std::unique_ptr array_builder; + arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); + checkStatus(status, column->getName(), format_name); + + fillArrowArray( + header_column.name, + column, + column_types[column_i], + nullptr, + array_builder.get(), + format_name, + offset, + offset + rows, + settings, + dictionary_values); + + std::shared_ptr arrow_array; + status = array_builder->Finish(&arrow_array); + checkStatus(status, column->getName(), format_name); + + table_data.at(column_i).emplace_back(std::move(arrow_array)); + } + + offset += rows; + } while (offset < num_rows); } std::vector> columns; diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h index 2544faf9ed1d..160a78ed1c9f 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h @@ -4,6 +4,7 @@ #if USE_ARROW || USE_PARQUET #include +#include #include #include @@ -33,6 +34,8 @@ class CHColumnToArrowColumn bool use_64_bit_indexes_for_dictionary = false; /// Output Date as UInt16 instead of Arrow DATE32 for backward compatibility. bool output_date_as_uint16 = false; + /// Upper bound on one record batch; a chunk holding more is written as several. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; }; CHColumnToArrowColumn(const Block & header, const std::string & format_name_, const Settings & settings_); diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp index 58e797b4d591..a6e69f02d3a8 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp @@ -59,7 +59,7 @@ MsgPackRowInputFormat::MsgPackRowInputFormat(SharedHeader header_, std::unique_p void MsgPackRowInputFormat::resetParser() { IRowInputFormat::resetParser(); - visitor.reset(); + parser.init(); } void MsgPackRowInputFormat::setReadBuffer(ReadBuffer & in_) @@ -83,7 +83,7 @@ void MsgPackVisitor::set_info(IColumn & column, DataTypePtr type, UInt8 & read) info_stack.push(Info{column, type, false, std::nullopt, &read}); } -void MsgPackVisitor::reset() +void MsgPackVisitor::init() { info_stack = {}; } @@ -667,10 +667,10 @@ DataTypePtr MsgPackSchemaReader::getDataType(const msgpack::object & object, siz msgpack::object_map object_map = object.via.map; if (object_map.size) { - auto key_type = removeNullable(getDataType(object_map.ptr[0].key, depth + 1)); + auto key_type = getDataType(object_map.ptr[0].key, depth + 1); auto value_type = getDataType(object_map.ptr[0].val, depth + 1); if (key_type && value_type) - return std::make_shared(key_type, value_type); + return std::make_shared(removeNullable(key_type), value_type); } return nullptr; } diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h index be9dd30d6e8f..323df67d9707 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h @@ -52,7 +52,8 @@ class MsgPackVisitor : public msgpack::null_visitor /// Update info_stack void set_info(IColumn & column, DataTypePtr type, UInt8 & read); - void reset(); + /// Called by msgpack's parse_helper::init. + void init(); private: /// Stack is needed to process arrays and maps diff --git a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp index 96bb9b23ef3c..a39c4d82ec12 100644 --- a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp @@ -377,8 +377,12 @@ static bool tryToExtractStructureFromCreateQuery(ReadBuffer & in, NamesAndTypesL if (!create_query) return false; + /// `CREATE TABLE ... LIKE` has no column list, and a column list with only indexes or constraints has no columns. + if (!create_query->columns_list) + return false; + const auto * create_defines = create_query->columns_list->as(); - if (!create_defines) + if (!create_defines || !create_defines->columns) return false; structure = getColumnsList(create_defines->columns); @@ -431,9 +435,10 @@ static void readFirstCreateAndInsertQueries(ReadBuffer & in, String & table_name if (type == MySQLQueryType::CREATE) { /// If we have CREATE query, we can extract columns names and types from it. + /// `tryToExtractStructureFromCreateQuery` reads the CREATE query up to and including its `;`, + /// so the next query must not be skipped: it can be the first INSERT query. if (tryToExtractStructureFromCreateQuery(in, structure_from_create)) column_names = structure_from_create.getNames(); - skipQuery(in); insert_query_present = skipToInsertQuery(table_name, in); } diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp index 0e999852c352..b2f26243171e 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp @@ -3,6 +3,7 @@ #if USE_ORC #include +#include #include #include #include @@ -10,8 +11,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include @@ -25,20 +29,26 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include +#include +#include #include #include #include -#include #include #include #include @@ -47,10 +57,11 @@ #include #include -#include #include +#include + namespace DB { namespace ErrorCodes @@ -66,9 +77,12 @@ extern const int TOO_DEEP_RECURSION; ORCInputStream::ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch) - : in(in_), file_size(file_size_), supports_read_at(use_prefetch && in_.supportsReadAt()) + : in(in_) + , file_size(file_size_) + , use_offset_based_read(in_.supportsReadAt()) + , use_async_prefetch(use_prefetch && use_offset_based_read) { - if (supports_read_at) + if (use_async_prefetch) async_runner = threadPoolCallbackRunnerUnsafe(getIOThreadPool().get(), ThreadName::ORC_FILE); } @@ -77,20 +91,23 @@ UInt64 ORCInputStream::getLength() const return file_size; } -UInt64 ORCInputStream::getNaturalReadSize() const -{ - return 128 * 1024; -} - void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) { - if (supports_read_at) + if (use_offset_based_read) { size_t bytes_read = 0; while (bytes_read < length) { size_t bytes_to_read = length - bytes_read; size_t n = in.readBigAt(reinterpret_cast(buf) + bytes_read, bytes_to_read, offset + bytes_read, nullptr); + if (n == 0) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Truncated or corrupted ORC input: readBigAt returned 0 bytes at offset {} ({} bytes remaining of {} requested from base offset {})", + offset + bytes_read, + bytes_to_read, + length, + offset); bytes_read += n; } } @@ -104,7 +121,7 @@ void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_t offset) { - if (supports_read_at) + if (use_async_prefetch) { return async_runner( [this, buf, length, offset] @@ -129,7 +146,7 @@ std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_ } } -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled) { bool has_file_size = isBufferWithFileSize(in); @@ -142,14 +159,15 @@ asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_pref return asORCInputStreamLoadIntoMemory(in, is_cancelled); } -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) { - size_t magic_size = strlen(ORC_MAGIC_BYTES); + static constexpr std::string_view orc_magic_bytes = "ORC"; + size_t magic_size = orc_magic_bytes.size(); std::string file_data(magic_size, '\0'); /// Avoid loading the whole file if it doesn't seem to even be in the correct format. size_t bytes_read = in.read(file_data.data(), magic_size); - if (bytes_read < magic_size || file_data != ORC_MAGIC_BYTES) + if (bytes_read < magic_size || file_data != orc_magic_bytes) throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file"); { @@ -161,53 +179,157 @@ std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in return std::make_unique(std::move(file_data), file_size); } -/// The default ORC memory pool allocates with `std::malloc`, which returns a null pointer when it -/// fails - and the library dereferences it - and which is invisible to the memory tracker. A -/// malformed file can ask for an arbitrarily large buffer, so allocate through `operator new` -/// instead: it is accounted for and it throws instead of returning null. -class ORCMemoryPool : public orc::MemoryPool +/// Defined below, next to the read path that also uses it. The sargs path resolves predicate column +/// names through the same recursive walk, so pruning and reading always agree on the column. +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case); + +struct ORCPredicateColumnTypes { -public: - char * malloc(uint64_t size) override { return new char[size]; } - void free(char * p) override { delete[] p; } + DataTypePtr result_type; + DataTypePtr declared_type; }; -orc::MemoryPool & getORCMemoryPool() +struct ORCSubcolumnInfo { - static ORCMemoryPool pool; - return pool; + ISerialization::SubstreamData data; + ISerialization::SubstreamPath substreams_path; +}; + +/// Finds a subcolumn of `type` together with the substreams path that leads to it. +static std::optional tryGetORCSubcolumnInfo(const IDataType & type, std::string_view subcolumn_name) +{ + std::optional result; + auto data = ISerialization::SubstreamData(type.getDefaultSerialization()).withType(type.getPtr()); + IDataType::forEachSubcolumn( + [&](const ISerialization::SubstreamPath & path, const String & name, const ISerialization::SubstreamData & subcolumn_data) + { + if (!result && name == subcolumn_name) + result = ORCSubcolumnInfo{subcolumn_data, path}; + }, + data); + return result; } -static const orc::Type * getORCTypeByName(const orc::Type & schema, const String & name, bool ignore_case) +/// True when `path` is a named tuple element at every level, so it is a file leaf with its own +/// statistics. Nullable, LowCardinality and Array are transparent; anything else is refused, +/// which is what rejects Map/Variant/JSON/Dynamic and `.null`, `.size0`, `.keys`, `.values`. +static bool isNamedTupleElementPath(const IDataType & type, std::string_view path, bool ignore_case) { - for (UInt64 i = 0; i != schema.getSubtypeCount(); ++i) - if (boost::equals(schema.getFieldName(i), name) || (ignore_case && boost::iequals(schema.getFieldName(i), name))) - return schema.getSubtype(i); - return nullptr; + const IDataType * current = &type; + while (true) + { + if (const auto * nullable = typeid_cast(current)) + current = nullable->getNestedType().get(); + else if (const auto * low_cardinality = typeid_cast(current)) + current = low_cardinality->getDictionaryType().get(); + else if (const auto * array = typeid_cast(current)) + current = array->getNestedType().get(); + else + break; + } + + const auto * tuple = typeid_cast(current); + if (!tuple || !tuple->hasExplicitNames()) + return false; + + if (tuple->tryGetPositionByName(path, ignore_case)) + return true; + + /// An element name may itself contain dots, so every split has to be considered. + for (size_t dot = path.find('.'); dot != std::string_view::npos; dot = path.find('.', dot + 1)) + { + auto head = path.substr(0, dot); + auto tail = path.substr(dot + 1); + if (head.empty() || tail.empty()) + continue; + if (auto position = tuple->tryGetPositionByName(head, ignore_case)) + if (isNamedTupleElementPath(*tuple->getElement(*position), tail, ignore_case)) + return true; + } + return false; +} + +/// Resolves a named tuple element and retains its declared type before ancestor wrappers are applied. +static std::optional findTupleElementKeyTypes( + const Block & header, const String & name, bool ignore_case) +{ + for (auto [column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(name)) + { + const auto * column = header.findByName(String(column_name), ignore_case); + if (!column || !isNamedTupleElementPath(*column->type, subcolumn_name, ignore_case)) + continue; + if (auto subcolumn = tryGetORCSubcolumnInfo(*column->type, subcolumn_name)) + { + const auto & path = subcolumn->substreams_path; + chassert(!path.empty() && path.back().data.type); + /// A dotted field name can also resolve to a virtual subcolumn of another element. + if (path.back().type != ISerialization::Substream::TupleElement) + continue; + return ORCPredicateColumnTypes{subcolumn->data.type, path.back().data.type}; + } + } + return {}; +} + +/// Resolves predicate types from the reader header, which can contain only the parent tuple column. +static std::optional findHeaderTypesByPath( + const Block & header, const String & name, bool ignore_case) +{ + if (const auto * column = header.findByName(name, ignore_case)) + return ORCPredicateColumnTypes{column->type, column->type}; + return findTupleElementKeyTypes(header, name, ignore_case); +} + +/// KeyCondition derives its key names from this block, and the ORC header carries only the parent +/// column, so a tuple element predicate would degrade to `unknown`. Only the local copy grows; +/// the reader header stays as it is, so the read path is unaffected. +static Block buildORCKeyConditionBlock(const Block & header, const ActionsDAG * filter_dag, bool ignore_case) +{ + if (!filter_dag) + return header; + + Block keys = header; + for (const auto & required : filter_dag->getRequiredColumns()) + { + if (keys.has(required.name)) + continue; + if (auto types = findTupleElementKeyTypes(header, required.name, ignore_case)) + keys.insert({types->result_type->createColumn(), types->result_type, required.name}); + } + return keys; } -static bool isDictionaryEncoded(const orc::StripeInformation * stripe_info, const orc::Type * orc_type) +static bool isDictionaryEncoded(const ORC::Proto::StripeFooter * stripe_footer, const ORC::Type * orc_type) { - if (!stripe_info) + if (!stripe_footer) return false; - auto encoding = stripe_info->getColumnEncoding(orc_type->getColumnId()); - return encoding == orc::ColumnEncodingKind_DICTIONARY || encoding == orc::ColumnEncodingKind_DICTIONARY_V2; + UInt64 column_id = orc_type->getColumnId(); + if (column_id >= stripe_footer->columns.size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Failed to read ORC schema: the first stripe has no encoding for column {}, it has {} column encodings", + column_id, + stripe_footer->columns.size()); + + auto encoding = stripe_footer->columns[column_id].kind; + return encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY || encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY_V2; } static DataTypePtr parseORCType( - const orc::Type * orc_type, + const ORC::Type * orc_type, bool skip_columns_with_unsupported_types, bool dictionary_as_low_cardinality, - const orc::StripeInformation * stripe_info, + const ORC::Proto::StripeFooter * stripe_info, bool & skipped, size_t max_depth = DBMS_DEFAULT_MAX_PARSER_DEPTH, size_t depth = 0) { - assert(orc_type != nullptr); + chassert(orc_type != nullptr); - /// ORC LIST/MAP/STRUCT types can be nested arbitrarily deep and the ORC library does not bound - /// the nesting, so reject deep nesting early (before building the type) with an explicit limit. + /// ORC LIST/MAP/STRUCT types can be nested deep (the ORC reader allows up to 2000 levels) + /// so reject deep nesting early (before building the type) with an explicit limit. /// This keeps schema inference cheap and interruptible instead of recursing over (and later /// walking) a pathologically deep type. checkStackSize is a last-resort backstop. /// max_depth == 0 means unlimited (matching the SQL parser), leaving only checkStackSize. @@ -220,34 +342,111 @@ static DataTypePtr parseORCType( checkStackSize(); const int subtype_count = static_cast(orc_type->getSubtypeCount()); + + /// ORC union maps to the ClickHouse Variant type. It is handled before the switch below so the + /// switch stays non-exhaustive (its default handles unsupported types). Variant sorts and + /// de-duplicates its nested types, but ORC keeps a separate physical stream per branch, so two + /// branches with identical types cannot be represented as a Variant; reject them explicitly + /// instead of silently squashing them. A branch that is itself a union is rejected too: it + /// would map to a Variant, which Variant does not allow to nest. + if (orc_type->getKind() == ORC::TypeKind::UNION) + { + /// A union with more branches than Variant can hold (ColumnVariant::MAX_NESTED_COLUMNS) + /// is valid ORC but not representable; reject it through the normal unsupported-type / + /// skip path before any branch is parsed - otherwise the DataTypeVariant constructor + /// throws a generic BAD_ARGUMENTS and the skip setting is never consulted. + if (static_cast(subtype_count) > ColumnVariant::MAX_NESTED_COLUMNS) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported: Variant supports at most {} nested types", + subtype_count, ColumnVariant::MAX_NESTED_COLUMNS); + } + + DataTypes nested_types; + std::unordered_set seen_type_names; + nested_types.reserve(subtype_count); + for (int i = 0; i < subtype_count; ++i) + { + const auto * subtype = orc_type->getSubtype(i); + + /// A union branch that is itself a union would map to a Variant, and Variant does not + /// allow a nested Variant. Reject it through the normal unsupported-type / skip path + /// here, before the outer DataTypeVariant is constructed - otherwise its constructor + /// throws a confusing BAD_ARGUMENTS ("Nested Variant types are not allowed") and the + /// skip setting is never consulted because the inner union has already been parsed. + if (subtype->getKind() == ORC::TypeKind::UNION) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported", + orc_type->toString()); + } + + auto parsed_type = parseORCType( + subtype, skip_columns_with_unsupported_types, dictionary_as_low_cardinality, stripe_info, skipped, max_depth, depth + 1); + if (skipped) + return {}; + + /// Branch identity must not depend on the stripe's physical encoding: a + /// dictionary-encoded branch parses as LowCardinality(...), which would let e.g. + /// uniontype with one dictionary-encoded branch slip past this check + /// (and the read would then fail on any stripe where the encodings agree). + if (!seen_type_names.insert(recursiveRemoveLowCardinality(parsed_type)->getName()).second) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported", + orc_type->toString()); + } + nested_types.push_back(parsed_type); + } + return std::make_shared(nested_types); + } + switch (orc_type->getKind()) { - case orc::TypeKind::BOOLEAN: + case ORC::TypeKind::BOOLEAN: return DataTypeFactory::instance().get("Bool"); - case orc::TypeKind::BYTE: + case ORC::TypeKind::BYTE: return std::make_shared(); - case orc::TypeKind::SHORT: + case ORC::TypeKind::SHORT: return std::make_shared(); - case orc::TypeKind::INT: + case ORC::TypeKind::INT: return std::make_shared(); - case orc::TypeKind::LONG: + case ORC::TypeKind::LONG: return std::make_shared(); - case orc::TypeKind::FLOAT: + case ORC::TypeKind::FLOAT: return std::make_shared(); - case orc::TypeKind::DOUBLE: + case ORC::TypeKind::DOUBLE: return std::make_shared(); - case orc::TypeKind::DATE: + case ORC::TypeKind::DATE: return std::make_shared(); - case orc::TypeKind::TIMESTAMP: + case ORC::TypeKind::TIMESTAMP: return std::make_shared(9); - case orc::TypeKind::TIMESTAMP_INSTANT: + case ORC::TypeKind::TIMESTAMP_INSTANT: return std::make_shared(9, "UTC"); - case orc::TypeKind::CHAR: - case orc::TypeKind::VARCHAR: - case orc::TypeKind::BINARY: - case orc::TypeKind::STRING: { + case ORC::TypeKind::CHAR: + case ORC::TypeKind::VARCHAR: + case ORC::TypeKind::BINARY: + case ORC::TypeKind::STRING: { DataTypePtr type; - if (orc_type->getKind() == orc::TypeKind::CHAR) + if (orc_type->getKind() == ORC::TypeKind::CHAR) type = std::make_shared(orc_type->getMaximumLength()); else type = std::make_shared(); @@ -258,7 +457,7 @@ static DataTypePtr parseORCType( return type; } - case orc::TypeKind::DECIMAL: { + case ORC::TypeKind::DECIMAL: { UInt64 precision = orc_type->getPrecision(); UInt64 scale = orc_type->getScale(); if (precision == 0) @@ -268,7 +467,7 @@ static DataTypePtr parseORCType( } return createDecimal(precision, scale); } - case orc::TypeKind::LIST: { + case ORC::TypeKind::LIST: { if (subtype_count != 1) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc List type {}", orc_type->toString()); @@ -279,7 +478,7 @@ static DataTypePtr parseORCType( return std::make_shared(nested_type); } - case orc::TypeKind::MAP: { + case ORC::TypeKind::MAP: { if (subtype_count != 2) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc Map type {}", orc_type->toString()); @@ -295,7 +494,7 @@ static DataTypePtr parseORCType( return std::make_shared(key_type, value_type); } - case orc::TypeKind::STRUCT: { + case ORC::TypeKind::STRUCT: { DataTypes nested_types; Strings nested_names; nested_types.reserve(subtype_count); @@ -322,7 +521,7 @@ static DataTypePtr parseORCType( throw Exception( ErrorCodes::UNKNOWN_TYPE, - "Unsupported ORC type '{}'." + "Unsupported ORC type '{}'. " "If you want to skip columns with unsupported types, " "you can enable setting input_format_orc_skip_columns_with_unsupported_types_in_schema_inference", orc_type->toString()); @@ -330,30 +529,30 @@ static DataTypePtr parseORCType( } } -static std::optional convertORCTypeToPredicateType(const orc::Type & orc_type) +static std::optional convertORCTypeToPredicateType(const ORC::Type & orc_type) { switch (orc_type.getKind()) { - case orc::BOOLEAN: - return orc::PredicateDataType::BOOLEAN; - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: - return orc::PredicateDataType::LONG; - case orc::FLOAT: - case orc::DOUBLE: - return orc::PredicateDataType::FLOAT; - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: - return orc::PredicateDataType::STRING; - case orc::DATE: - return orc::PredicateDataType::DATE; - case orc::TIMESTAMP: - return orc::PredicateDataType::TIMESTAMP; - case orc::DECIMAL: - return orc::PredicateDataType::DECIMAL; + case ORC::BOOLEAN: + return ORC::PredicateDataType::BOOLEAN; + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: + return ORC::PredicateDataType::LONG; + case ORC::FLOAT: + case ORC::DOUBLE: + return ORC::PredicateDataType::FLOAT; + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: + return ORC::PredicateDataType::STRING; + case ORC::DATE: + return ORC::PredicateDataType::DATE; + case ORC::TIMESTAMP: + return ORC::PredicateDataType::TIMESTAMP; + case ORC::DECIMAL: + return ORC::PredicateDataType::DECIMAL; default: return {}; } @@ -370,23 +569,23 @@ static String getColumnNameFromKeyCondition(const KeyCondition & key_condition, throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't get column from KeyCondition with indice {}", indice); } -static std::optional -convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) +static std::optional +convertFieldToORCLiteral(const ORC::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) { try { /// We always fallback to return null if possible CH type hint not consistent with ORC type switch (orc_type.getKind()) { - case orc::BOOLEAN: { + case ORC::BOOLEAN: { /// May throw exception auto val = field.safeGet(); - return orc::Literal(val != 0); + return ORC::Literal(val != 0); } - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: { + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: { /// May throw exception. /// /// In particular, it'll throw if we request the column as unsigned, like this: @@ -394,30 +593,30 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy /// We have to reject this, otherwise it would miss values > 127 (because /// they're treated as negative by ORC). auto val = field.safeGet(); - return orc::Literal(val); + return ORC::Literal(val); } - case orc::FLOAT: - case orc::DOUBLE: { - Float64 val; + case ORC::FLOAT: + case ORC::DOUBLE: { + Float64 val = 0; if (field.tryGet(val)) - return orc::Literal(val); + return ORC::Literal(val); break; } - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: { + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: { String str; if (field.tryGet(str)) - return orc::Literal(str.data(), str.size()); + return ORC::Literal(str.data(), str.size()); break; } - case orc::DATE: { - Int64 val; + case ORC::DATE: { + Int64 val = 0; if (field.tryGet(val)) - return orc::Literal(orc::PredicateDataType::DATE, val); + return ORC::Literal(ORC::PredicateDataType::DATE, val); break; } - case orc::TIMESTAMP: { + case ORC::TIMESTAMP: { if (type_hint && isDateTime64(type_hint)) { const auto * datetime64_type = typeid_cast(type_hint.get()); @@ -426,15 +625,23 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy } DecimalField ts; - if (field.tryGet(ts)) + if (field.tryGet(ts) && ts.getScale() <= 9) { - Int64 secs = (ts.getValue() / ts.getScaleMultiplier()).convertTo(); - Int32 nanos = (ts.getValue() - (ts.getValue() / ts.getScaleMultiplier()) * ts.getScaleMultiplier()).convertTo(); - return orc::Literal(secs, nanos); + /// The nanoseconds are not negative, as in the reference implementation and in the statistics. + const Int64 value = ts.getValue().value; + const Int64 multiplier = ts.getScaleMultiplier().value; + Int64 secs = value / multiplier; + Int64 rest = value % multiplier; + if (rest < 0) + { + rest += multiplier; + --secs; + } + return ORC::Literal(secs, static_cast(rest * (1'000'000'000 / multiplier))); } break; } - case orc::DECIMAL: { + case ORC::DECIMAL: { auto precision = orc_type.getPrecision(); if (precision == 0) precision = 38; @@ -445,8 +652,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -455,8 +662,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -464,10 +671,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy DecimalField val; if (field.tryGet(val)) { - Int64 high = val.getValue().value.items[1]; - UInt64 low = static_cast(val.getValue().value.items[0]); - return orc::Literal( - orc::Int128(high, low), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + val.getValue().value, static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } break; @@ -538,9 +743,9 @@ static bool evaluateRPNElement(const Field & field, const KeyCondition::RPNEleme static void buildORCSearchArgumentImpl( const KeyCondition & key_condition, const Block & header, - const orc::Type & schema, + const ORC::Type & schema, KeyCondition::RPN & rpn_stack, - orc::SearchArgumentBuilder & builder, + ORC::SearchArgumentBuilder & builder, const FormatSettings & format_settings) { if (rpn_stack.empty()) @@ -572,7 +777,7 @@ static void buildORCSearchArgumentImpl( /// Key filter expressions like "func(col) > 100" are not supported for ORC filter push down if (!curr.monotonic_functions_chain.empty()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -583,16 +788,32 @@ static void buildORCSearchArgumentImpl( { if (!set_index || set_index->getOrderedSet().size() != 1 || set_index->hasMonotonicFunctionsChain()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } String column_name = getColumnNameFromKeyCondition(key_condition, curr.getKeyColumn()); - const auto * orc_type = getORCTypeByName(schema, column_name, format_settings.orc.case_insensitive_column_matching); + const bool ignore_case = format_settings.orc.case_insensitive_column_matching; + + /// The predicate column may be a tuple element (`t.x`), which the ORC header does not + /// carry as a flat entry, so resolve it through the type as well as through the schema. + auto column_types = findHeaderTypesByPath(header, column_name, ignore_case); + if (!column_types) + { + builder.literal(ORC::TruthValue::YES_NO_NULL); + break; + } + + /// The resolver rewrites the type it is given when it descends a LIST (a flattened + /// Nested column), so give it a scratch copy: the guards below must judge the key's + /// own type, which is what KeyCondition's RPN holds. + const auto & column_type = column_types->result_type; + auto resolved_type = column_type; + const auto * orc_type = traverseDownORCTypeByName(column_name, &schema, resolved_type, ignore_case); if (!orc_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -607,30 +828,34 @@ static void buildORCSearchArgumentImpl( /// down filters would result in different outputs. bool skipped = false; auto expect_type = makeNullableRecursively(parseORCType(orc_type, true, false, nullptr, skipped, format_settings.max_parser_depth), format_settings); - const ColumnWithTypeAndName * column = header.findByName(column_name, format_settings.orc.case_insensitive_column_matching); - if (!expect_type || !column) + if (!expect_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - auto nested_type = removeNullable(recursiveRemoveLowCardinality(column->type)); + auto nested_type = removeNullable(recursiveRemoveLowCardinality(column_type)); auto expect_nested_type = removeNullable(expect_type); if (!nested_type->equals(*expect_nested_type)) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - /// If null_as_default is true, the only difference is nullable, and the evaluations of current RPNElement based on default and null field - /// have the same result, we still should push down current filter. - if (format_settings.null_as_default && !column->type->isNullable() && !column->type->isLowCardinalityNullable()) + /// A non-nullable element converts NULL to its default even when a nullable ancestor makes + /// its extracted type nullable. Pruning must agree with the values produced by the reader. + const auto & declared_type = column_types->declared_type; + if (format_settings.null_as_default && !isNullableOrLowCardinalityNullable(declared_type)) { - bool match_if_null = evaluateRPNElement({}, curr); - bool match_if_default = evaluateRPNElement(column->type->getDefault(), curr); + /// Use the column default inserted by `insertNullAsDefaultIfNeeded`. It differs from + /// the type default for `Date32`. + auto default_column = declared_type->createColumn(); + default_column->insertDefault(); + const bool match_if_null = evaluateRPNElement({}, curr); + const bool match_if_default = evaluateRPNElement((*default_column)[0], curr); if (match_if_default != match_if_null) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } @@ -638,13 +863,21 @@ static void buildORCSearchArgumentImpl( auto predicate_type = convertORCTypeToPredicateType(*orc_type); if (!predicate_type.has_value()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } if (need_wrap_not) builder.startNot(); + /// A relaxed atom can be false even when its approximation is true. Preserve that + /// possibility before negation, as `KeyCondition` does with `can_be_false`. + if (curr.relaxed) + { + builder.startAnd(); + builder.literal(ORC::TruthValue::YES_NO); + } + if (contains_is_null) { builder.isNull(orc_type->getColumnId(), *predicate_type); @@ -656,8 +889,8 @@ static void buildORCSearchArgumentImpl( bool has_right_bound = !range.right.isPositiveInfinity(); if (!has_left_bound && !has_right_bound) { - /// Transform whole range orc::TruthValue::YES_NULL - builder.literal(orc::TruthValue::YES_NULL); + /// Transform whole range ORC::TruthValue::YES_NULL + builder.literal(ORC::TruthValue::YES_NULL); } else if (has_left_bound && has_right_bound && range.left_included && range.right_included && range.left == range.right) { @@ -666,15 +899,15 @@ static void buildORCSearchArgumentImpl( if (literal.has_value()) builder.equals(orc_type->getColumnId(), *predicate_type, *literal); else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } else { - std::optional left_literal; + std::optional left_literal; if (has_left_bound) left_literal = convertFieldToORCLiteral(*orc_type, range.left); - std::optional right_literal; + std::optional right_literal; if (has_right_bound) right_literal = convertFieldToORCLiteral(*orc_type, range.right); @@ -694,7 +927,7 @@ static void buildORCSearchArgumentImpl( builder.end(); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_right_bound) @@ -707,7 +940,7 @@ static void buildORCSearchArgumentImpl( builder.lessThan(orc_type->getColumnId(), *predicate_type, *right_literal); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_left_bound && has_right_bound) @@ -721,7 +954,7 @@ static void buildORCSearchArgumentImpl( const auto & set_column = ordered_set[0]; bool fail = false; - std::vector literals; + std::vector literals; literals.reserve(set_column->size()); for (size_t i = 0; i < set_column->size(); ++i) { @@ -735,15 +968,28 @@ static void buildORCSearchArgumentImpl( literals.emplace_back(*literal); } - /// set has zero element - if (literals.empty()) - builder.literal(orc::TruthValue::YES); - else if (fail) - builder.literal(orc::TruthValue::YES_NO_NULL); + if (fail) + builder.literal(ORC::TruthValue::YES_NO_NULL); + else if (literals.empty()) + builder.literal(ORC::TruthValue::NO); else + { + /// A set without NULL has no NULL matches. ORC evaluates `IN` as NULL for a + /// NULL key, so exclude NULL explicitly before applying any outer negation. + /// This preserves `nullIn` and `notNullIn` semantics. For regular nullable + /// `IN`, it can only retain extra rows, which the query filter removes. + builder.startAnd(); + builder.startNot(); + builder.isNull(orc_type->getColumnId(), *predicate_type); + builder.end(); builder.in(orc_type->getColumnId(), *predicate_type, literals); + builder.end(); + } } + if (curr.relaxed) + builder.end(); + if (need_wrap_not) builder.end(); @@ -755,7 +1001,7 @@ static void buildORCSearchArgumentImpl( case KeyCondition::RPNElement::FUNCTION_POINT_IN_POLYGON: case KeyCondition::RPNElement::FUNCTION_UNKNOWN: { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); rpn_stack.pop_back(); break; } @@ -787,34 +1033,45 @@ static void buildORCSearchArgumentImpl( } case KeyCondition::RPNElement::ALWAYS_FALSE: { - builder.literal(orc::TruthValue::NO); + builder.literal(ORC::TruthValue::NO); rpn_stack.pop_back(); break; } case KeyCondition::RPNElement::ALWAYS_TRUE: { - builder.literal(orc::TruthValue::YES); + builder.literal(ORC::TruthValue::YES); rpn_stack.pop_back(); break; } } } -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings) +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings) { auto rpn_stack = key_condition.getRPN(); if (rpn_stack.empty()) return nullptr; - auto builder = orc::SearchArgumentFactory::newBuilder(); + auto builder = std::make_unique(); buildORCSearchArgumentImpl(key_condition, header, schema, rpn_stack, *builder, format_settings); return builder->build(); } +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options) +{ + auto reader = std::make_unique(std::move(stream), options); + if (reader->getType().getKind() != ORC::STRUCT) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC files whose root type is not a struct are not supported, the file has root type {}", + reader->getType().toString()); + return reader; +} + static void getFileReader( ReadBuffer & in, - std::unique_ptr & file_reader, + std::unique_ptr & file_reader, const FormatSettings & format_settings, bool use_prefetch, size_t min_bytes_for_seek, @@ -823,16 +1080,18 @@ static void getFileReader( if (is_stopped) return; - orc::ReaderOptions options; - options.setMemoryPool(getORCMemoryPool()); - options.setCacheOptions(orc::CacheOptions{.holeSizeLimit = min_bytes_for_seek, .rangeSizeLimit = 10 * 1024 * 1024UL}); + /// The ranges with the gaps up to `min_bytes_for_seek` are read with one request. + static constexpr UInt64 default_range_size_limit = 10 * 1024 * 1024UL; + ORC::ReaderOptions options; + options.hole_size_limit = min_bytes_for_seek; + options.range_size_limit = std::max(default_range_size_limit, min_bytes_for_seek); auto input_stream = asORCInputStream(in, format_settings, use_prefetch, is_stopped); - file_reader = orc::createReader(std::move(input_stream), options); + file_reader = createORCReader(std::move(input_stream), options); } -static const orc::Type * -traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type, DataTypePtr & type, bool ignore_case) +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case) { /// Recurses the file-controlled ORC type tree. The matching CH type (and the requested column /// name) bound the depth in practice, but keep a stack backstop here too, since this runs in @@ -842,39 +1101,50 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type if (target.empty()) return orc_type; - auto search_struct_field = [&](const std::string & target_, const orc::Type * type_) -> std::pair + auto search_struct_field = [&](const std::string & target_, const ORC::Type * type_) -> std::pair { - auto target_copy = target_; - if (ignore_case) - boost::to_lower(target_copy); - - for (size_t i = 0; i < type_->getSubtypeCount(); ++i) + auto search_pass = [&](bool fold) -> std::pair { - auto field_name = type_->getFieldName(i); - if (ignore_case) - boost::to_lower(field_name); + auto target_copy = target_; + if (fold) + boost::to_lower(target_copy); - if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + for (size_t i = 0; i < type_->getSubtypeCount(); ++i) { - return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + auto field_name = type_->getFieldName(i); + if (fold) + boost::to_lower(field_name); + + if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + { + return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + } } - } - return {"", nullptr}; + return {"", nullptr}; + }; + + /// A field spelled exactly like the request always wins: a struct may hold several fields + /// whose names differ only by case, and case-folding first binds the request to whichever + /// of them the file lists first. + auto exact_match = search_pass(/*fold=*/false); + if (exact_match.second || !ignore_case) + return exact_match; + return search_pass(/*fold=*/true); }; - if (orc::STRUCT == orc_type->getKind()) + if (ORC::STRUCT == orc_type->getKind()) { const auto [next_target, next_orc_type] = search_struct_field(target, orc_type); return next_orc_type ? traverseDownORCTypeByName(next_target, next_orc_type, type, ignore_case) : nullptr; } - if (orc::LIST == orc_type->getKind()) + if (ORC::LIST == orc_type->getKind()) { /// For cases in which header contains subcolumns flattened from nested columns. /// For example, "a Nested(x String, y Int64)" is flattened to "a.x Array(String), a.y Array(Int64)", and ORC file schema is still "a array>". /// In this case, we should skip possible array type and traverse down to its nested struct type. const auto * array_type = typeid_cast(removeNullable(type).get()); const auto * orc_nested_type = orc_type->getSubtype(0); - if (array_type && orc::STRUCT == orc_nested_type->getKind()) + if (array_type && ORC::STRUCT == orc_nested_type->getKind()) { auto next_type_and_target = search_struct_field(target, orc_nested_type); const auto & next_target = next_type_and_target.first; @@ -890,8 +1160,37 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type return nullptr; } -static void -updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_case, std::unordered_set & include_typeids) +/// Forward declarations: updateIncludeTypeIds needs the union branch-hint machinery (defined +/// below, near readColumnFromORCColumn, which is where it is also used) to prune struct-branch +/// fields the same way the read path does. See computeOrcUnionBranchHints. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive); +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type); +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching); + +/// Binds a name to a field of an ORC struct type. A field spelled exactly like the name always +/// wins over one that only matches case-folded, so a struct holding several fields whose names +/// differ only by case resolves the name to the same field everywhere. +static std::optional findORCStructFieldByName(const ORC::Type * orc_type, const String & name, bool ignore_case) +{ + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (name == orc_type->getFieldName(i)) + return i; + + if (ignore_case) + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (boost::iequals(name, orc_type->getFieldName(i))) + return i; + + return std::nullopt; +} + +/// Also collects the ORC structs that are requested as a `Tuple`. +static void updateIncludeTypeIds( + DataTypePtr type, + const ORC::Type * orc_type, + bool ignore_case, + std::unordered_set & include_typeids, + std::vector & requested_structs) { /// Recurses the file-controlled ORC type tree in lockstep with the (parser-bounded) CH type. /// Keep a stack backstop here too: this runs in prepareFileReader, before the @@ -908,71 +1207,121 @@ updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_c auto non_nullable_type = removeNullable(type); switch (orc_type->getKind()) { - case orc::LIST: { + case ORC::LIST: { const auto * array_type = typeid_cast(non_nullable_type.get()); if (array_type) { - updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids); + updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids, requested_structs); + return; } - return; + break; } - case orc::MAP: { + case ORC::MAP: { const auto * map_type = typeid_cast(non_nullable_type.get()); if (map_type) { - updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids); - updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids); + updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids, requested_structs); + updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids, requested_structs); + return; } - return; + break; } - case orc::STRUCT: { + case ORC::STRUCT: { /// To make sure tuple field pruning work fine, we should include only the fields of ORC struct type which are also contained in CH tuple types, instead of all fields of ORC struct type. /// For example, CH tupe type in header is "x Tuple(a String)", ORC struct type is "x struct", then only type id of field "x.a" should be included. /// For tuple field pruning purpose, we should never include "x.b" for it is not required in format header. const auto * tuple_type = typeid_cast(non_nullable_type.get()); if (tuple_type) { + requested_structs.push_back(orc_type); if (tuple_type->hasExplicitNames()) { - std::unordered_map orc_field_name_to_index; - orc_field_name_to_index.reserve(orc_type->getSubtypeCount()); - for (size_t struct_i = 0; struct_i < orc_type->getSubtypeCount(); ++struct_i) - { - String field_name = orc_type->getFieldName(struct_i); - if (ignore_case) - boost::to_lower(field_name); - - orc_field_name_to_index[field_name] = struct_i; - } - const auto & element_names = tuple_type->getElementNames(); for (size_t tuple_i = 0; tuple_i < element_names.size(); ++tuple_i) { - String element_name = element_names[tuple_i]; - if (ignore_case) - boost::to_lower(element_name); - - if (orc_field_name_to_index.contains(element_name)) - { + if (auto field_i = findORCStructFieldByName(orc_type, element_names[tuple_i], ignore_case)) updateIncludeTypeIds( - tuple_type->getElement(tuple_i), - orc_type->getSubtype(orc_field_name_to_index[element_name]), - ignore_case, - include_typeids); - } + tuple_type->getElement(tuple_i), orc_type->getSubtype(*field_i), ignore_case, include_typeids, requested_structs); } } else { for (size_t i = 0; i < tuple_type->getElements().size() && i < orc_type->getSubtypeCount(); ++i) - updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids); + updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids, requested_structs); } + return; + } + break; + } + case ORC::UNION: { + /// ORC union maps to the ClickHouse Variant type. A branch that gets a forced type hint + /// (the same way readColumnFromORCColumn computes it - see computeOrcUnionBranchHints) + /// is selected by recursing into the hint, so a STRUCT branch keeps the named-tuple + /// field pruning above: a field the hint's tuple does not reference (e.g. an + /// unsupported or corrupt one) is never added to include_typeids. A branch without a + /// forced hint is read in full, matching readColumnFromORCColumn's "no guess is ever + /// made" policy, so its entire subtree is selected. Every branch always contributes at + /// least one id, so ORC's ColumnSelector::selectParents never falls back to its "fully + /// select every branch or none" override for partial branch selection, and the union's + /// own tag stream is selected as the automatic parent of the selected branches. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, non_nullable_type, ignore_case); + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + { + const auto * branch_orc_type = orc_type->getSubtype(i); + if (branch_hints[i]) + updateIncludeTypeIds(branch_hints[i], branch_orc_type, ignore_case, include_typeids, requested_structs); + else + include_typeids.insert(branch_orc_type->getColumnId()); } return; } default: return; } + + /// A requested type of another kind reads the whole node, and the cast to the requested type converts it or throws. + include_typeids.insert(orc_type->getColumnId()); +} + +/// Whether a column of the subtree of `orc_type`, or one of its ancestors (which reads the subtree whole), is included. +static bool isORCTypeRead( + const ORC::Type & root, const ORC::Type & orc_type, const std::unordered_set & include_typeids) +{ + for (UInt64 id = orc_type.getColumnId(); id <= orc_type.getMaximumColumnId(); ++id) + { + if (include_typeids.contains(id)) + return true; + } + + const ORC::Type * node = &root; + while (node && node->getColumnId() < orc_type.getColumnId()) + { + if (include_typeids.contains(node->getColumnId())) + return true; + + const ORC::Type * child = nullptr; + for (UInt64 i = 0; i < node->getSubtypeCount() && !child; ++i) + { + if (node->getSubtype(i)->getMaximumColumnId() >= orc_type.getColumnId()) + child = node->getSubtype(i); + } + node = child; + } + return false; +} + +/// The field of an ORC struct with the fewest columns, or the struct itself if it has no fields. +static const ORC::Type & getNarrowestORCStructField(const ORC::Type & orc_struct) +{ + const ORC::Type * narrowest = &orc_struct; + for (UInt64 i = 0; i < orc_struct.getSubtypeCount(); ++i) + { + const auto * field = orc_struct.getSubtype(i); + if (narrowest == &orc_struct + || field->getMaximumColumnId() - field->getColumnId() < narrowest->getMaximumColumnId() - narrowest->getColumnId()) + narrowest = field; + } + return *narrowest; } NativeORCBlockInputFormat::NativeORCBlockInputFormat( @@ -999,34 +1348,51 @@ void NativeORCBlockInputFormat::prepareFileReader() return; if (format_filter_info) - format_filter_info->initKeyConditionOnce(getPort().getHeader()); - - std::unique_ptr stripe_info; - if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); - - orc_column_to_ch_column = std::make_unique( - getPort().getHeader(), - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.orc.case_insensitive_column_matching, - format_settings.orc.dictionary_as_low_cardinality); + format_filter_info->initKeyConditionOnce(buildORCKeyConditionBlock( + getPort().getHeader(), + format_filter_info->filter_actions_dag.get(), + format_settings.orc.case_insensitive_column_matching)); const bool ignore_case = format_settings.orc.case_insensitive_column_matching; const auto & header = getPort().getHeader(); const auto & file_schema = file_reader->getType(); std::unordered_set include_typeids; + std::vector requested_structs; for (const auto & column : header) { auto adjusted_type = column.type; const auto * orc_type = traverseDownORCTypeByName(column.name, &file_schema, adjusted_type, ignore_case); if (orc_type) - updateIncludeTypeIds(adjusted_type, orc_type, ignore_case, include_typeids); + updateIncludeTypeIds(adjusted_type, orc_type, ignore_case, include_typeids, requested_structs); + } + + /// A requested struct none of whose requested fields is in the file is still read, through its narrowest field, + /// for its presence and the sizes of the lists and maps around it; `matchORCTupleElementsByName` then fills the + /// requested fields with defaults. Inner structs first, as a read inner one makes its parents read. + std::ranges::sort(requested_structs, std::greater{}, &ORC::Type::getColumnId); + std::unordered_set count_only_fields; + for (const auto * orc_struct : requested_structs) + { + if (isORCTypeRead(file_schema, *orc_struct, include_typeids)) + continue; + const auto & narrowest = getNarrowestORCStructField(*orc_struct); + include_typeids.insert(narrowest.getColumnId()); + if (&narrowest != orc_struct) + count_only_fields.insert(narrowest.getColumnId()); } include_indices.assign(include_typeids.begin(), include_typeids.end()); + orc_column_to_ch_column = std::make_unique( + getPort().getHeader(), + format_settings.orc.allow_missing_columns, + format_settings.null_as_default, + format_settings.orc.case_insensitive_column_matching, + format_settings.orc.dictionary_as_low_cardinality, + format_settings.date_time_overflow_behavior, + std::move(count_only_fields)); + if (format_settings.orc.filter_push_down && format_filter_info && format_filter_info->key_condition && !sargs) - sargs = buildORCSearchArgument(*format_filter_info->key_condition, getPort().getHeader(), file_reader->getType(), format_settings); + sargs = buildORCSearchArgument(*format_filter_info->key_condition, header, file_schema, format_settings); selected_stripes = calculateSelectedStripes(static_cast(file_reader->getNumberOfStripes()), skip_stripes); read_iterator = 0; @@ -1048,7 +1414,7 @@ void NativeORCBlockInputFormat::prefetchStripes() int stripe = selected_stripes[prefetch_iterator]; stripes.push_back(stripe); - total_stripe_size += file_reader->getStripe(stripe)->getLength(); + total_stripe_size += ORC::Reader::getStripeLength(file_reader->getStripe(stripe)); ++prefetch_iterator; } @@ -1079,32 +1445,31 @@ std::vector NativeORCBlockInputFormat::calculateSelectedStripes(int num_str bool NativeORCBlockInputFormat::prepareStripeReader() { - assert(file_reader); + chassert(file_reader); if (read_iterator >= selected_stripes.size()) return false; int current_stripe = selected_stripes[read_iterator]; - current_stripe_info = file_reader->getStripe(current_stripe); - if (!current_stripe_info->getNumberOfRows()) + current_stripe_info = &file_reader->getStripe(current_stripe); + if (!current_stripe_info->number_of_rows) throw Exception(ErrorCodes::INCORRECT_DATA, "ORC stripe {} has no rows", current_stripe); - orc::RowReaderOptions row_reader_options; - row_reader_options.setEnableLazyDecoding(format_settings.orc.dictionary_as_low_cardinality); - row_reader_options.includeTypes(include_indices); - row_reader_options.setTimezoneName(format_settings.orc.reader_time_zone_name); - row_reader_options.range(current_stripe_info->getOffset(), current_stripe_info->getLength()); + ORC::RowReaderOptions row_reader_options; + row_reader_options.enable_lazy_decoding = format_settings.orc.dictionary_as_low_cardinality; + row_reader_options.include_types = include_indices; + row_reader_options.timezone_name = format_settings.orc.reader_time_zone_name; + row_reader_options.range_offset = current_stripe_info->offset; + row_reader_options.range_length = ORC::Reader::getStripeLength(*current_stripe_info); if (format_settings.orc.filter_push_down && sargs) - { - row_reader_options.searchArgument(sargs); - } + row_reader_options.search_argument = sargs; stripe_reader = file_reader->createRowReader(row_reader_options); ++read_iterator; if (use_prefetch) { /// Release outdated buffer before boundary to avoid OOM - file_reader->releaseBuffer(current_stripe_info->getOffset()); + file_reader->releaseBuffer(current_stripe_info->offset); /// Prefetch next selected stripe prefetchStripes(); @@ -1127,7 +1492,7 @@ Chunk NativeORCBlockInputFormat::read() int current_stripe = selected_stripes[read_iterator]; ++read_iterator; - return getChunkForCount(file_reader->getStripe(current_stripe)->getNumberOfRows()); + return getChunkForCount(file_reader->getStripe(current_stripe).number_of_rows); } if (!stripe_reader) @@ -1139,14 +1504,12 @@ Chunk NativeORCBlockInputFormat::read() if (is_stopped) return {}; - /// TODO: figure out why reuse batch would cause asan fatals in https://s3.amazonaws.com/clickhouse-test-reports/55330/be39d23af2d7e27f5ec7f168947cf75aeaabf674/stateless_tests__asan__[4_4].html - /// Not sure if it is a false positive case. Notice that reusing batch will speed up reading ORC by 1.15x. + /// The values are decoded directly into the columns of the batch, which are then handed over to the chunk. Stopwatch time; - auto batch = stripe_reader->createRowBatch(format_settings.orc.row_batch_size); + auto batch = stripe_reader->createRowBatch(); while (true) { - bool ok = stripe_reader->next(*batch); - if (ok) + if (stripe_reader->next(*batch, static_cast(format_settings.orc.row_batch_size))) break; /// No more rows to read in current stripe, continue to prepare reading next stripe @@ -1163,7 +1526,7 @@ Chunk NativeORCBlockInputFormat::read() orc_column_to_ch_column->orcTableToCHChunk(res, &schema, batch.get(), num_rows, &block_missing_values); LOG_TEST(getLogger("NativeORCBlockInputFormat"), "Convert {} rows take {} ms", num_rows, time.elapsedMilliseconds()); - approx_bytes_read_for_chunk = num_rows * current_stripe_info->getLength() / current_stripe_info->getNumberOfRows(); + approx_bytes_read_for_chunk = num_rows * ORC::Reader::getStripeLength(*current_stripe_info) / current_stripe_info->number_of_rows; return res; } @@ -1188,33 +1551,41 @@ NativeORCSchemaReader::NativeORCSchemaReader(ReadBuffer & in_, const FormatSetti { } -NamesAndTypesList NativeORCSchemaReader::readSchema() +void NativeORCSchemaReader::initializeIfNeeded() { - std::unique_ptr file_reader; - std::atomic is_stopped = 0; + if (initialized) + return; getFileReader(in, file_reader, format_settings, false, 0, is_stopped); + initialized = true; +} + +NamesAndTypesList NativeORCSchemaReader::readSchema() +{ + initializeIfNeeded(); const auto & schema = file_reader->getType(); Block header; - std::unique_ptr stripe_info; + std::optional first_stripe_footer; if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); + first_stripe_footer = file_reader->readStripeFooter(0); - for (size_t i = 0; i < schema.getSubtypeCount(); ++i) { - const std::string & name = schema.getFieldName(i); - const orc::Type * orc_type = schema.getSubtype(i); + for (size_t i = 0; i < schema.getSubtypeCount(); ++i) + { + const std::string & name = schema.getFieldName(i); + const ORC::Type * orc_type = schema.getSubtype(i); - bool skipped = false; - DataTypePtr type = parseORCType( - orc_type, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.orc.dictionary_as_low_cardinality, - stripe_info.get(), - skipped, - format_settings.max_parser_depth); - if (!skipped) - header.insert(ColumnWithTypeAndName{type, name}); + bool skipped = false; + DataTypePtr type = parseORCType( + orc_type, + format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + format_settings.orc.dictionary_as_low_cardinality, + first_stripe_footer ? &*first_stripe_footer : nullptr, + skipped, + format_settings.max_parser_depth); + if (!skipped) + header.insert(ColumnWithTypeAndName{type, name}); + } } /// ORC doesn't have non-nullable data types. @@ -1223,26 +1594,36 @@ NamesAndTypesList NativeORCSchemaReader::readSchema() return header.getNamesAndTypesList(); } +std::optional NativeORCSchemaReader::readNumberOrRows() +{ + initializeIfNeeded(); + return file_reader->getNumberOfRows(); +} + ORCColumnToCHColumn::ORCColumnToCHColumn( const Block & header_, bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_, - bool dictionary_as_low_cardinality_) + bool dictionary_as_low_cardinality_, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_, + std::unordered_set count_only_fields_) : header(header_) , allow_missing_columns(allow_missing_columns_) , null_as_default(null_as_default_) , case_insensitive_matching(case_insensitive_matching_) , dictionary_as_low_cardinality(dictionary_as_low_cardinality_) + , date_time_overflow_behavior(date_time_overflow_behavior_) + , count_only_fields(std::move(count_only_fields_)) { } void ORCColumnToCHColumn::orcTableToCHChunk( - Chunk & res, const orc::Type * schema, const orc::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, const ORC::Type * schema, const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) { - const auto * struct_batch = dynamic_cast(table); + const auto * struct_batch = dynamic_cast(table); if (!struct_batch) - throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", struct_batch->toString()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", demangle(typeid(*table).name())); if (schema->getSubtypeCount() != struct_batch->fields.size()) throw Exception( @@ -1250,24 +1631,26 @@ void ORCColumnToCHColumn::orcTableToCHChunk( size_t field_num = struct_batch->fields.size(); NameToColumnPtr name_to_column_ptr; + /// The file's own spellings, in file order: the keys above are what a request is matched + /// against, and a case-folded match has to pick among them in a fixed order. + Names orc_field_names; + orc_field_names.reserve(field_num); for (size_t i = 0; i < field_num; ++i) { - auto name = schema->getFieldName(i); + const auto & name = schema->getFieldName(i); const auto * field = struct_batch->fields[i]; if (!field) throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table field {} is null", name); - if (case_insensitive_matching) - boost::to_lower(name); - - name_to_column_ptr[std::move(name)] = {field, schema->getSubtype(i)}; + name_to_column_ptr[name] = {field, schema->getSubtype(i)}; + orc_field_names.push_back(name); } - orcColumnsToCHChunk(res, name_to_column_ptr, num_rows, block_missing_values); + orcColumnsToCHChunk(res, name_to_column_ptr, orc_field_names, num_rows, block_missing_values); } /// Creates a null bytemap from ORC's not-null bytemap -static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_column) +static ColumnPtr readByteMapFromORCColumn(const ORC::ColumnVectorBatch * orc_column) { if (!orc_column->hasNulls) return ColumnUInt8::create(orc_column->numElements, static_cast(0)); @@ -1282,70 +1665,67 @@ static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_col } -static const orc::ColumnVectorBatch * getNestedORCColumn(const orc::ListVectorBatch * orc_column) +/// A branch of an ORC union can be non-null at the union level yet select a null payload; ORC +/// leaves a placeholder (a default value) at such positions. When the branch is later cast to an +/// explicit Variant alternative, a value-checking cast (e.g. Int8 -> Enum8, or the same inside a +/// Tuple field) would reject those placeholders even though the rows are never read (they become +/// the Variant NULL discriminator). Overwrite every null-payload row with a copy of a non-null row +/// before casting; the copied values are discarded downstream. If every row is a null payload there +/// is nothing to read, so a null is returned and the caller uses a default-valued column instead. +static ColumnPtr replaceNullPayloadRowsWithValidRow(const ColumnPtr & column, const NullMap & null_map) +{ + size_t valid_row = column->size(); + for (size_t row = 0; row < column->size(); ++row) + if (!null_map[row]) + { + valid_row = row; + break; + } + + if (valid_row == column->size()) + return nullptr; + + auto result = column->cloneEmpty(); + result->reserve(column->size()); + for (size_t row = 0; row < column->size(); ++row) + result->insertFrom(*column, null_map[row] ? valid_row : row); + return result; +} + + +static const ORC::ColumnVectorBatch * getNestedORCColumn(const ORC::ListVectorBatch * orc_column) { return orc_column->elements.get(); } +/// The reader decodes the lengths directly into the end offsets, as in `ColumnArray`. template static ColumnPtr readOffsetsFromORCListColumn(const BatchType * orc_column) { - auto offsets_column = ColumnUInt64::create(); - ColumnArray::Offsets & offsets_data = assert_cast &>(*offsets_column).getData(); - offsets_data.reserve(orc_column->numElements); - - for (size_t i = 0; i < orc_column->numElements; ++i) - offsets_data.push_back(orc_column->offsets[i + 1]); - - return offsets_column; + return orc_column->offsets; } +/// The values of the primitive types are decoded directly into the columns (with zeros for the nulls). static ColumnWithTypeAndName -readColumnWithBooleanData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithBooleanData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_bool_column = dynamic_cast(orc_column); - auto internal_type = DataTypeFactory::instance().get("Bool"); - auto internal_column = internal_type->createColumn(); - auto & column_data = assert_cast &>(*internal_column).getData(); - - column_data.reserve(orc_bool_column->numElements); - for (size_t i = 0; i < orc_bool_column->numElements; ++i) - { - if (!orc_bool_column->hasNulls || orc_bool_column->notNull[i]) - column_data.push_back(static_cast(orc_bool_column->data[i])); - else - column_data.push_back(static_cast(0)); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_bool_column = typeid_cast(*orc_column); + return {orc_bool_column.column, DataTypeFactory::instance().get("Bool"), column_name}; } -template +template static ColumnWithTypeAndName -readColumnWithNumericData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithNumericData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - auto internal_type = std::make_shared>(); - auto internal_column = internal_type->createColumn(); - auto & column_data = static_cast &>(*internal_column).getData(); - const auto * orc_int_column = dynamic_cast(orc_column); - - column_data.reserve(orc_int_column->numElements); - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(NumericType(orc_int_column->data[i])); - else - column_data.push_back(NumericType{}); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_numeric_column = typeid_cast &>(*orc_column); + return {orc_numeric_column.column, std::make_shared>(), column_name}; } template static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( - const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name, bool nullable) + const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name, bool nullable) { /// Fill CH holder_column with ORC dictionary /// Note that holder_column is always a ColumnString or ColumnFixedstring whether nullable is true or false, because ORC dictionary doesn't contain null values. @@ -1358,60 +1738,45 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( DataTypePtr nested_type = nullable ? std::make_shared(holder_type) : holder_type; auto internal_type = std::make_shared(std::move(nested_type)); - const auto & orc_str_column = dynamic_cast(*orc_column); + const auto & orc_str_column = dynamic_cast(*orc_column); size_t rows = orc_str_column.numElements; - const auto & orc_dict = *orc_str_column.dictionary; - if (orc_dict.dictionaryOffset.size() <= 1) + const auto & orc_dict = assert_cast(*orc_str_column.dictionary->column); + size_t dict_size = orc_dict.size(); + if (dict_size == 0) { + /// Only nulls can be encoded with an empty dictionary. + for (size_t i = 0; i < rows; ++i) + { + if (!orc_str_column.hasNulls || orc_str_column.notNull[i]) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC dictionary index {} at row {} is out of range [0, 0)", + orc_str_column.index[i], i); + } auto result_column = internal_type->createColumn(); result_column->insertManyDefaults(rows); return {std::move(result_column), internal_type, column_name}; } - size_t dict_size = orc_dict.dictionaryOffset.size() - 1; - auto holder_column = holder_type->createColumn(); + /// The dictionary of ORC is already a `ColumnString`, which is the holder for `String`. + ColumnPtr holder_column = orc_str_column.dictionary->column; if constexpr (fixed_string) { const size_t n = orc_type->getMaximumLength(); - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - size_t reserve_size = dict_size * n; - column_chars.resize_exact(reserve_size); - size_t curr_offset = 0; + auto fixed_holder_column = ColumnFixedString::create(n); + PaddedPODArray & column_chars = fixed_holder_column->getChars(); + column_chars.resize_fill(dict_size * n); for (size_t i = 0; i < dict_size; ++i) { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - if (buf_size > n) + auto value = orc_dict.getDataAt(i); + if (value.size() > n) throw Exception( ErrorCodes::INCORRECT_DATA, "ORC dictionary entry {} has size {} that exceeds the declared FixedString length {}", - i, buf_size, n); - memcpy(&column_chars[curr_offset], buf, buf_size); - /// resize_exact does not zero-initialize, so pad shorter entries to keep FixedString values - /// deterministic and to avoid leaking uninitialized heap memory. - if (buf_size < n) - memset(&column_chars[curr_offset + buf_size], 0, n - buf_size); - curr_offset += n; - } - } - else - { - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - PaddedPODArray & column_offsets = concrete_holder_column.getOffsets(); - - column_chars.resize_exact(orc_dict.dictionaryBlob.size()); - column_offsets.resize_exact(dict_size); - size_t curr_offset = 0; - for (size_t i = 0; i < dict_size; ++i) - { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; + i, value.size(), n); + memcpy(&column_chars[i * n], value.data(), value.size()); } + holder_column = std::move(fixed_holder_column); } /// Insert CH dictionary_column from holder_column @@ -1475,57 +1840,22 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithStringData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static const ColumnString & getStringColumnFromBatch(const ORC::ColumnVectorBatch * orc_column, ColumnPtr & holder) { - auto internal_type = std::make_shared(); - auto internal_column = internal_type->createColumn(); - PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); - PaddedPODArray & column_offsets = assert_cast(*internal_column).getOffsets(); - - const auto * orc_str_column = dynamic_cast(orc_column); - size_t reserve_size = 0; - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - reserve_size += orc_str_column->length[i]; - } - - column_chars.resize_exact(reserve_size); - column_offsets.resize_exact(orc_str_column->numElements); - - size_t curr_offset = 0; - if (!orc_str_column->hasNulls) - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; - } - } - else - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (orc_str_column->notNull[i]) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - } + holder = ORC::getStringColumn(dynamic_cast(*orc_column)); + return assert_cast(*holder); +} - column_offsets[i] = curr_offset; - } - } - return {std::move(internal_column), internal_type, column_name}; +static ColumnWithTypeAndName +readColumnWithStringData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) +{ + ColumnPtr column; + getStringColumnFromBatch(orc_column, column); + return {column, std::make_shared(), column_name}; } static ColumnWithTypeAndName -readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name) +readColumnWithFixedStringData(const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name) { size_t fixed_len = orc_type->getMaximumLength(); auto internal_type = std::make_shared(fixed_len); @@ -1533,25 +1863,22 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); column_chars.reserve(orc_column->numElements * fixed_len); - const auto * orc_str_column = dynamic_cast(orc_column); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - { - const Int64 length = orc_str_column->length[i]; - if (length < 0 || static_cast(length) > fixed_len) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "ORC string value at row {} has size {} that doesn't fit into FixedString({})", - i, length, fixed_len); + /// The null values are empty strings. + auto value = strings.getDataAt(i); + if (value.size() > fixed_len) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC string value at row {} has size {} that doesn't fit into FixedString({})", + i, value.size(), fixed_len); - column_chars.insert_assume_reserved(orc_str_column->data[i], orc_str_column->data[i] + length); - /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. - if (static_cast(length) < fixed_len) - column_chars.resize_fill(column_chars.size() + (fixed_len - static_cast(length))); - } - else - column_chars.resize_fill(column_chars.size() + fixed_len); + column_chars.insert_assume_reserved(value.data(), value.data() + value.size()); + /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. + if (value.size() < fixed_len) + column_chars.resize_fill(column_chars.size() + (fixed_len - value.size())); } return {std::move(internal_column), internal_type, column_name}; @@ -1560,10 +1887,10 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o template static ColumnWithTypeAndName readColumnWithDecimalDataCast( - const orc::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) { using NativeType = typename DecimalType::NativeType; - static_assert(std::is_same_v || std::is_same_v); + static_assert(std::is_same_v || std::is_same_v); auto internal_column = internal_type->createColumn(); auto & column_data = static_cast &>(*internal_column).getData(); @@ -1574,13 +1901,10 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( { if (!orc_decimal_column->hasNulls || orc_decimal_column->notNull[i]) { - DecimalType decimal_value; - if constexpr (std::is_same_v) + DecimalType decimal_value{}; + if constexpr (std::is_same_v) { - Int128 int128_value; - int128_value.items[0] = orc_decimal_column->values[i].getLowBits(); - int128_value.items[1] = orc_decimal_column->values[i].getHighBits(); - decimal_value.value = static_cast(int128_value); + decimal_value.value = static_cast(orc_decimal_column->values[i]); } else decimal_value.value = static_cast(orc_decimal_column->values[i]); @@ -1595,26 +1919,30 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( } static ColumnWithTypeAndName -readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv6ColumnFromBinaryData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { /// If at least one value size is not 16 bytes, fallback to reading String column and further cast to IPv6. - if ((!orc_str_column->hasNulls || orc_str_column->notNull[i]) && orc_str_column->length[i] != sizeof(IPv6)) - return readColumnWithStringData(orc_column, column_name); + if ((!orc_column->hasNulls || orc_column->notNull[i]) && strings.getDataAt(i).size() != sizeof(IPv6)) + return {holder, std::make_shared(), column_name}; } auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & ipv6_column = assert_cast(*internal_column); - ipv6_column.reserve(orc_str_column->numElements); + ipv6_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - ipv6_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + if (!orc_column->hasNulls || orc_column->notNull[i]) + { + auto value = strings.getDataAt(i); + ipv6_column.insertData(value.data(), value.size()); + } else ipv6_column.insertDefault(); } @@ -1623,49 +1951,46 @@ readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const St } static ColumnWithTypeAndName -readIPv4ColumnWithInt32Data(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv4ColumnWithInt32Data(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_int_column = dynamic_cast(orc_column); + const auto & data = typeid_cast(*orc_column).getData(); auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); - column_data.reserve(orc_int_column->numElements); - - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(static_cast(orc_int_column->data[i])); - else - column_data.push_back(0); - } + column_data.resize(data.size()); + /// The null values are zeros. + for (size_t i = 0; i < data.size(); ++i) + column_data[i] = static_cast(data[i]); return {std::move(internal_column), internal_type, column_name}; } template static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); auto internal_column = column_type->createColumn(); auto & integer_column = assert_cast(*internal_column); - integer_column.reserve(orc_str_column->numElements); + integer_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) + if (!orc_column->hasNulls || orc_column->notNull[i]) { - if (sizeof(typename ColumnType::ValueType) != orc_str_column->length[i]) + auto value = strings.getDataAt(i); + if (sizeof(typename ColumnType::ValueType) != value.size()) throw Exception( ErrorCodes::INCORRECT_DATA, "ValueType size {} of column {} is not equal to size of binary data {}", sizeof(typename ColumnType::ValueType), integer_column.getName(), - orc_str_column->length[i]); + value.size()); - integer_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + integer_column.insertData(value.data(), value.size()); } else { @@ -1676,11 +2001,21 @@ static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( } static ColumnWithTypeAndName readColumnWithDateData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & type_hint) + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & raw_type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { + /// The hint is the raw header type: `readColumnFromORCColumn` strips an outer Nullable but not + /// LowCardinality, so e.g. a LowCardinality(DateTime('UTC')) target would fall through to the + /// raw Int32 branch below and the later context-less cast would read the day count as unix + /// seconds. Strip the wrappers so such targets take the same branches as the plain types. + const DataTypePtr type_hint = raw_type_hint ? removeNullable(recursiveRemoveLowCardinality(raw_type_hint)) : nullptr; + DataTypePtr internal_type; bool check_date32_range = false; bool check_date_range = false; + bool check_datetime_range = false; /// Make result type Date32 when requested type is actually Date32 or when we use schema inference if (!type_hint || isDate32(*type_hint)) @@ -1696,12 +2031,23 @@ static ColumnWithTypeAndName readColumnWithDateData( internal_type = std::make_shared(); check_date_range = true; } + else if (isDateTime(*type_hint)) + { + /// Keep the intermediate as Date32, so the later cast converts the day count to midnight + /// of that day instead of reading it as unix seconds. The cast is context-less, so + /// `date_time_overflow_behavior` does not reach it and a day number whose midnight does + /// not fit into DateTime would wrap to an unrelated timestamp. Validate the range here + /// against the same [0, MAX_DATETIME_DAY_NUM] window that `ToDateTimeImpl` uses. + internal_type = std::make_shared(); + check_datetime_range = true; + } else { internal_type = std::make_shared(); } - const auto * orc_int_column = dynamic_cast(orc_column); + const auto * orc_int_column = dynamic_cast(orc_column); + const auto & orc_int_data = orc_int_column->getData(); auto internal_column = internal_type->createColumn(); PaddedPODArray & column_data = assert_cast &>(*internal_column).getData(); column_data.reserve(orc_int_column->numElements); @@ -1710,25 +2056,50 @@ static ColumnWithTypeAndName readColumnWithDateData( { if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) { - Int32 days_num = static_cast(orc_int_column->data[i]); - if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < -DAYNUM_OFFSET_EPOCH)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", - days_num, - column_name, - -DAYNUM_OFFSET_EPOCH, - DATE_LUT_MAX_EXTEND_DAY_NUM); + /// Range-check the original Int64 day count before narrowing to Int32, + /// otherwise a malformed value could wrap into an apparently valid date. + Int64 days_num = orc_int_data[i]; + if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < (-DAYNUM_OFFSET_EPOCH))) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < (-DAYNUM_OFFSET_EPOCH)) ? (-DAYNUM_OFFSET_EPOCH) : DATE_LUT_MAX_EXTEND_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", + days_num, + column_name, + (-DAYNUM_OFFSET_EPOCH), + DATE_LUT_MAX_EXTEND_DAY_NUM); + } if (check_date_range && (days_num > DATE_LUT_MAX_DAY_NUM || days_num < 0)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", - days_num, - column_name, - DATE_LUT_MAX_DAY_NUM); + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : DATE_LUT_MAX_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", + days_num, + column_name, + DATE_LUT_MAX_DAY_NUM); + } + + if (check_datetime_range && (days_num > MAX_DATETIME_DAY_NUM || days_num < 0)) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : MAX_DATETIME_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the day range of type DateTime, which is [0, {}]", + days_num, + column_name, + MAX_DATETIME_DAY_NUM); + } - column_data.push_back(days_num); + column_data.push_back(static_cast(days_num)); } else { @@ -1739,40 +2110,65 @@ static ColumnWithTypeAndName readColumnWithDateData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static ColumnWithTypeAndName readColumnWithTimestampData( + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { - const auto * orc_ts_column = dynamic_cast(orc_column); + const auto * orc_ts_column = dynamic_cast(orc_column); + + /// ORC stores timestamps as (seconds, nanoseconds). ClickHouse used to convert them through a fixed + /// DateTime64(9) intermediate (seconds * 1e9 + nanoseconds), which overflows Int64 for timestamps beyond + /// ~year 2262 even when the requested DateTime64 scale can represent the value (e.g. Iceberg's DateTime64(6)). + /// Read directly at the requested scale so such values round-trip like Parquet, and only handle overflow when + /// even the target scale does not fit Int64. + UInt32 scale = 9; + if (type_hint) + { + const auto * dt64_hint = typeid_cast(removeNullable(recursiveRemoveLowCardinality(type_hint)).get()); + if (dt64_hint) + scale = dt64_hint->getScale(); + } - auto internal_type = std::make_shared(9); + auto internal_type = std::make_shared(scale); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); column_data.reserve(orc_ts_column->numElements); - constexpr Int64 multiplier = 1e9L; + /// Factor to go from nanoseconds down to the target scale (scale is in [0, 9]). + const Int128 divisor = DecimalUtils::scaleMultiplier(9 - scale); + const Int128 int64_min = std::numeric_limits::min(); + const Int128 int64_max = std::numeric_limits::max(); + for (size_t i = 0; i < orc_ts_column->numElements; ++i) { if (!orc_ts_column->hasNulls || orc_ts_column->notNull[i]) { - Int64 timestamp_value; - Int64 seconds = orc_ts_column->data[i]; - Int64 nanoseconds = orc_ts_column->nanoseconds[i]; + const Int64 seconds = orc_ts_column->data[i]; + const Int64 nanoseconds = orc_ts_column->nanoseconds[i]; - /// Check for overflow when converting timestamp to DateTime64(9) - bool overflow = common::mulOverflow(seconds, multiplier, timestamp_value); - overflow |= common::addOverflow(timestamp_value, nanoseconds, timestamp_value); + /// seconds * 1e9 + nanoseconds cannot overflow Int128 (|seconds| < 2^63, product < ~9.2e27 << Int128 max). + const Int128 nanos_total = static_cast(seconds) * 1'000'000'000 + nanoseconds; + /// Integer division truncates toward zero, matching the DateTime64(9) -> DateTime64(scale) cast that ran afterwards. + Int128 value = nanos_total / divisor; - if (overflow) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Timestamp value in column \"{}\" is out of range for DateTime64: seconds={}, nanoseconds={}", - column_name, - seconds, - nanoseconds); + if (value < int64_min || value > int64_max) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + value = value < int64_min ? int64_min : int64_max; + else + /// Throw for both `throw` and `ignore` (the default): keep the historical behavior and never silently corrupt data. + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp value in column \"{}\" is out of range for DateTime64({}): seconds={}, nanoseconds={}", + column_name, + scale, + seconds, + nanoseconds); + } - Decimal64 decimal64; - decimal64.value = timestamp_value; - column_data.emplace_back(std::move(decimal64)); + column_data.push_back(DateTime64(static_cast(value))); } else column_data.push_back(0); @@ -1780,9 +2176,504 @@ readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const Str return {std::move(internal_column), internal_type, column_name}; } +/// Whether a DateTime/DateTime64 target carries an explicit timezone - schema inference produces one +/// (UTC) for the ORC `TIMESTAMP_INSTANT` ("timestamp with local timezone") kind, but an explicit +/// schema may name any timezone. Used to tell the two ORC timestamp kinds apart when matching union +/// branches (see `orcUnionBranchMatchesType`). +static bool orcTimestampTargetHasExplicitTimeZone(const DataTypePtr & type) +{ + const auto * timezone = dynamic_cast(type.get()); + return timezone && timezone->hasExplicitTimeZone(); +} + +/// Whether a ClickHouse numeric type is a widening of an ORC integer branch whose values occupy +/// `orc_size` bytes: a strictly wider integer, or a float that represents every value of that width +/// exactly. The ordinary (non-union) ORC column path gets these conversions for free from the final +/// cast in `orcColumnsToCHChunk`; a union branch has to request them as a per-branch hint, because +/// the final cast of a union column is a `Variant` -> `Variant` cast, which only extends the set of +/// alternatives by exact type name and cannot widen an alternative. Equal-width targets are listed +/// explicitly by the caller (they include the writer's own mappings, such as the unsigned and `Enum` +/// types), so only strictly wider integers are accepted here. +static bool orcIntegerBranchWidensTo(const DataTypePtr & type, size_t orc_size) +{ + const WhichDataType which(type); + if (which.isFloat32()) + return orc_size <= 2; + if (which.isFloat64()) + return orc_size <= 4; + return which.isInteger() && type->getSizeOfValueInMemory() > orc_size; +} + +/// Whether a ClickHouse type can serve as the per-branch type hint for an ORC union branch of the +/// given ORC type. The correspondence is structural (up to Nullable and LowCardinality wrappers), +/// extended with the explicit-schema conversions the reader supports: the integer targets the +/// ordinary column path accepts through the final cast (the unsigned and Enum types of the +/// matching width - they are what the ORC writer maps to these ORC types - int -> IPv4, and the +/// widenings of `orcIntegerBranchWidensTo`, e.g. `Variant(Int64, String)` over +/// `uniontype`) and +/// the special binary readers (binary -> IPv6/Int128/UInt128/Int256/UInt256/Decimal256, +/// char -> big integers and Decimal256). Custom type names matter here: `Bool` is a custom-named +/// `UInt8`, but the writer maps it to BOOLEAN while a plain `UInt8` goes to BYTE, so only BOOLEAN +/// accepts `Bool` - otherwise `Variant(Bool, UInt8)` over `uniontype` would leave +/// both branches ambiguous. The two ORC timestamp kinds need the same care: both read back as plain +/// `DateTime64(9)`, but `TIMESTAMP` is inferred as `DateTime64(9)` and `TIMESTAMP_INSTANT` as +/// `DateTime64(9, 'UTC')`, so `TIMESTAMP_INSTANT` matches only an explicitly time-zoned target while +/// `TIMESTAMP` stays permissive - otherwise `uniontype`, +/// inferred as `Variant(DateTime64(9), DateTime64(9, 'UTC'))`, would leave both branches ambiguous, +/// collapse them to identical `DateTime64(9)`, and be rejected by the duplicate-branch check. Any +/// explicit timezone is accepted (not only `UTC`) so that an explicit schema like +/// `Variant(DateTime64(9), DateTime64(9, 'Europe/Berlin'))` is not rejected; the singles-elimination +/// step decides whether the assignment is forced, and the repair cast relabels the branch to the +/// target timezone (value-preserving for `DateTime64`). Variant sorts its nested types, so the +/// positional correspondence between ORC union branches and Variant alternatives is lost; this +/// predicate is used to reconstruct it. +/// +/// STRUCT branches follow the same named-tuple rules as the non-union ORC struct path: a target +/// tuple with explicit names matches by field name and may project and reorder the ORC struct's +/// fields (the per-branch repair cast then projects/reorders the read tuple to exactly the target), +/// while an unnamed target tuple is matched positionally with the same arity. `case_insensitive` +/// mirrors `input_format_orc_case_insensitive_column_matching` for that name-based matching. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive) +{ + checkStackSize(); + + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + /// A boolean holds only 0 and 1, so every integer type is a widening of it. + return which.isUInt8() || which.isEnum8() || orcIntegerBranchWidensTo(type, 0); + case ORC::TypeKind::BYTE: + return which.isInt8() || (which.isUInt8() && !isBool(type)) || which.isEnum8() || orcIntegerBranchWidensTo(type, 1); + case ORC::TypeKind::SHORT: + return which.isInt16() || which.isUInt16() || which.isEnum16() || orcIntegerBranchWidensTo(type, 2); + case ORC::TypeKind::INT: + return which.isInt32() || which.isUInt32() || which.isIPv4() || orcIntegerBranchWidensTo(type, 4); + case ORC::TypeKind::LONG: + return which.isInt64() || which.isUInt64() || orcIntegerBranchWidensTo(type, 8); + case ORC::TypeKind::FLOAT: + return which.isFloat32() || which.isFloat64(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::DATE: + return which.isDate32() || which.isDate(); + case ORC::TypeKind::TIMESTAMP: + /// Permissive: matches any DateTime/DateTime64 alternative. The repair cast relabels the + /// branch to the alternative's timezone, which is value-preserving for DateTime64. + return which.isDateTime64() || which.isDateTime(); + case ORC::TypeKind::TIMESTAMP_INSTANT: + /// Matches only an explicitly time-zoned target so it stays distinct from a TIMESTAMP + /// branch in the same union (both read back as DateTime64(9)); see the comment above the + /// function. + return (which.isDateTime64() || which.isDateTime()) && orcTimestampTargetHasExplicitTimeZone(type); + case ORC::TypeKind::DECIMAL: + return which.isDecimal(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isStringOrFixedString(); + case ORC::TypeKind::BINARY: + return which.isStringOrFixedString() || which.isIPv6() || which.isInt128() || which.isUInt128() || which.isInt256() + || which.isUInt256() || which.isDecimal256(); + case ORC::TypeKind::CHAR: + return which.isStringOrFixedString() || which.isInt128() || which.isUInt128() || which.isInt256() || which.isUInt256() + || which.isDecimal256(); + case ORC::TypeKind::LIST: + return which.isArray() && orc_branch_type->getSubtypeCount() == 1 + && orcUnionBranchMatchesType( + orc_branch_type->getSubtype(0), assert_cast(*type).getNestedType(), case_insensitive); + case ORC::TypeKind::MAP: + { + if (!which.isMap() || orc_branch_type->getSubtypeCount() != 2) + return false; + const auto & map_type = assert_cast(*type); + return orcUnionBranchMatchesType(orc_branch_type->getSubtype(0), map_type.getKeyType(), case_insensitive) + && orcUnionBranchMatchesType(orc_branch_type->getSubtype(1), map_type.getValueType(), case_insensitive); + } + case ORC::TypeKind::STRUCT: + { + if (!which.isTuple()) + return false; + const auto & tuple_type = assert_cast(*type); + const auto & elements = tuple_type.getElements(); + if (tuple_type.hasExplicitNames()) + { + /// Match by field name, like the non-union ORC struct path: the target tuple may be + /// a subset of the ORC struct's fields, in any order. Each target field must map to + /// an ORC field with a recursively matching type; extra ORC fields are projected out + /// by the repair cast. Build a name -> ORC subtype map for the lookup. + std::unordered_map orc_field_by_name; + orc_field_by_name.reserve(orc_branch_type->getSubtypeCount()); + for (size_t i = 0; i < orc_branch_type->getSubtypeCount(); ++i) + { + String field_name = orc_branch_type->getFieldName(i); + if (case_insensitive) + boost::to_lower(field_name); + orc_field_by_name.emplace(std::move(field_name), orc_branch_type->getSubtype(i)); + } + + const auto & element_names = tuple_type.getElementNames(); + for (size_t i = 0; i < elements.size(); ++i) + { + String element_name = element_names[i]; + if (case_insensitive) + boost::to_lower(element_name); + auto it = orc_field_by_name.find(element_name); + if (it == orc_field_by_name.end() || !orcUnionBranchMatchesType(it->second, elements[i], case_insensitive)) + return false; + } + return true; + } + + /// Unnamed tuple: positional, same arity (no ORC field is silently dropped). + if (elements.size() != orc_branch_type->getSubtypeCount()) + return false; + for (size_t i = 0; i < elements.size(); ++i) + if (!orcUnionBranchMatchesType(orc_branch_type->getSubtype(i), elements[i], case_insensitive)) + return false; + return true; + } + case ORC::TypeKind::UNION: + return which.isVariant(); + case ORC::TypeKind::GEOMETRY: + case ORC::TypeKind::GEOGRAPHY: + /// Added in ORC 2.3. We do not read these, so no target type can match such a branch. + return false; + } + + return false; +} + +/// The natural inference pairing of the string-like ORC kinds, used to tie-break their union-branch +/// matching: CHAR is inferred as FixedString of the same length and STRING/VARCHAR as String, but +/// all of them can be *read* as either (see orcUnionBranchMatchesType), so e.g. +/// uniontype with the inferred Variant(FixedString(1), String) leaves both branches +/// with two candidates. Without a hint each branch would materialize per the current stripe's +/// physical encoding (a dictionary-encoded stripe comes back as LowCardinality), making a supported +/// schema fail depending on per-stripe encoding choices; preferring the natural pairing keeps the +/// assignment stable. The target is inspected with the LowCardinality/Nullable wrappers stripped, +/// so a LowCardinality-wrapped alternative (inferred from a dictionary-encoded stripe) pairs the +/// same way. BINARY deliberately has no preference: it is the conversion-rich kind (IPv6, big +/// integers, Decimal256), so a preference could steal a String alternative from a STRING branch. +/// +/// The numeric kinds are tie-broken the same way, for the same reason: they match their widenings +/// too (see `orcIntegerBranchWidensTo`), so e.g. `uniontype` with the explicit +/// schema `Variant(Int8, Int64)` leaves the `BYTE` branch with two candidates. Preferring the +/// natural pairing keeps the exact-width alternative with its own branch and lets the wider +/// alternative go to the branch that needs it. +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type) +{ + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + return isBool(type); + case ORC::TypeKind::BYTE: + return which.isInt8(); + case ORC::TypeKind::SHORT: + return which.isInt16(); + case ORC::TypeKind::INT: + return which.isInt32(); + case ORC::TypeKind::LONG: + return which.isInt64(); + case ORC::TypeKind::FLOAT: + return which.isFloat32(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::CHAR: + return which.isFixedString() + && assert_cast(*type).getN() == orc_branch_type->getMaximumLength(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isString(); + default: + return false; + } +} + +/// Variant sorts its nested types, so the positional correspondence between ORC union branches +/// and the alternatives of an explicit (or inferred) Variant type hint is lost. Reconstruct it +/// structurally: collect the alternatives each branch can be read as (orcUnionBranchMatchesType), +/// then keep only the forced assignments (a branch takes an alternative when it is its only +/// remaining candidate), tie-breaking the string-like branches by their natural inference pairing +/// (orcUnionBranchPrefersType). A branch whose correspondence stays ambiguous is left without a +/// hint (nullptr in the result), so no guess is ever made. Shared between +/// readColumnFromORCColumn (drives the branch conversions) and updateIncludeTypeIds (prunes a +/// hinted STRUCT branch's fields the same way the read path does), so the two stay in sync. +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching) +{ + const size_t num_children = orc_type->getSubtypeCount(); + DataTypes branch_hints(num_children); + const auto * variant_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; + if (!variant_hint) + return branch_hints; + + const auto & alternatives = variant_hint->getVariants(); + std::vector> candidates(num_children); + for (size_t i = 0; i < num_children; ++i) + for (size_t a = 0; a < alternatives.size(); ++a) + if (orcUnionBranchMatchesType(orc_type->getSubtype(i), alternatives[a], case_insensitive_matching)) + candidates[i].push_back(a); + + std::vector alternative_taken(alternatives.size(), false); + const auto preferred_candidates = [&](size_t i) + { + std::vector preferred; + for (const size_t a : candidates[i]) + if (orcUnionBranchPrefersType(orc_type->getSubtype(i), alternatives[a])) + preferred.push_back(a); + return preferred; + }; + bool changed = true; + while (changed) + { + changed = false; + for (size_t i = 0; i < num_children; ++i) + { + if (branch_hints[i] || candidates[i].size() != 1) + continue; + const size_t a = candidates[i].front(); + if (alternative_taken[a]) + { + /// Another branch already took this alternative; leave this branch without a hint. + candidates[i].clear(); + continue; + } + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + + if (changed) + continue; + + /// The forced assignments are exhausted. Tie-break the string-like branches by their + /// natural inference pairing (see orcUnionBranchPrefersType): a branch takes the single + /// alternative it prefers among its remaining candidates, unless another unassigned + /// branch uniquely prefers the same one - a contested preference is still ambiguous and no + /// guess is ever made. One assignment at a time, then back to the forced-assignment loop + /// to propagate it. + for (size_t i = 0; i < num_children && !changed; ++i) + { + if (branch_hints[i] || candidates[i].size() < 2) + continue; + const auto preferred = preferred_candidates(i); + if (preferred.size() != 1) + continue; + const size_t a = preferred.front(); + bool contested = false; + for (size_t j = 0; j < num_children && !contested; ++j) + { + if (j == i || branch_hints[j]) + continue; + const auto preferred_j = preferred_candidates(j); + contested = preferred_j.size() == 1 && preferred_j.front() == a; + } + if (contested) + continue; + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + } + + return branch_hints; +} + +/// Strips Nullable from a Nullable(Tuple) and propagates the struct null map into its elements. +static ColumnWithTypeAndName unwrapORCNullableTuple(const ColumnWithTypeAndName & column) +{ + const auto * type_nullable = typeid_cast(column.type.get()); + if (!type_nullable) + return column; + + const auto * tuple_type = typeid_cast(type_nullable->getNestedType().get()); + if (!tuple_type) + return column; + + const auto & col_nullable = assert_cast(*column.column); + + const auto & null_map_data = col_nullable.getNullMapData(); + bool has_nulls = !memoryIsZero(null_map_data.data(), 0, null_map_data.size()); + + if (!has_nulls) + { + /// No actual nulls — just strip the Nullable wrapper. + return {col_nullable.getNestedColumnPtr(), type_nullable->getNestedType(), column.name}; + } + + /// Propagate the struct null map to each Tuple element. + const auto & inner_tuple = assert_cast(col_nullable.getNestedColumn()); + const auto & null_map_ptr = col_nullable.getNullMapColumnPtr(); + Columns new_elements; + DataTypes new_types; + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + auto elem_col = inner_tuple.getColumnPtr(i); + auto elem_type = tuple_type->getElement(i); + if (elem_type->isNullable()) + { + /// Element already Nullable — merge null maps (struct null OR element null). + const auto & existing = assert_cast(*elem_col); + auto merged = ColumnUInt8::create(null_map_ptr->size()); + const auto & s = assert_cast(*null_map_ptr).getData(); + const auto & e = existing.getNullMapData(); + auto & m = merged->getData(); + for (size_t j = 0; j < s.size(); ++j) + m[j] = s[j] | e[j]; + new_elements.push_back(ColumnNullable::create(existing.getNestedColumnPtr(), std::move(merged))); + new_types.push_back(elem_type); + } + else if (elem_type->canBeInsideNullable()) + { + new_elements.push_back(ColumnNullable::create(elem_col, null_map_ptr)); + new_types.push_back(std::make_shared(elem_type)); + } + else + { + /// Array, Map, etc. — replace values at null positions with type defaults. + const auto & nm = col_nullable.getNullMapData(); + auto mutable_col = elem_col->cloneEmpty(); + for (size_t j = 0; j < elem_col->size(); ++j) + { + if (nm[j]) + mutable_col->insertDefault(); + else + mutable_col->insertFrom(*elem_col, j); + } + new_elements.push_back(std::move(mutable_col)); + new_types.push_back(elem_type); + } + } + + auto result_type = tuple_type->hasExplicitNames() ? std::make_shared(std::move(new_types), tuple_type->getElementNames()) + : std::make_shared(std::move(new_types)); + return {ColumnTuple::create(std::move(new_elements)), result_type, column.name}; +} + +/// Matches the elements of the tuples in `column` to those of the named tuples in `requested_type` by name, through +/// Nullable, Array and Map: a requested element that was not read is filled with defaults, and an element that is +/// not requested is dropped. A CAST would match tuples with no common element names by position instead. +static ColumnWithTypeAndName +matchORCTupleElementsByName(const ColumnWithTypeAndName & column, const DataTypePtr & requested_type, bool case_insensitive) +{ + if (column.type->equals(*requested_type)) + return column; + + if (const auto * nullable_type = typeid_cast(column.type.get())) + { + const auto & nullable_column = assert_cast(*column.column); + auto nested = matchORCTupleElementsByName( + {nullable_column.getNestedColumnPtr(), nullable_type->getNestedType(), column.name}, + removeNullable(requested_type), + case_insensitive); + return { + ColumnNullable::create(nested.column, nullable_column.getNullMapColumnPtr()), + std::make_shared(nested.type), + column.name}; + } + + const auto requested_non_nullable_type = removeNullable(requested_type); + + if (const auto * array_type = typeid_cast(column.type.get())) + { + const auto * requested_array_type = typeid_cast(requested_non_nullable_type.get()); + if (!requested_array_type) + return column; + const auto & array_column = assert_cast(*column.column); + auto nested = matchORCTupleElementsByName( + {array_column.getDataPtr(), array_type->getNestedType(), column.name}, requested_array_type->getNestedType(), case_insensitive); + return { + ColumnArray::create(nested.column, array_column.getOffsetsPtr()), std::make_shared(nested.type), column.name}; + } + + if (const auto * map_type = typeid_cast(column.type.get())) + { + const auto * requested_map_type = typeid_cast(requested_non_nullable_type.get()); + if (!requested_map_type) + return column; + const auto & map_column = assert_cast(*column.column); + auto keys = matchORCTupleElementsByName( + {map_column.getNestedData().getColumnPtr(0), map_type->getKeyType(), "key"}, requested_map_type->getKeyType(), case_insensitive); + auto values = matchORCTupleElementsByName( + {map_column.getNestedData().getColumnPtr(1), map_type->getValueType(), "value"}, + requested_map_type->getValueType(), + case_insensitive); + return { + ColumnMap::create(keys.column, values.column, map_column.getNestedColumn().getOffsetsPtr()), + std::make_shared(keys.type, values.type), + column.name}; + } + + const auto * tuple_type = typeid_cast(column.type.get()); + const auto * requested_tuple_type = typeid_cast(requested_non_nullable_type.get()); + if (!tuple_type || !requested_tuple_type) + return column; + + const auto & tuple_column = assert_cast(*column.column); + const size_t num_rows = tuple_column.size(); + Columns elements; + DataTypes types; + Strings names; + + /// An unnamed tuple is matched by position and keeps its elements, so the CAST rejects a different number of them. + if (!requested_tuple_type->hasExplicitNames()) + { + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + ColumnWithTypeAndName element{tuple_column.getColumnPtr(i), tuple_type->getElement(i), tuple_type->getNameByPosition(i + 1)}; + if (i < requested_tuple_type->getElements().size()) + element = matchORCTupleElementsByName(element, requested_tuple_type->getElement(i), case_insensitive); + elements.push_back(std::move(element.column)); + types.push_back(std::move(element.type)); + } + auto result_column = elements.empty() ? ColumnTuple::create(num_rows) : ColumnTuple::create(std::move(elements)); + return {std::move(result_column), std::make_shared(std::move(types)), column.name}; + } + + for (size_t i = 0; i < requested_tuple_type->getElements().size(); ++i) + { + const auto & requested_element_type = requested_tuple_type->getElement(i); + const auto & name = requested_tuple_type->getNameByPosition(i + 1); + + auto pos = tuple_type->tryGetPositionByName(name, /*case_insensitive=*/false); + if (!pos && case_insensitive) + pos = tuple_type->tryGetPositionByName(name, /*case_insensitive=*/true); + + if (pos) + { + auto element = matchORCTupleElementsByName( + {tuple_column.getColumnPtr(*pos), tuple_type->getElement(*pos), name}, requested_element_type, case_insensitive); + elements.push_back(std::move(element.column)); + types.push_back(std::move(element.type)); + } + else + { + auto element = requested_element_type->createColumn(); + requested_element_type->insertManyDefaultsInto(*element, num_rows); + elements.push_back(std::move(element)); + types.push_back(requested_element_type); + } + names.push_back(name); + } + + auto result_type = std::make_shared(std::move(types), std::move(names)); + auto result_column = elements.empty() ? ColumnTuple::create(num_rows) : ColumnTuple::create(std::move(elements)); + return {std::move(result_column), std::move(result_type), column.name}; +} + ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint) const @@ -1793,8 +2684,8 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( bool skipped = false; - if (!inside_nullable && (orc_column->hasNulls || (type_hint && type_hint->isNullable())) && !orc_column->isEncoded - && (orc_type->getKind() != orc::LIST && orc_type->getKind() != orc::MAP && orc_type->getKind() != orc::STRUCT)) + if (!inside_nullable && (orc_column->hasNulls || (type_hint && isNullableOrLowCardinalityNullable(type_hint))) && !orc_column->isEncoded + && (orc_type->getKind() != ORC::LIST && orc_type->getKind() != ORC::MAP && orc_type->getKind() != ORC::UNION)) { DataTypePtr nested_type_hint; if (type_hint) @@ -1808,11 +2699,209 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( return {nullable_column, nullable_type, column_name}; } + /// ORC union maps to the ClickHouse Variant type. Handled before the switch below so the switch + /// stays non-exhaustive (its default handles unsupported types). + if (orc_type->getKind() == ORC::UNION) + { + const auto * orc_union_column = dynamic_cast(orc_column); + if (!orc_union_column) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC column for union type must be a UnionVectorBatch"); + + const size_t num_children = orc_type->getSubtypeCount(); + const size_t num_rows = orc_union_column->numElements; + + /// Mirror of the schema-inference guard: a union with more branches than Variant can hold + /// (ColumnVariant::MAX_NESTED_COLUMNS) is rejected explicitly instead of letting the + /// DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an explicit + /// structure, since schema inference already rejects oversized unions. + if (num_children > ColumnVariant::MAX_NESTED_COLUMNS) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported (Variant supports at most {} nested types), while reading column {}", + num_children, ColumnVariant::MAX_NESTED_COLUMNS, column_name); + + /// The hints enable the explicit-schema conversions the scalar readers support (e.g. + /// binary -> IPv6) and keep the branch types aligned with the hinted Variant (e.g. + /// Array(Nullable(...)) produced by schema inference). See computeOrcUnionBranchHints for + /// how a branch's forced alternative is reconstructed; updateIncludeTypeIds calls the same + /// function so a hinted STRUCT branch's field pruning matches what is actually read here. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, type_hint, case_insensitive_matching); + + /// Read each ORC union branch into its own column. ORC keeps a separate physical batch per + /// branch. Variant branches are non-nullable, and an ORC union row can be non-null yet + /// select a branch whose payload is null - such a row is represented by the Variant NULL + /// discriminator (see the row loop below). The branch null map is taken directly from the + /// ORC batch rather than from a Nullable result column: complex (LIST/MAP) and + /// dictionary-encoded branches never come back as ColumnNullable, yet their payload can + /// still be null. inside_nullable is set because nulls are handled here rather than by + /// wrapping the branch value in Nullable. + DataTypes branch_types; + Columns branch_columns; + std::vector branch_null_map_columns(num_children); /// keeps the null maps alive + std::vector branch_null_maps(num_children, nullptr); + branch_types.reserve(num_children); + branch_columns.reserve(num_children); + for (size_t i = 0; i < num_children; ++i) + { + /// A union branch that is itself a union would map to a nested Variant, which Variant + /// forbids; reject it explicitly (matching the schema-inference path) instead of letting + /// the DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an + /// explicit structure, since schema inference already rejects nested unions. + if (orc_type->getSubtype(i)->getKind() == ORC::UNION) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto branch = readColumnFromORCColumn( + orc_union_column->children[i], orc_type->getSubtype(i), column_name, /*inside_nullable=*/true, branch_hints[i]); + + if (orc_union_column->children[i]->hasNulls) + { + branch_null_map_columns[i] = readByteMapFromORCColumn(orc_union_column->children[i]); + branch_null_maps[i] = &assert_cast(*branch_null_map_columns[i]).getData(); + } + + /// A dictionary-encoded branch read without a hint comes back as + /// LowCardinality(Nullable(...)); Variant alternatives cannot be nullable, so strip the + /// inner Nullable (the nulls are tracked by the branch null map above). + ColumnWithTypeAndName branch_non_nullable{ + removeNullableOrLowCardinalityNullable(branch.column), + removeNullableOrLowCardinalityNullable(branch.type), + branch.name}; + + /// With a per-branch hint the branch must end up as exactly that alternative, so that + /// the resulting Variant type equals the hinted one (e.g. a branch of a + /// non-dictionary-encoded file read for a LowCardinality(String) alternative comes + /// back as plain String). Compared by name, not equals: Variant identity is name-based + /// and e.g. equals cannot tell the custom-named Bool from a plain UInt8, which would + /// skip the Bool -> UInt8 repair cast for a boolean branch hinted as UInt8. + if (branch_hints[i] && branch_hints[i]->getName() != branch_non_nullable.type->getName()) + { + if (branch_null_map_columns[i]) + { + /// A value-checking cast (e.g. Int8 -> Enum8, or the same on a nested Tuple + /// field) must not inspect the placeholder values ORC leaves at null-payload + /// positions - those rows become the Variant NULL discriminator below and are + /// never read. Replace them with a valid, castable row before casting. + /// Wrapping the branch in Nullable is not enough: a Nullable(Tuple) cast would + /// still descend into and reject a null nested field. + if (auto safe = replaceNullPayloadRowsWithValidRow(branch_non_nullable.column, *branch_null_maps[i])) + branch_non_nullable.column + = castColumn({safe, branch_non_nullable.type, branch_non_nullable.name}, branch_hints[i]); + else + /// Every row is a null payload and none is read, so a default-valued column + /// of the target type with the same number of rows is enough. + branch_non_nullable.column + = branch_hints[i]->createColumn()->cloneResized(branch_non_nullable.column->size()); + } + else + { + branch_non_nullable.column = castColumn(branch_non_nullable, branch_hints[i]); + } + branch_non_nullable.type = branch_hints[i]; + } + + branch_types.push_back(branch_non_nullable.type); + branch_columns.push_back(std::move(branch_non_nullable.column)); + } + + /// ORC keeps one physical stream per branch, so branches with identical types cannot be + /// represented as a Variant (which de-duplicates types); reject them explicitly. The + /// identity is compared with LowCardinality stripped, so it does not depend on the current + /// stripe's physical encoding (a dictionary-encoded branch materializes as LowCardinality), + /// mirroring the schema-inference check in parseORCType. + std::unordered_set seen_type_names; + for (const auto & branch_type : branch_types) + if (!seen_type_names.insert(recursiveRemoveLowCardinality(branch_type)->getName()).second) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto variant_type = std::make_shared(branch_types); + const auto & global_variants = assert_cast(*variant_type).getVariants(); + + /// Variant stores its branches sorted by type name, so remap ORC tags to global (sorted) + /// discriminators. The Variant sub-columns are built compactly (each must contain exactly + /// the values referenced by its discriminator, in appended order), so they are cloned empty + /// from the ORC branch columns and filled row by row below rather than placed wholesale. + std::unordered_map type_name_to_global; + for (size_t g = 0; g < global_variants.size(); ++g) + type_name_to_global[global_variants[g]->getName()] = static_cast(g); + + MutableColumns variant_columns(global_variants.size()); + std::vector tag_to_global(num_children); + for (size_t i = 0; i < num_children; ++i) + { + auto global = type_name_to_global.at(branch_types[i]->getName()); + tag_to_global[i] = global; + variant_columns[global] = branch_columns[i]->cloneEmpty(); + } + + auto local_discriminators = ColumnVariant::ColumnDiscriminators::create(); + auto & discriminators_data = local_discriminators->getData(); + discriminators_data.resize_exact(num_rows); + + auto offsets = ColumnVariant::ColumnOffsets::create(); + auto & offsets_data = offsets->getData(); + offsets_data.resize_exact(num_rows); + + const UInt8 * tags = orc_union_column->tags.data(); + const uint64_t * orc_offsets = orc_union_column->offsets.data(); + const char * not_null = orc_union_column->hasNulls ? orc_union_column->notNull.data() : nullptr; + + for (size_t row = 0; row < num_rows; ++row) + { + if (not_null && !not_null[row]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const size_t tag = tags[row]; + if (tag >= num_children) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union tag {} for union with {} branches while reading column {}", + tag, num_children, column_name); + + const size_t offset = orc_offsets[row]; + /// A malformed file can point past the selected branch's values; reject it rather than + /// reading out of bounds (the branch column and its null map share this size). + if (offset >= branch_columns[tag]->size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union offset {} into branch {} of size {} while reading column {}", + offset, tag, branch_columns[tag]->size(), column_name); + + /// A non-null union row can still select a branch whose payload is null (ORC keeps the + /// union-level null count at 0 in that case). Variant branches are non-nullable, so + /// represent such a row as a Variant NULL rather than the branch's nested default value. + if (branch_null_maps[tag] && (*branch_null_maps[tag])[offset]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const auto global = tag_to_global[tag]; + auto & variant_column = *variant_columns[global]; + discriminators_data[row] = global; + offsets_data[row] = variant_column.size(); + variant_column.insertFrom(*branch_columns[tag], offset); + } + + auto variant_column = ColumnVariant::create(std::move(local_discriminators), std::move(offsets), std::move(variant_columns)); + return {std::move(variant_column), variant_type, column_name}; + } + switch (orc_type->getKind()) { - case orc::STRING: - case orc::BINARY: - case orc::VARCHAR: + case ORC::STRING: + case ORC::BINARY: + case ORC::VARCHAR: { if (type_hint) { @@ -1844,7 +2933,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithStringData(orc_column, column_name); } - case orc::CHAR: + case ORC::CHAR: { if (type_hint) { @@ -1870,32 +2959,32 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithFixedStringData(orc_column, orc_type, column_name); } - case orc::BOOLEAN: + case ORC::BOOLEAN: return readColumnWithBooleanData(orc_column, column_name); - case orc::BYTE: - return readColumnWithNumericData(orc_column, column_name); - case orc::SHORT: - return readColumnWithNumericData(orc_column, column_name); - case orc::INT: + case ORC::BYTE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::SHORT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::INT: { /// ORC format doesn't have unsigned integers and we output IPv4 as Int32. /// We should allow to read it back from Int32. if (type_hint && isIPv4(type_hint)) return readIPv4ColumnWithInt32Data(orc_column, column_name); - return readColumnWithNumericData(orc_column, column_name); - } - case orc::LONG: - return readColumnWithNumericData(orc_column, column_name); - case orc::FLOAT: - return readColumnWithNumericData(orc_column, column_name); - case orc::DOUBLE: - return readColumnWithNumericData(orc_column, column_name); - case orc::DATE: - return readColumnWithDateData(orc_column, column_name, type_hint); - case orc::TIMESTAMP: [[fallthrough]]; - case orc::TIMESTAMP_INSTANT: - return readColumnWithTimestampData(orc_column, column_name); - case orc::DECIMAL: + return readColumnWithNumericData(orc_column, column_name); + } + case ORC::LONG: + return readColumnWithNumericData(orc_column, column_name); + case ORC::FLOAT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DOUBLE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DATE: + return readColumnWithDateData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::TIMESTAMP: [[fallthrough]]; + case ORC::TIMESTAMP_INSTANT: + return readColumnWithTimestampData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::DECIMAL: { auto interal_type = parseORCType(orc_type, false, false, nullptr, skipped); @@ -1904,15 +2993,15 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( precision = 38; if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); throw Exception( ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal precision {} in ORC type {} is out of bound", precision, orc_type->toString()); } - case orc::MAP: + case ORC::MAP: { DataTypePtr key_type_hint; DataTypePtr value_type_hint; @@ -1926,13 +3015,18 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } } - const auto * orc_map_column = dynamic_cast(orc_column); + const auto * orc_map_column = dynamic_cast(orc_column); const auto * orc_key_column = orc_map_column->keys.get(); const auto * orc_value_column = orc_map_column->elements.get(); const auto * orc_key_type = orc_type->getSubtype(0); const auto * orc_value_type = orc_type->getSubtype(1); auto key_column = readColumnFromORCColumn(orc_key_column, orc_key_type, "key", false, key_type_hint); + /// A map key cannot be Nullable. + if (!key_type_hint && !DataTypeMap::isValidKeyType(key_column.type)) + key_type_hint = removeNullableOrLowCardinalityNullable(key_column.type); + if (key_type_hint) + key_column = matchORCTupleElementsByName(key_column, key_type_hint, case_insensitive_matching); if (key_type_hint && !key_type_hint->equals(*key_column.type)) { /// Cast key column to target type, because it can happen @@ -1950,7 +3044,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( auto map_type = std::make_shared(key_column.type, value_column.type); return {map_column, map_type, column_name}; } - case orc::LIST: + case ORC::LIST: { DataTypePtr nested_type_hint; if (type_hint) @@ -1960,38 +3054,56 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( nested_type_hint = array_type_hint->getNestedType(); } - const auto * orc_list_column = dynamic_cast(orc_column); + const auto * orc_list_column = dynamic_cast(orc_column); const auto * orc_nested_column = getNestedORCColumn(orc_list_column); const auto * orc_nested_type = orc_type->getSubtype(0); auto nested_column = readColumnFromORCColumn(orc_nested_column, orc_nested_type, column_name, false, nested_type_hint); + /// A struct read only for its size has no elements, which `createNested` below rejects. Otherwise the elements + /// are matched after a subcolumn is extracted, as a hint for one can name a path, such as `x.v`. + const auto * read_tuple_type = typeid_cast(removeNullable(nested_column.type).get()); + if (type_hint && isNested(type_hint) && read_tuple_type && read_tuple_type->getElements().empty()) + nested_column = matchORCTupleElementsByName(nested_column, nested_type_hint, case_insensitive_matching); + auto offsets_column = readOffsetsFromORCListColumn(orc_list_column); - auto array_column = ColumnArray::create(nested_column.column, offsets_column); DataTypePtr array_type; - /// If type hint is Nested, we should return Nested type, - /// because we differentiate Nested and simple Array(Tuple) - if (type_hint && isNested(type_hint)) + ColumnPtr array_data_column = nested_column.column; + /// If type hint is Nested and the element is a named Tuple, return the Nested type + /// so that `Nested::flatten` can decompose it into separate arrays. + /// When the element is Nullable(Tuple(...)), unwrap it and propagate the struct null + /// map to each element via `unwrapNullableTuple`. + const auto * tuple_type = type_hint && isNested(type_hint) + ? typeid_cast(removeNullable(nested_column.type).get()) + : nullptr; + if (tuple_type) { - const auto & tuple_type = assert_cast(*nested_column.type); - array_type = createNested(tuple_type.getElements(), tuple_type.getElementNames()); + auto unwrapped = unwrapORCNullableTuple({array_data_column, nested_column.type, column_name}); + array_data_column = unwrapped.column; + const auto & result_tuple = assert_cast(*unwrapped.type); + array_type = createNested(result_tuple.getElements(), result_tuple.getElementNames()); } else { array_type = std::make_shared(nested_column.type); } + auto array_column = ColumnArray::create(array_data_column, offsets_column); return {array_column, array_type, column_name}; } - case orc::STRUCT: + case ORC::STRUCT: { Columns tuple_elements; DataTypes tuple_types; std::vector tuple_names; const auto * tuple_type_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; - const auto * orc_struct_column = dynamic_cast(orc_column); + const auto * orc_struct_column = dynamic_cast(orc_column); for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) { + /// Read only for the size and the null map of the struct, so its values are not converted. + if (count_only_fields.contains(orc_type->getSubtype(i)->getColumnId())) + continue; + auto field_name = orc_type->getFieldName(i); DataTypePtr nested_type_hint; @@ -1999,7 +3111,12 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( { if (tuple_type_hint->hasExplicitNames()) { - auto pos = tuple_type_hint->tryGetPositionByName(field_name, case_insensitive_matching); + /// An element spelled exactly like the field wins over one that only matches + /// case-folded, so two fields whose names differ only by case cannot both + /// claim the same element and leave the other one unread. + auto pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/false); + if (!pos && case_insensitive_matching) + pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/true); if (pos) { nested_type_hint = tuple_type_hint->getElement(*pos); @@ -2034,8 +3151,27 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } void ORCColumnToCHColumn::orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values) { + /// A file field spelled exactly like the request wins over one that only matches case-folded, + /// so two fields whose names differ only by case are not both answered by the same one. Among + /// fields that only match folded, the first in file order answers. + auto find_orc_column = [&](const String & name) + { + auto it = name_to_column_ptr.find(name); + if (it == name_to_column_ptr.end() && case_insensitive_matching) + { + for (const auto & field_name : orc_field_names) + if (boost::iequals(field_name, name)) + return name_to_column_ptr.find(field_name); + } + return it; + }; + Columns columns_list; columns_list.reserve(header.columns()); std::unordered_map>> nested_tables; @@ -2043,23 +3179,20 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( { const ColumnWithTypeAndName & header_column = header.getByPosition(column_i); - auto search_column_name = header_column.name; - if (case_insensitive_matching) - boost::to_lower(search_column_name); - ColumnWithTypeAndName column; - if (!name_to_column_ptr.contains(search_column_name)) + auto orc_column_it = find_orc_column(header_column.name); + if (orc_column_it == name_to_column_ptr.end()) { bool read_from_nested = false; /// Check if it's a column from nested table. String nested_table_name = Nested::extractTableName(header_column.name); - String search_nested_table_name = nested_table_name; - if (case_insensitive_matching) - boost::to_lower(search_nested_table_name); - if (name_to_column_ptr.contains(search_nested_table_name)) + auto orc_nested_column_it = find_orc_column(nested_table_name); + if (orc_nested_column_it != name_to_column_ptr.end()) { - if (!nested_tables.contains(search_nested_table_name)) + /// Keyed by the file's spelling, so requests that differ only by case share one. + const String & resolved_nested_table_name = orc_nested_column_it->first; + if (!nested_tables.contains(resolved_nested_table_name)) { NamesAndTypesList nested_columns; for (const auto & name_and_type : header.getNamesAndTypesList()) @@ -2069,15 +3202,17 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } auto nested_table_type = Nested::collect(nested_columns).front().type; - auto orc_column_with_type = name_to_column_ptr[search_nested_table_name]; + const auto & orc_column_with_type = orc_nested_column_it->second; ColumnsWithTypeAndName cols = {readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, nested_table_name, false, nested_table_type)}; BlockPtr block_ptr = std::make_shared(cols); auto column_extractor = std::make_shared(*block_ptr, case_insensitive_matching); - nested_tables[search_nested_table_name] = {block_ptr, column_extractor}; + nested_tables[resolved_nested_table_name] = {block_ptr, column_extractor}; } - auto nested_column = nested_tables[search_nested_table_name].second->extractColumn(search_column_name); + /// The requested spelling, not the file's one: the helper matches names + /// case-insensitively itself, and an exact element name outranks a folded match. + auto nested_column = nested_tables[resolved_nested_table_name].second->extractColumn(header_column.name); if (nested_column) { column = *nested_column; @@ -2103,11 +3238,12 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } else { - auto orc_column_with_type = name_to_column_ptr[search_column_name]; + const auto & orc_column_with_type = orc_column_it->second; column = readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, header_column.name, false, header_column.type); } + column = matchORCTupleElementsByName(column, header_column.type, case_insensitive_matching); if (null_as_default) insertNullAsDefaultIfNeeded(column, header_column, column_i, block_missing_values); @@ -2118,6 +3254,72 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( res.setColumns(columns_list, num_rows); } +void registerInputFormatORC(FormatFactory & factory); +void registerInputFormatORC(FormatFactory & factory) +{ + factory.registerRandomAccessInputFormat( + "ORC", + [](ReadBuffer & buf, + const Block & sample, + const FormatSettings & settings, + const ReadSettings & read_settings, + bool is_remote_fs, + FormatParserSharedResourcesPtr, + FormatFilterInfoPtr format_filter_info) + { + const bool has_file_size = isBufferWithFileSize(buf); + auto * seekable_in = dynamic_cast(&buf); + const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in + && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; + const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; + return std::make_shared( + buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); + }); + factory.markFormatSupportsSubsetOfColumns("ORC"); +} + +void registerORCSchemaReader(FormatFactory & factory); +void registerORCSchemaReader(FormatFactory & factory) +{ + factory.registerSchemaReader( + "ORC", + [](ReadBuffer & buf, const FormatSettings & settings) + { + return std::make_shared(buf, settings); + } + ); + + factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) + { + return fmt::format( + "schema_inference_make_columns_nullable={};schema_inference_allow_nullable_tuple_type={};" + "dictionary_as_low_cardinality={};skip_columns_with_unsupported_types={};max_parser_depth={}", + settings.schema_inference_make_columns_nullable, + settings.schema_inference_allow_nullable_tuple_type, + settings.orc.dictionary_as_low_cardinality, + settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + settings.max_parser_depth); + }); +} + +} + +#else + +namespace DB +{ + class FormatFactory; + + void registerInputFormatORC(FormatFactory &); + void registerORCSchemaReader(FormatFactory &); + + void registerInputFormatORC(FormatFactory &) + { + } + + void registerORCSchemaReader(FormatFactory &) + { + } } #endif diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h index c58c59889a8c..42cf3556c66e 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h @@ -6,13 +6,12 @@ #include #include -#include #include #include #include #include #include -#include +#include #include namespace DB @@ -20,21 +19,23 @@ namespace DB class KeyCondition; -class ORCInputStream : public orc::InputStream +class ORCInputStream : public ORC::InputStream { public: ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch); - uint64_t getLength() const override; - uint64_t getNaturalReadSize() const override; - void read(void * buf, uint64_t length, uint64_t offset) override; - std::future readAsync(void * buf, uint64_t length, uint64_t offset) override; + UInt64 getLength() const override; + void read(void * buf, UInt64 length, UInt64 offset) override; + std::future readAsync(void * buf, UInt64 length, UInt64 offset) override; const std::string & getName() const override { return name; } protected: SeekableReadBuffer & in; size_t file_size; - bool supports_read_at; + /// Use offset-based reads (ReadBuffer::readBigAt) instead of seek+read; needed for ORC tail. + bool use_offset_based_read; + /// Async wrapper only when caller enabled prefetch and the buffer supports read-at. + bool use_async_prefetch; ThreadPoolCallbackRunnerUnsafe async_runner; std::string name = "ORCInputStream"; @@ -50,22 +51,20 @@ class ORCInputStreamFromString : public ReadBufferFromOwnString, public ORCInput } }; -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled); // Reads the whole file into a memory buffer, owned by the returned RandomAccessFile. -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); -/// The memory pool to set on the options of every ORC reader and writer we create: unlike the -/// default one of the library, it is accounted for by the memory tracker and it throws on failure -/// instead of returning a null pointer that the library dereferences. -orc::MemoryPool & getORCMemoryPool(); +/// Creates an ORC file reader; throws INCORRECT_DATA if the root type of the file is not a struct. +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options); -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings); +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings); class ORCColumnToCHColumn; -class NativeORCBlockInputFormat : public IInputFormat +class NativeORCBlockInputFormat final : public IInputFormat { public: NativeORCBlockInputFormat( @@ -96,14 +95,14 @@ class NativeORCBlockInputFormat : public IInputFormat bool prepareStripeReader(); void prefetchStripes(); - std::unique_ptr file_reader; - std::unique_ptr stripe_reader; + std::unique_ptr file_reader; + std::unique_ptr stripe_reader; std::unique_ptr orc_column_to_ch_column; - std::shared_ptr sargs; + std::shared_ptr sargs; // indices of columns to read from ORC file - std::list include_indices; + std::vector include_indices; BlockMissingValues block_missing_values; size_t approx_bytes_read_for_chunk = 0; @@ -115,30 +114,36 @@ class NativeORCBlockInputFormat : public IInputFormat FormatFilterInfoPtr format_filter_info; std::vector selected_stripes; - size_t read_iterator; - size_t prefetch_iterator; + size_t read_iterator{}; + size_t prefetch_iterator{}; - std::unique_ptr current_stripe_info; + const ORC::Proto::StripeInformation * current_stripe_info = nullptr; std::atomic is_stopped{0}; }; -class NativeORCSchemaReader : public ISchemaReader +class NativeORCSchemaReader final : public ISchemaReader { public: NativeORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); NamesAndTypesList readSchema() override; + std::optional readNumberOrRows() override; private: + void initializeIfNeeded(); + const FormatSettings format_settings; + std::unique_ptr file_reader; + std::atomic is_stopped{0}; + bool initialized = false; }; class ORCColumnToCHColumn { public: - using ORCColumnPtr = const orc::ColumnVectorBatch *; - using ORCTypePtr = const orc::Type *; + using ORCColumnPtr = const ORC::ColumnVectorBatch *; + using ORCTypePtr = const ORC::Type *; using ORCColumnWithType = std::pair; using NameToColumnPtr = std::unordered_map; @@ -147,22 +152,28 @@ class ORCColumnToCHColumn bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_ = false, - bool dictionary_as_low_cardinality_ = false); + bool dictionary_as_low_cardinality_ = false, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_ = FormatSettings::DateTimeOverflowBehavior::Ignore, + std::unordered_set count_only_fields_ = {}); void orcTableToCHChunk( Chunk & res, - const orc::Type * schema, - const orc::ColumnVectorBatch * table, + const ORC::Type * schema, + const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); void orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values = nullptr); private: ColumnWithTypeAndName readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint = nullptr) const; @@ -173,6 +184,9 @@ class ORCColumnToCHColumn bool null_as_default; bool case_insensitive_matching; bool dictionary_as_low_cardinality; + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior; + /// ORC column ids of the struct fields that are read only for the size and the null map of their struct. + const std::unordered_set count_only_fields; }; } #endif diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.cpp b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp new file mode 100644 index 000000000000..f792e8d980ad --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp @@ -0,0 +1,1218 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +RleVersion getRleVersion(const Proto::ColumnEncoding & encoding) +{ + switch (encoding.kind) + { + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DICTIONARY: + return RleVersion::V1; + case Proto::ColumnEncodingKind::DIRECT_V2: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return RleVersion::V2; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding {}", static_cast(encoding.kind)); +} + +std::unique_ptr getRequiredStream(StripeStreams & stripe, UInt64 column_id, Proto::StreamKind kind, const char * stream_name, const char * column_kind) +{ + auto stream = stripe.getStream(column_id, kind); + if (!stream) + throw Exception(ErrorCodes::INCORRECT_DATA, "{} stream not found in ORC {} column {}", stream_name, column_kind, column_id); + return stream; +} + +/// Converts the bytes read into the beginning of a buffer of integers into the integers, in place. +/// BOOLEAN and BYTE: the values are decoded into the bytes of the column. +template +class ByteColumnReaderImpl final : public ColumnReader +{ +public: + ByteColumnReaderImpl(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", type.toString().c_str())) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle.skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle.next(reinterpret_cast(data.data()), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + } + +private: + Decoder rle; +}; + +using BooleanColumnReader = ByteColumnReaderImpl; +using ByteColumnReader = ByteColumnReaderImpl; + +/// SHORT, INT, LONG and DATE: the values are decoded into a column of the matching width. +template +class IntegerColumnReader final : public ColumnReader +{ +public: + IntegerColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "integer"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle->next(data.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + std::unique_ptr rle; +}; + +/// FLOAT and DOUBLE: the values are stored as is (little endian), so they are copied into the column. +template +class FloatingColumnReader final : public ColumnReader +{ +public: + FloatingColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , stream(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "floating point")) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + stream->skipBytes(num_values * sizeof(ItemType)); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & data = typeid_cast &>(batch).prepareColumn(num_values); + ItemType * out = data.data(); + + /// The stream has only the non-null values: read them at once to the beginning of the column. + size_t num_present = num_values; + if (not_null) + num_present = std::count_if(not_null, not_null + num_values, [](char c) { return c != 0; }); + + stream->readBytes(reinterpret_cast(out), num_present * sizeof(ItemType)); + if constexpr (std::endian::native == std::endian::big) + for (size_t i = 0; i < num_present; ++i) + out[i] = std::bit_cast(std::byteswap(std::bit_cast(out[i]))); + + if (!not_null) + return; + + /// Move the values to their rows from the back: the k-th value goes to a row i >= k, so it is not overwritten before it is moved. + size_t next_value = num_present; + for (size_t i = num_values; i-- > 0;) + out[i] = not_null[i] ? out[--next_value] : 0; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + stream->seek(positions.at(column_id)); + } + +private: + using Bits = std::conditional_t; + + std::unique_ptr stream; +}; + +/// Converts the lengths in `offsets` into the end offsets (as in `ColumnString` and `ColumnArray`), starting +/// from `total`, and returns the total length. The lengths of the null values are zeros. +UInt64 lengthsToEndOffsets(UInt64 * offsets, size_t num_values, UInt64 column_id, UInt64 total = 0) +{ + for (size_t i = 0; i < num_values; ++i) + { + /// The lengths are non-negative, a negative one is huge as unsigned. + if (offsets[i] > static_cast(std::numeric_limits::max()) || common::addOverflow(total, offsets[i], total) + || total > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid length {} in ORC column {}", static_cast(offsets[i]), column_id); + offsets[i] = total; + } + return total; +} + +/// Reads the strings with their lengths in a separate stream into a `ColumnString`. +ColumnString::MutablePtr readStrings( + IntRleDecoder & length_rle, InputByteStream & blob_stream, size_t num_values, const char * not_null, UInt64 column_id) +{ + /// The buffers grow as the data is decoded: a malformed count or length must not allocate memory + /// before the streams prove to contain the data. + static constexpr size_t MIN_STEP = 64 * 1024; + auto column = ColumnString::create(); + auto & offsets = column->getOffsets(); + UInt64 total = 0; + while (offsets.size() < num_values) + { + size_t done = offsets.size(); + size_t step = std::min(num_values - done, std::max(MIN_STEP, done)); + offsets.resize(done + step); + length_rle.next(offsets.data() + done, step, not_null ? not_null + done : nullptr); + total = lengthsToEndOffsets(offsets.data() + done, step, column_id, total); + } + auto & chars = column->getChars(); + while (chars.size() < total) + { + size_t done = chars.size(); + size_t step = std::min(total - done, std::max(MIN_STEP, done)); + chars.resize(done + step); + blob_stream.readBytes(reinterpret_cast(chars.data() + done), step); + } + return column; +} + +std::shared_ptr loadStringDictionary(UInt64 column_id, StripeStreams & stripe) +{ + const auto & encoding = stripe.getEncoding(column_id); + /// The dictionary is not bounded by the number of rows of the stripe: a column nested in a list or a map + /// can have more values than the stripe has rows. + UInt32 dictionary_size = encoding.dictionary_size; + + auto dictionary = std::make_shared(); + if (dictionary_size == 0) + { + dictionary->column = ColumnString::create(); + return dictionary; + } + + auto length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string dictionary"), false, getRleVersion(encoding)); + auto blob_stream = stripe.getStream(column_id, Proto::StreamKind::DICTIONARY_DATA); + if (!blob_stream) + { + /// All entries can be empty strings, then the stream is not needed. + blob_stream = std::make_unique(std::string_view{}, CompressionKind::NONE, 0, "empty dictionary"); + } + dictionary->column = readStrings(*length_rle, *blob_stream, dictionary_size, nullptr, column_id); + return dictionary; +} + +class StringDictionaryColumnReader final : public ColumnReader +{ +public: + StringDictionaryColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string dictionary"), + false, getRleVersion(stripe.getEncoding(column_id))); + dictionary = loadStringDictionary(column_id, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & string_batch = dynamic_cast(batch); + index.resize(num_values); + rle->next(index.data(), num_values, not_null); + string_batch.isEncoded = false; + string_batch.column = decodeDictionary(assert_cast(*dictionary->column), index.data(), not_null, num_values); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + readIndex(dynamic_cast(batch), num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + void readIndex(EncodedStringVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + batch.isEncoded = true; + batch.dictionary = dictionary; + batch.column = nullptr; + batch.index.resize(num_values); + rle->next(batch.index.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + std::shared_ptr dictionary; + std::unique_ptr rle; + PaddedPODArray index; +}; + +class StringDirectColumnReader final : public ColumnReader +{ +public: + StringDirectColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string"), + false, getRleVersion(stripe.getEncoding(column_id))); + blob_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string"); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + static constexpr size_t BUFFER_SIZE = 1024; + UInt64 buffer[BUFFER_SIZE]; + size_t done = 0; + size_t total_bytes = 0; + while (done < num_values) + { + size_t step = std::min(BUFFER_SIZE, num_values - done); + length_rle->next(buffer, step, nullptr); + total_bytes += lengthsToEndOffsets(buffer, step, column_id); + done += step; + } + blob_stream->skipBytes(total_bytes); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & string_batch = dynamic_cast(batch); + string_batch.isEncoded = false; + string_batch.column = readStrings(*length_rle, *blob_stream, num_values, batch.hasNulls ? batch.notNull.data() : nullptr, column_id); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + blob_stream->seek(provider); + length_rle->seek(provider); + } + +private: + std::unique_ptr length_rle; + std::unique_ptr blob_stream; +}; + +class TimestampColumnReader final : public ColumnReader +{ +public: + TimestampColumnReader(const Type & type, StripeStreams & stripe, bool is_instant) + : ColumnReader(type, stripe) + , writer_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getWriterTimezone()) + , reader_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getReaderTimezone()) + , same_timezone(&writer_timezone == &reader_timezone || writer_timezone.getTimeZone() == reader_timezone.getTimeZone()) + , writer_offset_of(writer_timezone) + , reader_offset_of(reader_timezone) + { + /// The base of the seconds is 2015-01-01 00:00:00 in the time zone of the writer. + static constexpr Int64 UTC_2015_01_01 = 1420070400; + epoch_offset = UTC_2015_01_01 - writer_timezone.timezoneOffset(UTC_2015_01_01); + + RleVersion version = getRleVersion(stripe.getEncoding(column_id)); + seconds_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "timestamp"), true, version); + nanos_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "timestamp"), false, version); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + seconds_rle->skip(num_values); + nanos_rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & timestamp_batch = typeid_cast(batch); + timestamp_batch.data.resize(num_values); + timestamp_batch.nanoseconds.resize(num_values); + Int64 * seconds = timestamp_batch.data.data(); + Int64 * nanos = timestamp_batch.nanoseconds.data(); + seconds_rle->next(seconds, num_values, not_null); + nanos_rle->next(nanos, num_values, not_null); + + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + + const Int64 encoded_nanos = nanos[i]; + /// The lowest 3 bits are the number of the trailing zeros (minus one) that are removed. + UInt64 zeros = nanos[i] & 0x7; + /// An arithmetic shift, as in the reference implementation: some writers (the Arrow + /// adapter) store negative nanoseconds for the timestamps before the epoch. + nanos[i] >>= 3; + if (zeros != 0 && common::mulOverflow(nanos[i], POWERS_OF_TEN_FOR_NANOS[zeros + 1], nanos[i])) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (nanos[i] < -999'999'999 || nanos[i] > 999'999'999) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + Int64 writer_time = 0; + if (common::addOverflow(seconds[i], epoch_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (writer_time < 0 && nanos[i] > 999999 && common::subOverflow(writer_time, Int64{1}, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + if (!same_timezone) + { + /// Keep the same wall clock time when the writer and the reader time zones differ. + Int64 writer_offset = writer_offset_of(writer_time); + Int64 reader_offset = reader_offset_of(writer_time); + if (writer_offset != reader_offset) + { + /// If the adjustment crosses a DST boundary, the offset has to be reevaluated. + Int64 adjusted_time = 0; + if (common::addOverflow(writer_time, writer_offset - reader_offset, adjusted_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + Int64 adjusted_reader_offset = reader_offset_of(adjusted_time); + if (common::addOverflow(writer_time, writer_offset - adjusted_reader_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + } + } + seconds[i] = writer_time; + } + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + seconds_rle->seek(provider); + nanos_rle->seek(provider); + } + +private: + static constexpr Int64 POWERS_OF_TEN_FOR_NANOS[9] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; + + [[noreturn]] void throwInvalidTimestamp(Int64 seconds, Int64 encoded_nanos) const + { + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid timestamp in ORC column {}: seconds={}, encoded nanoseconds={}", column_id, seconds, encoded_nanos); + } + + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + const bool same_timezone; + const TimezoneOffset writer_offset_of; + const TimezoneOffset reader_offset_of; + Int64 epoch_offset = 0; + std::unique_ptr seconds_rle; + std::unique_ptr nanos_rle; +}; + +constexpr UInt32 MAX_PRECISION_64 = 18; +constexpr UInt32 MAX_PRECISION_128 = 38; + +constexpr Int64 POWERS_OF_TEN[MAX_PRECISION_64 + 1] = { + 1LL, + 10LL, + 100LL, + 1000LL, + 10000LL, + 100000LL, + 1000000LL, + 10000000LL, + 100000000LL, + 1000000000LL, + 10000000000LL, + 100000000000LL, + 1000000000000LL, + 10000000000000LL, + 100000000000000LL, + 1000000000000000LL, + 10000000000000000LL, + 100000000000000000LL, + 1000000000000000000LL}; + +/// The DECIMAL columns: an unbounded signed varint per value in the DATA stream and the scale of +/// each value in the SECONDARY stream. The values are rescaled to the scale of the type. +class DecimalColumnReader : public ColumnReader +{ +public: + DecimalColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getPrecision() > MAX_PRECISION_128 || type.getScale() > MAX_PRECISION_128) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + value_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"); + scale_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "decimal"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + size_t skipped = 0; + while (skipped < num_values) + if (!(value_stream->readByte() & 0x80)) + ++skipped; + scale_decoder->skip(num_values); + return num_values; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + value_stream->seek(provider); + scale_decoder->seek(provider); + } + +protected: + /// Reads the zigzag-encoded varint of up to 128 bits. + Int128 readInt128() + { + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + if (shift < 128) + value |= static_cast(byte & 0x7F) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + return static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + } + + /// The scale of each value is read from the file. The valid scales are from 0 to 38, the bound + /// also keeps the differences of the scales and the rescaling work small. + Int32 getValueScale(Int64 value_scale) const + { + if (value_scale < -Int64(MAX_PRECISION_128) || value_scale > Int64(MAX_PRECISION_128)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", value_scale, column_id); + return static_cast(value_scale); + } + + static void scaleInt128(Int128 & value, Int32 target_scale, Int32 current_scale) + { + while (target_scale > current_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, target_scale - current_scale); + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[adjust])); + current_scale += adjust; + } + while (current_scale > target_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, current_scale - target_scale); + value /= POWERS_OF_TEN[adjust]; + current_scale -= adjust; + } + } + + const Int32 precision; + Int32 scale; + std::unique_ptr value_stream; + std::unique_ptr scale_decoder; + PaddedPODArray scales; +}; + +class Decimal64ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int64 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt64(getValueScale(scales[i])); + } + } + +private: + Int64 readInt64(Int32 current_scale) + { + UInt64 encoded = readVarint(*value_stream); + Int64 value = static_cast((encoded >> 1) ^ (~(encoded & 1) + 1)); + if (scale > current_scale && static_cast(scale - current_scale) <= MAX_PRECISION_64) + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[scale - current_scale])); + else if (scale < current_scale && static_cast(current_scale - scale) <= MAX_PRECISION_64) + value /= POWERS_OF_TEN[current_scale - scale]; + else if (scale != current_scale) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", current_scale, column_id); + return value; + } +}; + +class Decimal128ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt128(); + scaleInt128(values[i], scale, getValueScale(scales[i])); + } + } +}; + +/// The DECIMAL columns with the precision up to 18 in the files of the format version 1.9999 +/// (`UNSTABLE_PRE_2_0`): the unscaled values are signed RLEv2 integers in the DATA stream, +/// all with the scale of the type, and there is no SECONDARY stream. +class Decimal64V2ColumnReader final : public ColumnReader +{ +public: + Decimal64V2ColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getScale() > type.getPrecision()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + /// As in the reference implementation, RLEv2 is used regardless of the column encoding. + value_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"), true, RleVersion::V2); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + value_decoder->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & decimal_batch = typeid_cast(batch); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + value_decoder->next(decimal_batch.values.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + value_decoder->seek(positions.at(column_id)); + } + +private: + const Int32 precision; + const Int32 scale; + std::unique_ptr value_decoder; +}; + +/// The DECIMAL columns written by Hive 0.11, without the precision and the scale in the type. +/// As in the reference implementation, the values are read with the scale 6 and must have at most 38 digits. +class DecimalHive11ColumnReader final : public DecimalColumnReader +{ +public: + DecimalHive11ColumnReader(const Type & type, StripeStreams & stripe) + : DecimalColumnReader(type, stripe) + { + scale = 6; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + + static const Int128 max_value = Int128(10000000000000000000ULL) * Int128(10000000000000000000ULL) - 1; + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + bool overflow = false; + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + UInt32 bits = byte & 0x7F; + if (shift > 128 || (shift == 126 && bits > 3)) + overflow = true; + if (shift < 128) + value |= static_cast(bits) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + Int128 decoded = static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + if (!overflow) + { + scaleInt128(decoded, scale, getValueScale(scales[i])); + overflow = decoded > max_value || decoded < -max_value; + } + if (overflow) + throw Exception(ErrorCodes::INCORRECT_DATA, "Hive 0.11 decimal was more than 38 digits in ORC column {}", column_id); + values[i] = decoded; + } + } +}; + +class StructColumnReader final : public ColumnReader +{ +public: + StructColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + const auto & encoding = stripe.getEncoding(column_id); + if (encoding.kind != Proto::ColumnEncodingKind::DIRECT) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown encoding {} of ORC struct column {}", static_cast(encoding.kind), column_id); + const auto & selected = stripe.getSelectedColumns(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children.push_back(buildColumnReader(child, stripe)); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + for (auto & child : children) + child->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + for (auto & child : children) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & struct_batch = typeid_cast(batch); + for (size_t i = 0; i < children.size(); ++i) + { + if constexpr (encoded) + children[i]->nextEncoded(*struct_batch.fields[i], num_values, not_null); + else + children[i]->next(*struct_batch.fields[i], num_values, not_null); + } + } + + std::vector> children; +}; + +/// Reads the lengths of the lists or maps as the end offsets, returns the total number of the children. +UInt64 readListOffsets(IntRleDecoder & rle, ColumnPtr & result, size_t num_values, const char * not_null, UInt64 column_id) +{ + auto column = ColumnUInt64::create(num_values); + auto & offsets = column->getData(); + rle.next(offsets.data(), num_values, not_null); + UInt64 total = lengthsToEndOffsets(offsets.data(), num_values, column_id); + result = std::move(column); + return total; +} + +UInt64 sumLengths(IntRleDecoder & rle, size_t num_values, UInt64 column_id) +{ + static constexpr size_t BUFFER_SIZE = 1024; + Int64 buffer[BUFFER_SIZE]; + UInt64 total = 0; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + { + if (buffer[i] < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Negative length {} in ORC column {}", buffer[i], column_id); + total += static_cast(buffer[i]); + } + read += chunk; + } + return total; +} + +class ListColumnReader final : public ColumnReader +{ +public: + ListColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "list"), + false, getRleVersion(stripe.getEncoding(column_id))); + const Type & child_type = *type.getSubtype(0); + if (stripe.getSelectedColumns()[child_type.getColumnId()]) + child = buildColumnReader(child_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (child) + child->skip(sumLengths(*rle, num_values, column_id)); + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (child) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & list_batch = typeid_cast(batch); + const char * not_null = list_batch.hasNulls ? list_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, list_batch.offsets, num_values, not_null, column_id); + if (child) + { + if constexpr (encoded) + child->nextEncoded(*list_batch.elements, total, nullptr); + else + child->next(*list_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr child; +}; + +class MapColumnReader final : public ColumnReader +{ +public: + MapColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "map"), + false, getRleVersion(stripe.getEncoding(column_id))); + const auto & selected = stripe.getSelectedColumns(); + const Type & key_type = *type.getSubtype(0); + if (selected[key_type.getColumnId()]) + key_reader = buildColumnReader(key_type, stripe); + const Type & value_type = *type.getSubtype(1); + if (selected[value_type.getColumnId()]) + value_reader = buildColumnReader(value_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (key_reader || value_reader) + { + UInt64 total = sumLengths(*rle, num_values, column_id); + if (key_reader) + key_reader->skip(total); + if (value_reader) + value_reader->skip(total); + } + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (key_reader) + key_reader->seekToRowGroup(positions); + if (value_reader) + value_reader->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & map_batch = typeid_cast(batch); + const char * not_null = map_batch.hasNulls ? map_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, map_batch.offsets, num_values, not_null, column_id); + if (key_reader) + { + if constexpr (encoded) + key_reader->nextEncoded(*map_batch.keys, total, nullptr); + else + key_reader->next(*map_batch.keys, total, nullptr); + } + if (value_reader) + { + if constexpr (encoded) + value_reader->nextEncoded(*map_batch.elements, total, nullptr); + else + value_reader->next(*map_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr key_reader; + std::unique_ptr value_reader; +}; + +class UnionColumnReader final : public ColumnReader +{ +public: + UnionColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "union")) + , num_children(type.getSubtypeCount()) + { + children.resize(num_children); + counts.resize(num_children); + const auto & selected = stripe.getSelectedColumns(); + for (size_t i = 0; i < num_children; ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children[i] = buildColumnReader(child, stripe); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + std::fill(counts.begin(), counts.end(), 0); + static constexpr size_t BUFFER_SIZE = 1024; + char buffer[BUFFER_SIZE]; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + ++counts[checkedTag(static_cast(buffer[i]))]; + read += chunk; + } + for (size_t i = 0; i < num_children; ++i) + if (counts[i] && children[i]) + children[i]->skip(counts[i]); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + for (auto & child : children) + if (child) + child->seekToRowGroup(positions); + } + +private: + size_t checkedTag(UInt8 tag) const + { + if (tag >= num_children) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid union tag {} for union with {} children in ORC column {}", static_cast(tag), num_children, column_id); + return tag; + } + + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & union_batch = typeid_cast(batch); + const char * not_null = union_batch.hasNulls ? union_batch.notNull.data() : nullptr; + union_batch.tags.resize(num_values); + union_batch.offsets.resize(num_values); + UInt8 * tags = union_batch.tags.data(); + UInt64 * offsets = union_batch.offsets.data(); + memset(tags, 0, num_values); + rle.next(reinterpret_cast(tags), num_values, not_null); + std::fill(counts.begin(), counts.end(), 0); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + offsets[i] = counts[checkedTag(tags[i])]++; + } + for (size_t i = 0; i < num_children; ++i) + { + if (!children[i]) + continue; + if constexpr (encoded) + children[i]->nextEncoded(*union_batch.children[i], counts[i], nullptr); + else + children[i]->next(*union_batch.children[i], counts[i], nullptr); + } + } + + ByteRleDecoder rle; + const size_t num_children; + std::vector> children; + std::vector counts; +}; + +} + + +ColumnReader::ColumnReader(const Type & type, StripeStreams & stripe) + : column_id(type.getColumnId()) +{ + if (auto stream = stripe.getStream(column_id, Proto::StreamKind::PRESENT)) + not_null_decoder = std::make_unique(std::move(stream)); +} + +void ColumnReader::next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) +{ + batch.reset(num_values); + + if (not_null_decoder) + { + char * not_null = batch.notNull.data(); + not_null_decoder->next(not_null, num_values, incoming_mask); + batch.hasNulls = memchr(not_null, 0, num_values) != nullptr; + return; + } + if (incoming_mask) + { + batch.hasNulls = true; + memcpy(batch.notNull.data(), incoming_mask, num_values); + return; + } + batch.hasNulls = false; +} + +size_t ColumnReader::skip(size_t num_values) +{ + if (!not_null_decoder) + return num_values; + + static constexpr size_t BUFFER_SIZE = 32768; + char buffer[BUFFER_SIZE]; + size_t remaining = num_values; + while (remaining) + { + size_t chunk = std::min(remaining, BUFFER_SIZE); + not_null_decoder->next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + if (!buffer[i]) + --num_values; + remaining -= chunk; + } + return num_values; +} + +void ColumnReader::seekToRowGroup(std::unordered_map & positions) +{ + if (not_null_decoder) + { + auto it = positions.find(column_id); + if (it == positions.end()) + throw Exception(ErrorCodes::INCORRECT_DATA, "No row index for ORC column {}", column_id); + not_null_decoder->seek(it->second); + } +} + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, stripe); + case BYTE: + return std::make_unique(type, stripe); + case SHORT: + return std::make_unique>(type, stripe); + case INT: + return std::make_unique>(type, stripe); + case LONG: + case DATE: + return std::make_unique>(type, stripe); + case FLOAT: + return std::make_unique>(type, stripe); + case DOUBLE: + return std::make_unique>(type, stripe); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + switch (stripe.getEncoding(type.getColumnId()).kind) + { + case Proto::ColumnEncodingKind::DICTIONARY: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return std::make_unique(type, stripe); + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DIRECT_V2: + return std::make_unique(type, stripe); + } + break; + case TIMESTAMP: + return std::make_unique(type, stripe, false); + case TIMESTAMP_INSTANT: + return std::make_unique(type, stripe, true); + case DECIMAL: + if (type.getPrecision() == 0) + return std::make_unique(type, stripe); + if (type.getPrecision() <= MAX_PRECISION_64) + { + if (stripe.isDecimalAsLong()) + return std::make_unique(type, stripe); + return std::make_unique(type, stripe); + } + return std::make_unique(type, stripe); + case STRUCT: + return std::make_unique(type, stripe); + case LIST: + return std::make_unique(type, stripe); + case MAP: + return std::make_unique(type, stripe); + case UNION: + return std::make_unique(type, stripe); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Reading ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.h b/src/Processors/Formats/Impl/ORC/ColumnReader.h new file mode 100644 index 000000000000..1abaedb6fff5 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +/// Access to the streams of one stripe for the column readers. +class StripeStreams +{ +public: + virtual ~StripeStreams() = default; + + virtual const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const = 0; + /// Returns nullptr if the stripe does not have this stream. + virtual std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const = 0; + virtual const std::vector & getSelectedColumns() const = 0; + /// The time zones for TIMESTAMP (not TIMESTAMP_INSTANT) columns. + virtual const DateLUTImpl & getWriterTimezone() const = 0; + virtual const DateLUTImpl & getReaderTimezone() const = 0; + virtual UInt64 getNumberOfRows() const = 0; + /// Whether the file has the format version 1.9999 (`UNSTABLE_PRE_2_0` in the reference implementation), + /// where DECIMAL columns with the precision up to 18 are written as signed RLEv2 integers in the DATA stream + /// without the SECONDARY stream of scales. + virtual bool isDecimalAsLong() const = 0; +}; + +class ColumnReader +{ +public: + ColumnReader(const Type & type, StripeStreams & stripe); + virtual ~ColumnReader() = default; + + /// Reads the next `num_values` values into `batch`. `incoming_mask` is the mask of the + /// non-null values of the parent (or nullptr). + virtual void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask); + + /// Same, but the string columns with dictionary encoding fill `EncodedStringVectorBatch` + /// without decoding the dictionary. + virtual void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + next(batch, num_values, incoming_mask); + } + + /// Skips `num_values` values, returns the number of the skipped non-null values. + virtual size_t skip(size_t num_values); + + /// Moves to the beginning of a row group, by the positions from the row indexes of the columns. + virtual void seekToRowGroup(std::unordered_map & positions); + +protected: + const UInt64 column_id; + std::unique_ptr not_null_decoder; +}; + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe); + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.cpp b/src/Processors/Formats/Impl/ORC/Compression.cpp new file mode 100644 index 000000000000..cfacdc431ca8 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.cpp @@ -0,0 +1,437 @@ +#include + +#include + +#include +#include +#include +/// For `ZSTD_decompressBound`, which is not in the stable ABI of zstd. It is safe, as zstd is linked statically from contrib. +#define ZSTD_STATIC_LINKING_ONLY +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int CANNOT_COMPRESS; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +[[noreturn]] void throwMalformedLzo(size_t offset) +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed LZO-compressed data in ORC file at offset {}", offset); +} + +/// LZO1X decompressor, as written by the Hadoop codecs (and the ORC Java writer). A chunk can be a +/// concatenation of several LZO blocks, each terminated with the end-of-stream marker. +size_t decompressLzo(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + const UInt8 * input = reinterpret_cast(src); + const UInt8 * const input_begin = input; + const UInt8 * const input_end = input + src_size; + char * output = dst; + char * const output_end = dst + dst_capacity; + + auto offset = [&] { return static_cast(input - input_begin); }; + + auto read_byte = [&]() -> UInt32 + { + if (input >= input_end) + throwMalformedLzo(offset()); + return *input++; + }; + + /// A run of zero bytes extends a length by 255 each, then the next byte is added. + auto read_variable_length = [&](UInt32 base) -> size_t + { + size_t length = base; + UInt32 next = 0; + while ((next = read_byte()) == 0) + { + length += 0xFF; + if (length > dst_capacity) + throwMalformedLzo(offset()); + } + return length + next; + }; + + while (input < input_end) + { + bool first_command = true; + size_t last_literal_length = 0; + + while (true) + { + UInt32 command = read_byte(); + if (command == 0x11) + break; + + size_t match_length = 0; + size_t match_offset = 0; + size_t literal_length = 0; + + if ((command & 0xF0) == 0) + { + if (last_literal_length == 0) + { + /// A long run of literals. + literal_length = command & 0xF; + if (literal_length == 0) + literal_length = read_variable_length(0xF); + literal_length += 3; + } + else if (last_literal_length <= 3) + { + match_length = 3; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + match_offset |= 0x800; + literal_length = command & 0x3; + } + else + { + match_length = 2; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + literal_length = command & 0x3; + } + } + else if (first_command) + { + literal_length = command - 17; + } + else if ((command & 0xF0) == 0x10) + { + match_length = command & 0x7; + if (match_length == 0) + match_length = read_variable_length(0x7); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + match_offset |= (command & 0x8) ? 0x8000 : 0x4000; + --match_offset; + literal_length = trailer & 0x3; + } + else if ((command & 0xE0) == 0x20) + { + match_length = command & 0x1F; + if (match_length == 0) + match_length = read_variable_length(0x1F); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + literal_length = trailer & 0x3; + } + else if ((command & 0xC0) != 0) + { + match_length = ((command & 0xE0) >> 5) + 1; + match_offset = (command & 0x1C) >> 2; + match_offset |= read_byte() << 3; + literal_length = command & 0x3; + } + else + throwMalformedLzo(offset()); + + first_command = false; + + if (match_length != 0) + { + /// LZO encodes the match offset minus one. + ++match_offset; + if (match_offset > static_cast(output - dst) || match_length > static_cast(output_end - output)) + throwMalformedLzo(offset()); + const char * match = output - match_offset; + /// The source can overlap the destination, so copy byte by byte. + for (size_t i = 0; i < match_length; ++i) + output[i] = match[i]; + output += match_length; + } + + if (literal_length > static_cast(output_end - output) || literal_length > static_cast(input_end - input)) + throwMalformedLzo(offset()); + memcpy(output, input, literal_length); + output += literal_length; + input += literal_length; + last_literal_length = literal_length; + } + + /// The end-of-stream marker is 0x11 0x00 0x00. + if (input_end - input < 2 || input[0] != 0 || input[1] != 0) + throwMalformedLzo(offset()); + input += 2; + } + + return output - dst; +} + +size_t decompressZlib(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + z_stream stream{}; + if (inflateInit2(&stream, -15) != Z_OK) + throw Exception(ErrorCodes::INCORRECT_DATA, "Cannot initialize zlib decompression for ORC file"); + + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(dst); + stream.avail_out = static_cast(dst_capacity); + + int ret = inflate(&stream, Z_FINISH); + size_t result = dst_capacity - stream.avail_out; + inflateEnd(&stream); + + if (ret != Z_STREAM_END) + { + if (ret == Z_BUF_ERROR && stream.avail_out == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A zlib-compressed chunk of ORC file decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zlib-compressed data in ORC file (zlib error {})", ret); + } + return result; +} + +size_t decompressSnappy(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + if (uncompressed_size > dst_capacity) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A snappy-compressed chunk of ORC file decompresses to {} bytes, more than the {} bytes allowed for the chunk", + uncompressed_size, dst_capacity); + if (!snappy::RawUncompress(src, src_size, dst)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + return uncompressed_size; +} + +size_t decompressLz4(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + if (src_size > static_cast(std::numeric_limits::max()) || dst_capacity > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "LZ4-compressed chunk of ORC file is too large"); + int res = LZ4_decompress_safe(src, dst, static_cast(src_size), static_cast(dst_capacity)); + if (res < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed LZ4-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + return static_cast(res); +} + +size_t decompressZstd(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t res = ZSTD_decompress(dst, dst_capacity, src, src_size); + if (ZSTD_isError(res)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed zstd-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk: {}", + dst_capacity, ZSTD_getErrorName(res)); + return res; +} + + +class ZlibCompressor final : public Compressor +{ +public: + ZlibCompressor() + { + /// The level and the parameters are the same as in the C++ ORC library with its default + /// compression strategy, "speed". + if (deflateInit2(&stream, Z_BEST_SPEED + 1, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot initialize zlib compression for ORC"); + } + + ~ZlibCompressor() override { deflateEnd(&stream); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + if (deflateReset(&stream) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot reset zlib compression for ORC"); + + size_t old_size = out.size(); + /// Allow only the output smaller than the input. + out.resize(old_size + src_size); + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(out.data() + old_size); + stream.avail_out = static_cast(src_size); + + int ret = deflate(&stream, Z_FINISH); + if (ret == Z_STREAM_END && stream.avail_out > 0) + { + size_t compressed = src_size - stream.avail_out; + out.resize(old_size + compressed); + return compressed; + } + out.resize(old_size); + if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zlib compression failed with error {}", ret); + return 0; + } + +private: + z_stream stream{}; +}; + +class SnappyCompressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + out.resize(old_size + snappy::MaxCompressedLength(src_size)); + size_t compressed = 0; + snappy::RawCompress(src, src_size, out.data() + old_size, &compressed); + return finish(out, old_size, compressed, src_size); + } + + static size_t finish(std::string & out, size_t old_size, size_t compressed, size_t src_size) + { + if (compressed >= src_size) + { + out.resize(old_size); + return 0; + } + out.resize(old_size + compressed); + return compressed; + } +}; + +class Lz4Compressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + int bound = LZ4_compressBound(static_cast(src_size)); + out.resize(old_size + bound); + int compressed = LZ4_compress_default(src, out.data() + old_size, static_cast(src_size), bound); + if (compressed <= 0) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "LZ4 compression failed"); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } +}; + +class ZstdCompressor final : public Compressor +{ +public: + ZstdCompressor() : context(ZSTD_createCCtx()) + { + if (!context) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot create zstd compression context"); + } + + ~ZstdCompressor() override { ZSTD_freeCCtx(context); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + size_t bound = ZSTD_compressBound(src_size); + out.resize(old_size + bound); + /// Level 1, as in the C++ ORC library with its default compression strategy, "speed". + size_t compressed = ZSTD_compressCCtx(context, out.data() + old_size, bound, src, src_size, 1); + if (ZSTD_isError(compressed)) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zstd compression failed: {}", ZSTD_getErrorName(compressed)); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } + +private: + ZSTD_CCtx * context; +}; + +} + + +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size) +{ + /// The ratios are the theoretical maximums of the formats, rounded up, so that valid chunks are never rejected. + /// The sizes stored in the chunks are only trusted below these bounds. + static constexpr size_t SLACK = 1024; + switch (kind) + { + case CompressionKind::NONE: + return src_size; + case CompressionKind::SNAPPY: + { + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + /// A copy of 64 bytes takes at least 3 bytes. + return std::min(uncompressed_size, src_size * 22 + SLACK); + } + case CompressionKind::ZSTD: + { + /// Sums the content sizes of all frames, or 128 KiB per block when a frame omits its size, as in `ArrowIPC/BufferCompression.cpp`. + UInt64 bound = ZSTD_decompressBound(src, src_size); + if (bound == ZSTD_CONTENTSIZE_ERROR) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zstd-compressed data in ORC file"); + /// A block of at most 128 KiB takes at least 4 bytes (an RLE block). + return std::min(bound, src_size * 32768 + SLACK); + } + /// A deflate match of 258 bytes takes at least 2 bits. + case CompressionKind::ZLIB: + return src_size * 1032 + SLACK; + /// Every byte of a match length extension adds at most 255 bytes. + case CompressionKind::LZ4: + case CompressionKind::LZO: + return src_size * 256 + SLACK; + default: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + switch (kind) + { + case CompressionKind::ZLIB: return decompressZlib(src, src_size, dst, dst_capacity); + case CompressionKind::SNAPPY: return decompressSnappy(src, src_size, dst, dst_capacity); + case CompressionKind::LZO: return decompressLzo(src, src_size, dst, dst_capacity); + case CompressionKind::LZ4: return decompressLz4(src, src_size, dst, dst_capacity); + case CompressionKind::ZSTD: return decompressZstd(src, src_size, dst, dst_capacity); + case CompressionKind::NONE: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +std::unique_ptr createCompressor(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return nullptr; + case CompressionKind::ZLIB: return std::make_unique(); + case CompressionKind::SNAPPY: return std::make_unique(); + case CompressionKind::LZ4: return std::make_unique(); + case CompressionKind::ZSTD: return std::make_unique(); + case CompressionKind::LZO: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC with compression {} is not supported", compressionKindToString(kind)); +} + +String compressionKindToString(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return "NONE"; + case CompressionKind::ZLIB: return "ZLIB"; + case CompressionKind::SNAPPY: return "SNAPPY"; + case CompressionKind::LZO: return "LZO"; + case CompressionKind::LZ4: return "LZ4"; + case CompressionKind::ZSTD: return "ZSTD"; + case CompressionKind::BROTLI: return "BROTLI"; + } + return "UNKNOWN(" + std::to_string(static_cast(kind)) + ")"; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.h b/src/Processors/Formats/Impl/ORC/Compression.h new file mode 100644 index 000000000000..7e0ceddb72a7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include +#include + +namespace DB::ORC +{ + +using Proto::CompressionKind; + +/// Every compressed chunk of an ORC stream is prefixed with a 3-byte little-endian header: +/// `(chunk_length << 1) | is_original`, where `is_original` means the chunk is stored as is. +static constexpr size_t COMPRESSION_HEADER_SIZE = 3; + +/// Decompresses one chunk into `dst`, which has room for `dst_capacity` bytes (the compression block +/// size of the file). Returns the decompressed size. Throws `INCORRECT_DATA` on malformed input, +/// including a chunk that decompresses to more than `dst_capacity` bytes. +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity); + +/// An upper bound of the decompressed size of a chunk, from the maximum compression ratio of the codec +/// (and the size stored in the chunk), to avoid allocating the whole compression block for a small chunk. +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size); + +/// Compresses chunks of an ORC stream. +class Compressor +{ +public: + virtual ~Compressor() = default; + + /// Appends the compressed representation of `src` to `out` and returns its size, + /// or appends nothing and returns 0 if it would not be smaller than the input. + virtual size_t compress(const char * src, size_t src_size, std::string & out) = 0; +}; + +/// Returns nullptr for `NONE`. +std::unique_ptr createCompressor(CompressionKind kind); + +String compressionKindToString(CompressionKind kind); + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.cpp b/src/Processors/Formats/Impl/ORC/Proto.cpp new file mode 100644 index 000000000000..19e504dfd365 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.cpp @@ -0,0 +1,944 @@ +#include + +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC::Proto +{ + +void WireReader::check(size_t n) const +{ + if (static_cast(end - pos) < n) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated protobuf message in ORC metadata"); +} + +UInt64 WireReader::readVarint() +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + check(1); + UInt8 byte = static_cast(*pos++); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC metadata"); +} + +UInt64 WireReader::readFixed64() +{ + check(8); + UInt64 v = 0; + memcpy(&v, pos, 8); + pos += 8; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +UInt32 WireReader::readFixed32() +{ + check(4); + UInt32 v = 0; + memcpy(&v, pos, 4); + pos += 4; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +double WireReader::readDouble() +{ + return std::bit_cast(readFixed64()); +} + +std::string_view WireReader::readBytes() +{ + UInt64 size = readVarint(); + check(size); + std::string_view res(pos, size); + pos += size; + return res; +} + +bool WireReader::nextField(UInt32 & field_number, WireType & wire_type) +{ + if (pos == end) + return false; + UInt64 key = readVarint(); + field_number = static_cast(key >> 3); + wire_type = static_cast(key & 7); + if (field_number == 0 || (key >> 3) > std::numeric_limits::max()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed field key in ORC metadata"); + return true; +} + +void WireReader::skip(WireType wire_type) +{ + switch (wire_type) + { + case VARINT: readVarint(); return; + case FIXED64: check(8); pos += 8; return; + case LENGTH_DELIMITED: readBytes(); return; + case FIXED32: check(4); pos += 4; return; + case START_GROUP: + case END_GROUP: + break; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unsupported protobuf wire type {} in ORC metadata", static_cast(wire_type)); +} + +bool WireReader::readRepeatedVarint(WireType wire_type, std::vector & out) +{ + if (wire_type == LENGTH_DELIMITED) + { + WireReader packed(readBytes()); + while (packed.pos != packed.end) + out.push_back(packed.readVarint()); + return true; + } + if (wire_type == VARINT) + { + out.push_back(readVarint()); + return true; + } + return false; +} + + +void WireWriter::appendRawVarint(std::string & s, UInt64 value) +{ + while (value >= 0x80) + { + s.push_back(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + s.push_back(static_cast(value)); +} + +void WireWriter::writeVarint(UInt32 field, UInt64 value) +{ + writeKey(field, WireReader::VARINT); + appendRawVarint(out, value); +} + +void WireWriter::writeDouble(UInt32 field, double value) +{ + writeKey(field, WireReader::FIXED64); + UInt64 v = std::bit_cast(value); + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + out.append(reinterpret_cast(&v), 8); +} + +void WireWriter::writeBytes(UInt32 field, std::string_view value) +{ + writeKey(field, WireReader::LENGTH_DELIMITED); + appendRawVarint(out, value.size()); + out.append(value); +} + +void WireWriter::writePackedVarint(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + appendRawVarint(packed, v); + writeBytes(field, packed); +} + +void WireWriter::writePackedFixed64(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + { + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + packed.append(reinterpret_cast(&v), 8); + } + writeBytes(field, packed); +} + + +namespace +{ + +using WireType = WireReader::WireType; + +/// A field with an unexpected wire type is an unknown field, which the Protocol Buffers rules +/// require to skip. It is detected before anything is read, and handled in `parseMessage`. +struct WireTypeMismatch : std::exception +{ +}; + +void expectWireType(WireType actual, WireType expected) +{ + if (actual != expected) + throw WireTypeMismatch{}; +} + +UInt64 readVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readVarint(); +} + +Int64 readSignedVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readSignedVarint(); +} + +UInt32 readUInt32Field(WireReader & r, WireType t) +{ + /// Protobuf truncates the 64-bit varint for 32-bit fields. + return static_cast(readVarintField(r, t)); +} + +/// For `sint32` fields. +Int32 readSignedVarint32Field(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + UInt32 v = static_cast(r.readVarint()); + return static_cast((v >> 1) ^ (~(v & 1) + 1)); +} + +double readDoubleField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::FIXED64); + return r.readDouble(); +} + +std::string_view readBytesField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::LENGTH_DELIMITED); + return r.readBytes(); +} + +void checkCount(size_t count, size_t max_count, std::string_view what) +{ + if (count >= max_count) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many {} in ORC metadata, at most {} expected", what, max_count); +} + +template +void parseMessage(std::string_view data, F && handle_field) +{ + WireReader r(data); + UInt32 field = 0; + WireType type = WireReader::VARINT; + while (r.nextField(field, type)) + { + bool handled = false; + try + { + handled = handle_field(r, field, type); + } + catch (const WireTypeMismatch &) + { + handled = false; + } + if (!handled) + r.skip(type); + } +} + +IntegerStatistics parseIntegerStatistics(std::string_view data) +{ + IntegerStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +DoubleStatistics parseDoubleStatistics(std::string_view data) +{ + DoubleStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readDoubleField(r, type); return true; + case 2: res.maximum = readDoubleField(r, type); return true; + case 3: res.sum = readDoubleField(r, type); return true; + default: return false; + } + }); + return res; +} + +StringStatistics parseStringStatistics(std::string_view data) +{ + StringStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + case 4: res.lower_bound = std::string(readBytesField(r, type)); return true; + case 5: res.upper_bound = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +BucketStatistics parseBucketStatistics(std::string_view data) +{ + BucketStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + return r.readRepeatedVarint(type, res.count); + }); + return res; +} + +DecimalStatistics parseDecimalStatistics(std::string_view data) +{ + DecimalStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +DateStatistics parseDateStatistics(std::string_view data) +{ + DateStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarint32Field(r, type); return true; + case 2: res.maximum = readSignedVarint32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +TimestampStatistics parseTimestampStatistics(std::string_view data) +{ + TimestampStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.minimum_utc = readSignedVarintField(r, type); return true; + case 4: res.maximum_utc = readSignedVarintField(r, type); return true; + case 5: res.minimum_nanos = readVarintField(r, type); return true; + case 6: res.maximum_nanos = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +BinaryStatistics parseBinaryStatistics(std::string_view data) +{ + BinaryStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + res.sum = readSignedVarintField(r, type); + return true; + }); + return res; +} + +CollectionStatistics parseCollectionStatistics(std::string_view data) +{ + CollectionStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.min_children = readVarintField(r, type); return true; + case 2: res.max_children = readVarintField(r, type); return true; + case 3: res.total_children = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +Stream parseStream(std::string_view data) +{ + Stream res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: res.column = readUInt32Field(r, type); return true; + case 3: res.length = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +ColumnEncoding parseColumnEncoding(std::string_view data) +{ + ColumnEncoding res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: + { + UInt32 kind = readUInt32Field(r, type); + if (kind > static_cast(ColumnEncodingKind::DICTIONARY_V2)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding kind {}", kind); + res.kind = static_cast(kind); + return true; + } + case 2: res.dictionary_size = readUInt32Field(r, type); return true; + case 3: res.bloom_encoding = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +Type parseType(std::string_view data) +{ + Type res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: return r.readRepeatedVarint(type, res.subtypes); + case 3: res.field_names.emplace_back(readBytesField(r, type)); return true; + case 4: res.maximum_length = readUInt32Field(r, type); return true; + case 5: res.precision = readUInt32Field(r, type); return true; + case 6: res.scale = readUInt32Field(r, type); return true; + case 7: + { + StringPair pair; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: pair.key = std::string(readBytesField(rr, t)); return true; + case 2: pair.value = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + res.attributes.push_back(std::move(pair)); + return true; + } + case 8: res.crs = std::string(readBytesField(r, type)); return true; + case 9: res.algorithm = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +StripeInformation parseStripeInformation(std::string_view data) +{ + StripeInformation res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.offset = readVarintField(r, type); return true; + case 2: res.index_length = readVarintField(r, type); return true; + case 3: res.data_length = readVarintField(r, type); return true; + case 4: res.footer_length = readVarintField(r, type); return true; + case 5: res.number_of_rows = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +UserMetadataItem parseUserMetadataItem(std::string_view data) +{ + UserMetadataItem res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.name = std::string(readBytesField(r, type)); return true; + case 2: res.value = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +std::string serializeIntegerStatistics(const IntegerStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + return out; +} + +std::string serializeDoubleStatistics(const DoubleStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeDouble(1, *s.minimum); + if (s.maximum) w.writeDouble(2, *s.maximum); + if (s.sum) w.writeDouble(3, *s.sum); + return out; +} + +std::string serializeStringStatistics(const StringStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + if (s.lower_bound) w.writeBytes(4, *s.lower_bound); + if (s.upper_bound) w.writeBytes(5, *s.upper_bound); + return out; +} + +std::string serializeDecimalStatistics(const DecimalStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeBytes(3, *s.sum); + return out; +} + +std::string serializeDateStatistics(const DateStatistics & s) +{ + std::string out; + WireWriter w(out); + auto zigzag32 = [](Int32 v) { return static_cast((static_cast(v) << 1) ^ static_cast(v >> 31)); }; + if (s.minimum) w.writeVarint(1, zigzag32(*s.minimum)); + if (s.maximum) w.writeVarint(2, zigzag32(*s.maximum)); + return out; +} + +std::string serializeTimestampStatistics(const TimestampStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.minimum_utc) w.writeSignedVarint(3, *s.minimum_utc); + if (s.maximum_utc) w.writeSignedVarint(4, *s.maximum_utc); + /// `int32` fields: negative values are sign-extended to 64 bits. + if (s.minimum_nanos) w.writeVarint(5, *s.minimum_nanos); + if (s.maximum_nanos) w.writeVarint(6, *s.maximum_nanos); + return out; +} + +std::string serializeCollectionStatistics(const CollectionStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.min_children) w.writeVarint(1, *s.min_children); + if (s.max_children) w.writeVarint(2, *s.max_children); + if (s.total_children) w.writeVarint(3, *s.total_children); + return out; +} + +std::string serializeType(const Type & t) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, t.kind); + w.writePackedVarint(2, t.subtypes); + for (const auto & name : t.field_names) + w.writeBytes(3, name); + if (t.maximum_length) w.writeVarint(4, *t.maximum_length); + if (t.precision) w.writeVarint(5, *t.precision); + if (t.scale) w.writeVarint(6, *t.scale); + for (const auto & attr : t.attributes) + { + std::string pair; + WireWriter pw(pair); + pw.writeBytes(1, attr.key); + pw.writeBytes(2, attr.value); + w.writeBytes(7, pair); + } + if (t.crs) w.writeBytes(8, *t.crs); + if (t.algorithm) w.writeVarint(9, *t.algorithm); + return out; +} + +std::string serializeStripeInformation(const StripeInformation & s) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, s.offset); + w.writeVarint(2, s.index_length); + w.writeVarint(3, s.data_length); + w.writeVarint(4, s.footer_length); + w.writeVarint(5, s.number_of_rows); + return out; +} + +} + + +void PostScript::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: footer_length = readVarintField(r, type); return true; + case 2: + { + UInt64 kind = readVarintField(r, type); + if (kind > static_cast(CompressionKind::BROTLI)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC compression kind {}", kind); + compression = static_cast(kind); + return true; + } + case 3: compression_block_size = readVarintField(r, type); return true; + case 4: return r.readRepeatedVarint(type, version); + case 5: metadata_length = readVarintField(r, type); return true; + case 6: writer_version = readUInt32Field(r, type); return true; + case 8000: magic = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string PostScript::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, footer_length); + w.writeVarint(2, static_cast(compression)); + w.writeVarint(3, compression_block_size); + w.writePackedVarint(4, version); + w.writeVarint(5, metadata_length); + w.writeVarint(6, writer_version); + w.writeBytes(8000, magic); + return out; +} + +void ColumnStatistics::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: number_of_values = readVarintField(r, type); return true; + case 2: int_statistics = parseIntegerStatistics(readBytesField(r, type)); return true; + case 3: double_statistics = parseDoubleStatistics(readBytesField(r, type)); return true; + case 4: string_statistics = parseStringStatistics(readBytesField(r, type)); return true; + case 5: bucket_statistics = parseBucketStatistics(readBytesField(r, type)); return true; + case 6: decimal_statistics = parseDecimalStatistics(readBytesField(r, type)); return true; + case 7: date_statistics = parseDateStatistics(readBytesField(r, type)); return true; + case 8: binary_statistics = parseBinaryStatistics(readBytesField(r, type)); return true; + case 9: timestamp_statistics = parseTimestampStatistics(readBytesField(r, type)); return true; + case 10: has_null = readVarintField(r, type) != 0; return true; + case 11: bytes_on_disk = readVarintField(r, type); return true; + case 12: collection_statistics = parseCollectionStatistics(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string ColumnStatistics::serialize() const +{ + std::string out; + WireWriter w(out); + if (number_of_values) w.writeVarint(1, *number_of_values); + if (int_statistics) w.writeBytes(2, serializeIntegerStatistics(*int_statistics)); + if (double_statistics) w.writeBytes(3, serializeDoubleStatistics(*double_statistics)); + if (string_statistics) w.writeBytes(4, serializeStringStatistics(*string_statistics)); + if (bucket_statistics) + { + std::string bucket; + WireWriter(bucket).writePackedVarint(1, bucket_statistics->count); + w.writeBytes(5, bucket); + } + if (decimal_statistics) w.writeBytes(6, serializeDecimalStatistics(*decimal_statistics)); + if (date_statistics) w.writeBytes(7, serializeDateStatistics(*date_statistics)); + if (binary_statistics) + { + std::string binary; + if (binary_statistics->sum) + WireWriter(binary).writeSignedVarint(1, *binary_statistics->sum); + w.writeBytes(8, binary); + } + if (timestamp_statistics) w.writeBytes(9, serializeTimestampStatistics(*timestamp_statistics)); + if (has_null) w.writeVarint(10, *has_null); + if (bytes_on_disk) w.writeVarint(11, *bytes_on_disk); + if (collection_statistics) w.writeBytes(12, serializeCollectionStatistics(*collection_statistics)); + return out; +} + +void RowIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view entry_data = readBytesField(r, type); + checkCount(entry.size(), max_entries, "row index entries"); + auto & e = entry.emplace_back(); + parseMessage(entry_data, [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: return rr.readRepeatedVarint(t, e.positions); + case 2: e.statistics.emplace().parse(readBytesField(rr, t)); return true; + default: return false; + } + }); + return true; + }); +} + +std::string RowIndex::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & e : entry) + { + std::string entry_data; + WireWriter ew(entry_data); + ew.writePackedVarint(1, e.positions); + if (e.statistics) + ew.writeBytes(2, e.statistics->serialize()); + w.writeBytes(1, entry_data); + } + return out; +} + +void BloomFilterIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + checkCount(bloom_filter.size(), max_entries, "bloom filters"); + BloomFilter bf; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: bf.num_hash_functions = readUInt32Field(rr, t); return true; + case 2: + { + if (t == WireReader::LENGTH_DELIMITED) + { + /// Packed fixed64: a sequence of 8-byte little-endian values. + std::string_view bytes = rr.readBytes(); + if (bytes.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed bloom filter bitset in ORC file"); + WireReader packed(bytes); + for (size_t i = 0; i < bytes.size() / 8; ++i) + bf.bitset.push_back(packed.readFixed64()); + } + else + { + expectWireType(t, WireReader::FIXED64); + bf.bitset.push_back(rr.readFixed64()); + } + return true; + } + case 3: bf.utf8bitset = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + bloom_filter.push_back(std::move(bf)); + return true; + }); +} + +void StripeFooter::parse(std::string_view data, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: streams.push_back(parseStream(readBytesField(r, type))); return true; + case 2: + { + std::string_view encoding_data = readBytesField(r, type); + checkCount(columns.size(), max_columns, "column encodings"); + columns.push_back(parseColumnEncoding(encoding_data)); + return true; + } + case 3: writer_timezone = std::string(readBytesField(r, type)); return true; + case 4: readBytesField(r, type); ++encryption_variants; return true; + default: return false; + } + }); +} + +std::string StripeFooter::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & s : streams) + { + std::string stream; + WireWriter sw(stream); + if (s.kind) + sw.writeVarint(1, *s.kind); + sw.writeVarint(2, s.column); + sw.writeVarint(3, s.length); + w.writeBytes(1, stream); + } + for (const auto & c : columns) + { + std::string encoding; + WireWriter ew(encoding); + ew.writeVarint(1, static_cast(c.kind)); + if (c.kind == ColumnEncodingKind::DICTIONARY || c.kind == ColumnEncodingKind::DICTIONARY_V2) + ew.writeVarint(2, c.dictionary_size); + w.writeBytes(2, encoding); + } + if (writer_timezone) + w.writeBytes(3, *writer_timezone); + return out; +} + +void Metadata::parse(std::string_view data, size_t max_stripes, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view stripe_data = readBytesField(r, type); + checkCount(stripe_stats.size(), max_stripes, "stripe statistics"); + StripeStatistics stats; + parseMessage(stripe_data, [&](WireReader & rr, UInt32 f, WireType t) + { + if (f != 1) + return false; + std::string_view column_data = readBytesField(rr, t); + checkCount(stats.col_stats.size(), max_columns, "column statistics"); + stats.col_stats.emplace_back().parse(column_data); + return true; + }); + stripe_stats.push_back(std::move(stats)); + return true; + }); +} + +std::string Metadata::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & stats : stripe_stats) + { + std::string stripe; + WireWriter sw(stripe); + for (const auto & col : stats.col_stats) + sw.writeBytes(1, col.serialize()); + w.writeBytes(1, stripe); + } + return out; +} + +void Footer::parse(std::string_view data) +{ + /// The statistics are parsed after the types, to limit their number by the number of columns. + std::vector statistics_data; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: header_length = readVarintField(r, type); return true; + case 2: content_length = readVarintField(r, type); return true; + case 3: stripes.push_back(parseStripeInformation(readBytesField(r, type))); return true; + case 4: types.push_back(parseType(readBytesField(r, type))); return true; + case 5: metadata.push_back(parseUserMetadataItem(readBytesField(r, type))); return true; + case 6: number_of_rows = readVarintField(r, type); return true; + case 7: statistics_data.push_back(readBytesField(r, type)); return true; + case 8: row_index_stride = readUInt32Field(r, type); return true; + case 9: writer = readUInt32Field(r, type); return true; + case 10: readBytesField(r, type); has_encryption = true; return true; + case 12: software_version = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + if (statistics_data.size() > types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many column statistics in ORC footer: {}, the file has {} columns", + statistics_data.size(), types.size()); + statistics.resize(statistics_data.size()); + for (size_t i = 0; i < statistics_data.size(); ++i) + statistics[i].parse(statistics_data[i]); +} + +std::string Footer::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, header_length); + w.writeVarint(2, content_length); + for (const auto & s : stripes) + w.writeBytes(3, serializeStripeInformation(s)); + for (const auto & t : types) + w.writeBytes(4, serializeType(t)); + for (const auto & item : metadata) + { + std::string m; + WireWriter mw(m); + mw.writeBytes(1, item.name); + mw.writeBytes(2, item.value); + w.writeBytes(5, m); + } + w.writeVarint(6, number_of_rows); + for (const auto & s : statistics) + w.writeBytes(7, s.serialize()); + w.writeVarint(8, row_index_stride); + if (writer) + w.writeVarint(9, *writer); + if (software_version) + w.writeBytes(12, *software_version); + return out; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.h b/src/Processors/Formats/Impl/ORC/Proto.h new file mode 100644 index 000000000000..999839f6ab5d --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.h @@ -0,0 +1,343 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +/// Structures of the ORC file metadata, which is serialized with Protocol Buffers. +/// See `orc_proto.proto` in the ORC specification: https://orc.apache.org/specification/ORCv1/ +/// +/// Only the messages and the fields that are used by the reader and the writer are represented. +/// The parser skips the unknown fields, as required by the Protocol Buffers rules, so the files +/// written by newer writers can be read. + +namespace DB::ORC::Proto +{ + +/// Low-level reader of the Protocol Buffers wire format over a contiguous buffer. +/// Throws `INCORRECT_DATA` on a malformed or truncated message. +class WireReader +{ +public: + enum WireType : UInt8 + { + VARINT = 0, + FIXED64 = 1, + LENGTH_DELIMITED = 2, + START_GROUP = 3, + END_GROUP = 4, + FIXED32 = 5, + }; + + WireReader(const char * begin_, const char * end_) : pos(begin_), end(end_) {} + explicit WireReader(std::string_view data) : pos(data.data()), end(data.data() + data.size()) {} + + /// Reads the next field key. Returns false at the end of the message. + bool nextField(UInt32 & field_number, WireType & wire_type); + + UInt64 readVarint(); + Int64 readSignedVarint() { UInt64 v = readVarint(); return static_cast((v >> 1) ^ (~(v & 1) + 1)); } + UInt64 readFixed64(); + UInt32 readFixed32(); + double readDouble(); + std::string_view readBytes(); + + /// Skips a field of the given wire type. + void skip(WireType wire_type); + + /// Reads a scalar field that can be either packed or not packed. + /// Returns false (and reads nothing) if the wire type is not suitable. + [[nodiscard]] bool readRepeatedVarint(WireType wire_type, std::vector & out); + +private: + void check(size_t n) const; + + const char * pos; + const char * end; +}; + +/// Low-level writer of the Protocol Buffers wire format. +class WireWriter +{ +public: + explicit WireWriter(std::string & out_) : out(out_) {} + + void writeVarint(UInt32 field, UInt64 value); + void writeSignedVarint(UInt32 field, Int64 value) { writeVarint(field, (static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeDouble(UInt32 field, double value); + void writeBytes(UInt32 field, std::string_view value); + void writePackedVarint(UInt32 field, const std::vector & values); + void writePackedFixed64(UInt32 field, const std::vector & values); + + static void appendRawVarint(std::string & s, UInt64 value); + +private: + void writeKey(UInt32 field, UInt8 wire_type) { appendRawVarint(out, (static_cast(field) << 3) | wire_type); } + + std::string & out; +}; + + +enum class CompressionKind : UInt8 +{ + NONE = 0, + ZLIB = 1, + SNAPPY = 2, + LZO = 3, + LZ4 = 4, + ZSTD = 5, + BROTLI = 6, +}; + +struct PostScript +{ + UInt64 footer_length = 0; + CompressionKind compression = CompressionKind::NONE; + /// The default value in the specification. + UInt64 compression_block_size = 256 * 1024; + std::vector version; + UInt64 metadata_length = 0; + UInt32 writer_version = 0; + std::string magic; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct IntegerStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DoubleStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct StringStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; + std::optional lower_bound; + std::optional upper_bound; +}; + +struct BucketStatistics +{ + std::vector count; +}; + +struct DecimalStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DateStatistics +{ + std::optional minimum; + std::optional maximum; +}; + +struct TimestampStatistics +{ + /// In milliseconds, in the local time zone of the writer (deprecated). + std::optional minimum; + std::optional maximum; + /// In milliseconds since the epoch in UTC. + std::optional minimum_utc; + std::optional maximum_utc; + /// The sub-millisecond part of the nanoseconds plus one, if not zero. Unvalidated when read from a file. + std::optional minimum_nanos; + std::optional maximum_nanos; +}; + +struct BinaryStatistics +{ + std::optional sum; +}; + +struct CollectionStatistics +{ + std::optional min_children; + std::optional max_children; + std::optional total_children; +}; + +struct ColumnStatistics +{ + std::optional number_of_values; + std::optional int_statistics; + std::optional double_statistics; + std::optional string_statistics; + std::optional bucket_statistics; + std::optional decimal_statistics; + std::optional date_statistics; + std::optional binary_statistics; + std::optional timestamp_statistics; + std::optional has_null; + std::optional bytes_on_disk; + std::optional collection_statistics; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct RowIndexEntry +{ + std::vector positions; + std::optional statistics; +}; + +struct RowIndex +{ + std::vector entry; + + /// The limits of the number of the repeated objects keep a small malformed message from allocating much memory. + void parse(std::string_view data, size_t max_entries); + std::string serialize() const; +}; + +struct BloomFilter +{ + UInt32 num_hash_functions = 0; + std::vector bitset; + std::optional utf8bitset; +}; + +struct BloomFilterIndex +{ + std::vector bloom_filter; + + void parse(std::string_view data, size_t max_entries); +}; + +enum class StreamKind : UInt32 +{ + PRESENT = 0, + DATA = 1, + LENGTH = 2, + DICTIONARY_DATA = 3, + DICTIONARY_COUNT = 4, + SECONDARY = 5, + ROW_INDEX = 6, + BLOOM_FILTER = 7, + BLOOM_FILTER_UTF8 = 8, + ENCRYPTED_INDEX = 9, + ENCRYPTED_DATA = 10, + STRIPE_STATISTICS = 100, + FILE_STATISTICS = 101, +}; + +struct Stream +{ + std::optional kind; + UInt32 column = 0; + UInt64 length = 0; +}; + +enum class ColumnEncodingKind : UInt32 +{ + DIRECT = 0, + DICTIONARY = 1, + DIRECT_V2 = 2, + DICTIONARY_V2 = 3, +}; + +struct ColumnEncoding +{ + ColumnEncodingKind kind = ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; + /// 1 means the bloom filters use UTF-8 for the strings and UTC for the timestamps. + std::optional bloom_encoding; +}; + +struct StripeFooter +{ + std::vector streams; + std::vector columns; + std::optional writer_timezone; + /// Non-zero if the stripe has encrypted columns, which are not supported. + size_t encryption_variants = 0; + + void parse(std::string_view data, size_t max_columns); + std::string serialize() const; +}; + +struct StringPair +{ + std::string key; + std::string value; +}; + +struct Type +{ + UInt32 kind = 0; + std::vector subtypes; + std::vector field_names; + std::optional maximum_length; + std::optional precision; + std::optional scale; + std::vector attributes; + /// Only for GEOMETRY and GEOGRAPHY. + std::optional crs; + std::optional algorithm; +}; + +struct StripeInformation +{ + UInt64 offset = 0; + UInt64 index_length = 0; + UInt64 data_length = 0; + UInt64 footer_length = 0; + UInt64 number_of_rows = 0; +}; + +struct UserMetadataItem +{ + std::string name; + std::string value; +}; + +struct StripeStatistics +{ + std::vector col_stats; +}; + +struct Metadata +{ + std::vector stripe_stats; + + void parse(std::string_view data, size_t max_stripes, size_t max_columns); + std::string serialize() const; +}; + +struct Footer +{ + UInt64 header_length = 0; + UInt64 content_length = 0; + std::vector stripes; + std::vector types; + std::vector metadata; + UInt64 number_of_rows = 0; + std::vector statistics; + UInt32 row_index_stride = 0; + std::optional writer; + bool has_encryption = false; + std::optional software_version; + + void parse(std::string_view data); + std::string serialize() const; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.cpp b/src/Processors/Formats/Impl/ORC/RLE.cpp new file mode 100644 index 000000000000..7b9762e32de3 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.cpp @@ -0,0 +1,1129 @@ +#include + +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +namespace +{ + +inline Int64 unZigZag(UInt64 value) +{ + return static_cast((value >> 1) ^ (~(value & 1) + 1)); +} + +inline UInt64 zigZag(Int64 value) +{ + return (static_cast(value) << 1) ^ static_cast(value >> 63); +} + +/// The 5-bit codes of the bit widths in RLE v2. +constexpr UInt8 code_to_bit_width[32] = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 40, 48, 56, 64}; + +/// The smallest bit width representable in RLE v2 that fits the given number of bits. +constexpr UInt8 closest_fixed_bits[65] = { + 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 26, 26, 28, 28, 30, 30, 32, 32, 40, 40, 40, 40, 40, 40, 40, 40, 48, 48, 48, + 48, 48, 48, 48, 48, 56, 56, 56, 56, 56, 56, 56, 56, 64, 64, 64, 64, 64, 64, 64, 64}; + +inline UInt32 decodeBitWidth(UInt32 code) +{ + return code_to_bit_width[code & 0x1F]; +} + +inline UInt32 getClosestFixedBits(UInt32 n) +{ + return n <= 64 ? closest_fixed_bits[n] : 64; +} + +inline UInt32 encodeBitWidth(UInt32 width) +{ + width = getClosestFixedBits(width); + if (width <= 24) + return width - 1; + switch (width) + { + case 26: return 24; + case 28: return 25; + case 30: return 26; + case 32: return 27; + case 40: return 28; + case 48: return 29; + case 56: return 30; + default: return 31; + } +} + +/// The number of bits required to represent the value, rounded to a representable bit width. +/// Negative values require 64 bits. +inline UInt32 findClosestNumBits(Int64 value) +{ + if (value < 0) + return 64; + UInt32 count = 64 - static_cast(std::countl_zero(static_cast(value))); + return getClosestFixedBits(count); +} + +} + + +UInt64 readVarint(InputByteStream & stream) +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + UInt8 byte = stream.readByte(); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC stream {}", stream.getName()); +} + +Int64 readSignedVarint(InputByteStream & stream) +{ + return unZigZag(readVarint(stream)); +} + + +void ByteRleDecoder::readHeader() +{ + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + value = static_cast(stream->readByte()); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } +} + +void ByteRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + if (not_null) + memset(data, 0, num_values); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + if (repeating) + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = value; + ++consumed; + } + } + } + else + { + memset(data + position, value, count); + consumed = count; + } + } + else + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = static_cast(stream->readByte()); + ++consumed; + } + } + } + else + { + stream->readBytes(data + position, count); + consumed = count; + } + } + remaining_values -= consumed; + position += count; + } +} + +void ByteRleDecoder::skip(size_t num_values) +{ + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (!repeating) + stream->skipBytes(count); + } +} + +void ByteRleDecoder::seek(PositionProvider & positions) +{ + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); +} + + +void BooleanRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + { + /// The PRESENT stream of a child column is read with the mask of its parent, + /// and the masked positions must be null. + data[i] = 0; + continue; + } + if (remaining_bits == 0) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8; + } + --remaining_bits; + data[i] = (last_byte >> remaining_bits) & 1; + } +} + +void BooleanRleDecoder::skip(size_t num_values) +{ + if (num_values <= remaining_bits) + { + remaining_bits -= num_values; + return; + } + num_values -= remaining_bits; + byte_decoder.skip(num_values / 8); + if (num_values % 8) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - num_values % 8; + } + else + remaining_bits = 0; +} + +void BooleanRleDecoder::seek(PositionProvider & positions) +{ + byte_decoder.seek(positions); + UInt64 consumed = positions.next(); + remaining_bits = 0; + if (consumed > 8) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid seek position {} of a boolean stream in ORC file", consumed); + if (consumed) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - consumed; + } +} + + +namespace +{ + +class IntRleDecoderV1 final : public IntRleDecoder +{ +public: + IntRleDecoderV1(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + for (size_t i = 0; i < count; ++i) + { + if (not_null && !not_null[position + i]) + continue; + if (repeating) + { + data[position + i] = static_cast(value); + value = static_cast(static_cast(value) + static_cast(delta)); + } + else + data[position + i] = static_cast(readValue()); + ++consumed; + } + remaining_values -= consumed; + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (repeating) + value = static_cast(static_cast(value) + static_cast(delta) * count); + else + for (size_t i = 0; i < count; ++i) + readVarint(*stream); + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); + } + +private: + Int64 readValue() + { + return is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + } + + void readHeader() + { + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + delta = static_cast(stream->readByte()); + value = readValue(); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } + } + + std::unique_ptr stream; + const bool is_signed; + size_t remaining_values = 0; + bool repeating = false; + Int64 value = 0; + Int64 delta = 0; +}; + + +class IntRleDecoderV2 final : public IntRleDecoder +{ +public: + IntRleDecoderV2(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (run_read == run_length) + readRun(); + + size_t count = std::min(num_values - position, run_length - run_read); + if (not_null) + { + for (size_t i = position; i < position + count; ++i) + if (not_null[i]) + data[i] = static_cast(literals[run_read++]); + } + else if constexpr (sizeof(T) == sizeof(Int64)) + { + memcpy(static_cast(data + position), literals.data() + run_read, count * sizeof(Int64)); + run_read += count; + } + else + { + for (size_t i = 0; i < count; ++i) + data[position + i] = static_cast(literals[run_read + i]); + run_read += count; + } + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (run_read == run_length) + readRun(); + size_t count = std::min(num_values, run_length - run_read); + run_read += count; + num_values -= count; + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + run_read = run_length = 0; + skip(positions.next()); + } + +private: + enum EncodingType : UInt8 + { + SHORT_REPEAT = 0, + DIRECT = 1, + PATCHED_BASE = 2, + DELTA = 3, + }; + + Int64 readLongBE(size_t num_bytes) + { + UInt64 result = 0; + for (size_t i = 0; i < num_bytes; ++i) + result = (result << 8) | stream->readByte(); + return static_cast(result); + } + + template + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count) + { + for (size_t i = 0; i < count; ++i, in += num_bytes) + { + UInt64 value = 0; + for (size_t j = 0; j < num_bytes; ++j) + value = (value << 8) | in[j]; + out[i] = static_cast(value); + } + } + + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count, size_t num_bytes) + { + switch (num_bytes) + { + case 1: decodeBigEndian<1>(in, out, count); return; + case 2: decodeBigEndian<2>(in, out, count); return; + case 3: decodeBigEndian<3>(in, out, count); return; + case 4: decodeBigEndian<4>(in, out, count); return; + case 5: decodeBigEndian<5>(in, out, count); return; + case 6: decodeBigEndian<6>(in, out, count); return; + case 7: decodeBigEndian<7>(in, out, count); return; + default: decodeBigEndian<8>(in, out, count); return; + } + } + + /// The only bit widths that are not a multiple of 8 are at most 30. + template + static void decodeBitPacked(Int64 * out, size_t count, UInt32 bit_width, ReadByte && read_byte) + { + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + while (bits_in_buffer < bit_width) + { + buffer = (buffer << 8) | read_byte(); + bits_in_buffer += 8; + } + bits_in_buffer -= bit_width; + out[i] = static_cast((buffer >> bits_in_buffer) & mask); + } + } + + /// Reads `count` bit-packed values of `bit_width` bits, starting and ending at a byte boundary. + void readInts(Int64 * out, size_t count, UInt32 bit_width) + { + if (bit_width % 8 == 0) + { + const size_t num_bytes = bit_width / 8; + while (count) + { + /// Decode the values that are entirely in the current chunk directly from it. + size_t in_chunk = std::min(count, static_cast(stream->end - stream->pos) / num_bytes); + if (in_chunk == 0) + { + *out = readLongBE(num_bytes); + ++out; + --count; + continue; + } + decodeBigEndian(reinterpret_cast(stream->pos), out, in_chunk, num_bytes); + stream->pos += in_chunk * num_bytes; + out += in_chunk; + count -= in_chunk; + } + return; + } + + const size_t total_bytes = (count * bit_width + 7) / 8; + if (static_cast(stream->end - stream->pos) >= total_bytes) + { + const UInt8 * in = reinterpret_cast(stream->pos); + decodeBitPacked(out, count, bit_width, [&] { return *in++; }); + stream->pos += total_bytes; + } + else + { + decodeBitPacked(out, count, bit_width, [&] { return stream->readByte(); }); + } + } + + void readRun() + { + UInt8 first_byte = stream->readByte(); + auto encoding = static_cast(first_byte >> 6); + run_read = 0; + switch (encoding) + { + case SHORT_REPEAT: + { + size_t num_bytes = ((first_byte >> 3) & 0x07) + 1; + run_length = (first_byte & 0x07) + 3; + Int64 value = readLongBE(num_bytes); + if (is_signed) + value = unZigZag(static_cast(value)); + std::fill(literals.begin(), literals.begin() + run_length, value); + break; + } + case DIRECT: + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + readInts(literals.data(), run_length, bit_width); + if (is_signed) + for (size_t i = 0; i < run_length; ++i) + literals[i] = unZigZag(static_cast(literals[i])); + break; + } + case PATCHED_BASE: + readPatchedBase(first_byte); + break; + case DELTA: + readDelta(first_byte); + break; + } + } + + void readPatchedBase(UInt8 first_byte) + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + UInt8 third_byte = stream->readByte(); + size_t base_bytes = ((third_byte >> 5) & 0x07) + 1; + UInt32 patch_bit_width = decodeBitWidth(third_byte & 0x1F); + + UInt8 fourth_byte = stream->readByte(); + UInt32 patch_gap_width = ((fourth_byte >> 5) & 0x07) + 1; + size_t patch_list_length = fourth_byte & 0x1F; + if (patch_list_length == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (empty patch list)", stream->getName()); + + Int64 base = readLongBE(base_bytes); + Int64 sign_mask = static_cast(1ULL << (base_bytes * 8 - 1)); + if (base & sign_mask) + { + base &= ~sign_mask; + base = -base; + } + + readInts(literals.data(), run_length, bit_width); + + if (patch_bit_width + patch_gap_width > 64) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Corrupt PATCHED_BASE encoded data in ORC stream {} (patch width + patch gap width > 64)", stream->getName()); + + Int64 patches[32]; + readInts(patches, patch_list_length, getClosestFixedBits(patch_bit_width + patch_gap_width)); + + const Int64 patch_mask = patch_bit_width >= 64 ? -1 : static_cast((1ULL << patch_bit_width) - 1); + size_t patch_index = 0; + Int64 gap = 0; + Int64 patch = 0; + + auto adjust_gap_and_patch = [&] + { + UInt64 current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + Int64 actual_gap = 0; + /// A gap of 255 with a zero patch means that the gap continues in the next entry. + while (current_gap == 255 && patch == 0) + { + actual_gap += 255; + ++patch_index; + if (patch_index >= patch_list_length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (unterminated gap)", stream->getName()); + current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + } + gap = actual_gap + static_cast(current_gap); + }; + + adjust_gap_and_patch(); + for (size_t i = 0; i < run_length; ++i) + { + if (static_cast(i) != gap) + { + literals[i] = static_cast(static_cast(literals[i]) + static_cast(base)); + } + else + { + UInt64 patched = static_cast(literals[i]) | (bit_width < 64 ? static_cast(patch) << bit_width : 0); + literals[i] = static_cast(static_cast(base) + patched); + ++patch_index; + if (patch_index < patch_list_length) + { + adjust_gap_and_patch(); + /// The next gap is relative to the current position. + gap += static_cast(i); + } + } + } + } + + void readDelta(UInt8 first_byte) + { + UInt32 code = (first_byte >> 1) & 0x1F; + UInt32 bit_width = code ? decodeBitWidth(code) : 0; + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + Int64 first_value = is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + literals[0] = first_value; + Int64 delta_base = readSignedVarint(*stream); + + if (bit_width == 0) + { + /// Fixed delta. + for (size_t i = 1; i < run_length; ++i) + literals[i] = static_cast(static_cast(literals[i - 1]) + static_cast(delta_base)); + return; + } + + if (run_length < 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal run length {} for delta encoding in ORC stream {}", run_length, stream->getName()); + + Int64 previous = static_cast(static_cast(first_value) + static_cast(delta_base)); + literals[1] = previous; + readInts(literals.data() + 2, run_length - 2, bit_width); + for (size_t i = 2; i < run_length; ++i) + { + if (delta_base < 0) + previous = static_cast(static_cast(previous) - static_cast(literals[i])); + else + previous = static_cast(static_cast(previous) + static_cast(literals[i])); + literals[i] = previous; + } + } + + std::unique_ptr stream; + const bool is_signed; + std::array literals{}; + size_t run_length = 0; + size_t run_read = 0; +}; + +} + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version) +{ + if (version == RleVersion::V1) + return std::make_unique(std::move(stream), is_signed); + return std::make_unique(std::move(stream), is_signed); +} + + +void ByteRleEncoder::writeValues() +{ + if (num_literals == 0) + return; + if (repeat) + { + stream.writeByte(static_cast(num_literals - MIN_REPEAT)); + stream.writeByte(static_cast(literals[0])); + } + else + { + stream.writeByte(static_cast(-static_cast(num_literals))); + stream.write(literals, num_literals); + } + repeat = false; + tail_run_length = 0; + num_literals = 0; +} + +void ByteRleEncoder::write(char value) +{ + if (num_literals == 0) + { + literals[num_literals++] = value; + tail_run_length = 1; + } + else if (repeat) + { + if (value == literals[0]) + { + ++num_literals; + if (num_literals == MAX_REPEAT_SIZE) + writeValues(); + } + else + { + writeValues(); + literals[num_literals++] = value; + tail_run_length = 1; + } + } + else + { + if (value == literals[num_literals - 1]) + ++tail_run_length; + else + tail_run_length = 1; + + if (tail_run_length == MIN_REPEAT) + { + if (num_literals + 1 == MIN_REPEAT) + { + repeat = true; + ++num_literals; + } + else + { + num_literals -= MIN_REPEAT - 1; + writeValues(); + literals[0] = value; + repeat = true; + num_literals = MIN_REPEAT; + } + } + else + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + writeValues(); + } + } +} + +void ByteRleEncoder::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void ByteRleEncoder::flush() +{ + writeValues(); +} + + +void BooleanRleEncoder::write(bool value) +{ + current = static_cast((current << 1) | (value ? 1 : 0)); + ++bits_in_current; + if (bits_in_current == 8) + { + byte_encoder.write(static_cast(current)); + current = 0; + bits_in_current = 0; + } +} + +void BooleanRleEncoder::recordPosition(std::vector & positions) const +{ + byte_encoder.recordPosition(positions); + positions.push_back(bits_in_current); +} + +void BooleanRleEncoder::flush() +{ + if (bits_in_current) + { + byte_encoder.write(static_cast(current << (8 - bits_in_current))); + current = 0; + bits_in_current = 0; + } + byte_encoder.flush(); +} + + +void IntRleEncoderV2::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void IntRleEncoderV2::flush() +{ + size_t literal_start = 0; + size_t i = 0; + while (i < num_literals) + { + size_t j = i + 1; + while (j < num_literals && literals[j] == literals[i]) + ++j; + if (j - i >= 3) + { + if (literal_start < i) + encodeLiterals(literals + literal_start, i - literal_start); + encodeRepeat(literals[i], j - i); + literal_start = j; + } + i = j; + } + if (literal_start < num_literals) + encodeLiterals(literals + literal_start, num_literals - literal_start); + num_literals = 0; +} + +void IntRleEncoderV2::writeVarint(UInt64 value) +{ + while (value >= 0x80) + { + stream.writeByte(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + stream.writeByte(static_cast(value)); +} + +void IntRleEncoderV2::writeInts(const Int64 * values, size_t count, UInt32 bit_width) +{ + if (bit_width % 8 == 0) + { + size_t num_bytes = bit_width / 8; + for (size_t i = 0; i < count; ++i) + { + UInt64 v = static_cast(values[i]); + for (size_t b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(v >> ((b - 1) * 8))); + } + return; + } + + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + buffer = (buffer << bit_width) | (static_cast(values[i]) & mask); + bits_in_buffer += bit_width; + while (bits_in_buffer >= 8) + { + bits_in_buffer -= 8; + stream.writeByte(static_cast(buffer >> bits_in_buffer)); + } + } + if (bits_in_buffer) + stream.writeByte(static_cast(buffer << (8 - bits_in_buffer))); +} + +void IntRleEncoderV2::encodeRepeat(Int64 value, size_t count) +{ + UInt64 encoded = is_signed ? zigZag(value) : static_cast(value); + if (count <= 10) + { + /// SHORT_REPEAT + UInt32 bits = findClosestNumBits(static_cast(encoded)); + UInt32 num_bytes = (bits + 7) / 8; + stream.writeByte(static_cast(((num_bytes - 1) << 3) | (count - 3))); + for (UInt32 b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(encoded >> ((b - 1) * 8))); + return; + } + + /// DELTA with zero fixed delta. + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeVarint(encoded); + writeSignedVarint(0); +} + +void IntRleEncoderV2::writeDirect(const Int64 * values, size_t count) +{ + Int64 encoded[MAX_LITERAL_SIZE]; + UInt32 bit_width = 1; + for (size_t i = 0; i < count; ++i) + { + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + bit_width = std::max(bit_width, findClosestNumBits(encoded[i])); + } + size_t length = count - 1; + stream.writeByte(static_cast((1 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeInts(encoded, count, bit_width); +} + +namespace +{ + +/// The bit width that is enough for the given fraction `p` of the values (as in the reference implementation). +UInt32 percentileBits(const Int64 * values, size_t count, double p) +{ + UInt32 histogram[32] = {}; + for (size_t i = 0; i < count; ++i) + ++histogram[encodeBitWidth(findClosestNumBits(values[i]))]; + + Int64 per_len = static_cast(static_cast(count) * (1.0 - p)); + for (Int32 i = 31; i >= 0; --i) + { + per_len -= histogram[i]; + if (per_len < 0) + return decodeBitWidth(i); + } + return 0; +} + +} + +void IntRleEncoderV2::encodeLiterals(const Int64 * values, size_t count) +{ + if (count <= 3) + { + writeDirect(values, count); + return; + } + + Int64 min = values[0]; + Int64 max = values[0]; + bool is_increasing = true; + bool is_decreasing = true; + bool is_fixed_delta = true; + bool deltas_overflow = false; + Int64 initial_delta = 0; + if (__builtin_sub_overflow(values[1], values[0], &initial_delta)) + deltas_overflow = true; + + /// Absolute values of the deltas, starting from the second one. + Int64 abs_deltas[MAX_LITERAL_SIZE]; + UInt64 max_abs_delta = 0; + + for (size_t i = 1; i < count; ++i) + { + min = std::min(min, values[i]); + max = std::max(max, values[i]); + is_increasing &= values[i - 1] <= values[i]; + is_decreasing &= values[i - 1] >= values[i]; + + Int64 delta = 0; + if (__builtin_sub_overflow(values[i], values[i - 1], &delta)) + { + deltas_overflow = true; + is_fixed_delta = false; + continue; + } + is_fixed_delta &= (delta == initial_delta); + if (i > 1) + { + UInt64 abs_delta = delta < 0 ? (0 - static_cast(delta)) : static_cast(delta); + abs_deltas[i - 2] = static_cast(abs_delta); + max_abs_delta = std::max(max_abs_delta, abs_delta); + } + } + + Int64 range = 0; + if (__builtin_sub_overflow(max, min, &range)) + { + writeDirect(values, count); + return; + } + + if (!deltas_overflow && is_fixed_delta) + { + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + return; + } + + if (!deltas_overflow && initial_delta != 0 && (is_increasing || is_decreasing) + && max_abs_delta <= static_cast(std::numeric_limits::max())) + { + UInt32 bit_width = findClosestNumBits(static_cast(max_abs_delta)); + /// The bit width code 0 means a fixed delta, so the width 1 is not representable. + if (bit_width == 1) + bit_width = 2; + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + writeInts(abs_deltas, count - 2, bit_width); + return; + } + + /// DIRECT or PATCHED_BASE. + Int64 encoded[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + + UInt32 bits_100p = percentileBits(encoded, count, 1.0); + UInt32 bits_90p = percentileBits(encoded, count, 0.9); + + static constexpr Int64 BASE_VALUE_LIMIT = 1LL << 56; + if (bits_100p - bits_90p <= 1 || min <= -BASE_VALUE_LIMIT || min >= BASE_VALUE_LIMIT) + { + writeDirect(values, count); + return; + } + + Int64 base_reduced[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + base_reduced[i] = values[i] - min; + + UInt32 br_bits_95p = percentileBits(base_reduced, count, 0.95); + UInt32 br_bits_100p = percentileBits(base_reduced, count, 1.0); + if (br_bits_100p == br_bits_95p) + { + writeDirect(values, count); + return; + } + + UInt32 patch_width = getClosestFixedBits(br_bits_100p - br_bits_95p); + if (patch_width == 64) + { + patch_width = 56; + br_bits_95p = 8; + } + const Int64 mask = static_cast((1ULL << br_bits_95p) - 1); + + size_t gaps[MAX_LITERAL_SIZE]; + Int64 patches[MAX_LITERAL_SIZE]; + size_t num_patches = 0; + size_t previous = 0; + size_t max_gap = 0; + for (size_t i = 0; i < count; ++i) + { + if (base_reduced[i] > mask) + { + size_t gap = i - previous; + max_gap = std::max(max_gap, gap); + previous = i; + gaps[num_patches] = gap; + patches[num_patches] = base_reduced[i] >> br_bits_95p; + ++num_patches; + base_reduced[i] &= mask; + } + } + + UInt32 patch_gap_width = (max_gap == 0) ? 1 : findClosestNumBits(static_cast(max_gap)); + patch_gap_width = std::min(patch_gap_width, 8u); + + Int64 patch_list[MAX_LITERAL_SIZE]; + size_t patch_list_length = 0; + for (size_t p = 0; p < num_patches; ++p) + { + size_t gap = gaps[p]; + while (gap > 255) + { + patch_list[patch_list_length++] = static_cast(255ULL << patch_width); + gap -= 255; + } + patch_list[patch_list_length++] = static_cast((static_cast(gap) << patch_width) | static_cast(patches[p])); + } + + /// The length of the patch list is stored in 5 bits. + if (patch_list_length > 31) + { + writeDirect(values, count); + return; + } + + bool is_negative = min < 0; + UInt64 base = is_negative ? static_cast(-min) : static_cast(min); + UInt32 base_width = findClosestNumBits(static_cast(base)) + 1; + UInt32 base_bytes = (base_width + 7) / 8; + if (is_negative) + base |= 1ULL << (base_bytes * 8 - 1); + + size_t length = count - 1; + stream.writeByte(static_cast((2 << 6) | (encodeBitWidth(br_bits_95p) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + stream.writeByte(static_cast(((base_bytes - 1) << 5) | encodeBitWidth(patch_width))); + stream.writeByte(static_cast(((patch_gap_width - 1) << 5) | patch_list_length)); + for (UInt32 b = base_bytes; b > 0; --b) + stream.writeByte(static_cast(base >> ((b - 1) * 8))); + writeInts(base_reduced, count, getClosestFixedBits(br_bits_95p)); + writeInts(patch_list, patch_list_length, getClosestFixedBits(patch_gap_width + patch_width)); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.h b/src/Processors/Formats/Impl/ORC/RLE.h new file mode 100644 index 000000000000..c5212bf5fbf6 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.h @@ -0,0 +1,151 @@ +#pragma once + +#include + +#include +#include + +/// Run-length encodings of ORC: https://orc.apache.org/specification/ORCv1/#run-length-encoding +/// +/// All decoders fill the positions where `not_null` is non-zero (or all positions if it is +/// nullptr), consuming one value from the stream for each of them; the other positions are set to zero. + +namespace DB::ORC +{ + +/// Byte run-length encoding, used for the bytes and for the booleans (packed into bytes). +class ByteRleDecoder +{ +public: + explicit ByteRleDecoder(std::unique_ptr stream_) : stream(std::move(stream_)) {} + + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + void readHeader(); + + std::unique_ptr stream; + size_t remaining_values = 0; + bool repeating = false; + char value = 0; +}; + +/// Booleans packed into bytes, most significant bit first, encoded with the byte run-length encoding. +class BooleanRleDecoder +{ +public: + explicit BooleanRleDecoder(std::unique_ptr stream_) : byte_decoder(std::move(stream_)) {} + + /// Writes 0 or 1. + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + ByteRleDecoder byte_decoder; + size_t remaining_bits = 0; + UInt8 last_byte = 0; +}; + +/// Integer run-length encodings, version 1 and 2. +class IntRleDecoder +{ +public: + virtual ~IntRleDecoder() = default; + /// The values are converted to the type of the output, which can be narrower than the encoded values. + virtual void next(Int64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(UInt64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int32 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int16 * data, size_t num_values, const char * not_null) = 0; + virtual void skip(size_t num_values) = 0; + virtual void seek(PositionProvider & positions) = 0; +}; + +enum class RleVersion : UInt8 +{ + V1, + V2, +}; + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version); + +/// Reads a base 128 varint, as used by the DECIMAL columns. +UInt64 readVarint(InputByteStream & stream); +Int64 readSignedVarint(InputByteStream & stream); + + +class ByteRleEncoder +{ +public: + explicit ByteRleEncoder(OutputByteStream & stream_) : stream(stream_) {} + + void write(char value); + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + +private: + void writeValues(); + + static constexpr size_t MIN_REPEAT = 3; + static constexpr size_t MAX_LITERAL_SIZE = 128; + static constexpr size_t MAX_REPEAT_SIZE = 127 + MIN_REPEAT; + + OutputByteStream & stream; + char literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; + size_t tail_run_length = 0; + bool repeat = false; +}; + +class BooleanRleEncoder +{ +public: + explicit BooleanRleEncoder(OutputByteStream & stream_) : byte_encoder(stream_) {} + + void write(bool value); + void recordPosition(std::vector & positions) const; + void flush(); + +private: + ByteRleEncoder byte_encoder; + UInt8 current = 0; + size_t bits_in_current = 0; +}; + +/// Integer run-length encoding, version 2. +class IntRleEncoderV2 +{ +public: + IntRleEncoderV2(OutputByteStream & stream_, bool is_signed_) : stream(stream_), is_signed(is_signed_) {} + + void write(Int64 value) + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + flush(); + } + + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + + static constexpr size_t MAX_LITERAL_SIZE = 512; + +private: + void encodeLiterals(const Int64 * values, size_t count); + void encodeRepeat(Int64 value, size_t count); + void writeDirect(const Int64 * values, size_t count); + void writeVarint(UInt64 value); + void writeSignedVarint(Int64 value) { writeVarint((static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeInts(const Int64 * values, size_t count, UInt32 bit_width); + + OutputByteStream & stream; + const bool is_signed; + Int64 literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.cpp b/src/Processors/Formats/Impl/ORC/Reader.cpp new file mode 100644 index 000000000000..76c6a432d1b0 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.cpp @@ -0,0 +1,842 @@ +#include + +#include +#include +#include +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +std::future InputStream::readAsync(void * buf, UInt64 length, UInt64 offset) +{ + read(buf, length, offset); + std::promise promise; + promise.set_value(); + return promise.get_future(); +} + + +Reader::Reader(std::unique_ptr stream_, const ReaderOptions & options_) + : stream(std::move(stream_)), options(options_) +{ + readTail(); +} + +Reader::~Reader() +{ + /// The background reads write into the buffers of the cache. + for (auto & range : cache) + if (!range.ready && range.future.valid()) + range.future.wait(); +} + +void Reader::readTail() +{ + const UInt64 file_size = stream->getLength(); + /// The header "ORC" and at least the length of the postscript. + if (file_size < 4) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {} is too small ({} bytes)", stream->getName(), file_size); + + static constexpr UInt64 DIRECTORY_SIZE_GUESS = 16 * 1024; + UInt64 tail_size = std::min(file_size, DIRECTORY_SIZE_GUESS); + std::string tail(tail_size, '\0'); + stream->read(tail.data(), tail_size, file_size - tail_size); + + postscript_length = static_cast(tail.back()); + if (postscript_length + 1 > tail_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid postscript length {} in ORC file {}", postscript_length, stream->getName()); + + postscript.parse(std::string_view(tail).substr(tail_size - 1 - postscript_length, postscript_length)); + + if (postscript.magic != "ORC") + { + /// Very old files do not have the magic in the postscript, but they have it at the beginning. + char header[3]; + stream->read(header, 3, 0); + if (memcmp(header, "ORC", 3) != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {}", stream->getName()); + } + + if (postscript.compression != CompressionKind::NONE) + { + if (postscript.compression_block_size == 0 || postscript.compression_block_size > (1ULL << 30)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid compression block size {} in ORC file {}", postscript.compression_block_size, stream->getName()); + if (postscript.compression == CompressionKind::BROTLI) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "BROTLI compression in ORC files is not supported"); + } + + UInt64 tail_length = 0; + if (__builtin_add_overflow(postscript.footer_length, postscript.metadata_length, &tail_length) + || __builtin_add_overflow(tail_length, postscript_length + 1, &tail_length) + || tail_length > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Invalid footer length {} and metadata length {} in ORC file {} of size {}", + postscript.footer_length, postscript.metadata_length, stream->getName(), file_size); + + if (tail_length > tail_size) + { + tail.resize(tail_length); + tail_size = tail_length; + stream->read(tail.data(), tail_size, file_size - tail_size); + } + + std::string_view footer_data = std::string_view(tail).substr(tail_size - 1 - postscript_length - postscript.footer_length, postscript.footer_length); + footer.parse(decompress(footer_data, "footer")); + + if (footer.has_encryption) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + + schema = Type::fromProto(footer.types); + + /// Validate the stripes once, so that the sums of their offsets and lengths cannot overflow later. + if (footer.stripes.size() > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many stripes {} in ORC file {}", footer.stripes.size(), stream->getName()); + for (size_t i = 0; i < footer.stripes.size(); ++i) + { + const auto & stripe = footer.stripes[i]; + UInt64 stripe_end = 0; + if (common::addOverflow(stripe.offset, stripe.index_length, stripe_end) + || common::addOverflow(stripe_end, stripe.data_length, stripe_end) + || common::addOverflow(stripe_end, stripe.footer_length, stripe_end) + || stripe_end > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + i, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, file_size); + } + + std::string_view metadata_data = std::string_view(tail).substr( + tail_size - 1 - postscript_length - postscript.footer_length - postscript.metadata_length, postscript.metadata_length); + if (!metadata_data.empty()) + metadata.emplace().parse(decompress(metadata_data, "metadata"), footer.stripes.size(), footer.types.size()); + else + metadata.emplace(); +} + +const Proto::Metadata & Reader::getMetadata() +{ + return *metadata; +} + +std::string Reader::decompress(std::string_view data, const std::string & name) const +{ + if (postscript.compression == CompressionKind::NONE) + return std::string(data); + + std::string result; + InputByteStream in(data, postscript.compression, postscript.compression_block_size, name); + while (in.nextChunk()) + result.append(in.pos, in.end); + return result; +} + +Proto::StripeFooter Reader::readStripeFooter(size_t stripe_index) +{ + const auto & stripe = getStripe(stripe_index); + UInt64 offset = stripe.offset + stripe.index_length + stripe.data_length; + UInt64 end = 0; + if (__builtin_add_overflow(offset, stripe.footer_length, &end) || end > stream->getLength() || offset < stripe.offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + stripe_index, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, stream->getLength()); + + auto slices = readRanges({{offset, stripe.footer_length}}); + Proto::StripeFooter result; + result.parse(decompress(slices[0].data, "stripe footer"), footer.types.size()); + if (result.encryption_variants) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + return result; +} + +std::vector> Reader::getStripeRanges( + size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const +{ + const auto & stripe = getStripe(stripe_index); + std::vector> ranges; + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + for (const auto & s : stripe_footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream at offset {} of length {} in stripe {} of ORC file {}", offset, s.length, stripe_index, stream->getName()); + if (s.kind && s.column < selected.size() && selected[s.column] && s.length) + ranges.emplace_back(offset, s.length); + offset = stream_end; + } + return ranges; +} + +std::vector Reader::readRanges(const std::vector> & ranges) +{ + std::vector result(ranges.size()); + + std::vector order(ranges.size()); + for (size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return ranges[a].first < ranges[b].first; }); + + size_t i = 0; + while (i < order.size()) + { + UInt64 begin = ranges[order[i]].first; + UInt64 end = begin + ranges[order[i]].second; + size_t j = i + 1; + while (j < order.size()) + { + UInt64 next_begin = ranges[order[j]].first; + UInt64 next_end = next_begin + ranges[order[j]].second; + UInt64 new_end = std::max(end, next_end); + if (next_begin > end && next_begin - end > options.hole_size_limit) + break; + if (new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + std::shared_ptr> holder; + const char * base = nullptr; + UInt64 base_offset = begin; + { + std::lock_guard lock(cache_mutex); + for (auto & cached : cache) + { + if (cached.offset <= begin && end <= cached.offset + cached.length) + { + if (!cached.ready) + { + cached.ready = true; + cached.future.get(); + } + holder = cached.buffer; + base = cached.buffer->data(); + base_offset = cached.offset; + break; + } + } + } + + if (!holder) + { + if (end > stream->getLength()) + throw Exception(ErrorCodes::INCORRECT_DATA, "A range at {} of length {} goes beyond the end of ORC file {}", begin, end - begin, stream->getName()); + auto buffer = std::make_shared>(end - begin); + if (end > begin) + stream->read(buffer->data(), end - begin, begin); + base = buffer->data(); + holder = std::move(buffer); + } + + for (size_t k = i; k < j; ++k) + { + const auto & range = ranges[order[k]]; + result[order[k]] = Slice{holder, std::string_view(base + (range.first - base_offset), range.second)}; + } + i = j; + } + return result; +} + +void Reader::preBuffer(const std::vector & stripes, const std::vector & include_types) +{ + auto selected = selectColumnsByTypeIds(*schema, include_types); + for (UInt32 stripe_index : stripes) + { + const auto & stripe = getStripe(stripe_index); + auto stripe_footer = readStripeFooter(stripe_index); + auto ranges = getStripeRanges(stripe_index, stripe_footer, selected); + ranges.emplace_back(stripe.offset + stripe.index_length + stripe.data_length, stripe.footer_length); + std::sort(ranges.begin(), ranges.end()); + + size_t i = 0; + while (i < ranges.size()) + { + UInt64 begin = ranges[i].first; + UInt64 end = begin + ranges[i].second; + size_t j = i + 1; + while (j < ranges.size()) + { + UInt64 next_begin = ranges[j].first; + UInt64 new_end = std::max(end, next_begin + ranges[j].second); + if ((next_begin > end && next_begin - end > options.hole_size_limit) || new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + auto buffer = std::make_shared>(end - begin); + { + /// The entry must be owned by the cache before the background read starts, so that + /// the destructor waits for the read even if an exception is thrown in between. + std::lock_guard lock(cache_mutex); + auto & cached = cache.emplace_back(CachedRange{.offset = begin, .length = end - begin, .buffer = std::move(buffer), .future = {}}); + try + { + cached.future = stream->readAsync(cached.buffer->data(), end - begin, begin); + } + catch (...) + { + /// Nothing has been scheduled, so the entry can be removed safely. + cache.pop_back(); + throw; + } + } + i = j; + } + } +} + +void Reader::releaseBuffer(UInt64 boundary) +{ + std::lock_guard lock(cache_mutex); + for (auto it = cache.begin(); it != cache.end();) + { + if (it->offset + it->length <= boundary) + { + /// The buffer can be destroyed only after the background read finishes. The data has + /// not been used, so an error of reading it does not matter. + if (!it->ready && it->future.valid()) + it->future.wait(); + it = cache.erase(it); + } + else + ++it; + } +} + +std::unique_ptr Reader::createRowReader(const RowReaderOptions & row_options) +{ + return std::make_unique(*this, row_options); +} + + +class RowReader::StripeStreamsImpl final : public StripeStreams +{ +public: + StripeStreamsImpl( + Reader & reader_, + size_t stripe_index_, + Proto::StripeFooter footer_, + const std::vector & selected_columns_, + const DateLUTImpl & writer_timezone_, + const DateLUTImpl & reader_timezone_) + : reader(reader_) + , stripe_index(stripe_index_) + , footer(std::move(footer_)) + , selected_columns(selected_columns_) + , writer_timezone(writer_timezone_) + , reader_timezone(reader_timezone_) + { + const auto & stripe = reader.getStripe(stripe_index); + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + + for (const auto & s : footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: streamOffset={}, streamLength={}, stripeOffset={}, stripeIndexLength={}, stripeDataLength={}", + stripe_index, offset, s.length, stripe.offset, stripe.index_length, stripe.data_length); + if (s.kind && s.column < selected_columns.size() && selected_columns[s.column]) + { + /// Use the first stream if there are several of the same kind, as the reference implementation. + stream_ranges.try_emplace({static_cast(s.column), *s.kind}, offset, s.length); + } + else if (s.kind && s.column >= selected_columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: column {} is out of range, the file has {} columns", + stripe_index, s.column, selected_columns.size()); + offset = stream_end; + } + } + + static bool isIndexStream(UInt32 kind) + { + return kind == static_cast(Proto::StreamKind::ROW_INDEX) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER_UTF8); + } + + /// Reads the streams into memory at once, only the index streams or all of them. The streams + /// that are not read are loaded on demand by `getStream`. + void loadStreams(bool only_index) + { + std::vector> ranges; + std::vector> keys; + for (const auto & [key, range] : stream_ranges) + { + if (streams.contains(key) || (only_index && !isIndexStream(key.second))) + continue; + keys.push_back(key); + ranges.push_back(range); + } + + auto new_slices = reader.readRanges(ranges); + for (size_t i = 0; i < keys.size(); ++i) + streams.emplace(keys[i], new_slices[i].data); + slices.insert(slices.end(), std::make_move_iterator(new_slices.begin()), std::make_move_iterator(new_slices.end())); + } + + const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const override + { + if (column_id >= footer.columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC stripe {} has no encoding for column {}, it has {} column encodings", stripe_index, column_id, footer.columns.size()); + return footer.columns[column_id]; + } + + std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const override + { + std::pair key{column_id, static_cast(kind)}; + auto name = fmt::format("column {} kind {} in stripe {}", column_id, static_cast(kind), stripe_index); + if (auto it = streams.find(key); it != streams.end()) + return std::make_unique(it->second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + + auto it = stream_ranges.find(key); + if (it == stream_ranges.end()) + return nullptr; + auto loader = [&file_reader = reader, stream_offset = it->second.first](UInt64 offset, UInt64 length) + { + auto loaded = file_reader.readRanges({{stream_offset + offset, length}}); + return LoadedRange{std::move(loaded[0].holder), loaded[0].data}; + }; + return std::make_unique( + std::move(loader), it->second.second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + } + + std::optional getStreamData(UInt64 column_id, Proto::StreamKind kind) const + { + auto it = streams.find({column_id, static_cast(kind)}); + if (it == streams.end()) + return {}; + return it->second; + } + + const std::vector & getSelectedColumns() const override { return selected_columns; } + const DateLUTImpl & getWriterTimezone() const override { return writer_timezone; } + const DateLUTImpl & getReaderTimezone() const override { return reader_timezone; } + UInt64 getNumberOfRows() const override { return reader.getStripe(stripe_index).number_of_rows; } + bool isDecimalAsLong() const override + { + const auto & version = reader.getPostScript().version; + return version.size() == 2 && version[0] == 1 && version[1] == 9999; + } + + const Proto::StripeFooter & getFooter() const { return footer; } + +private: + Reader & reader; + size_t stripe_index; + Proto::StripeFooter footer; + const std::vector & selected_columns; + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + /// The offset in the file and the length of each selected stream. + std::map, std::pair> stream_ranges; + /// The streams read into memory. + std::vector slices; + std::map, std::string_view> streams; +}; + + +RowReader::RowReader(Reader & reader_, const RowReaderOptions & options_) + : reader(reader_) + , options(options_) + , reader_timezone(DateLUT::instance(options.timezone_name)) +{ + const Type & schema = reader.getType(); + if (options.include_types) + selected_columns = selectColumnsByTypeIds(schema, *options.include_types); + else + selected_columns.assign(schema.getMaximumColumnId() + 1, true); + selected_type = Type::buildSelectedType(schema, selected_columns); + + UInt64 range_end = options.range_offset + std::min(options.range_length, std::numeric_limits::max() - options.range_offset); + const auto & stripes = reader.getFooter().stripes; + current_stripe = stripes.size(); + last_stripe = 0; + for (size_t i = 0; i < stripes.size(); ++i) + { + if (stripes[i].offset >= options.range_offset && stripes[i].offset < range_end) + { + current_stripe = std::min(current_stripe, i); + last_stripe = std::max(last_stripe, i + 1); + } + } + if (current_stripe >= last_stripe) + current_stripe = last_stripe = 0; + + /// The search argument can be applied only if there are row indexes. + if (reader.getFooter().row_index_stride == 0) + options.search_argument.reset(); +} + +RowReader::~RowReader() = default; + +std::unique_ptr RowReader::createRowBatch() const +{ + return ORC::createRowBatch(*selected_type, options.enable_lazy_decoding); +} + +bool Reader::hasBadBloomFilters() const +{ + /// Same as in the reference implementation. Only the C++ writer (id 1) of some old releases wrote bad bloom filters. + if (footer.writer.value_or(0) != 1) + return false; + /// `software_version` is written since 1.5.13, 1.6.11 and 1.7.0, and the C++ writer supports bloom filters since 1.6.0, + /// so the files of the C++ writer without `software_version` have bad bloom filters. + if (!footer.software_version) + return true; + /// Strip the suffix of snapshot versions, like 1.6.12-SNAPSHOT. + std::string_view version = *footer.software_version; + version = version.substr(0, version.find('-')); + static constexpr std::string_view bad_versions[] = { + "1.6.0", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.6.7", "1.6.8", "1.6.9", "1.6.10", "1.6.11", "1.7.0"}; + return std::find(std::begin(bad_versions), std::end(bad_versions), version) != std::end(bad_versions); +} + +const DateLUTImpl & RowReader::getWriterTimezone(const Proto::StripeFooter & stripe_footer) const +{ + if (stripe_footer.writer_timezone) + return DateLUT::instance(*stripe_footer.writer_timezone); + /// The reference implementation uses the local time zone of the reader if the file does not specify it. + return DateLUT::serverTimezoneInstance(); +} + +bool RowReader::evaluateStatistics(const std::vector & stats) const +{ + const auto & leaves = options.search_argument->getLeaves(); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + UInt32 writer_version = reader.getPostScript().writer_version; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + if (column < stats.size()) + values[i] = leaves[i].evaluate(writer_version, stats[column], nullptr); + } + return isNeeded(options.search_argument->evaluate(values)); +} + +UInt64 RowReader::numberOfRowGroups() const +{ + const UInt64 stride = reader.getFooter().row_index_stride; + return rows_in_current_stripe / stride + (rows_in_current_stripe % stride != 0); +} + +void RowReader::loadStripeIndex() +{ + row_indexes.clear(); + bloom_filters.clear(); + /// One extra entry is accepted from lenient writers. + const UInt64 max_entries = std::min(numberOfRowGroups(), std::numeric_limits::max() - 1) + 1; + const bool use_bloom_filters = !reader.hasBadBloomFilters(); + const auto & stripe_footer = stripe_streams->getFooter(); + for (const auto & s : stripe_footer.streams) + { + if (!s.kind || s.column >= selected_columns.size() || !selected_columns[s.column]) + continue; + auto kind = static_cast(*s.kind); + if (kind == Proto::StreamKind::ROW_INDEX) + { + if (row_indexes.contains(s.column)) + continue; + auto data = stripe_streams->getStreamData(s.column, kind); + row_indexes[s.column].parse(reader.decompress(data.value_or(std::string_view{}), "row index"), max_entries); + } + else if (kind == Proto::StreamKind::BLOOM_FILTER_UTF8 && use_bloom_filters) + { + if (bloom_filters.contains(s.column)) + continue; + const auto & encoding = stripe_streams->getEncoding(s.column); + Proto::BloomFilterIndex index; + auto data = stripe_streams->getStreamData(s.column, kind); + index.parse(reader.decompress(data.value_or(std::string_view{}), "bloom filter"), max_entries); + auto & filters = bloom_filters[s.column]; + for (const auto & bf : index.bloom_filter) + { + /// Only the bloom filters with the UTF-8 strings and UTC timestamps can be used. + if (encoding.bloom_encoding.value_or(0) == 1 && bf.num_hash_functions && bf.utf8bitset) + filters.push_back(std::make_shared(bf)); + else + filters.push_back(nullptr); + } + } + } +} + +void RowReader::pickRowGroups() +{ + const UInt64 stride = reader.getFooter().row_index_stride; + const UInt64 groups = numberOfRowGroups(); + const auto & leaves = options.search_argument->getLeaves(); + + /// The number of the row groups comes from the file. Check it against the row indexes, which are already + /// read, before allocating memory for it. + bool has_leaf_index = false; + for (const auto & leaf : leaves) + { + auto it = row_indexes.find(leaf.getColumnId()); + if (it == row_indexes.end()) + continue; + has_leaf_index = true; + if (it->second.entry.size() < groups) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + it->first, it->second.entry.size(), groups, current_stripe); + } + + if (!has_leaf_index) + { + /// Without the row indexes all row groups are read. + next_skipped_rows.clear(); + return; + } + + next_skipped_rows.assign(groups, 0); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + const UInt32 writer_version = reader.getPostScript().writer_version; + const Proto::ColumnStatistics empty_statistics; + + UInt64 next_skipped_group = groups; + for (UInt64 group = groups; group > 0;) + { + --group; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + auto it = row_indexes.find(column); + if (it == row_indexes.end()) + { + values[i] = TruthValue::YES_NO_NULL; + continue; + } + if (group >= it->second.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + column, it->second.entry.size(), groups, current_stripe); + const auto & entry = it->second.entry[group]; + const BloomFilter * bloom_filter = nullptr; + if (auto bf = bloom_filters.find(column); bf != bloom_filters.end() && group < bf->second.size()) + bloom_filter = bf->second[group].get(); + values[i] = leaves[i].evaluate(writer_version, entry.statistics ? *entry.statistics : empty_statistics, bloom_filter); + } + + bool needed = isNeeded(options.search_argument->evaluate(values)); + if (!needed) + { + next_skipped_rows[group] = 0; + next_skipped_group = group; + } + else + next_skipped_rows[group] = (next_skipped_group == groups) ? rows_in_current_stripe : next_skipped_group * stride; + } +} + +UInt64 RowReader::advanceToNextRowGroup(UInt64 current_row) const +{ + const UInt64 groups = next_skipped_rows.size(); + if (groups == 0) + return std::min(current_row, rows_in_current_stripe); + + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return rows_in_current_stripe; + if (next_skipped_rows[group] != 0) + return current_row; + while (group < groups && next_skipped_rows[group] == 0) + ++group; + if (group < groups) + return group * stride; + return rows_in_current_stripe; +} + +UInt64 RowReader::computeBatchSize(UInt64 requested, UInt64 current_row) const +{ + UInt64 end_row = rows_in_current_stripe; + const UInt64 groups = next_skipped_rows.size(); + if (groups > 0) + { + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return 0; + UInt64 next_skipped_row = next_skipped_rows[group]; + if (next_skipped_row == 0) + return 0; + end_row = next_skipped_row; + } + return std::min(requested, end_row - current_row); +} + +void RowReader::seekToRowGroup(size_t row_group) +{ + std::unordered_map positions; + for (const auto & [column, index] : row_indexes) + { + if (row_group >= index.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, the row group {} is requested", column, index.entry.size(), row_group); + positions.emplace(column, PositionProvider(index.entry[row_group].positions)); + } + column_reader->seekToRowGroup(positions); +} + +void RowReader::startNextStripe() +{ + column_reader.reset(); + stripe_streams.reset(); + row_indexes.clear(); + bloom_filters.clear(); + next_skipped_rows.clear(); + + const auto & search_argument = options.search_argument; + const auto & footer = reader.getFooter(); + + if (search_argument && !file_statistics_evaluated) + { + file_statistics_result = footer.statistics.empty() || evaluateStatistics(footer.statistics); + file_statistics_evaluated = true; + } + if (search_argument && !file_statistics_result) + { + current_stripe = last_stripe; + return; + } + + do + { + const auto & stripe = footer.stripes[current_stripe]; + rows_in_current_stripe = stripe.number_of_rows; + + bool is_stripe_needed = true; + const auto & stripe_statistics = reader.getMetadata().stripe_stats; + if (search_argument && stripe_statistics.size() == footer.stripes.size()) + { + const auto & stats = stripe_statistics[current_stripe].col_stats; + is_stripe_needed = stats.empty() || evaluateStatistics(stats); + } + + if (is_stripe_needed) + { + auto stripe_footer = reader.readStripeFooter(current_stripe); + const DateLUTImpl & writer_timezone = getWriterTimezone(stripe_footer); + stripe_streams = std::make_unique( + reader, current_stripe, std::move(stripe_footer), selected_columns, writer_timezone, reader_timezone); + if (!search_argument) + stripe_streams->loadStreams(/* only_index */ false); + + if (search_argument) + { + stripe_streams->loadStreams(/* only_index */ true); + loadStripeIndex(); + pickRowGroups(); + bool has_selected = next_skipped_rows.empty(); + for (UInt64 group = current_row_in_stripe / footer.row_index_stride; !has_selected && group < next_skipped_rows.size(); ++group) + has_selected = next_skipped_rows[group] != 0; + if (has_selected) + { + /// If some row groups are skipped, the data is loaded on demand, only around the + /// selected row groups. Otherwise the whole stripe is read at once. + bool has_skipped = std::find(next_skipped_rows.begin(), next_skipped_rows.end(), 0) != next_skipped_rows.end(); + if (!has_skipped) + stripe_streams->loadStreams(/* only_index */ false); + break; + } + is_stripe_needed = false; + stripe_streams.reset(); + } + } + + if (!is_stripe_needed) + { + ++current_stripe; + current_row_in_stripe = 0; + } + } while (search_argument && current_stripe < last_stripe); + + if (current_stripe >= last_stripe) + return; + + column_reader = buildColumnReader(reader.getType(), *stripe_streams); + + if (search_argument) + { + current_row_in_stripe = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe > 0) + seekToRowGroup(current_row_in_stripe / footer.row_index_stride); + } +} + +bool RowReader::next(ColumnVectorBatch & batch, size_t max_rows) +{ + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + if (current_row_in_stripe == 0) + startNextStripe(); + + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + UInt64 rows_to_read = std::min(max_rows, rows_in_current_stripe - current_row_in_stripe); + if (options.search_argument && rows_to_read > 0) + rows_to_read = computeBatchSize(rows_to_read, current_row_in_stripe); + + batch.numElements = rows_to_read; + if (rows_to_read == 0) + { + current_stripe = last_stripe; + return false; + } + + if (options.enable_lazy_decoding) + column_reader->nextEncoded(batch, rows_to_read, nullptr); + else + column_reader->next(batch, rows_to_read, nullptr); + + current_row_in_stripe += rows_to_read; + + if (options.search_argument) + { + UInt64 next_row = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe != next_row) + { + current_row_in_stripe = next_row; + if (current_row_in_stripe < rows_in_current_stripe) + seekToRowGroup(current_row_in_stripe / reader.getFooter().row_index_stride); + } + } + + if (current_row_in_stripe >= rows_in_current_stripe) + { + ++current_stripe; + current_row_in_stripe = 0; + } + return true; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.h b/src/Processors/Formats/Impl/ORC/Reader.h new file mode 100644 index 000000000000..981ab8c5c799 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.h @@ -0,0 +1,188 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/// The reader of the ORC files: https://orc.apache.org/specification/ORCv1/ + +namespace DB::ORC +{ + +/// Random access to the file. +class InputStream +{ +public: + virtual ~InputStream() = default; + + virtual UInt64 getLength() const = 0; + /// Reads exactly `length` bytes at `offset`. Must be thread-safe if `readAsync` is used. + virtual void read(void * buf, UInt64 length, UInt64 offset) = 0; + /// Reads in the background. The default implementation reads synchronously. + virtual std::future readAsync(void * buf, UInt64 length, UInt64 offset); + virtual const std::string & getName() const = 0; +}; + +struct ReaderOptions +{ + /// Two ranges are read with one request if the gap between them is at most this size... + UInt64 hole_size_limit = 8192; + /// ... and the combined range is at most this size. + UInt64 range_size_limit = 32 * 1024 * 1024; +}; + +struct RowReaderOptions +{ + /// The ids of the columns to read, with the same semantics as in the reference implementation + /// (see `selectColumnsByTypeIds`). If not set, all columns are read. + std::optional> include_types; + /// Read only the stripes that start in `[range_offset, range_offset + range_length)`. + UInt64 range_offset = 0; + UInt64 range_length = std::numeric_limits::max(); + /// For the dictionary-encoded string columns, fill `EncodedStringVectorBatch`. + bool enable_lazy_decoding = false; + /// The time zone to show the values of the TIMESTAMP (not TIMESTAMP_INSTANT) columns in. + std::string timezone_name = "GMT"; + std::shared_ptr search_argument; +}; + +class RowReader; + +class Reader +{ +public: + Reader(std::unique_ptr stream_, const ReaderOptions & options_); + ~Reader(); + + const Type & getType() const { return *schema; } + UInt64 getNumberOfRows() const { return footer.number_of_rows; } + UInt64 getNumberOfStripes() const { return footer.stripes.size(); } + const Proto::StripeInformation & getStripe(size_t index) const { return footer.stripes.at(index); } + static UInt64 getStripeLength(const Proto::StripeInformation & stripe) { return stripe.index_length + stripe.data_length + stripe.footer_length; } + + const Proto::Footer & getFooter() const { return footer; } + const Proto::PostScript & getPostScript() const { return postscript; } + CompressionKind getCompression() const { return postscript.compression; } + /// Whether the bloom filters of the file were written by a version of the C++ writer + /// that hashed the integers incorrectly (ORC-1024), so they must not be used. + bool hasBadBloomFilters() const; + UInt64 getCompressionBlockSize() const { return postscript.compression_block_size; } + + /// The statistics of the whole file, one per column. + const std::vector & getStatistics() const { return footer.statistics; } + /// The statistics of the stripes, read on the first call. Can be empty. + const Proto::Metadata & getMetadata(); + + /// Reads the stripe footer. Not thread-safe. + Proto::StripeFooter readStripeFooter(size_t stripe_index); + + std::unique_ptr createRowReader(const RowReaderOptions & options); + + /// Starts reading the data of the selected columns of the stripes in the background. + void preBuffer(const std::vector & stripes, const std::vector & include_types); + /// Releases the prefetched data that ends before `boundary`. + void releaseBuffer(UInt64 boundary); + + /// A piece of the file in memory. + struct Slice + { + std::shared_ptr> holder; + std::string_view data; + }; + + /// Reads the ranges `(offset, length)` of the file, from the prefetched data if possible. + /// The adjacent ranges are coalesced according to the options. + std::vector readRanges(const std::vector> & ranges); + + /// Decompresses a whole metadata stream (a footer, an index). + std::string decompress(std::string_view data, const std::string & name) const; + +private: + void readTail(); + + struct CachedRange + { + UInt64 offset; + UInt64 length; + std::shared_ptr> buffer; + std::future future; + bool ready = false; + }; + + /// Returns the ranges of the streams of the selected columns in the stripe, and the stripe footer. + std::vector> getStripeRanges(size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const; + + std::unique_ptr stream; + ReaderOptions options; + Proto::PostScript postscript; + UInt64 postscript_length = 0; + Proto::Footer footer; + std::optional metadata; + std::unique_ptr schema; + + std::mutex cache_mutex; + std::list cache; +}; + +/// Reads the rows of the selected stripes and columns in batches. +class RowReader +{ +public: + RowReader(Reader & reader_, const RowReaderOptions & options_); + ~RowReader(); + + std::unique_ptr createRowBatch() const; + + /// Fills the batch with the next rows, at most `max_rows`. Returns false at the end. + bool next(ColumnVectorBatch & batch, size_t max_rows); + + /// The type of the file with only the selected columns. The batches have this structure. + const Type & getSelectedType() const { return *selected_type; } + +private: + class StripeStreamsImpl; + + void startNextStripe(); + void loadStripeIndex(); + UInt64 numberOfRowGroups() const; + void pickRowGroups(); + void seekToRowGroup(size_t row_group); + UInt64 advanceToNextRowGroup(UInt64 current_row) const; + UInt64 computeBatchSize(UInt64 requested, UInt64 current_row) const; + bool evaluateStatistics(const std::vector & stats) const; + const DateLUTImpl & getWriterTimezone(const Proto::StripeFooter & stripe_footer) const; + + Reader & reader; + RowReaderOptions options; + std::vector selected_columns; + std::unique_ptr selected_type; + const DateLUTImpl & reader_timezone; + + UInt64 current_stripe = 0; + UInt64 last_stripe = 0; + UInt64 rows_in_current_stripe = 0; + UInt64 current_row_in_stripe = 0; + bool file_statistics_evaluated = false; + bool file_statistics_result = true; + + std::unique_ptr stripe_streams; + std::unique_ptr column_reader; + + /// For the predicate pushdown, by the column id. + std::unordered_map row_indexes; + std::unordered_map>> bloom_filters; + /// For each row group of the current stripe: zero if it is skipped, otherwise the row (in the + /// stripe) of the next skipped row group or the number of rows in the stripe. + std::vector next_skipped_rows; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.cpp b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp new file mode 100644 index 000000000000..e0543230c614 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp @@ -0,0 +1,1075 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +TruthValue operator||(TruthValue left, TruthValue right) +{ + if (right == TruthValue::YES || left == TruthValue::YES) + return TruthValue::YES; + if (right == TruthValue::YES_NULL || left == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + if (right == TruthValue::NO) + return left; + if (left == TruthValue::NO) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::NO_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::NO_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (left == TruthValue::NO_NULL && right == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator&&(TruthValue left, TruthValue right) +{ + if (right == TruthValue::NO || left == TruthValue::NO) + return TruthValue::NO; + if (right == TruthValue::NO_NULL || left == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + if (right == TruthValue::YES) + return left; + if (left == TruthValue::YES) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::YES_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::YES_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (left == TruthValue::YES_NULL && right == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator!(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: return TruthValue::YES; + case TruthValue::YES: return TruthValue::NO; + case TruthValue::IS_NULL: + case TruthValue::YES_NO: + case TruthValue::YES_NO_NULL: + return value; + case TruthValue::NO_NULL: return TruthValue::YES_NULL; + case TruthValue::YES_NULL: return TruthValue::NO_NULL; + } + return value; +} + +bool isNeeded(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: + case TruthValue::IS_NULL: + case TruthValue::NO_NULL: + return false; + default: + return true; + } +} + + +bool Literal::Decimal::parse(std::string_view s) +{ + bool negative = false; + size_t i = 0; + if (i < s.size() && (s[i] == '-' || s[i] == '+')) + { + negative = s[i] == '-'; + ++i; + } + Int256 result = 0; + bool has_digits = false; + bool has_point = false; + Int32 result_scale = 0; + for (; i < s.size(); ++i) + { + char c = s[i]; + if (c == '.' && !has_point) + { + has_point = true; + continue; + } + if (c < '0' || c > '9') + return false; + has_digits = true; + result = result * 10 + (c - '0'); + if (has_point) + ++result_scale; + /// More than 38 digits do not fit into the 128-bit value. + if (result > Int256(std::numeric_limits::max())) + return false; + } + if (!has_digits) + return false; + value = static_cast(negative ? -result : result); + scale = result_scale; + return true; +} + +std::string Literal::Decimal::toString() const +{ + bool negative = value < 0; + std::string digits = DB::toString(negative ? -Int256(value) : Int256(value)); + std::string result; + if (scale <= 0) + result = digits; + else + { + if (digits.size() <= static_cast(scale)) + digits = std::string(scale - digits.size() + 1, '0') + digits; + result = digits.substr(0, digits.size() - scale) + "." + digits.substr(digits.size() - scale); + size_t last = result.find_last_not_of('0'); + if (result[last] == '.') + result.resize(last); + else + result.resize(last + 1); + } + return negative ? "-" + result : result; +} + +namespace +{ + +int compareDecimals(const Literal::Decimal & a, const Literal::Decimal & b) +{ + Int256 left = a.value; + Int256 right = b.value; + for (Int32 s = a.scale; s < b.scale; ++s) + left *= 10; + for (Int32 s = b.scale; s < a.scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +} + +Literal::Literal(bool value) : type(PredicateDataType::BOOLEAN), int_value(value) {} +Literal::Literal(Int64 value) : type(PredicateDataType::LONG), int_value(value) {} +Literal::Literal(double value) : type(PredicateDataType::FLOAT), float_value(value) {} +Literal::Literal(const char * data, size_t size) : type(PredicateDataType::STRING), string_value(data, size) {} + +Literal::Literal(PredicateDataType type_, Int64 value) : type(type_), int_value(value) +{ + if (type != PredicateDataType::DATE) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Only DATE literals can be created from a type and an integer"); +} + +Literal::Literal(Int64 second, Int32 nanos) : type(PredicateDataType::TIMESTAMP), timestamp_value{second, nanos} {} + +Literal::Literal(Int128 value, Int32 /*precision*/, Int32 scale) : type(PredicateDataType::DECIMAL), decimal_value{value, scale} {} + + +namespace +{ + +/// Where a point is relative to the range [min, max]. +enum class Location : UInt8 +{ + BEFORE, + MIN, + MIDDLE, + MAX, + AFTER, +}; + +template +Location compareToRange(const T & point, const T & min, const T & max, Less less, Equal equal) +{ + if (less(point, min)) + return Location::BEFORE; + if (equal(point, min)) + return Location::MIN; + if (less(max, point)) + return Location::AFTER; + if (equal(point, max)) + return Location::MAX; + return Location::MIDDLE; +} + +template +TruthValue evaluatePredicateRange( + PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null, Less less, Equal equal) +{ + auto loc_of = [&](const T & v) { return compareToRange(v, min_value, max_value, less, equal); }; + bool min_equals_max = equal(min_value, max_value); + + switch (op) + { + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::AFTER) + return TruthValue::NO; + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + auto loc = loc_of(values.at(0)); + if (min_equals_max && loc == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::MIN) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER || loc == Location::MAX || (loc == Location::MIN && min_equals_max)) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IN: + { + if (min_equals_max) + { + for (const auto & value : values) + if (loc_of(value) == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + for (const auto & value : values) + { + auto loc = loc_of(value); + if (loc == Location::MIN || loc == Location::MIDDLE || loc == Location::MAX) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + case PredicateLeaf::Operator::BETWEEN: + { + if (values.empty()) + return TruthValue::YES_NO; + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::MIN) + { + auto loc2 = loc_of(values.at(1)); + if (loc2 == Location::AFTER || loc2 == Location::MAX) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc2 == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + if (loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; +} + +template +TruthValue evaluateRange(PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null) +{ + return evaluatePredicateRange(op, values, min_value, max_value, has_null, + [](const T & a, const T & b) { return a < b; }, + [](const T & a, const T & b) { return a == b; }); +} + +TruthValue evaluateBoolPredicate(PredicateLeaf::Operator op, const std::vector & literals, const Proto::ColumnStatistics & stats) +{ + bool has_null = stats.has_null.value_or(false); + if (!stats.bucket_statistics || stats.bucket_statistics->count.empty()) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + + UInt64 true_count = stats.bucket_statistics->count[0]; + UInt64 false_count = stats.number_of_values.value_or(0) - true_count; + switch (op) + { + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return TruthValue::NO; + if (false_count == 0) + return TruthValue::YES; + } + else + { + if (false_count == 0) + return TruthValue::NO; + if (true_count == 0) + return TruthValue::YES; + } + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (false_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + else + { + if (false_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (true_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +template +std::vector literalsTo(const std::vector & literals, Get get) +{ + std::vector result; + for (const auto & literal : literals) + if (!literal.isNull()) + result.push_back(get(literal)); + return result; +} + +/// From the reference implementation: the writer version that fixed the timestamp statistics. +constexpr UInt32 WRITER_VERSION_ORC_135 = 6; + +} + +TruthValue PredicateLeaf::evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const +{ + TruthValue result = TruthValue::YES_NO_NULL; + bool has_null = stats.has_null.value_or(false); + + switch (type) + { + case PredicateDataType::LONG: + { + if (stats.int_statistics && stats.int_statistics->minimum && stats.int_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getLong(); }), + *stats.int_statistics->minimum, *stats.int_statistics->maximum, has_null); + break; + } + case PredicateDataType::FLOAT: + { + if (stats.double_statistics && stats.double_statistics->minimum && stats.double_statistics->maximum) + { + if (!std::isfinite(stats.double_statistics->sum.value_or(0))) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + else + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getFloat(); }), + *stats.double_statistics->minimum, *stats.double_statistics->maximum, has_null); + } + break; + } + case PredicateDataType::STRING: + { + if (stats.string_statistics && stats.string_statistics->minimum && stats.string_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getString(); }), + *stats.string_statistics->minimum, *stats.string_statistics->maximum, has_null); + break; + } + case PredicateDataType::DATE: + { + if (stats.date_statistics && stats.date_statistics->minimum && stats.date_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getDate(); }), + static_cast(*stats.date_statistics->minimum), static_cast(*stats.date_statistics->maximum), has_null); + break; + } + case PredicateDataType::TIMESTAMP: + { + const auto & ts = stats.timestamp_statistics; + /// The stored nanoseconds are the sub-millisecond part plus one; malformed ones disable the pruning. + auto valid_nanos = [](const std::optional & nanos) { return !nanos || (*nanos >= 1 && *nanos <= 1'000'000); }; + if (ts && ts->minimum_utc && ts->maximum_utc && valid_nanos(ts->minimum_nanos) && valid_nanos(ts->maximum_nanos)) + { + Int32 min_nanos = ts->minimum_nanos ? static_cast(*ts->minimum_nanos) - 1 : 0; + Int32 max_nanos = ts->maximum_nanos ? static_cast(*ts->maximum_nanos) - 1 : 999999; + /// The milliseconds are rounded down, so the nanoseconds are not negative, as in the literals. + auto to_timestamp = [](Int64 millis, Int32 nanos) + { + Int64 second = millis / 1000; + Int64 rest = millis % 1000; + if (rest < 0) + { + rest += 1000; + --second; + } + return Literal::Timestamp{second, static_cast(rest * 1000000) + nanos}; + }; + Literal::Timestamp min = to_timestamp(*ts->minimum_utc, min_nanos); + Literal::Timestamp max = to_timestamp(*ts->maximum_utc, max_nanos); + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getTimestamp(); }), + min, max, has_null); + } + break; + } + case PredicateDataType::DECIMAL: + { + const auto & ds = stats.decimal_statistics; + if (ds && ds->minimum && ds->maximum) + { + Literal::Decimal min; + Literal::Decimal max; + if (min.parse(*ds->minimum) && max.parse(*ds->maximum)) + result = evaluatePredicateRange(op, + literalsTo(literals, [](const Literal & l) { return l.getDecimal(); }), + min, max, has_null, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) < 0; }, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) == 0; }); + } + break; + } + case PredicateDataType::BOOLEAN: + { + if (stats.bucket_statistics) + result = evaluateBoolPredicate(op, literals, stats); + break; + } + } + + /// Respect a null literal for IN. + if (op == Operator::IN && has_null) + for (const auto & literal : literals) + if (literal.isNull()) + return TruthValue::YES_NO_NULL; + + return result; +} + +namespace +{ + +TruthValue checkInBloomFilter(PredicateDataType type, const Literal & literal, const BloomFilter & bf, bool has_null) +{ + TruthValue result = has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (literal.isNull()) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::NO; + else + { + bool found = true; + switch (type) + { + case PredicateDataType::LONG: found = bf.testLong(literal.getLong()); break; + case PredicateDataType::FLOAT: found = bf.testDouble(literal.getFloat()); break; + case PredicateDataType::STRING: found = bf.testBytes(literal.getString().data(), literal.getString().size()); break; + case PredicateDataType::DECIMAL: + { + std::string s = literal.getDecimal().toString(); + found = bf.testBytes(s.data(), s.size()); + break; + } + case PredicateDataType::TIMESTAMP: + { + /// The writers round the negative milliseconds differently: the Java one down, the C++ one toward zero. + const auto timestamp = literal.getTimestamp(); + const Int64 millis_down = timestamp.getMillis(); + const bool has_fraction = timestamp.second < 0 && timestamp.nanos % 1000000 != 0; + found = bf.testLong(millis_down) || (has_fraction && bf.testLong(millis_down + 1)); + break; + } + case PredicateDataType::DATE: found = bf.testLong(literal.getDate()); break; + case PredicateDataType::BOOLEAN: found = true; break; + } + if (found) + result = TruthValue::YES_NO_NULL; + } + + if (result == TruthValue::YES_NO_NULL && !has_null) + result = TruthValue::YES_NO; + return result; +} + +} + +TruthValue PredicateLeaf::evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const +{ + switch (op) + { + case Operator::NULL_SAFE_EQUALS: + /// Null-safe equals does not return the `*_NULL` variants. + return checkInBloomFilter(type, literals.front(), bloom_filter, false); + case Operator::EQUALS: + return checkInBloomFilter(type, literals.front(), bloom_filter, has_null); + case Operator::IN: + for (const auto & literal : literals) + { + TruthValue result = checkInBloomFilter(type, literal, bloom_filter, has_null); + if (result == TruthValue::YES_NO_NULL || result == TruthValue::YES_NO) + return result; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +TruthValue PredicateLeaf::evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const +{ + /// The files written before ORC-135 store the timestamps in the local time zone of the writer. + if (type == PredicateDataType::TIMESTAMP && writer_version < WRITER_VERSION_ORC_135) + return TruthValue::YES_NO_NULL; + + /// The files written by some writers do not have the `has_null` field. + if (!stats.has_null) + return TruthValue::YES_NO_NULL; + + bool has_null = *stats.has_null; + bool all_null = has_null && stats.number_of_values.value_or(0) == 0; + if (op == Operator::IS_NULL || ((op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS) && literals.at(0).isNull())) + return all_null ? TruthValue::YES : (has_null ? TruthValue::YES_NO : TruthValue::NO); + if (all_null) + return TruthValue::IS_NULL; + + TruthValue result = evaluatePredicateMinMax(stats); + if (bloom_filter && result != TruthValue::NO_NULL && result != TruthValue::NO + && (op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS || op == Operator::IN)) + return evaluatePredicateBloomFilter(*bloom_filter, has_null); + return result; +} + + +class ExpressionTree +{ +public: + enum class Operator : UInt8 + { + OR, + AND, + NOT, + LEAF, + CONSTANT, + }; + + explicit ExpressionTree(Operator op_) : op(op_) {} + explicit ExpressionTree(TruthValue constant_) : op(Operator::CONSTANT), constant(constant_) {} + explicit ExpressionTree(size_t leaf_) : op(Operator::LEAF), leaf(leaf_) {} + ExpressionTree(Operator op_, std::vector children_) : op(op_), children(std::move(children_)) {} + + TruthValue evaluate(const std::vector & leaves) const + { + switch (op) + { + case Operator::OR: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && !isNeeded(result); ++i) + result = children[i]->evaluate(leaves) || result; + return result; + } + case Operator::AND: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && isNeeded(result); ++i) + result = children[i]->evaluate(leaves) && result; + return result; + } + case Operator::NOT: + return !children.at(0)->evaluate(leaves); + case Operator::LEAF: + return leaves.at(leaf); + case Operator::CONSTANT: + return constant; + } + return TruthValue::YES_NO_NULL; + } + + Operator op; + TruthValue constant = TruthValue::YES_NO_NULL; + size_t leaf = 0; + std::vector children; +}; + + +SearchArgument::SearchArgument(ExpressionTreePtr root_, std::vector leaves_) + : root(std::move(root_)), leaves(std::move(leaves_)) +{ +} + +TruthValue SearchArgument::evaluate(const std::vector & leaf_values) const +{ + return root ? root->evaluate(leaf_values) : TruthValue::YES_NO_NULL; +} + + +namespace +{ + +using Op = ExpressionTree::Operator; + +/// Pushes the negations down to the leaves and removes the double negations. +ExpressionTreePtr pushDownNot(ExpressionTreePtr root) +{ + if (root->op == Op::NOT) + { + ExpressionTreePtr child = root->children.at(0); + switch (child->op) + { + case Op::NOT: + return pushDownNot(child->children.at(0)); + case Op::CONSTANT: + return std::make_shared(!child->constant); + case Op::AND: + case Op::OR: + { + auto result = std::make_shared(child->op == Op::AND ? Op::OR : Op::AND); + for (const auto & kid : child->children) + result->children.push_back(pushDownNot(std::make_shared(Op::NOT, std::vector{kid}))); + return result; + } + case Op::LEAF: + break; + } + } + else + { + for (auto & kid : root->children) + kid = pushDownNot(kid); + } + return root; +} + +/// Removes the MAYBE (YES_NO_NULL) constants: they are dropped from AND and they replace OR. +ExpressionTreePtr foldMaybe(ExpressionTreePtr expr) +{ + for (auto & kid : expr->children) + { + ExpressionTreePtr child = foldMaybe(kid); + if (child->op == Op::CONSTANT && child->constant == TruthValue::YES_NO_NULL) + { + if (expr->op == Op::AND) + kid = nullptr; + else if (expr->op == Op::OR) + return child; + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Got a maybe as a child of a NOT in ORC search argument"); + } + else + kid = child; + } + + if (!expr->children.empty()) + { + std::erase(expr->children, nullptr); + if (expr->children.empty()) + return std::make_shared(TruthValue::YES_NO_NULL); + } + return expr; +} + +/// Converts multi-level ANDs and ORs into single level ones. +ExpressionTreePtr flatten(ExpressionTreePtr root) +{ + std::vector nodes; + for (auto & kid : root->children) + { + ExpressionTreePtr child = flatten(kid); + if (child->op == root->op && child->op != Op::NOT) + nodes.insert(nodes.end(), child->children.begin(), child->children.end()); + else + nodes.push_back(child); + } + root->children = std::move(nodes); + if ((root->op == Op::OR || root->op == Op::AND) && root->children.size() == 1) + return root->children[0]; + return root; +} + +ExpressionTreePtr copyTree(const ExpressionTreePtr & node) +{ + auto result = std::make_shared(*node); + return result; +} + +void generateAllCombinations( + std::vector & result, const std::vector & and_list, size_t and_index, const std::vector & non_and_list) +{ + const auto & kids = and_list[and_index]->children; + if (result.empty()) + { + for (const auto & kid : kids) + { + auto node = std::make_shared(Op::OR); + for (const auto & non_and : non_and_list) + node->children.push_back(copyTree(non_and)); + node->children.push_back(kid); + result.push_back(node); + } + } + else + { + std::vector work = std::move(result); + result.clear(); + for (const auto & kid : kids) + { + for (const auto & node : work) + { + auto copy = copyTree(node); + copy->children.push_back(kid); + result.push_back(copy); + } + } + } + if (and_index + 1 < and_list.size()) + generateAllCombinations(result, and_list, and_index + 1, non_and_list); +} + +constexpr size_t CNF_COMBINATIONS_THRESHOLD = 256; + +/// Converts the expression into the conjunctive normal form, if it is not too large. +ExpressionTreePtr convertToCNF(ExpressionTreePtr root) +{ + for (auto & kid : root->children) + kid = convertToCNF(kid); + + if (root->op != Op::OR) + return root; + + std::vector non_and_list; + std::vector and_list; + for (const auto & child : root->children) + { + if (child->op == Op::AND) + and_list.push_back(child); + else if (child->op == Op::OR) + non_and_list.insert(non_and_list.end(), child->children.begin(), child->children.end()); + else + non_and_list.push_back(child); + } + + if (and_list.empty()) + return root; + + size_t num_combinations = 1; + for (const auto & node : and_list) + { + num_combinations *= node->children.size(); + if (num_combinations > CNF_COMBINATIONS_THRESHOLD) + return std::make_shared(TruthValue::YES_NO_NULL); + } + + auto result = std::make_shared(Op::AND); + generateAllCombinations(result->children, and_list, 0, non_and_list); + return result; +} + +void collectUsedLeaves(const ExpressionTreePtr & node, std::vector & reorder, size_t & next) +{ + if (node->op == Op::LEAF) + { + if (reorder[node->leaf] == std::numeric_limits::max()) + reorder[node->leaf] = next++; + return; + } + for (const auto & kid : node->children) + collectUsedLeaves(kid, reorder, next); +} + +/// The trees can share nodes after the CNF conversion, so rewrite every leaf node exactly once. +void rewriteLeaves(const ExpressionTreePtr & root, const std::vector & reorder) +{ + std::unordered_set leaves; + std::deque nodes{root.get()}; + while (!nodes.empty()) + { + ExpressionTree * node = nodes.front(); + nodes.pop_front(); + if (node->op == Op::LEAF) + leaves.insert(node); + else + for (const auto & kid : node->children) + nodes.push_back(kid.get()); + } + for (auto * leaf : leaves) + leaf->leaf = reorder[leaf->leaf]; +} + +} + + +SearchArgumentBuilder::SearchArgumentBuilder() +{ + root = std::make_shared(Op::AND); + stack.push_back(root); +} + +SearchArgumentBuilder & SearchArgumentBuilder::start(UInt8 op) +{ + auto node = std::make_shared(static_cast(op)); + stack.back()->children.push_back(node); + stack.push_back(node); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::startOr() { return start(static_cast(Op::OR)); } +SearchArgumentBuilder & SearchArgumentBuilder::startAnd() { return start(static_cast(Op::AND)); } +SearchArgumentBuilder & SearchArgumentBuilder::startNot() { return start(static_cast(Op::NOT)); } + +SearchArgumentBuilder & SearchArgumentBuilder::end() +{ + auto current = stack.back(); + stack.pop_back(); + if (stack.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unbalanced end() in ORC search argument builder"); + if (current->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an expression with no children in ORC search argument builder"); + if (current->op == Op::NOT && current->children.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "A NOT expression must have exactly one child in ORC search argument builder"); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::literal(TruthValue value) +{ + stack.back()->children.push_back(std::make_shared(value)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::addLeaf(PredicateLeaf leaf) +{ + size_t index = leaves.size(); + leaves.push_back(std::move(leaf)); + stack.back()->children.push_back(std::make_shared(index)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThan(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::equals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::NULL_SAFE_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::in(UInt64 column_id, PredicateDataType type, const std::vector & values) +{ + if (values.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an IN expression with no arguments in ORC search argument builder"); + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IN, type, column_id, values)); +} + +SearchArgumentBuilder & SearchArgumentBuilder::isNull(UInt64 column_id, PredicateDataType type) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IS_NULL, type, column_id, {})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::BETWEEN, type, column_id, {std::move(lower), std::move(upper)})); +} + +std::unique_ptr SearchArgumentBuilder::build() +{ + if (stack.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to end {} operations in ORC search argument builder", stack.size() - 1); + if (root->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Empty ORC search argument"); + + root = pushDownNot(root); + root = foldMaybe(root); + root = flatten(root); + root = convertToCNF(root); + root = flatten(root); + + std::vector reorder(leaves.size(), std::numeric_limits::max()); + size_t num_used = 0; + collectUsedLeaves(root, reorder, num_used); + rewriteLeaves(root, reorder); + + std::vector used_leaves; + used_leaves.reserve(num_used); + std::vector by_new_index(num_used); + for (size_t i = 0; i < leaves.size(); ++i) + if (reorder[i] != std::numeric_limits::max()) + by_new_index[reorder[i]] = &leaves[i]; + for (const auto * leaf : by_new_index) + used_leaves.push_back(*leaf); + + return std::make_unique(root, std::move(used_leaves)); +} + + +namespace +{ + +constexpr UInt32 MURMUR3_DEFAULT_SEED = 104729; + +inline UInt64 rotl64(UInt64 x, int r) +{ + return (x << r) | (x >> (64 - r)); +} + +inline UInt64 fmix64(UInt64 value) +{ + value ^= (value >> 33); + value *= 0xff51afd7ed558ccdULL; + value ^= (value >> 33); + value *= 0xc4ceb9fe1a85ec53ULL; + value ^= (value >> 33); + return value; +} + +/// The 64-bit variant of Murmur3 used by ORC (the lower half of the 128-bit hash with one state). +UInt64 murmur3Hash64(const UInt8 * data, size_t size) +{ + UInt64 h = MURMUR3_DEFAULT_SEED; + const UInt64 c1 = 0x87c37b91114253d5ULL; + const UInt64 c2 = 0x4cf5ad432745937fULL; + size_t blocks = size >> 3; + for (size_t i = 0; i < blocks; ++i) + { + UInt64 k = 0; + memcpy(&k, data + i * 8, 8); + if constexpr (std::endian::native == std::endian::big) + k = std::byteswap(k); + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + h = rotl64(h, 27); + h = h * 5 + 0x52dce729; + } + + UInt64 k = 0; + size_t idx = blocks << 3; + size_t tail = size - idx; + for (size_t i = tail; i > 0; --i) + k ^= static_cast(data[idx + i - 1]) << ((i - 1) * 8); + if (tail) + { + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + } + + h ^= static_cast(size); + return fmix64(h); +} + +/// Thomas Wang's 64-bit integer hash, as in the reference implementation. +Int64 getLongHash(Int64 key) +{ + UInt64 k = static_cast(key); + k = (~k) + (k << 21); + k = k ^ static_cast(static_cast(k) >> 24); + k = (k + (k << 3)) + (k << 8); + k = k ^ static_cast(static_cast(k) >> 14); + k = (k + (k << 2)) + (k << 4); + k = k ^ static_cast(static_cast(k) >> 28); + k = k + (k << 31); + return static_cast(k); +} + +} + +BloomFilter::BloomFilter(const Proto::BloomFilter & proto) : num_hash_functions(proto.num_hash_functions) +{ + /// The writers use a few hash functions (the optimal number for the false positive probability), + /// a huge number from a corrupt file would make every probe extremely slow. + static constexpr UInt32 MAX_HASH_FUNCTIONS = 256; + if (num_hash_functions == 0 || num_hash_functions > MAX_HASH_FUNCTIONS) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid number of hash functions {} of a bloom filter in ORC file, must be from 1 to {}", + num_hash_functions, MAX_HASH_FUNCTIONS); + const std::string & bitset = proto.utf8bitset.value(); + if (bitset.empty() || bitset.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "The size of a bloom filter in ORC file must be a positive multiple of 8 bytes"); + bits.resize(bitset.size() / 8); + memcpy(bits.data(), bitset.data(), bitset.size()); + if constexpr (std::endian::native == std::endian::big) + for (auto & word : bits) + word = std::byteswap(word); +} + +bool BloomFilter::testHash(Int64 hash) const +{ + Int32 hash1 = static_cast(hash & 0xffffffff); + Int32 hash2 = static_cast(static_cast(hash) >> 32); + UInt64 num_bits = bits.size() * 64; + for (UInt32 i = 1; i <= num_hash_functions; ++i) + { + Int32 combined = static_cast(static_cast(hash1) + i * static_cast(hash2)); + if (combined < 0) + combined = ~combined; + UInt64 pos = static_cast(combined) % num_bits; + if (!(bits[pos >> 6] & (1ULL << (pos % 64)))) + return false; + } + return true; +} + +bool BloomFilter::testLong(Int64 value) const +{ + return testHash(getLongHash(value)); +} + +bool BloomFilter::testDouble(double value) const +{ + return testLong(std::bit_cast(value)); +} + +bool BloomFilter::testBytes(const char * data, size_t size) const +{ + return testHash(static_cast(murmur3Hash64(reinterpret_cast(data), size))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.h b/src/Processors/Formats/Impl/ORC/SearchArgument.h new file mode 100644 index 000000000000..da19904275e7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.h @@ -0,0 +1,198 @@ +#pragma once + +#include + +#include +#include +#include + +/// Predicates for skipping stripes and row groups by the column statistics and the bloom filters. +/// The semantics (the truth values, the normalization of the expression, the evaluation of each +/// predicate against the statistics) are the same as in the reference implementation. + +namespace DB::ORC +{ + +/// The possible outcomes of a predicate over a set of rows: whether any row can satisfy it (YES), +/// fail it (NO), or evaluate it to NULL. +enum class TruthValue : UInt8 +{ + YES, + NO, + IS_NULL, + YES_NULL, + NO_NULL, + YES_NO, + YES_NO_NULL, +}; + +TruthValue operator||(TruthValue left, TruthValue right); +TruthValue operator&&(TruthValue left, TruthValue right); +TruthValue operator!(TruthValue value); +/// Whether the rows have to be read. +bool isNeeded(TruthValue value); + +enum class PredicateDataType : UInt8 +{ + LONG, + FLOAT, + STRING, + DATE, + DECIMAL, + TIMESTAMP, + BOOLEAN, +}; + +class Literal +{ +public: + struct Timestamp + { + Int64 second = 0; + Int32 nanos = 0; + + /// Rounded down, as the nanoseconds are not negative. + Int64 getMillis() const { return second * 1000 + nanos / 1000000; } + auto operator<=>(const Timestamp &) const = default; + }; + + struct Decimal + { + Int128 value = 0; + Int32 scale = 0; + + /// Parses a decimal number like `-123.45`. Returns false if it is malformed. + bool parse(std::string_view s); + /// Without the trailing zeros in the fraction, as in the bloom filters. + std::string toString() const; + }; + + explicit Literal(bool value); + explicit Literal(Int64 value); + explicit Literal(double value); + Literal(const char * data, size_t size); + /// Only for DATE: the number of days since the epoch. + Literal(PredicateDataType type, Int64 value); + /// TIMESTAMP: the seconds since the epoch in UTC and the nanoseconds. + Literal(Int64 second, Int32 nanos); + Literal(Int128 value, Int32 precision, Int32 scale); + + PredicateDataType getType() const { return type; } + bool isNull() const { return is_null; } + + bool getBool() const { return int_value != 0; } + Int64 getLong() const { return int_value; } + Int64 getDate() const { return int_value; } + double getFloat() const { return float_value; } + const std::string & getString() const { return string_value; } + Timestamp getTimestamp() const { return timestamp_value; } + Decimal getDecimal() const { return decimal_value; } + +private: + PredicateDataType type; + bool is_null = false; + Int64 int_value = 0; + double float_value = 0; + std::string string_value; + Timestamp timestamp_value; + Decimal decimal_value; +}; + +class BloomFilter; + +class PredicateLeaf +{ +public: + enum class Operator : UInt8 + { + EQUALS, + NULL_SAFE_EQUALS, + LESS_THAN, + LESS_THAN_EQUALS, + IN, + BETWEEN, + IS_NULL, + }; + + PredicateLeaf(Operator op_, PredicateDataType type_, UInt64 column_id_, std::vector literals_) + : op(op_), type(type_), column_id(column_id_), literals(std::move(literals_)) {} + + UInt64 getColumnId() const { return column_id; } + + /// `writer_version` is from the postscript of the file. `bloom_filter` can be nullptr. + TruthValue evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const; + +private: + TruthValue evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const; + TruthValue evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const; + + Operator op; + PredicateDataType type; + UInt64 column_id; + std::vector literals; +}; + +class ExpressionTree; +using ExpressionTreePtr = std::shared_ptr; + +class SearchArgument +{ +public: + SearchArgument(ExpressionTreePtr root_, std::vector leaves_); + + const std::vector & getLeaves() const { return leaves; } + TruthValue evaluate(const std::vector & leaf_values) const; + +private: + ExpressionTreePtr root; + std::vector leaves; +}; + +class SearchArgumentBuilder +{ +public: + SearchArgumentBuilder(); + + SearchArgumentBuilder & startOr(); + SearchArgumentBuilder & startAnd(); + SearchArgumentBuilder & startNot(); + SearchArgumentBuilder & end(); + + SearchArgumentBuilder & literal(TruthValue value); + SearchArgumentBuilder & lessThan(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & equals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & in(UInt64 column_id, PredicateDataType type, const std::vector & values); + SearchArgumentBuilder & isNull(UInt64 column_id, PredicateDataType type); + SearchArgumentBuilder & between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper); + + std::unique_ptr build(); + +private: + SearchArgumentBuilder & start(UInt8 op); + SearchArgumentBuilder & addLeaf(PredicateLeaf leaf); + + std::vector stack; + ExpressionTreePtr root; + std::vector leaves; +}; + +/// A bloom filter of a row group (or a stripe), from the BLOOM_FILTER_UTF8 stream. +class BloomFilter +{ +public: + explicit BloomFilter(const Proto::BloomFilter & proto); + + bool testLong(Int64 value) const; + bool testDouble(double value) const; + bool testBytes(const char * data, size_t size) const; + +private: + bool testHash(Int64 hash) const; + + UInt32 num_hash_functions; + std::vector bits; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.cpp b/src/Processors/Formats/Impl/ORC/Statistics.cpp new file mode 100644 index 000000000000..0b1b4c86cd9b --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.cpp @@ -0,0 +1,462 @@ +#include +#include + +#include + +#include + + +namespace DB::ORC +{ + +namespace +{ + +int compareDecimals(Int128 a, Int32 a_scale, Int128 b, Int32 b_scale) +{ + Int256 left = a; + Int256 right = b; + for (Int32 s = a_scale; s < b_scale; ++s) + left *= 10; + for (Int32 s = b_scale; s < a_scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +std::string decimalToString(Int128 value, Int32 scale) +{ + return Literal::Decimal{value, scale}.toString(); +} + +} + +void StatisticsBuilder::updateInteger(Int64 value) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + if (has_int_sum && __builtin_add_overflow(int_sum, value, &int_sum)) + has_int_sum = false; +} + +void StatisticsBuilder::updateDouble(double value) +{ + if (!has_minimum) + { + has_minimum = true; + double_minimum = double_maximum = value; + } + else + { + double_minimum = std::min(double_minimum, value); + double_maximum = std::max(double_maximum, value); + } + double_sum += value; +} + +void StatisticsBuilder::updateString(std::string_view value) +{ + if (!has_minimum) + { + has_minimum = true; + string_minimum = value; + string_maximum = value; + } + else + { + if (value < std::string_view(string_minimum)) + string_minimum = value; + if (value > std::string_view(string_maximum)) + string_maximum = value; + } + total_length += value.size(); +} + +void StatisticsBuilder::updateBinary(size_t length) +{ + total_length += length; +} + +void StatisticsBuilder::updateBoolean(bool value) +{ + if (value) + ++true_count; +} + +void StatisticsBuilder::updateDate(Int32 value) +{ + updateInteger(value); +} + +void StatisticsBuilder::updateDecimal(Int128 value, Int32 scale) +{ + if (!has_minimum) + { + has_minimum = true; + decimal_minimum = decimal_maximum = value; + decimal_minimum_scale = decimal_maximum_scale = scale; + } + else + { + if (compareDecimals(value, scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = value; + decimal_minimum_scale = scale; + } + if (compareDecimals(value, scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = value; + decimal_maximum_scale = scale; + } + } + + if (has_decimal_sum) + { + Int256 sum = decimal_sum; + Int256 addend = value; + Int32 result_scale = std::max(decimal_sum_scale, scale); + for (Int32 s = decimal_sum_scale; s < result_scale; ++s) + sum *= 10; + for (Int32 s = scale; s < result_scale; ++s) + addend *= 10; + sum += addend; + if (sum > Int256(std::numeric_limits::max()) || sum < Int256(std::numeric_limits::min())) + has_decimal_sum = false; + else + { + decimal_sum = static_cast(sum); + decimal_sum_scale = result_scale; + } + } +} + +void StatisticsBuilder::updateTimestamp(Int64 millis, Int32 nanos) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = millis; + minimum_nanos = maximum_nanos = nanos; + return; + } + if (millis <= int_minimum) + { + if (millis < int_minimum || nanos < minimum_nanos) + minimum_nanos = nanos; + int_minimum = millis; + } + if (millis >= int_maximum) + { + if (millis > int_maximum || nanos > maximum_nanos) + maximum_nanos = nanos; + int_maximum = millis; + } +} + +void StatisticsBuilder::updateCollection(UInt64 children) +{ + Int64 value = static_cast(children); + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + total_children += children; +} + +void StatisticsBuilder::merge(const StatisticsBuilder & other) +{ + number_of_values += other.number_of_values; + has_null |= other.has_null; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + case DATE: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + has_int_sum = has_int_sum && other.has_int_sum; + if (has_int_sum && __builtin_add_overflow(int_sum, other.int_sum, &int_sum)) + has_int_sum = false; + break; + case FLOAT: + case DOUBLE: + if (other.has_minimum) + { + if (!has_minimum) + { + double_minimum = other.double_minimum; + double_maximum = other.double_maximum; + } + else + { + double_minimum = std::min(double_minimum, other.double_minimum); + double_maximum = std::max(double_maximum, other.double_maximum); + } + has_minimum = true; + } + double_sum += other.double_sum; + break; + case STRING: + case CHAR: + case VARCHAR: + if (other.has_minimum) + { + if (!has_minimum) + { + string_minimum = other.string_minimum; + string_maximum = other.string_maximum; + } + else + { + if (other.string_minimum < string_minimum) + string_minimum = other.string_minimum; + if (other.string_maximum > string_maximum) + string_maximum = other.string_maximum; + } + has_minimum = true; + } + total_length += other.total_length; + break; + case BINARY: + total_length += other.total_length; + break; + case BOOLEAN: + true_count += other.true_count; + break; + case DECIMAL: + if (other.has_minimum) + { + if (!has_minimum) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + else + { + if (compareDecimals(other.decimal_minimum, other.decimal_minimum_scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + } + if (compareDecimals(other.decimal_maximum, other.decimal_maximum_scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + } + has_minimum = true; + } + has_decimal_sum = has_decimal_sum && other.has_decimal_sum; + if (has_decimal_sum) + { + /// Reuse the update of the sum without touching the minimum and the maximum. + bool saved_has_minimum = has_minimum; + Int128 saved_min = decimal_minimum; + Int32 saved_min_scale = decimal_minimum_scale; + Int128 saved_max = decimal_maximum; + Int32 saved_max_scale = decimal_maximum_scale; + updateDecimal(other.decimal_sum, other.decimal_sum_scale); + has_minimum = saved_has_minimum; + decimal_minimum = saved_min; + decimal_minimum_scale = saved_min_scale; + decimal_maximum = saved_max; + decimal_maximum_scale = saved_max_scale; + } + break; + case TIMESTAMP: + case TIMESTAMP_INSTANT: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + minimum_nanos = other.minimum_nanos; + maximum_nanos = other.maximum_nanos; + has_minimum = true; + } + else + { + if (other.int_minimum <= int_minimum) + { + if (other.int_minimum < int_minimum || other.minimum_nanos < minimum_nanos) + minimum_nanos = other.minimum_nanos; + int_minimum = other.int_minimum; + } + if (other.int_maximum >= int_maximum) + { + if (other.int_maximum > int_maximum || other.maximum_nanos > maximum_nanos) + maximum_nanos = other.maximum_nanos; + int_maximum = other.int_maximum; + } + } + } + break; + case LIST: + case MAP: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + total_children += other.total_children; + break; + default: + break; + } +} + +void StatisticsBuilder::reset() +{ + *this = StatisticsBuilder(kind); +} + +Proto::ColumnStatistics StatisticsBuilder::toProto() const +{ + Proto::ColumnStatistics res; + res.has_null = has_null; + res.number_of_values = number_of_values; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + { + auto & stats = res.int_statistics.emplace(); + if (has_minimum) + { + stats.minimum = int_minimum; + stats.maximum = int_maximum; + } + if (has_int_sum) + stats.sum = int_sum; + break; + } + case DATE: + { + auto & stats = res.date_statistics.emplace(); + if (has_minimum) + { + stats.minimum = static_cast(int_minimum); + stats.maximum = static_cast(int_maximum); + } + break; + } + case FLOAT: + case DOUBLE: + { + auto & stats = res.double_statistics.emplace(); + if (has_minimum) + { + stats.minimum = double_minimum; + stats.maximum = double_maximum; + } + stats.sum = double_sum; + break; + } + case STRING: + case CHAR: + case VARCHAR: + { + auto & stats = res.string_statistics.emplace(); + if (has_minimum) + { + stats.minimum = string_minimum; + stats.maximum = string_maximum; + } + stats.sum = static_cast(total_length); + break; + } + case BINARY: + res.binary_statistics.emplace().sum = static_cast(total_length); + break; + case BOOLEAN: + res.bucket_statistics.emplace().count.push_back(true_count); + break; + case DECIMAL: + { + auto & stats = res.decimal_statistics.emplace(); + if (has_minimum) + { + stats.minimum = decimalToString(decimal_minimum, decimal_minimum_scale); + stats.maximum = decimalToString(decimal_maximum, decimal_maximum_scale); + } + if (has_decimal_sum) + stats.sum = decimalToString(decimal_sum, decimal_sum_scale); + break; + } + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + auto & stats = res.timestamp_statistics.emplace(); + if (has_minimum) + { + stats.minimum_utc = int_minimum; + stats.maximum_utc = int_maximum; + if (minimum_nanos != 0) + stats.minimum_nanos = static_cast(minimum_nanos) + 1; + if (maximum_nanos != 999999) + stats.maximum_nanos = static_cast(maximum_nanos) + 1; + } + break; + } + case LIST: + case MAP: + { + auto & stats = res.collection_statistics.emplace(); + if (has_minimum) + { + stats.min_children = static_cast(int_minimum); + stats.max_children = static_cast(int_maximum); + } + stats.total_children = total_children; + break; + } + default: + break; + } + return res; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.h b/src/Processors/Formats/Impl/ORC/Statistics.h new file mode 100644 index 000000000000..c00c00e07b94 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.h @@ -0,0 +1,71 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// Accumulates the statistics of a column for a row group, a stripe or the whole file, +/// in the same way as the reference implementation. +class StatisticsBuilder +{ +public: + explicit StatisticsBuilder(TypeKind kind_) : kind(kind_) {} + + void increase(UInt64 count) { number_of_values += count; } + void setHasNull() { has_null = true; } + + void updateInteger(Int64 value); + void updateDouble(double value); + void updateString(std::string_view value); + void updateBinary(size_t length); + void updateBoolean(bool value); + void updateDate(Int32 value); + void updateDecimal(Int128 value, Int32 scale); + /// `millis` since the epoch in UTC, `nanos` is the sub-millisecond part. + void updateTimestamp(Int64 millis, Int32 nanos); + void updateCollection(UInt64 children); + + void merge(const StatisticsBuilder & other); + void reset(); + + Proto::ColumnStatistics toProto() const; + +private: + TypeKind kind; + UInt64 number_of_values = 0; + bool has_null = false; + bool has_minimum = false; + + Int64 int_minimum = 0; + Int64 int_maximum = 0; + Int64 int_sum = 0; + bool has_int_sum = true; + + double double_minimum = 0; + double double_maximum = 0; + double double_sum = 0; + + std::string string_minimum; + std::string string_maximum; + UInt64 total_length = 0; + + UInt64 true_count = 0; + + Int128 decimal_minimum = 0; + Int32 decimal_minimum_scale = 0; + Int128 decimal_maximum = 0; + Int32 decimal_maximum_scale = 0; + Int128 decimal_sum = 0; + Int32 decimal_sum_scale = 0; + bool has_decimal_sum = true; + + Int32 minimum_nanos = 0; + Int32 maximum_nanos = 999999; + + UInt64 total_children = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.cpp b/src/Processors/Formats/Impl/ORC/Stream.cpp new file mode 100644 index 000000000000..275e75915dca --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.cpp @@ -0,0 +1,248 @@ +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +UInt64 PositionProvider::next() +{ + if (index >= positions.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not enough positions in a row index entry of ORC file"); + return positions[index++]; +} + + +InputByteStream::InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_) + : data(data_), length(data_.size()), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +InputByteStream::InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_) + : length(length_), loader(std::move(loader_)), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +std::string_view InputByteStream::getRange(UInt64 offset, UInt64 size) +{ + if (!loader) + return data.substr(offset, size); + + if (offset < window_offset || offset + size > window_offset + data.size()) + { + UInt64 load_size = std::min(length - offset, std::max(size, LAZY_READ_SIZE)); + auto range = loader(offset, load_size); + if (range.data.size() != load_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Loaded {} bytes instead of {} from ORC stream {}", range.data.size(), load_size, name); + window_holder = std::move(range.holder); + data = range.data; + window_offset = offset; + } + return data.substr(offset - window_offset, size); +} + +bool InputByteStream::nextChunk() +{ + while (next_chunk_offset < length) + { + if (compression == CompressionKind::NONE) + { + UInt64 size = length - next_chunk_offset; + if (loader) + size = std::min(size, LAZY_READ_SIZE); + pos = getRange(next_chunk_offset, size).data(); + end = pos + size; + next_chunk_offset += size; + return true; + } + + if (length - next_chunk_offset < COMPRESSION_HEADER_SIZE) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated compression chunk header in ORC stream {}", name); + + const UInt8 * header = reinterpret_cast(getRange(next_chunk_offset, COMPRESSION_HEADER_SIZE).data()); + UInt32 header_value = header[0] | (header[1] << 8) | (header[2] << 16); + bool is_original = header_value & 1; + size_t chunk_length = header_value >> 1; + size_t chunk_offset = next_chunk_offset + COMPRESSION_HEADER_SIZE; + + if (chunk_length > length - chunk_offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Compression chunk of size {} at offset {} goes beyond the end of ORC stream {} of size {}", + chunk_length, next_chunk_offset, name, length); + + next_chunk_offset = chunk_offset + chunk_length; + const char * chunk = getRange(chunk_offset, chunk_length).data(); + + if (is_original) + { + pos = chunk; + end = chunk + chunk_length; + } + else + { + /// The chunk length is at most 8 MiB, so the bound does not overflow. + size_t capacity = std::min(block_size, maxDecompressedSize(compression, chunk, chunk_length)); + if (decompressed.size() < capacity) + decompressed.resize(capacity); + size_t size = decompressChunk(compression, chunk, chunk_length, decompressed.data(), capacity); + pos = decompressed.data(); + end = decompressed.data() + size; + } + + if (pos != end) + return true; + } + + pos = end = nullptr; + return false; +} + +void InputByteStream::readBytes(char * to, size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + memcpy(to, pos, count); + pos += count; + to += count; + n -= count; + } +} + +void InputByteStream::skipBytes(size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + pos += count; + n -= count; + } +} + +void InputByteStream::seek(PositionProvider & positions) +{ + if (compression == CompressionKind::NONE) + { + UInt64 offset = positions.next(); + if (offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", offset, name, length); + next_chunk_offset = offset; + pos = end = nullptr; + nextChunk(); + return; + } + + UInt64 chunk_offset = positions.next(); + UInt64 uncompressed_offset = positions.next(); + if (chunk_offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", chunk_offset, name, length); + + next_chunk_offset = chunk_offset; + pos = end = nullptr; + if (!nextChunk()) + { + if (uncompressed_offset != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {}", uncompressed_offset, name); + return; + } + + if (uncompressed_offset > static_cast(end - pos)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Seek position {} is beyond the end of the compression chunk of size {} in ORC stream {}", + uncompressed_offset, end - pos, name); + pos += uncompressed_offset; +} + +void InputByteStream::throwUnexpectedEnd() const +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected end of ORC stream {}", name); +} + + +OutputByteStream::OutputByteStream(Compressor * compressor_, size_t block_size_) + : compressor(compressor_), block_size(block_size_) +{ + buffer.reserve(std::min(block_size, 64 * 1024)); +} + +void OutputByteStream::write(const char * data, size_t size) +{ + while (size) + { + if (buffer.size() == block_size) + flushChunk(); + size_t count = std::min(size, block_size - buffer.size()); + buffer.append(data, count); + data += count; + size -= count; + } +} + +void OutputByteStream::recordPosition(std::vector & positions) const +{ + if (compressor) + { + positions.push_back(output.size()); + positions.push_back(buffer.size()); + } + else + positions.push_back(output.size() + buffer.size()); +} + +void OutputByteStream::flushChunk() +{ + if (buffer.empty()) + return; + + if (!compressor) + { + output.append(buffer); + buffer.clear(); + return; + } + + size_t header_offset = output.size(); + output.append(COMPRESSION_HEADER_SIZE, '\0'); + size_t compressed_size = compressor->compress(buffer.data(), buffer.size(), output); + + UInt32 header_value = 0; + if (compressed_size) + header_value = static_cast(compressed_size << 1); + else + { + output.append(buffer); + header_value = static_cast((buffer.size() << 1) | 1); + } + + output[header_offset] = static_cast(header_value & 0xFF); + output[header_offset + 1] = static_cast((header_value >> 8) & 0xFF); + output[header_offset + 2] = static_cast((header_value >> 16) & 0xFF); + buffer.clear(); +} + +size_t OutputByteStream::finish() +{ + flushChunk(); + return output.size(); +} + +void OutputByteStream::reset() +{ + buffer.clear(); + output.clear(); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.h b/src/Processors/Formats/Impl/ORC/Stream.h new file mode 100644 index 000000000000..44d209d38321 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace DB::ORC +{ + +/// A sequence of positions from a row index entry, consumed by the streams and the decoders of a +/// column in their order. +class PositionProvider +{ +public: + explicit PositionProvider(const std::vector & positions_) : positions(positions_) {} + UInt64 next(); + +private: + const std::vector & positions; + size_t index = 0; +}; + +/// A piece of a stream loaded from the file. `data` is valid while `holder` is alive. +struct LoadedRange +{ + std::shared_ptr holder; + std::string_view data; +}; + +/// Loads the range `(offset, length)` of a stream from the file. +using RangeLoader = std::function; + +/// A stream of an ORC column, such as PRESENT or DATA, decompressed chunk by chunk. The decoders +/// read from the buffer `[pos, end)` of the current chunk directly. +class InputByteStream +{ +public: + /// The whole stream in memory. `data` must outlive the stream. + InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_); + /// The stream of `length_` bytes is loaded from the file on demand, by `loader_`, a window of + /// at least `LAZY_READ_SIZE` bytes at a time. Used when only some row groups are read. + InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_); + + static constexpr size_t LAZY_READ_SIZE = 1024 * 1024; + + /// Loads the next chunk. Returns false at the end of the stream. + bool nextChunk(); + + bool eof() + { + return pos == end && !nextChunk(); + } + + UInt8 readByte() + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + return static_cast(*pos++); + } + + void readBytes(char * to, size_t n); + void skipBytes(size_t n); + + /// Moves to the position from the row index: one value (the byte offset) for an uncompressed + /// stream, two values (the offset of the compressed chunk and the offset in its decompressed + /// data) for a compressed one. + void seek(PositionProvider & positions); + + [[noreturn]] void throwUnexpectedEnd() const; + + const std::string & getName() const { return name; } + + const char * pos = nullptr; + const char * end = nullptr; + +private: + /// Returns the range `[offset, offset + length)` of the stream. It is valid until the next call. + std::string_view getRange(UInt64 offset, UInt64 length); + + /// The stream in memory, or the currently loaded window of a lazily loaded stream. + std::string_view data; + UInt64 length; + RangeLoader loader; + /// For a lazily loaded stream: the offset of `data` in the stream, and its owner. + UInt64 window_offset = 0; + std::shared_ptr window_holder; + + CompressionKind compression; + size_t block_size; + std::string name; + + /// The offset of the next chunk to read in `data`. + size_t next_chunk_offset = 0; + PODArray decompressed; +}; + +/// Accumulates a stream of an ORC column, compressing it chunk by chunk. +class OutputByteStream +{ +public: + /// `compressor` can be nullptr, which means no compression. + OutputByteStream(Compressor * compressor_, size_t block_size_); + + void writeByte(UInt8 byte) + { + if (buffer.size() == block_size) + flushChunk(); + buffer.push_back(static_cast(byte)); + } + + void write(const char * data, size_t size); + + /// Appends the current position to `positions`, in the format that `InputByteStream::seek` expects. + void recordPosition(std::vector & positions) const; + + /// Finishes the stream and returns its size in bytes. + size_t finish(); + + const std::string & getOutput() const { return output; } + + /// Clears the stream to start a new stripe. + void reset(); + + size_t estimateSize() const { return output.size() + buffer.size(); } + +private: + void flushChunk(); + + Compressor * compressor; + size_t block_size; + std::string buffer; + std::string output; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.cpp b/src/Processors/Formats/Impl/ORC/Timezone.cpp new file mode 100644 index 000000000000..33a1574507d2 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.cpp @@ -0,0 +1,87 @@ +#include + +#include +#include + +#include + +/// The embedded time zone files, see `DateLUTImpl.cpp`. +std::string_view getTimeZone(const char * name); /// NOLINT(misc-use-internal-linkage) + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +TimezoneOffset::TimezoneOffset(const DateLUTImpl & lut_) + : lut(lut_) +{ + const std::string & name = lut.getTimeZone(); + const std::string_view file = getTimeZone(name.c_str()); + /// `Fixed/UTC±HH:MM:SS` zones have no file. On this branch `DateLUT` also loads zones that are not embedded + /// (`libc:` names, the host database), so keep the offsets of `DateLUTImpl` for all of them. + if (file.empty()) + return; + + /// Raw records, as `cctz::time_zone::next_transition` skips no-op ones (Europe/Lisbon has one in 1884). + static constexpr size_t header_size = 44; + size_t pos = 0; + auto check = [&](size_t size) + { + if (size > file.size() - pos) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + }; + auto read_count = [&](size_t index) { return unalignedLoadBigEndian(file.data() + pos + 20 + index * 4); }; + + check(header_size); + if (!file.starts_with("TZif")) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + size_t time_size = 4; + /// Version 2 and later repeat the data with 64-bit times after the 32-bit section. + if (file[4] != '\0') + { + const size_t v1_size = read_count(3) * 5 + read_count(4) * 6 + read_count(5) + read_count(2) * 8 + read_count(1) + read_count(0); + check(header_size + v1_size); + pos += header_size + v1_size; + check(header_size); + time_size = 8; + } + const size_t time_count = read_count(3); + const size_t type_count = read_count(4); + pos += header_size; + check(time_count * (time_size + 1) + type_count * 6); + if (time_count == 0) + return; + + const char * times = file.data() + pos; + const auto * type_indices = reinterpret_cast(times + time_count * time_size); + const char * types = times + time_count * (time_size + 1); + auto type_record = [&](size_t type) + { + if (type >= type_count) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + return types + type * 6; + }; + + first_transition = time_size == 8 ? unalignedLoadBigEndian(times) : unalignedLoadBigEndian(times); + /// The oldest standard time, or the first type if all of them are daylight saving time. + const char * ancient = type_record(0); + for (size_t i = 0; i < time_count; ++i) + { + const char * record = type_record(type_indices[i]); + if (record[4] == 0) + { + ancient = record; + break; + } + } + ancient_offset = unalignedLoadBigEndian(ancient); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.h b/src/Processors/Formats/Impl/ORC/Timezone.h new file mode 100644 index 000000000000..8a7dbd7361fd --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// The UTC offset as in the reference implementation: before the first transition record it is the oldest +/// standard time, not the local mean time (Asia/Shanghai +08:00, not +08:05:43). Shared by reader and writer. +class TimezoneOffset +{ +public: + explicit TimezoneOffset(const DateLUTImpl & lut_); + + Int64 operator()(Int64 t) const { return t < first_transition ? ancient_offset : lut.timezoneOffset(t); } + +private: + const DateLUTImpl & lut; + Int64 first_transition = std::numeric_limits::min(); + Int64 ancient_offset = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.cpp b/src/Processors/Formats/Impl/ORC/Type.cpp new file mode 100644 index 000000000000..b716b8c9ccb1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.cpp @@ -0,0 +1,380 @@ +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int UNKNOWN_TYPE; + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +namespace +{ + +bool isUnquotedFieldName(const std::string & name) +{ + for (char c : name) + if (!isalnum(static_cast(c)) && c != '_') + return false; + return true; +} + +std::string algorithmToString(UInt32 algorithm) +{ + switch (algorithm) + { + case 0: return "spherical"; + case 1: return "vincenty"; + case 2: return "thomas"; + case 3: return "andoyer"; + case 4: return "karney"; + default: return std::to_string(algorithm); + } +} + +/// The same limit as in the reference implementation. +constexpr size_t MAX_TYPE_NESTING_DEPTH = 2000; + +std::unique_ptr convertType(const std::vector & types, UInt64 index, UInt64 & next_id, size_t depth) +{ + checkStackSize(); + + if (depth > MAX_TYPE_NESTING_DEPTH) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: type nesting depth exceeds the limit of {}", MAX_TYPE_NESTING_DEPTH); + + /// The types are listed in pre-order and the column id of each type is its index in the list. + if (index != next_id || index >= types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: the types are not a tree listed in pre-order (type {} is referenced at position {})", + index, next_id); + ++next_id; + + const auto & proto = types[index]; + if (proto.kind > GEOGRAPHY) + throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown ORC type kind {}", proto.kind); + + auto kind = static_cast(proto.kind); + auto result = std::make_unique(kind); + + switch (kind) + { + case LIST: + if (proto.subtypes.size() != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC LIST type that doesn't contain one subtype"); + break; + case MAP: + if (proto.subtypes.size() != 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC MAP type that doesn't contain two subtypes"); + break; + case UNION: + if (proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type that doesn't contain any subtypes"); + /// The tags of a union are bytes. + if (proto.subtypes.size() > 256) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type with {} subtypes, more than 256", proto.subtypes.size()); + break; + case STRUCT: + if (proto.subtypes.size() > proto.field_names.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC STRUCT type that contains less field names than subtypes"); + break; + default: + if (!proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC type {} with subtypes", proto.kind); + break; + } + + if (kind == CHAR || kind == VARCHAR) + result->setMaximumLength(proto.maximum_length.value_or(0)); + if (kind == DECIMAL) + result->setPrecisionAndScale(proto.precision.value_or(0), proto.scale.value_or(0)); + if (kind == GEOMETRY || kind == GEOGRAPHY) + result->setGeospatial(proto.crs.value_or("OGC:CRS84"), proto.algorithm.value_or(0)); + + for (size_t i = 0; i < proto.subtypes.size(); ++i) + { + auto child = convertType(types, proto.subtypes[i], next_id, depth + 1); + if (kind == STRUCT) + result->addStructField(proto.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + + for (const auto & attribute : proto.attributes) + result->setAttribute(attribute.key, attribute.value); + + return result; +} + +void selectChildren(std::vector & selected, const Type & type) +{ + for (UInt64 c = type.getColumnId(); c <= type.getMaximumColumnId(); ++c) + selected[c] = true; +} + +bool selectParents(std::vector & selected, const Type & type) +{ + size_t id = type.getColumnId(); + bool result = selected[id]; + size_t num_selected_subtypes = 0; + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + { + if (selectParents(selected, *type.getSubtype(c))) + { + result = true; + ++num_selected_subtypes; + } + } + selected[id] = result; + + /// The branches of a union are either all selected or all not selected. + if (type.getKind() == UNION && result && num_selected_subtypes > 0 && num_selected_subtypes < type.getSubtypeCount()) + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + selectChildren(selected, *type.getSubtype(c)); + + return result; +} + +} + + +std::string Type::toString() const +{ + switch (kind) + { + case BOOLEAN: return "boolean"; + case BYTE: return "tinyint"; + case SHORT: return "smallint"; + case INT: return "int"; + case LONG: return "bigint"; + case FLOAT: return "float"; + case DOUBLE: return "double"; + case STRING: return "string"; + case BINARY: return "binary"; + case TIMESTAMP: return "timestamp"; + case TIMESTAMP_INSTANT: return "timestamp with local time zone"; + case LIST: return "array<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + ">"; + case MAP: + return "map<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + "," + + (subtypes.size() < 2 ? std::string("void") : subtypes[1]->toString()) + ">"; + case STRUCT: + { + std::string result = "struct<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + if (isUnquotedFieldName(field_names[i])) + result += field_names[i]; + else + { + result += "`"; + for (char c : field_names[i]) + { + if (c == '`') + result += "``"; + else + result += c; + } + result += "`"; + } + result += ":"; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case UNION: + { + std::string result = "uniontype<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case DECIMAL: return "decimal(" + std::to_string(precision) + "," + std::to_string(scale) + ")"; + case DATE: return "date"; + case VARCHAR: return "varchar(" + std::to_string(maximum_length) + ")"; + case CHAR: return "char(" + std::to_string(maximum_length) + ")"; + case GEOMETRY: return "geometry(" + crs + ")"; + case GEOGRAPHY: return "geography(" + crs + "," + algorithmToString(algorithm) + ")"; + } + return "unknown"; +} + +Type * Type::addStructField(const std::string & name, std::unique_ptr field) +{ + field_names.push_back(name); + return addChild(std::move(field)); +} + +Type * Type::addChild(std::unique_ptr child) +{ + subtypes.push_back(std::move(child)); + return subtypes.back().get(); +} + +UInt64 Type::assignIds(UInt64 start) +{ + column_id = start; + UInt64 next = start + 1; + for (auto & subtype : subtypes) + next = subtype->assignIds(next); + maximum_column_id = next - 1; + return next; +} + +void Type::toProto(std::vector & out) const +{ + size_t index = out.size(); + if (index != column_id) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type ids are not assigned in pre-order"); + out.emplace_back(); + { + auto & proto = out.back(); + proto.kind = kind; + for (const auto & subtype : subtypes) + proto.subtypes.push_back(subtype->getColumnId()); + proto.field_names = field_names; + if (kind == CHAR || kind == VARCHAR) + proto.maximum_length = static_cast(maximum_length); + if (kind == DECIMAL) + { + proto.precision = static_cast(precision); + proto.scale = static_cast(scale); + } + for (const auto & [key, value] : attributes) + proto.attributes.push_back({key, value}); + } + /// `out` may be reallocated by the recursive calls, so do not keep the reference. + for (const auto & subtype : subtypes) + subtype->toProto(out); +} + +std::unique_ptr Type::createPrimitiveType(TypeKind kind) +{ + return std::make_unique(kind); +} + +std::unique_ptr Type::createCharType(TypeKind kind, UInt64 maximum_length) +{ + auto result = std::make_unique(kind); + result->maximum_length = maximum_length; + return result; +} + +std::unique_ptr Type::createDecimalType(UInt64 precision, UInt64 scale) +{ + auto result = std::make_unique(DECIMAL); + result->precision = precision; + result->scale = scale; + return result; +} + +std::unique_ptr Type::createStructType() +{ + return std::make_unique(STRUCT); +} + +std::unique_ptr Type::createListType(std::unique_ptr element) +{ + auto result = std::make_unique(LIST); + result->addChild(std::move(element)); + return result; +} + +std::unique_ptr Type::createMapType(std::unique_ptr key, std::unique_ptr value) +{ + auto result = std::make_unique(MAP); + result->addChild(std::move(key)); + result->addChild(std::move(value)); + return result; +} + +std::unique_ptr Type::createUnionType() +{ + return std::make_unique(UNION); +} + +std::unique_ptr Type::fromProto(const std::vector & types) +{ + if (types.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: it has no types"); + UInt64 next_id = 0; + auto root = convertType(types, 0, next_id, 0); + if (next_id != types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: {} of {} types are not reachable from the root type", types.size() - next_id, types.size()); + root->assignIds(0); + return root; +} + +std::unique_ptr Type::buildSelectedType(const Type & type, const std::vector & selected) +{ + if (!selected.at(type.column_id)) + return nullptr; + + auto result = std::make_unique(type.kind); + result->maximum_length = type.maximum_length; + result->precision = type.precision; + result->scale = type.scale; + result->crs = type.crs; + result->algorithm = type.algorithm; + result->attributes = type.attributes; + result->column_id = type.column_id; + result->maximum_column_id = type.maximum_column_id; + + for (size_t i = 0; i < type.subtypes.size(); ++i) + { + auto child = buildSelectedType(*type.subtypes[i], selected); + if (!child) + continue; + if (type.kind == STRUCT) + result->addStructField(type.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + return result; +} + +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids) +{ + std::vector selected(root.getMaximumColumnId() + 1, false); + + /// Find the types by ids with a walk over the tree. + std::vector by_id(selected.size()); + std::vector stack{&root}; + while (!stack.empty()) + { + const Type * type = stack.back(); + stack.pop_back(); + by_id[type->getColumnId()] = type; + for (UInt64 i = 0; i < type->getSubtypeCount(); ++i) + stack.push_back(type->getSubtype(i)); + } + + for (UInt64 id : type_ids) + { + if (id >= selected.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid ORC type id {} selected out of {}", id, selected.size()); + selectChildren(selected, *by_id[id]); + } + + selectParents(selected, root); + selected[0] = true; + return selected; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.h b/src/Processors/Formats/Impl/ORC/Type.h new file mode 100644 index 000000000000..9a30f4455076 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.h @@ -0,0 +1,114 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace DB::ORC +{ + +enum TypeKind : UInt32 +{ + BOOLEAN = 0, + BYTE = 1, + SHORT = 2, + INT = 3, + LONG = 4, + FLOAT = 5, + DOUBLE = 6, + STRING = 7, + BINARY = 8, + TIMESTAMP = 9, + LIST = 10, + MAP = 11, + STRUCT = 12, + UNION = 13, + DECIMAL = 14, + DATE = 15, + VARCHAR = 16, + CHAR = 17, + TIMESTAMP_INSTANT = 18, + GEOMETRY = 19, + GEOGRAPHY = 20, +}; + +/// A node of the type tree of an ORC file. Every node is a column of the file; the column ids are +/// assigned in pre-order, so the subtree of a column `c` occupies the ids `[c, c.getMaximumColumnId()]`. +class Type +{ +public: + explicit Type(TypeKind kind_) : kind(kind_) {} + + TypeKind getKind() const { return kind; } + UInt64 getColumnId() const { return column_id; } + UInt64 getMaximumColumnId() const { return maximum_column_id; } + UInt64 getSubtypeCount() const { return subtypes.size(); } + const Type * getSubtype(UInt64 i) const { return subtypes.at(i).get(); } + /// Only for STRUCT. + const std::string & getFieldName(UInt64 i) const { return field_names.at(i); } + /// Only for CHAR and VARCHAR. + UInt64 getMaximumLength() const { return maximum_length; } + /// Only for DECIMAL. + UInt64 getPrecision() const { return precision; } + UInt64 getScale() const { return scale; } + + bool hasAttributeKey(const std::string & key) const { return attributes.contains(key); } + const std::string & getAttributeValue(const std::string & key) const { return attributes.at(key); } + void setAttribute(const std::string & key, const std::string & value) { attributes[key] = value; } + const std::map & getAttributes() const { return attributes; } + + /// The type name in the same format as in the reference implementation (Hive type names). + std::string toString() const; + + void setMaximumLength(UInt64 value) { maximum_length = value; } + void setPrecisionAndScale(UInt64 precision_, UInt64 scale_) { precision = precision_; scale = scale_; } + void setGeospatial(std::string crs_, UInt32 algorithm_) { crs = std::move(crs_); algorithm = algorithm_; } + + Type * addStructField(const std::string & name, std::unique_ptr field); + Type * addChild(std::unique_ptr child); + + /// Assigns the column ids in pre-order, starting from `start`. Returns the next free id. + UInt64 assignIds(UInt64 start); + + /// Appends the types of this subtree to `out` in pre-order. The ids must be assigned. + void toProto(std::vector & out) const; + + static std::unique_ptr createPrimitiveType(TypeKind kind); + static std::unique_ptr createCharType(TypeKind kind, UInt64 maximum_length); + static std::unique_ptr createDecimalType(UInt64 precision, UInt64 scale); + static std::unique_ptr createStructType(); + static std::unique_ptr createListType(std::unique_ptr element); + static std::unique_ptr createMapType(std::unique_ptr key, std::unique_ptr value); + static std::unique_ptr createUnionType(); + + /// Builds the type tree from the types in the file footer. Throws `INCORRECT_DATA` if they do + /// not form a tree with the ids in pre-order. + static std::unique_ptr fromProto(const std::vector & types); + + /// Builds a copy of the tree with only the selected columns (by id). The parent of every + /// selected column must also be selected. Returns nullptr if the root is not selected. + static std::unique_ptr buildSelectedType(const Type & type, const std::vector & selected); + +private: + TypeKind kind; + UInt64 column_id = 0; + UInt64 maximum_column_id = 0; + std::vector> subtypes; + std::vector field_names; + UInt64 maximum_length = 0; + UInt64 precision = 0; + UInt64 scale = 0; + std::string crs; + UInt32 algorithm = 0; + std::map attributes; +}; + +/// The column selection with the same semantics as in the reference implementation: +/// selecting a column selects its whole subtree, and then all parents of the selected columns +/// are selected. If only some branches of a UNION are selected, all its branches are selected. +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids); + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.cpp b/src/Processors/Formats/Impl/ORC/Vector.cpp new file mode 100644 index 000000000000..ce7b5cdac8de --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int NOT_IMPLEMENTED; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values) +{ + const size_t dictionary_size = dictionary.size(); + const auto & dictionary_offsets = dictionary.getOffsets(); + const auto & dictionary_chars = dictionary.getChars(); + + auto result = ColumnString::create(); + auto & chars = result->getChars(); + auto & offsets = result->getOffsets(); + offsets.resize(num_values); + + size_t total = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + Int64 entry = index[i]; + if (entry < 0 || static_cast(entry) >= dictionary_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC dictionary index {} at row {} is out of range [0, {})", entry, i, dictionary_size); + total += dictionary_offsets[entry] - dictionary_offsets[entry - 1]; + } + offsets[i] = total; + } + + chars.resize(total); + UInt8 * out = chars.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + size_t begin = dictionary_offsets[index[i] - 1]; + size_t size = dictionary_offsets[index[i]] - begin; + memcpy(out, dictionary_chars.data() + begin, size); + out += size; + } + } + return result; +} + +ColumnPtr getStringColumn(const StringVectorBatch & batch) +{ + if (!batch.isEncoded) + return batch.column; + + const auto & encoded = typeid_cast(batch); + return decodeDictionary( + assert_cast(*encoded.dictionary->column), + encoded.index.data(), + batch.hasNulls ? batch.notNull.data() : nullptr, + batch.numElements); +} + +std::unique_ptr createRowBatch(const Type & type, bool encoded) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(); + case BYTE: + return std::make_unique(); + case SHORT: + return std::make_unique(); + case INT: + return std::make_unique(); + case LONG: + case DATE: + return std::make_unique(); + case FLOAT: + return std::make_unique(); + case DOUBLE: + return std::make_unique(); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + if (encoded) + return std::make_unique(); + return std::make_unique(); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + return std::make_unique(); + case STRUCT: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addField(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case LIST: + { + auto result = std::make_unique(); + if (type.getSubtypeCount()) + result->elements = createRowBatch(*type.getSubtype(0), encoded); + return result; + } + case MAP: + { + auto result = std::make_unique(); + if (type.getSubtypeCount() > 0) + result->keys = createRowBatch(*type.getSubtype(0), encoded); + if (type.getSubtypeCount() > 1) + result->elements = createRowBatch(*type.getSubtype(1), encoded); + return result; + } + case UNION: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addChild(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case DECIMAL: + if (type.getPrecision() == 0 || type.getPrecision() > 18) + return std::make_unique(); + return std::make_unique(); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.h b/src/Processors/Formats/Impl/ORC/Vector.h new file mode 100644 index 000000000000..1e44a80a61d1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.h @@ -0,0 +1,174 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +/// Batches of column values filled by the reader. The values of the primitive types are decoded +/// directly into ClickHouse columns, which the conversion to the requested types takes without +/// copying. The structure follows the reference implementation: a batch has the null mask of its +/// values, and the batches of the compound types have the batches of their children. + +namespace DB::ORC +{ + +struct ColumnVectorBatch +{ + ColumnVectorBatch() = default; + virtual ~ColumnVectorBatch() = default; + + ColumnVectorBatch(const ColumnVectorBatch &) = delete; + ColumnVectorBatch & operator=(const ColumnVectorBatch &) = delete; + + /// Prepares the batch for `num_values` values. + void reset(size_t num_values) + { + numElements = num_values; + notNull.resize(num_values); + } + + size_t numElements = 0; + /// Non-zero for the non-null values, valid only if `hasNulls`. + PaddedPODArray notNull; + bool hasNulls = false; + /// For string batches read with lazy dictionary decoding. + bool isEncoded = false; +}; + +/// The values of a primitive type in a ClickHouse column (`ColumnVector` of `T`). The null values are zeros. +template +struct NumericVectorBatch : public ColumnVectorBatch +{ + using Container = PaddedPODArray; + + /// Creates a new column for the next values: the previous column can be still referenced. + Container & prepareColumn(size_t num_values) + { + auto new_column = ColumnVector::create(num_values); + auto & data = new_column->getData(); + column = std::move(new_column); + return data; + } + + const Container & getData() const { return assert_cast &>(*column).getData(); } + + ColumnPtr column; +}; + +/// BOOLEAN: 0 or 1. +using BoolVectorBatch = NumericVectorBatch; +using ByteVectorBatch = NumericVectorBatch; +using ShortVectorBatch = NumericVectorBatch; +using IntVectorBatch = NumericVectorBatch; +/// LONG and DATE (days since the epoch, not narrowed, so that the range can be checked). +using LongVectorBatch = NumericVectorBatch; +using FloatVectorBatch = NumericVectorBatch; +using DoubleVectorBatch = NumericVectorBatch; + +/// The values in a `ColumnString`. The null values are empty strings. +struct StringVectorBatch : public ColumnVectorBatch +{ + ColumnPtr column; +}; + +struct StringDictionary +{ + /// The entries of the dictionary. + ColumnPtr column; +}; + +/// A string batch with the dictionary indices, without decoding the values. `column` is not set. +struct EncodedStringVectorBatch : public StringVectorBatch +{ + std::shared_ptr dictionary; + PaddedPODArray index; +}; + +/// Builds a `ColumnString` from the dictionary entries by the indices (the null values are empty strings). +/// Throws `INCORRECT_DATA` if an index is out of range. +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values); + +/// Returns the values of a string batch as a `ColumnString`, decoding the dictionary for an encoded batch. +ColumnPtr getStringColumn(const StringVectorBatch & batch); + +struct StructVectorBatch : public ColumnVectorBatch +{ + void addField(std::unique_ptr field) + { + fields.push_back(field.get()); + owned_fields.push_back(std::move(field)); + } + + std::vector fields; + +private: + std::vector> owned_fields; +}; + +/// LIST and MAP: the end offsets of the values in the children, as in `ColumnArray`. +struct ListVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr elements; +}; + +struct MapVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr keys; + std::unique_ptr elements; +}; + +struct UnionVectorBatch : public ColumnVectorBatch +{ + void addChild(std::unique_ptr child) + { + children.push_back(child.get()); + owned_children.push_back(std::move(child)); + } + + /// The branch of each value. + PaddedPODArray tags; + /// The position of each value in its branch. + PaddedPODArray offsets; + std::vector children; + +private: + std::vector> owned_children; +}; + +/// For DECIMAL with the precision at most 18. +struct Decimal64VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +/// For DECIMAL with the precision above 18 or unspecified (zero). +struct Decimal128VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +struct TimestampVectorBatch : public ColumnVectorBatch +{ + /// Seconds since the epoch in UTC. + PaddedPODArray data; + PaddedPODArray nanoseconds; +}; + +/// Creates a batch tree matching the type. With `encoded`, the string columns get +/// `EncodedStringVectorBatch`, which the reader fills without decoding the dictionaries. +std::unique_ptr createRowBatch(const Type & type, bool encoded = false); + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.cpp b/src/Processors/Formats/Impl/ORC/Writer.cpp new file mode 100644 index 000000000000..cfab65634955 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.cpp @@ -0,0 +1,1493 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; + extern const int LOGICAL_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE; +} +} + +namespace DB::ORC +{ + +struct WriterContext +{ + Compressor * compressor = nullptr; + size_t block_size = 0; + bool enable_index = false; + double dictionary_key_size_threshold = 0; + std::optional timezone_offset; + bool timezone_is_utc = true; + /// 2015-01-01 00:00:00 in the time zone of the writer, as seconds since the epoch. + Int64 epoch_offset = 0; +}; + +namespace +{ + +struct StreamData +{ + Proto::StreamKind kind; + UInt32 column; + std::string data; +}; + +std::string compressWhole(const WriterContext & context, const std::string & data) +{ + OutputByteStream stream(context.compressor, context.block_size); + stream.write(data.data(), data.size()); + stream.finish(); + return stream.getOutput(); +} + +} + +class ColumnWriter +{ +public: + ColumnWriter(const Type & type, WriterContext & context_) + : column_id(type.getColumnId()) + , context(context_) + , present_stream(context.compressor, context.block_size) + , present_encoder(present_stream) + , index_statistics(type.getKind()) + , stripe_statistics(type.getKind()) + , file_statistics(type.getKind()) + { + } + + virtual ~ColumnWriter() = default; + + /// Must be called by the most derived constructor, after the streams are created. + void init() + { + if (context.enable_index) + recordPositions(); + } + + /// Adds the values `[offset, offset + num_values)` of `column`, which is not `Nullable`. + /// `null_map` (1 for a null) and `parent_null_map` (1 for a null in the parent struct, for which + /// no value is written at all) are for these values only, so they start at the first value. + virtual void add(const IColumn & /*column*/, const UInt8 * null_map, size_t /*offset*/, size_t num_values, const UInt8 * parent_null_map) + { + addPresent(null_map, num_values, parent_null_map); + } + + /// Writes the PRESENT stream for the values. + void addPresent(const UInt8 * null_map, size_t num_values, const UInt8 * parent_null_map) + { + for (size_t i = 0; i < num_values; ++i) + { + if (parent_null_map && parent_null_map[i]) + continue; + present_encoder.write(!null_map || !null_map[i]); + } + if (null_map) + { + for (size_t i = 0; i < num_values && !has_null_value; ++i) + if (null_map[i]) + has_null_value = true; + } + } + + virtual void createRowIndexEntry() + { + entries.push_back(Entry{std::move(current_present_positions), std::move(current_data_positions), index_statistics.toProto()}); + current_present_positions.clear(); + current_data_positions.clear(); + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + recordPositions(); + } + + virtual void mergeRowGroupStatsIntoStripeStats() + { + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + } + + /// Encodes the deferred data of the stripe. + virtual void finalizeStripe() {} + + virtual void writeIndex(std::vector & streams) + { + Proto::RowIndex index; + for (const auto & entry : entries) + { + auto & proto_entry = index.entry.emplace_back(); + /// The positions of the PRESENT stream are written only if the stream is written. + if (has_null_value) + proto_entry.positions = entry.present_positions; + proto_entry.positions.insert(proto_entry.positions.end(), entry.data_positions.begin(), entry.data_positions.end()); + proto_entry.statistics = entry.statistics; + } + streams.push_back({Proto::StreamKind::ROW_INDEX, static_cast(column_id), compressWhole(context, index.serialize())}); + } + + virtual void flush(std::vector & streams) + { + present_encoder.flush(); + present_stream.finish(); + if (has_null_value) + streams.push_back({Proto::StreamKind::PRESENT, static_cast(column_id), present_stream.getOutput()}); + } + + virtual void getColumnEncodings(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + + virtual void getStripeStatistics(std::vector & stats) const + { + stats.push_back(stripe_statistics.toProto()); + } + + virtual void getFileStatistics(std::vector & stats) const + { + stats.push_back(file_statistics.toProto()); + } + + virtual void mergeStripeStatsIntoFileStats() + { + file_statistics.merge(stripe_statistics); + stripe_statistics.reset(); + } + + virtual size_t estimateSize() const + { + return present_stream.estimateSize(); + } + + /// Starts a new stripe. + virtual void reset() + { + present_stream.reset(); + has_null_value = false; + entries.clear(); + current_present_positions.clear(); + current_data_positions.clear(); + resetStreams(); + if (context.enable_index) + recordPositions(); + } + +protected: + /// Appends the positions of the data streams, in the order the reader seeks them. + virtual void recordDataPositions(std::vector & positions) = 0; + /// Clears the data streams for a new stripe. + virtual void resetStreams() = 0; + + /// The number of the non-null values, also updates the statistics with the count. + size_t countValues(const UInt8 * null_map, size_t num_values) + { + size_t count = num_values; + if (null_map) + { + count = 0; + for (size_t i = 0; i < num_values; ++i) + count += !null_map[i]; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + return count; + } + + struct Entry + { + std::vector present_positions; + std::vector data_positions; + Proto::ColumnStatistics statistics; + }; + + const UInt64 column_id; + WriterContext & context; + OutputByteStream present_stream; + BooleanRleEncoder present_encoder; + bool has_null_value = false; + StatisticsBuilder index_statistics; + StatisticsBuilder stripe_statistics; + StatisticsBuilder file_statistics; + std::vector entries; + +private: + void recordPositions() + { + present_encoder.recordPosition(current_present_positions); + recordDataPositions(current_data_positions); + } + + std::vector current_present_positions; + std::vector current_data_positions; +}; + +namespace +{ + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type, WriterContext & context); + +/// Adds the values of a column that can be `Nullable`. The values that are null in the parent +/// (`outer_null_map`, for the fields of a struct) are null as well. +void addColumn( + ColumnWriter & writer, const IColumn & column, const UInt8 * outer_null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) +{ + if (const auto * nullable = typeid_cast(&column)) + { + const UInt8 * null_map = nullable->getNullMapData().data() + offset; + if (!outer_null_map) + { + writer.add(nullable->getNestedColumn(), null_map, offset, num_values, parent_null_map); + return; + } + PaddedPODArray merged(num_values); + for (size_t i = 0; i < num_values; ++i) + merged[i] = null_map[i] | outer_null_map[i]; + writer.add(nullable->getNestedColumn(), merged.data(), offset, num_values, parent_null_map); + return; + } + writer.add(column, outer_null_map, offset, num_values, parent_null_map); +} + +/// The raw values of a column with fixed-size values. +template +const T * getRawValues(const IColumn & column) +{ + auto raw = column.getRawData(); + if (column.sizeOfValueIfFixed() != sizeof(T)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} with values of size {} for ORC (expected {})", + column.getName(), column.sizeOfValueIfFixed(), sizeof(T)); + return reinterpret_cast(raw.data()); +} + +/// The value of the integer column (of any width up to 8 bytes) as a signed number of the same width, +/// as ORC does not have unsigned types. +Int64 readSignedValue(const char * data, size_t width, size_t row) +{ + switch (width) + { + case 1: return unalignedLoad(data + row); + case 2: return unalignedLoad(data + row * 2); + case 4: return unalignedLoad(data + row * 4); + default: return unalignedLoad(data + row * 8); + } +} + +/// The writers that have children call the same methods for them. +class CompoundColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void createRowIndexEntry() override + { + ColumnWriter::createRowIndexEntry(); + for (auto & child : children) + child->createRowIndexEntry(); + } + + void mergeRowGroupStatsIntoStripeStats() override + { + ColumnWriter::mergeRowGroupStatsIntoStripeStats(); + for (auto & child : children) + child->mergeRowGroupStatsIntoStripeStats(); + } + + void finalizeStripe() override + { + for (auto & child : children) + child->finalizeStripe(); + } + + void writeIndex(std::vector & streams) override + { + ColumnWriter::writeIndex(streams); + for (auto & child : children) + child->writeIndex(streams); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + flushOwnStreams(streams); + for (auto & child : children) + child->flush(streams); + } + + void getColumnEncodings(std::vector & encodings) const override + { + getOwnColumnEncoding(encodings); + for (const auto & child : children) + child->getColumnEncodings(encodings); + } + + void getStripeStatistics(std::vector & stats) const override + { + ColumnWriter::getStripeStatistics(stats); + for (const auto & child : children) + child->getStripeStatistics(stats); + } + + void getFileStatistics(std::vector & stats) const override + { + ColumnWriter::getFileStatistics(stats); + for (const auto & child : children) + child->getFileStatistics(stats); + } + + void mergeStripeStatsIntoFileStats() override + { + ColumnWriter::mergeStripeStatsIntoFileStats(); + for (auto & child : children) + child->mergeStripeStatsIntoFileStats(); + } + + size_t estimateSize() const override + { + size_t size = ColumnWriter::estimateSize() + estimateOwnSize(); + for (const auto & child : children) + size += child->estimateSize(); + return size; + } + + void reset() override + { + ColumnWriter::reset(); + for (auto & child : children) + (*child).reset(); + } + +protected: + virtual void flushOwnStreams(std::vector &) {} + virtual void getOwnColumnEncoding(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + virtual size_t estimateOwnSize() const { return 0; } + + std::vector> children; +}; + +class StructColumnWriter final : public CompoundColumnWriter +{ +public: + StructColumnWriter(const Type & type, const DataTypes & field_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + { + if (field_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC struct {} has {} fields, the ClickHouse type has {}", + type.toString(), type.getSubtypeCount(), field_types.size()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), field_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & tuple = assert_cast(column); + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The fields of the null values are null, and they are not written. + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], tuple.getColumn(i), null_map, offset, num_values, null_map); + countValues(null_map, num_values); + } + + /// Adds the rows of the root struct, which are the columns of the file. + void addRoot(const Columns & columns, size_t offset, size_t num_values) + { + if (columns.size() != children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Expected {} columns for ORC, got {}", children.size(), columns.size()); + addPresent(nullptr, num_values, nullptr); + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], *columns[i], nullptr, offset, num_values, nullptr); + countValues(nullptr, num_values); + } + +protected: + void recordDataPositions(std::vector &) override {} + void resetStreams() override {} +}; + +template +class CollectionColumnWriter final : public CompoundColumnWriter +{ +public: + CollectionColumnWriter(const Type & type, const DataTypes & child_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , length_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + { + if (child_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), child_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const ColumnArray & array = is_map ? assert_cast(column).getNestedColumn() : assert_cast(column); + /// The offsets of `ColumnArray` are the end offsets, and the one before the first is zero. + const auto & offsets = array.getOffsets(); + + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + + UInt64 element_offset = offsets[static_cast(offset) - 1]; + UInt64 total_elements = offsets[offset + num_values - 1] - element_offset; + + if constexpr (is_map) + { + const auto & key_value = assert_cast(array.getData()); + addColumn(*children[0], key_value.getColumn(0), nullptr, element_offset, total_elements, nullptr); + addColumn(*children[1], key_value.getColumn(1), nullptr, element_offset, total_elements, nullptr); + } + else + { + addColumn(*children[0], array.getData(), nullptr, element_offset, total_elements, nullptr); + } + + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + UInt64 length = offsets[row] - offsets[static_cast(row) - 1]; + length_encoder.write(static_cast(length)); + index_statistics.updateCollection(length); + ++count; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + length_encoder.recordPosition(positions); + } + + void resetStreams() override + { + length_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + + void getOwnColumnEncoding(std::vector & encodings) const override + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT_V2, 0, {}}); + } + + size_t estimateOwnSize() const override { return length_stream.estimateSize(); } + +private: + OutputByteStream length_stream; + IntRleEncoderV2 length_encoder; +}; + +class UnionColumnWriter final : public CompoundColumnWriter +{ +public: + /// The branches of the union are in the same order as the variants of the `Variant` type, + /// so the global discriminator of a value is its tag. + UnionColumnWriter(const Type & type, const DataTypes & variant_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , tag_stream(context.compressor, context.block_size) + , tag_encoder(tag_stream) + { + if (variant_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC union {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), variant_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & variant = assert_cast(column); + + /// A `NULL` of `Variant` is a null value of the union. + PaddedPODArray union_null_map(num_values); + bool has_nulls = false; + for (size_t i = 0; i < num_values; ++i) + { + union_null_map[i] = (null_map && null_map[i]) || variant.globalDiscriminatorAt(offset + i) == ColumnVariant::NULL_DISCRIMINATOR; + has_nulls |= union_null_map[i]; + } + const UInt8 * union_nulls = has_nulls ? union_null_map.data() : nullptr; + + ColumnWriter::add(column, union_nulls, offset, num_values, parent_null_map); + + std::vector child_offset(children.size(), -1); + std::vector child_length(children.size(), 0); + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (union_nulls && union_nulls[i]) + continue; + size_t row = offset + i; + auto tag = variant.globalDiscriminatorAt(row); + if (tag >= children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid union tag {} for union with {} children", static_cast(tag), children.size()); + if (child_offset[tag] == -1) + child_offset[tag] = static_cast(variant.offsetAt(row)); + ++child_length[tag]; + tag_encoder.write(static_cast(tag)); + ++count; + } + + /// The values of each branch are consecutive in its column. + for (size_t i = 0; i < children.size(); ++i) + if (child_length[i]) + addColumn(*children[i], variant.getVariantByGlobalDiscriminator(i), nullptr, static_cast(child_offset[i]), child_length[i], nullptr); + + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + tag_encoder.recordPosition(positions); + } + + void resetStreams() override + { + tag_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + tag_encoder.flush(); + tag_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), tag_stream.getOutput()}); + } + + size_t estimateOwnSize() const override { return tag_stream.estimateSize(); } + +private: + OutputByteStream tag_stream; + ByteRleEncoder tag_encoder; +}; + + +/// The writers of the primitive columns. +class PrimitiveColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void getColumnEncodings(std::vector & encodings) const override + { + encodings.push_back({encoding_kind, dictionary_size, {}}); + } + +protected: + Proto::ColumnEncodingKind encoding_kind = Proto::ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; +}; + +class BooleanColumnWriter final : public PrimitiveColumnWriter +{ +public: + BooleanColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const UInt8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(data[i] != 0); + index_statistics.updateBoolean(data[i] != 0); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + BooleanRleEncoder encoder; +}; + +class ByteColumnWriter final : public PrimitiveColumnWriter +{ +public: + ByteColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width. + const Int8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(static_cast(data[i])); + index_statistics.updateInteger(data[i]); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + ByteRleEncoder encoder; +}; + +/// SHORT, INT, LONG and DATE. +class IntegerColumnWriter final : public PrimitiveColumnWriter +{ +public: + IntegerColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream, true) + , is_date(type.getKind() == DATE) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width (except `Date`). + const size_t width = column.sizeOfValueIfFixed(); + if (width != 2 && width != 4 && width != 8) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC integer", column.getName()); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + /// `Date` is the unsigned number of days (up to 2149), which must not wrap around + /// to the negative ones after 2059. `Date32` is signed, as the other integers. + Int64 value = (is_date && width == 2) + ? unalignedLoad(data + (offset + i) * sizeof(UInt16)) + : readSignedValue(data, width, offset + i); + encoder.write(value); + if (is_date) + index_statistics.updateDate(static_cast(value)); + else + index_statistics.updateInteger(value); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + IntRleEncoderV2 encoder; + const bool is_date; +}; + +template +class FloatingColumnWriter final : public PrimitiveColumnWriter +{ +public: + FloatingColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const ItemType * data = getRawValues(column) + offset; + if (!null_map && std::endian::native == std::endian::little) + { + data_stream.write(reinterpret_cast(data), num_values * sizeof(ItemType)); + for (size_t i = 0; i < num_values; ++i) + index_statistics.updateDouble(static_cast(data[i])); + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + ItemType value = data[i]; + if constexpr (std::endian::native == std::endian::big) + value = std::bit_cast(std::byteswap(std::bit_cast>(value))); + data_stream.write(reinterpret_cast(&value), sizeof(value)); + index_statistics.updateDouble(static_cast(data[i])); + } + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { data_stream.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; +}; + +/// STRING, VARCHAR, CHAR and BINARY. The values of a stripe are kept in memory and encoded at the +/// end of the stripe, either directly or with a dictionary. +class StringColumnWriter final : public PrimitiveColumnWriter +{ +public: + StringColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , is_binary(type.getKind() == BINARY) + , data_stream(context.compressor, context.block_size) + , length_stream(context.compressor, context.block_size) + , dictionary_data_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + , index_encoder(data_stream, false) + { + /// The binary columns never use dictionaries, as in the reference implementation. + if (is_binary || context.dictionary_key_size_threshold <= 0) + use_dictionary = false; + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `String`, or the raw bytes of the values of fixed size (`FixedString`, `IPv6`, big integers). + auto add_value = [&](std::string_view value) + { + blob.append(value); + value_ends.push_back(blob.size()); + if (is_binary) + index_statistics.updateBinary(value.size()); + else + index_statistics.updateString(value); + }; + + if (const auto * strings = typeid_cast(&column)) + { + const auto & offsets = strings->getOffsets(); + const auto * chars = reinterpret_cast(strings->getChars().data()); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + add_value(std::string_view(chars + offsets[row - 1], offsets[row] - offsets[row - 1])); + } + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + add_value(column.getDataAt(offset + i)); + } + } + countValues(null_map, num_values); + } + + void createRowIndexEntry() override + { + if (!use_dictionary) + decideDictionary(); + ColumnWriter::createRowIndexEntry(); + } + + void finalizeStripe() override + { + if (!use_dictionary) + decideDictionary(); + + /// The start of the group without an entry is not needed. + group_starts.resize(entries.size()); + + if (*use_dictionary) + encodeWithDictionary(); + else + encodeDirect(); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + if (*use_dictionary) + { + index_encoder.flush(); + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + dictionary_data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::DICTIONARY_DATA, static_cast(column_id), dictionary_data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + else + { + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + blob.size() + value_ends.size() * sizeof(UInt64); + } + +protected: + void recordDataPositions(std::vector &) override + { + /// The positions are known only after the encoding, at the end of the stripe. + group_starts.push_back(value_ends.size()); + } + + void resetStreams() override + { + data_stream.reset(); + length_stream.reset(); + dictionary_data_stream.reset(); + blob.clear(); + value_ends.clear(); + group_starts.clear(); + dictionary_size = 0; + } + +private: + std::string_view getValue(size_t i) const + { + size_t begin = i ? value_ends[i - 1] : 0; + return std::string_view(blob.data() + begin, value_ends[i] - begin); + } + + /// The decision is made once for the file, by the values of the first row group (or the first + /// stripe without the row index), as in the reference implementation. + void decideDictionary() + { + std::unordered_set distinct; + for (size_t i = 0; i < value_ends.size(); ++i) + distinct.insert(getValue(i)); + /// Compare as doubles: the threshold is user-provided and the product may not fit in `size_t`. + use_dictionary = static_cast(distinct.size()) <= static_cast(value_ends.size()) * context.dictionary_key_size_threshold; + } + + void encodeDirect() + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + auto & positions = entries[group].data_positions; + data_stream.recordPosition(positions); + length_encoder.recordPosition(positions); + ++group; + } + if (i == value_ends.size()) + break; + auto value = getValue(i); + data_stream.write(value.data(), value.size()); + length_encoder.write(static_cast(value.size())); + } + } + + void encodeWithDictionary() + { + encoding_kind = Proto::ColumnEncodingKind::DICTIONARY_V2; + + /// The dictionary is sorted, as in the reference implementation. + std::unordered_map index_of; + std::vector keys; + for (size_t i = 0; i < value_ends.size(); ++i) + { + auto value = getValue(i); + if (index_of.emplace(value, 0).second) + keys.push_back(value); + } + std::sort(keys.begin(), keys.end()); + for (size_t i = 0; i < keys.size(); ++i) + index_of[keys[i]] = static_cast(i); + dictionary_size = static_cast(keys.size()); + + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + index_encoder.recordPosition(entries[group].data_positions); + ++group; + } + if (i == value_ends.size()) + break; + index_encoder.write(index_of[getValue(i)]); + } + + for (const auto & key : keys) + { + dictionary_data_stream.write(key.data(), key.size()); + length_encoder.write(static_cast(key.size())); + } + } + + const bool is_binary; + std::optional use_dictionary; + OutputByteStream data_stream; + OutputByteStream length_stream; + OutputByteStream dictionary_data_stream; + IntRleEncoderV2 length_encoder; + IntRleEncoderV2 index_encoder; + + std::string blob; + std::vector value_ends; + /// The index of the first value of each row group. + std::vector group_starts; +}; + +class TimestampColumnWriter final : public PrimitiveColumnWriter +{ +public: + /// `scale` is of `DateTime64`, or nullopt for `DateTime` (`UInt32` seconds). + TimestampColumnWriter(const Type & type, std::optional scale_, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(scale_) + , seconds_stream(context.compressor, context.block_size) + , nanos_stream(context.compressor, context.block_size) + , seconds_encoder(seconds_stream, true) + , nanos_encoder(nanos_stream, false) + , is_utc(type.getKind() == TIMESTAMP_INSTANT || context.timezone_is_utc) + , epoch_offset(type.getKind() == TIMESTAMP_INSTANT ? 1420070400 : context.epoch_offset) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const char * data = column.getRawData().data(); + const Int64 multiplier = scale ? common::exp10_i64(static_cast(*scale)) : 1; + const Int64 nanos_multiplier = scale ? common::exp10_i64(9 - static_cast(*scale)) : 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + Int64 secs = 0; + Int64 nano = 0; + if (scale) + { + /// For the values before the epoch, the nanoseconds are negative (as in the Arrow ORC adapter). + Int64 value = unalignedLoad(data + (offset + i) * sizeof(Int64)); + secs = value / multiplier; + nano = (value % multiplier) * nanos_multiplier; + } + else + { + secs = unalignedLoad(data + (offset + i) * sizeof(UInt32)); + nano = 0; + } + + /// The statistics have the milliseconds rounded down and the rest of the nanoseconds, which is not negative. + Int64 nano_millis = nano / 1000000; + Int64 nano_rest = nano % 1000000; + if (nano_rest < 0) + { + nano_rest += 1000000; + --nano_millis; + } + Int64 utc_seconds = secs; + Int64 millis = 0; + Int64 encoded_seconds = 0; + if ((!is_utc && common::addOverflow(secs, (*context.timezone_offset)(secs), utc_seconds)) + || common::mulOverflow(utc_seconds, Int64{1000}, millis) + || common::addOverflow(millis, nano_millis, millis) + || common::subOverflow(secs + (secs < 0 && nano > 999999), epoch_offset, encoded_seconds)) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp (seconds={}, nanoseconds={}) in ORC column {} is out of the range supported by the ORC format", secs, nano, column_id); + index_statistics.updateTimestamp(millis, static_cast(nano_rest)); + + seconds_encoder.write(encoded_seconds); + nanos_encoder.write(formatNanos(nano)); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + seconds_encoder.flush(); + seconds_stream.finish(); + nanos_encoder.flush(); + nanos_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), seconds_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), nanos_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + seconds_stream.estimateSize() + nanos_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + seconds_encoder.recordPosition(positions); + nanos_encoder.recordPosition(positions); + } + + void resetStreams() override + { + seconds_stream.reset(); + nanos_stream.reset(); + } + +private: + /// The trailing zeros are removed and their number is kept in the lowest 3 bits. + static Int64 formatNanos(Int64 nanos) + { + if (nanos == 0) + return 0; + if (nanos % 100 != 0) + return nanos << 3; + nanos /= 100; + Int64 trailing_zeros = 1; + while (nanos % 10 == 0 && trailing_zeros < 7) + { + nanos /= 10; + ++trailing_zeros; + } + return (nanos << 3) | trailing_zeros; + } + + const std::optional scale; + OutputByteStream seconds_stream; + OutputByteStream nanos_stream; + IntRleEncoderV2 seconds_encoder; + IntRleEncoderV2 nanos_encoder; + const bool is_utc; + const Int64 epoch_offset; +}; + +class DecimalColumnWriter final : public PrimitiveColumnWriter +{ +public: + DecimalColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(static_cast(type.getScale())) + , value_stream(context.compressor, context.block_size) + , scale_stream(context.compressor, context.block_size) + , scale_encoder(scale_stream, true) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `Decimal32`, `Decimal64` or `Decimal128`. + const size_t width = column.sizeOfValueIfFixed(); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + Int128 value; + if (width == 16) + value = unalignedLoad(data + row * 16); + else if (width == 8) + value = unalignedLoad(data + row * 8); + else if (width == 4) + value = unalignedLoad(data + row * 4); + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC decimal", column.getName()); + + /// Zigzag-encoded base 128 varint. + UInt128 encoded = (static_cast(value) << 1) ^ static_cast(value >> 127); + while (encoded >= 0x80) + { + char byte = static_cast(static_cast(encoded & 0x7F) | 0x80); + value_stream.write(&byte, 1); + encoded >>= 7; + } + char last = static_cast(static_cast(encoded)); + value_stream.write(&last, 1); + + scale_encoder.write(scale); + index_statistics.updateDecimal(value, scale); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + value_stream.finish(); + scale_encoder.flush(); + scale_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), value_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), scale_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + value_stream.estimateSize() + scale_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + value_stream.recordPosition(positions); + scale_encoder.recordPosition(positions); + } + + void resetStreams() override + { + value_stream.reset(); + scale_stream.reset(); + } + +private: + const Int32 scale; + OutputByteStream value_stream; + OutputByteStream scale_stream; + IntRleEncoderV2 scale_encoder; +}; + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type_with_nulls, WriterContext & context) +{ + checkStackSize(); + + /// The nulls are handled by `addColumn`. + DataTypePtr data_type = removeNullable(data_type_with_nulls); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, context); + case BYTE: + return std::make_unique(type, context); + case SHORT: + case INT: + case LONG: + case DATE: + return std::make_unique(type, context); + case FLOAT: + return std::make_unique>(type, context); + case DOUBLE: + return std::make_unique>(type, context); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + return std::make_unique(type, context); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + std::optional scale; + if (const auto * datetime64 = typeid_cast(data_type.get())) + scale = datetime64->getScale(); + return std::make_unique(type, scale, context); + } + case DECIMAL: + return std::make_unique(type, context); + case STRUCT: + return std::make_unique(type, assert_cast(*data_type).getElements(), context); + case LIST: + return std::make_unique>( + type, DataTypes{assert_cast(*data_type).getNestedType()}, context); + case MAP: + { + const auto & map_type = assert_cast(*data_type); + return std::make_unique>(type, DataTypes{map_type.getKeyType(), map_type.getValueType()}, context); + } + case UNION: + return std::make_unique(type, assert_cast(*data_type).getVariants(), context); + case GEOMETRY: + case GEOGRAPHY: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC type {} is not supported", type.toString()); +} + +} + + +Writer::Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_) + : out(out_), options(options_) +{ + if (options.compression_block_size == 0 || options.compression_block_size >= (1ULL << 23)) + throw Exception(ErrorCodes::BAD_ARGUMENTS, + "The ORC compression block size must be positive and less than 8 MiB, got {}", options.compression_block_size); + + schema = Type::buildSelectedType(schema_, std::vector(schema_.getMaximumColumnId() + 1, true)); + schema->assignIds(0); + + compressor = createCompressor(options.compression); + + context = std::make_unique(); + context->compressor = compressor.get(); + context->block_size = options.compression_block_size; + context->enable_index = options.row_index_stride > 0; + context->dictionary_key_size_threshold = options.dictionary_key_size_threshold; + context->timezone_offset.emplace(DateLUT::instance(options.timezone_name)); + context->timezone_is_utc = options.timezone_name == "GMT" || options.timezone_name == "UTC"; + static constexpr Int64 UTC_2015_01_01 = 1420070400; + context->epoch_offset = UTC_2015_01_01 - (*context->timezone_offset)(UTC_2015_01_01); + + if (schema->getKind() != STRUCT) + throw Exception(ErrorCodes::LOGICAL_ERROR, "The root type of ORC file must be a struct"); + column_writer = std::make_unique(*schema, column_types, *context); + + write("ORC"); + footer.header_length = current_offset; + footer.row_index_stride = static_cast(options.row_index_stride); + /// The identifier of the C++ writer of the reference implementation, which this writer follows. + footer.writer = 1; + footer.software_version = "ClickHouse"; + schema->toProto(footer.types); +} + +Writer::~Writer() = default; + +void Writer::write(const std::string & data) +{ + out.write(data.data(), data.size()); + current_offset += data.size(); +} + +void Writer::add(const Columns & columns, size_t num_rows) +{ + auto & root = typeid_cast(*column_writer); + + if (context->enable_index) + { + size_t position = 0; + while (position < num_rows) + { + size_t chunk = std::min(num_rows - position, options.row_index_stride - index_rows); + root.addRoot(columns, position, chunk); + position += chunk; + index_rows += chunk; + stripe_rows += chunk; + if (index_rows >= options.row_index_stride) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + } + } + else + { + stripe_rows += num_rows; + root.addRoot(columns, 0, num_rows); + } + + if (column_writer->estimateSize() >= options.stripe_size) + writeStripe(); +} + +void Writer::writeStripe() +{ + if (context->enable_index && index_rows != 0) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + else + column_writer->mergeRowGroupStatsIntoStripeStats(); + + column_writer->finalizeStripe(); + + std::vector index_streams; + std::vector data_streams; + if (context->enable_index) + column_writer->writeIndex(index_streams); + column_writer->flush(data_streams); + + Proto::StripeFooter stripe_footer; + UInt64 index_length = 0; + UInt64 data_length = 0; + for (const auto & s : index_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + index_length += s.data.size(); + } + for (const auto & s : data_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + data_length += s.data.size(); + } + column_writer->getColumnEncodings(stripe_footer.columns); + stripe_footer.writer_timezone = options.timezone_name; + + auto & stripe_statistics = metadata.stripe_stats.emplace_back(); + column_writer->getStripeStatistics(stripe_statistics.col_stats); + column_writer->mergeStripeStatsIntoFileStats(); + + Proto::StripeInformation stripe; + stripe.offset = current_offset; + + for (const auto & s : index_streams) + write(s.data); + for (const auto & s : data_streams) + write(s.data); + + std::string footer_data = compressWhole(*context, stripe_footer.serialize()); + write(footer_data); + + stripe.index_length = index_length; + stripe.data_length = data_length; + stripe.footer_length = footer_data.size(); + stripe.number_of_rows = stripe_rows; + footer.stripes.push_back(stripe); + + total_rows += stripe_rows; + stripe_rows = 0; + index_rows = 0; + (*column_writer).reset(); +} + +void Writer::close() +{ + if (stripe_rows > 0) + writeStripe(); + + Proto::PostScript postscript; + + /// The content length covers only the stripes, not the metadata section with the stripe statistics. + footer.content_length = current_offset - footer.header_length; + + std::string metadata_data = compressWhole(*context, metadata.serialize()); + write(metadata_data); + postscript.metadata_length = metadata_data.size(); + + footer.number_of_rows = total_rows; + footer.statistics.clear(); + column_writer->getFileStatistics(footer.statistics); + std::string footer_data = compressWhole(*context, footer.serialize()); + write(footer_data); + + postscript.footer_length = footer_data.size(); + postscript.compression = options.compression; + postscript.compression_block_size = options.compression_block_size; + postscript.version = {0, 12}; + /// ORC-135: the timestamp statistics are in UTC. + postscript.writer_version = 6; + postscript.magic = "ORC"; + std::string postscript_data = postscript.serialize(); + if (postscript_data.size() > 255) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC postscript is too large: {} bytes", postscript_data.size()); + write(postscript_data); + write(std::string(1, static_cast(postscript_data.size()))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.h b/src/Processors/Formats/Impl/ORC/Writer.h new file mode 100644 index 000000000000..111c20ac0fab --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +class OutputStream +{ +public: + virtual ~OutputStream() = default; + virtual void write(const void * buf, size_t length) = 0; +}; + +struct WriterOptions +{ + CompressionKind compression = CompressionKind::ZSTD; + UInt64 compression_block_size = 256 * 1024; + /// The number of rows between the row index entries; 0 means no row index. + UInt64 row_index_stride = 10000; + /// Use the dictionary encoding for a string column if the number of distinct values in the + /// first row group is at most this fraction of the number of values. 0 disables the dictionaries. + double dictionary_key_size_threshold = 0.0; + /// The time zone of the writer, which is written into the stripe footers. + std::string timezone_name = "GMT"; + /// A stripe is written when the estimated size of its data reaches this size. + UInt64 stripe_size = 64 * 1024 * 1024; +}; + +class ColumnWriter; +struct WriterContext; + +class Writer +{ +public: + /// `column_types` are the ClickHouse types (without `LowCardinality`) of the columns of the file, + /// which are the fields of `schema` (a struct). The values are converted as follows: + /// the unsigned integers are written as the signed ones of the same width (but `Date` as is); + /// `DateTime` and `DateTime64` as TIMESTAMP; `FixedString`, `IPv6` and the big integers + /// as their raw bytes; `Variant` as UNION with the branches in the order of its variants. + Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_); + ~Writer(); + + /// Adds the rows of the columns (in the order of the fields of the schema). + void add(const Columns & columns, size_t num_rows); + + /// Writes the remaining data and the file footer. + void close(); + +private: + void writeStripe(); + void write(const std::string & data); + + std::unique_ptr schema; + OutputStream & out; + WriterOptions options; + std::unique_ptr compressor; + std::unique_ptr context; + std::unique_ptr column_writer; + + Proto::Footer footer; + Proto::Metadata metadata; + UInt64 current_offset = 0; + UInt64 stripe_rows = 0; + UInt64 index_rows = 0; + UInt64 total_rows = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp deleted file mode 100644 index 95d9cd537d74..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp +++ /dev/null @@ -1,276 +0,0 @@ -#include -#include - -#if USE_ORC -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -namespace DB -{ - -namespace ErrorCodes -{ - extern const int BAD_ARGUMENTS; - extern const int CANNOT_READ_ALL_DATA; -} - -ORCBlockInputFormat::ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_) - : IInputFormat(std::move(header_), &in_) - , block_missing_values(getPort().getHeader().columns()) - , format_settings(format_settings_) - , skip_stripes(format_settings.orc.skip_stripes) -{ -} - -Chunk ORCBlockInputFormat::read() -{ - block_missing_values.clear(); - - if (!file_reader) - prepareReader(); - - if (is_stopped) - return {}; - - for (; stripe_current < stripe_total && skip_stripes.contains(stripe_current); ++stripe_current) - ; - - if (stripe_current >= stripe_total) - return {}; - - if (need_only_count) - return getChunkForCount(file_reader->GetRawORCReader()->getStripe(stripe_current++)->getNumberOfRows()); - - auto batch_result = file_reader->ReadStripe(stripe_current, include_indices); - if (!batch_result.ok()) - throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Failed to create batch reader: {}", batch_result.status().ToString()); - - auto batch = batch_result.ValueOrDie(); - if (!batch) - return {}; - - /// Validate validity bitmaps before building the table: Table::FromRecordBatches computes - /// each column's null_count, and Arrow derives an unknown FieldNode null_count by scanning - /// the bitmap over the declared length, which reads out of bounds on a truncated bitmap. - ArrowColumnToCHColumn::checkRecordBatchValidityBitmaps(*batch); - - auto table_result = arrow::Table::FromRecordBatches({batch}); - if (!table_result.ok()) - throw Exception( - ErrorCodes::CANNOT_READ_ALL_DATA, "Error while reading batch of ORC data: {}", table_result.status().ToString()); - - /// We should extract the number of rows directly from the stripe, because in case when - /// record batch contains 0 columns (for example if we requested only columns that - /// are not presented in data) the number of rows in record batch will be 0. - size_t num_rows = file_reader->GetRawORCReader()->getStripe(stripe_current)->getNumberOfRows(); - - const auto & table = table_result.ValueOrDie(); - if (!table || !num_rows) - return {}; - - approx_bytes_read_for_chunk = file_reader->GetRawORCReader()->getStripe(stripe_current)->getDataLength(); - ++stripe_current; - - /// If defaults_for_omitted_fields is true, calculate the default values from default expression for omitted fields. - /// Otherwise fill the missing columns with zero values of its type. - BlockMissingValues * block_missing_values_ptr = format_settings.defaults_for_omitted_fields ? &block_missing_values : nullptr; - std::shared_ptr metadata; - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueOrDie(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected error while reading parquet metadata {}", status.status().message()); - - return arrow_column_to_ch_column->arrowTableToCHChunk(table, num_rows, metadata, block_missing_values_ptr); -} - -void ORCBlockInputFormat::resetParser() -{ - IInputFormat::resetParser(); - - file_reader.reset(); - include_indices.clear(); - block_missing_values.clear(); -} - -const BlockMissingValues * ORCBlockInputFormat::getMissingValues() const -{ - return &block_missing_values; -} - - -static void getFileReaderAndSchema( - ReadBuffer & in, - std::unique_ptr & file_reader, - std::shared_ptr & schema, - const FormatSettings & format_settings, - std::atomic & is_stopped) -{ - auto arrow_file = asArrowFile(in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES); - if (is_stopped) - return; - - auto result = arrow::adapters::orc::ORCFileReader::Open(arrow_file, ArrowMemoryPool::instance()); - if (!result.ok()) - throw Exception::createDeprecated(result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - file_reader = std::move(result).ValueOrDie(); - - auto read_schema_result = file_reader->ReadSchema(); - if (!read_schema_result.ok()) - throw Exception::createDeprecated(read_schema_result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - schema = std::move(read_schema_result).ValueOrDie(); -} - -void ORCBlockInputFormat::prepareReader() -{ - std::shared_ptr schema; - getFileReaderAndSchema(*in, file_reader, schema, format_settings, is_stopped); - if (is_stopped) - return; - - stripe_total = static_cast(file_reader->NumberOfStripes()); - stripe_current = 0; - - arrow_column_to_ch_column = std::make_unique( - getPort().getHeader(), - "ORC", - format_settings, - std::nullopt, - std::nullopt, - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.date_time_overflow_behavior, - format_settings.parquet.allow_geoparquet_parser, - format_settings.orc.case_insensitive_column_matching); - - const bool ignore_case = format_settings.orc.case_insensitive_column_matching; - std::unordered_set nested_table_names = Nested::getAllTableNames(getPort().getHeader(), ignore_case); - for (int i = 0; i < schema->num_fields(); ++i) - { - const auto & name = schema->field(i)->name(); - if (getPort().getHeader().has(name, ignore_case) || nested_table_names.contains(ignore_case ? boost::to_lower_copy(name) : name)) - include_indices.push_back(i); - } -} - -ORCSchemaReader::ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_) - : ISchemaReader(in_), format_settings(format_settings_) -{ -} - -void ORCSchemaReader::initializeIfNeeded() -{ - if (file_reader) - return; - - std::atomic is_stopped = 0; - getFileReaderAndSchema(in, file_reader, schema, format_settings, is_stopped); - - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueUnsafe(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Error while reading incorrect metadata of ORC {}", status.status().message()); -} - -NamesAndTypesList ORCSchemaReader::readSchema() -{ - initializeIfNeeded(); - - auto header = ArrowColumnToCHColumn::arrowSchemaToCHHeader( - *schema, - metadata, - "ORC", - format_settings, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.schema_inference_make_columns_nullable != 0, - false, - format_settings.parquet.allow_geoparquet_parser); - if (format_settings.schema_inference_make_columns_nullable == 1) - return getNamesAndRecursivelyNullableTypes(header, format_settings); - return header.getNamesAndTypesList(); -} - -std::optional ORCSchemaReader::readNumberOrRows() -{ - initializeIfNeeded(); - return file_reader->NumberOfRows(); -} - -void registerInputFormatORC(FormatFactory & factory) -{ - factory.registerRandomAccessInputFormat( - "ORC", - [](ReadBuffer & buf, - const Block & sample, - const FormatSettings & settings, - const ReadSettings & read_settings, - bool is_remote_fs, - FormatParserSharedResourcesPtr, - FormatFilterInfoPtr format_filter_info) - { - InputFormatPtr res; - if (settings.orc.use_fast_decoder) - { - const bool has_file_size = isBufferWithFileSize(buf); - auto * seekable_in = dynamic_cast(&buf); - const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in - && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; - const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; - res = std::make_shared( - buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); - } - else - res = std::make_shared(buf, std::make_shared(sample), settings); - - return res; - }); - factory.markFormatSupportsSubsetOfColumns("ORC"); -} - -void registerORCSchemaReader(FormatFactory & factory) -{ - factory.registerSchemaReader( - "ORC", - [](ReadBuffer & buf, const FormatSettings & settings) - { - SchemaReaderPtr res; - if (settings.orc.use_fast_decoder) - res = std::make_shared(buf, settings); - else - res = std::make_shared(buf, settings); - - return res; - } - ); - - factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) - { - return fmt::format("schema_inference_make_columns_nullable={}", settings.schema_inference_make_columns_nullable); - }); -} - -} -#else - -namespace DB -{ - class FormatFactory; - void registerInputFormatORC(FormatFactory &) - { - } - - void registerORCSchemaReader(FormatFactory &) - { - } -} - -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.h b/src/Processors/Formats/Impl/ORCBlockInputFormat.h deleted file mode 100644 index 622a6276c344..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once -#include "config.h" -#if USE_ORC - -#include -#include -#include -#include - -#include - -namespace arrow::adapters::orc -{ - class ORCFileReader; -} - -namespace DB -{ - -class ArrowColumnToCHColumn; - -class ORCBlockInputFormat : public IInputFormat -{ -public: - ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_); - - String getName() const override { return "ORCBlockInputFormat"; } - - void resetParser() override; - - const BlockMissingValues * getMissingValues() const override; - - size_t getApproxBytesReadForChunk() const override { return approx_bytes_read_for_chunk; } - -protected: - Chunk read() override; - - void onCancel() noexcept override - { - is_stopped = 1; - } - -private: - void prepareReader(); - - // TODO: check that this class implements every part of its parent - - std::unique_ptr file_reader; - - std::unique_ptr arrow_column_to_ch_column; - - // indices of columns to read from ORC file - std::vector include_indices; - - BlockMissingValues block_missing_values; - size_t approx_bytes_read_for_chunk = 0; - - const FormatSettings format_settings; - const std::unordered_set & skip_stripes; - - int stripe_total = 0; - int stripe_current = 0; - - std::atomic is_stopped{0}; -}; - -class ORCSchemaReader : public ISchemaReader -{ -public: - ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); - - NamesAndTypesList readSchema() override; - std::optional readNumberOrRows() override; - -private: - void initializeIfNeeded(); - - std::unique_ptr file_reader; - std::shared_ptr metadata; - std::shared_ptr schema; - const FormatSettings format_settings; -}; - -} -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp index b9f8bd463152..acf3371b9249 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp @@ -1,5 +1,9 @@ #include +#include + +#include + #if USE_ORC #include @@ -11,6 +15,7 @@ #include #include #include +#include #include #include @@ -20,8 +25,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -38,495 +45,257 @@ namespace ErrorCodes namespace { -orc::CompressionKind getORCCompression(FormatSettings::ORCCompression method) +ORC::CompressionKind getORCCompression(FormatSettings::ORCCompression method) { if (method == FormatSettings::ORCCompression::NONE) - return orc::CompressionKind::CompressionKind_NONE; + return ORC::CompressionKind::NONE; #if USE_SNAPPY if (method == FormatSettings::ORCCompression::SNAPPY) - return orc::CompressionKind::CompressionKind_SNAPPY; + return ORC::CompressionKind::SNAPPY; #endif if (method == FormatSettings::ORCCompression::ZSTD) - return orc::CompressionKind::CompressionKind_ZSTD; + return ORC::CompressionKind::ZSTD; if (method == FormatSettings::ORCCompression::LZ4) - return orc::CompressionKind::CompressionKind_LZ4; + return ORC::CompressionKind::LZ4; if (method == FormatSettings::ORCCompression::ZLIB) - return orc::CompressionKind::CompressionKind_ZLIB; + return ORC::CompressionKind::ZLIB; throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported compression method"); } -} - -ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} - -uint64_t ORCOutputStream::getLength() const +/// Two ORC types get the same key exactly when `parseORCType` (NativeORCBlockInputFormat.cpp) reads +/// them back as the same ClickHouse type: `BINARY` and `STRING` both read as `String`, and a nested +/// `UNION` reads as a `Variant`, which sorts its branches, while ORC keeps them positional. +/// A field name is length-prefixed so a name containing `:` or `,` cannot forge another key. +String orcTypeDedupKey(const ORC::Type & type) { - return out.count(); + const auto kind = type.getKind(); + if (kind == ORC::TypeKind::BINARY || kind == ORC::TypeKind::STRING) + return "string"; + if (kind == ORC::TypeKind::DECIMAL) + return fmt::format("decimal({},{})", type.getPrecision(), type.getScale()); + + std::vector children; + for (size_t i = 0; i < type.getSubtypeCount(); ++i) + { + auto child = orcTypeDedupKey(*type.getSubtype(i)); + if (kind == ORC::TypeKind::STRUCT) + child = fmt::format("{}:{}:{}", type.getFieldName(i).size(), type.getFieldName(i), child); + children.push_back(std::move(child)); + } + if (kind == ORC::TypeKind::UNION) + std::sort(children.begin(), children.end()); + /// Every remaining kind the writer emits is a parameterless primitive mapping to a distinct + /// ClickHouse type, so for those the kind alone is the key and there are no children. + return fmt::format("{}<{}>", static_cast(kind), fmt::join(children, ",")); } -uint64_t ORCOutputStream::getNaturalWriteSize() const -{ - out.nextIfAtEnd(); - return out.available(); } +ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} + void ORCOutputStream::write(const void* buf, size_t length) { out.write(static_cast(buf), length); } -ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_) +ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_) : IOutputFormat(header_, out_) , format_settings{format_settings_} , output_stream(out_) + , column_mapper(std::move(column_mapper_)) { for (const auto & type : header_->getDataTypes()) data_types.push_back(recursiveRemoveLowCardinality(type)); } -std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type) +std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type, const String & column_path) { - switch (type->getTypeId()) + /// Nullable(T) maps to the same ORC node as T; only the Iceberg `required` flag differs. + bool required = !type->isNullable(); + const DataTypePtr unwrapped = removeNullable(type); + + std::unique_ptr result; + switch (unwrapped->getTypeId()) { case TypeIndex::UInt8: { - if (isBool(type)) - return orc::createPrimitiveType(orc::TypeKind::BOOLEAN); - return orc::createPrimitiveType(orc::TypeKind::BYTE); + if (isBool(unwrapped)) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BOOLEAN); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum8: [[fallthrough]]; case TypeIndex::Int8: { - return orc::createPrimitiveType(orc::TypeKind::BYTE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum16: [[fallthrough]]; case TypeIndex::UInt16: [[fallthrough]]; case TypeIndex::Int16: { - return orc::createPrimitiveType(orc::TypeKind::SHORT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::SHORT); + break; } case TypeIndex::UInt32: [[fallthrough]]; case TypeIndex::IPv4: [[fallthrough]]; case TypeIndex::Int32: { - return orc::createPrimitiveType(orc::TypeKind::INT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::INT); + break; } case TypeIndex::UInt64: [[fallthrough]]; case TypeIndex::Int64: { - return orc::createPrimitiveType(orc::TypeKind::LONG); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::LONG); + break; } case TypeIndex::Float32: { - return orc::createPrimitiveType(orc::TypeKind::FLOAT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::FLOAT); + break; } case TypeIndex::Float64: { - return orc::createPrimitiveType(orc::TypeKind::DOUBLE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DOUBLE); + break; } case TypeIndex::Date32: [[fallthrough]]; case TypeIndex::Date: { - return orc::createPrimitiveType(orc::TypeKind::DATE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DATE); + break; } case TypeIndex::DateTime: [[fallthrough]]; case TypeIndex::DateTime64: { - return orc::createPrimitiveType(orc::TypeKind::TIMESTAMP); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::TIMESTAMP); + break; } case TypeIndex::Int128: [[fallthrough]]; case TypeIndex::UInt128: [[fallthrough]]; case TypeIndex::Int256: [[fallthrough]]; case TypeIndex::UInt256: [[fallthrough]]; case TypeIndex::Decimal256: - return orc::createPrimitiveType(orc::TypeKind::BINARY); - case TypeIndex::FixedString: [[fallthrough]]; - case TypeIndex::String: - { - if (format_settings.orc.output_string_as_string) - return orc::createPrimitiveType(orc::TypeKind::STRING); - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::IPv6: - { - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::Nullable: - { - return getORCType(removeNullable(type)); - } - case TypeIndex::Array: - { - const auto * array_type = assert_cast(type.get()); - return orc::createListType(getORCType(array_type->getNestedType())); - } - case TypeIndex::Decimal32: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal64: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal128: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Tuple: - { - const auto * tuple_type = assert_cast(type.get()); - const auto & nested_names = tuple_type->getElementNames(); - const auto & nested_types = tuple_type->getElements(); - auto struct_type = orc::createStructType(); - for (size_t i = 0; i < nested_types.size(); ++i) - struct_type->addStructField(nested_names[i], getORCType(nested_types[i])); - return struct_type; - } - case TypeIndex::Map: - { - const auto * map_type = assert_cast(type.get()); - return orc::createMapType( - getORCType(map_type->getKeyType()), - getORCType(map_type->getValueType()) - ); - } - default: - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); - } - } -} - -template -void ORCBlockOutputFormat::writeNumbers( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - NumberVectorBatch & number_orc_column = dynamic_cast(orc_column); - const auto & number_column = assert_cast &>(column); - - number_orc_column.data.resize(number_column.size()); - for (size_t i = 0; i != number_column.size(); ++i) - number_orc_column.data[i] = convert(number_column.getElement(i)); -} - -template -void ORCBlockOutputFormat::writeDecimals( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - DecimalVectorBatch & decimal_orc_column = dynamic_cast(orc_column); - const auto & decimal_column = assert_cast &>(column); - const auto * decimal_type = assert_cast *>(type.get()); - decimal_orc_column.precision = decimal_type->getPrecision(); - decimal_orc_column.scale = decimal_type->getScale(); - decimal_orc_column.resize(decimal_column.size()); - - decimal_orc_column.values.resize(decimal_column.size()); - for (size_t i = 0; i != decimal_column.size(); ++i) - decimal_orc_column.values[i] = convert(decimal_column.getElement(i).value); -} - -template -void ORCBlockOutputFormat::writeStrings( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * null_bytemap) -{ - orc::StringVectorBatch & string_orc_column = dynamic_cast(orc_column); - const auto & string_column = assert_cast(column); - - string_orc_column.data.resize(string_column.size()); - string_orc_column.length.resize(string_column.size()); - for (size_t i = 0; i != string_column.size(); ++i) - { - const std::string_view string = string_column.getDataAt(i); - string_orc_column.data[i] = (null_bytemap && (*null_bytemap)[i]) ? nullptr : const_cast(string.data()); - string_orc_column.length[i] = string.size(); - } -} - -template -void ORCBlockOutputFormat::writeDateTimes( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - GetSecondsFunc get_seconds, - GetNanosecondsFunc get_nanoseconds) -{ - orc::TimestampVectorBatch & timestamp_orc_column = dynamic_cast(orc_column); - const auto & timestamp_column = assert_cast(column); - - timestamp_orc_column.data.resize(timestamp_column.size()); - timestamp_orc_column.nanoseconds.resize(timestamp_column.size()); - for (size_t i = 0; i != timestamp_column.size(); ++i) - { - timestamp_orc_column.data[i] = static_cast(get_seconds(timestamp_column.getElement(i))); - timestamp_orc_column.nanoseconds[i] = static_cast(get_nanoseconds(timestamp_column.getElement(i))); - } -} - -void ORCBlockOutputFormat::writeColumn( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * null_bytemap) -{ - size_t rows = column.size(); - orc_column.resize(rows); - orc_column.numElements = rows; - - /// Calculate orc_column.hasNulls - if (null_bytemap) - orc_column.hasNulls = !memoryIsZero(null_bytemap->data(), 0, null_bytemap->size()); - else - orc_column.hasNulls = false; - - /// Fill orc_column.notNull - if (orc_column.hasNulls) - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = !(*null_bytemap)[i]; - } - else - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = 1; - } - - /// ORC doesn't have unsigned types, so cast everything to signed and sign-extend to Int64 to - /// make the ORC library calculate min and max correctly. - switch (type->getTypeId()) - { - case TypeIndex::Enum8: [[fallthrough]]; - case TypeIndex::Int8: - { - /// Note: Explicit cast to avoid clang-tidy error: 'signed char' to 'long' conversion; consider casting to 'unsigned char' first. - writeNumbers(orc_column, column, null_bytemap, [](const Int8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::UInt8: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::Enum16: [[fallthrough]]; - case TypeIndex::Int16: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int16 & value){ return value; }); - break; - } - case TypeIndex::Date: [[fallthrough]]; - case TypeIndex::UInt16: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt16 & value){ return Int64(Int16(value)); }); - break; - } - case TypeIndex::Date32: [[fallthrough]]; - case TypeIndex::Int32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int32 & value){ return value; }); - break; - } - case TypeIndex::UInt32: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt32 & value){ return Int64(Int32(value)); }); - break; - } - case TypeIndex::IPv4: - { - writeNumbers(orc_column, column, null_bytemap, [](const IPv4 & value){ return Int64(Int32(value.toUnderType())); }); - break; - } - case TypeIndex::Int64: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int64 & value){ return value; }); - break; - } - case TypeIndex::UInt64: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt64 & value){ return value; }); - break; - } - case TypeIndex::Int128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Int256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Float32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Float32 & value){ return value; }); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; - } - case TypeIndex::Float64: + case TypeIndex::String: { - writeNumbers(orc_column, column, null_bytemap, [](const Float64 & value){ return value; }); + bool force_string = format_settings.orc.output_string_as_string; + result = ORC::Type::createPrimitiveType(force_string ? ORC::TypeKind::STRING : ORC::TypeKind::BINARY); break; } case TypeIndex::FixedString: { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::String: - { - writeStrings(orc_column, column, null_bytemap); + /// Iceberg `fixed[L]` (FixedString) must stay ORC `binary`, so for Iceberg writes + /// force `binary` regardless of the setting; keep the setting-driven choice otherwise. + if (format_settings.orc.output_string_as_string && !column_mapper) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::STRING); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } case TypeIndex::IPv6: { - writeStrings(orc_column, column, null_bytemap); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } - case TypeIndex::DateTime: + case TypeIndex::Array: { - writeDateTimes( - orc_column, - column, null_bytemap, - [](UInt32 value){ return value; }, - [](UInt32){ return 0; }); + const auto * array_type = assert_cast(unwrapped.get()); + result = ORC::Type::createListType(getORCType(array_type->getNestedType(), Nested::concatenateName(column_path, "element"))); break; } - case TypeIndex::DateTime64: + case TypeIndex::Decimal32: { - const auto * timestamp_type = assert_cast(type.get()); - UInt32 scale = timestamp_type->getScale(); - writeDateTimes( - orc_column, - column, - null_bytemap, - [scale](Int64 value) { return value / Int64(std::pow(10, scale)); }, - [scale](Int64 value) { return (value % Int64(std::pow(10, scale))) * Int64(std::pow(10, 9 - scale)); }); - break; - } - case TypeIndex::Decimal32: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int32 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal64: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int64 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal128: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int128 value){ return orc::Int128(static_cast(value >> 64), static_cast((value << 64) >> 64)); }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } - case TypeIndex::Decimal256: + case TypeIndex::Tuple: { - writeStrings>(orc_column, column, null_bytemap); + const auto * tuple_type = assert_cast(unwrapped.get()); + const auto & nested_names = tuple_type->getElementNames(); + const auto & nested_types = tuple_type->getElements(); + auto struct_type = ORC::Type::createStructType(); + for (size_t i = 0; i < nested_types.size(); ++i) + struct_type->addStructField(nested_names[i], getORCType(nested_types[i], Nested::concatenateName(column_path, nested_names[i]))); + result = std::move(struct_type); break; } - case TypeIndex::Nullable: + case TypeIndex::Map: { - chassert(!null_bytemap); - const auto & nullable_column = assert_cast(column); - const PaddedPODArray & new_null_bytemap = assert_cast &>(*nullable_column.getNullMapColumnPtr()).getData(); - auto nested_type = removeNullable(type); - writeColumn(orc_column, nullable_column.getNestedColumn(), nested_type, &new_null_bytemap); + const auto * map_type = assert_cast(unwrapped.get()); + result = ORC::Type::createMapType( + getORCType(map_type->getKeyType(), Nested::concatenateName(column_path, "key")), + getORCType(map_type->getValueType(), Nested::concatenateName(column_path, "value")) + ); break; } - case TypeIndex::Array: - { - orc::ListVectorBatch & list_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column); - auto nested_type = assert_cast(*type).getNestedType(); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - list_orc_column.offsets.resize(column_size + 1); - - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - list_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - list_orc_column.offsets[i + 1] = offsets[i]; - - orc::ColumnVectorBatch & nested_orc_column = *list_orc_column.elements; - writeColumn(nested_orc_column, list_column.getData(), nested_type, nullptr); + case TypeIndex::Variant: + { + const auto & variant_type = assert_cast(*unwrapped); + auto union_type = ORC::Type::createUnionType(); + /// ORC keeps one physical stream per union branch and identifies a branch only by its + /// ORC type, so two variants that map to the same ORC type (e.g. `Int32` and `UInt32`, + /// both ORC `int`) would produce a union with duplicate branches, which the reader + /// rejects. Branches whose ORC types merely read back as one ClickHouse type collide the + /// same way, so they are keyed by `orcTypeDedupKey` rather than by the ORC type itself. + std::unordered_map> variant_by_orc_type; + /// A union child is addressed by its type name, the way a `Variant` subcolumn is + /// (`v.Int32`). Iceberg has no union type, so no field id is expected to be found there. + for (const auto & nested_type : variant_type.getVariants()) + { + auto child_type = getORCType(nested_type, Nested::concatenateName(column_path, nested_type->getName())); + auto [it, inserted] = variant_by_orc_type.emplace( + orcTypeDedupKey(*child_type), std::pair{nested_type->getName(), child_type->toString()}); + if (!inserted) + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Type {} is not supported for ORC output format: variant {} is written as ORC type '{}' and variant {} as " + "'{}', which are read back as the same type, and ORC unions with duplicate branch types cannot be read back", + unwrapped->getName(), it->second.first, it->second.second, nested_type->getName(), child_type->toString()); + union_type->addChild(std::move(child_type)); + } + result = std::move(union_type); break; } - case TypeIndex::Tuple: + default: { - orc::StructVectorBatch & struct_orc_column = dynamic_cast(orc_column); - const auto & tuple_column = assert_cast(column); - auto nested_types = assert_cast(type.get())->getElements(); - for (size_t i = 0; i != tuple_column.tupleSize(); ++i) - writeColumn(*struct_orc_column.fields[i], tuple_column.getColumn(i), nested_types[i], nullptr); - break; + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", unwrapped->getName()); } - case TypeIndex::Map: - { - orc::MapVectorBatch & map_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column).getNestedColumn(); - const auto & map_type = assert_cast(*type); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - - map_orc_column.offsets.resize(column_size + 1); - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - map_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - map_orc_column.offsets[i + 1] = offsets[i]; - - const auto nested_columns = assert_cast(list_column.getDataPtr().get())->getColumns(); - - orc::ColumnVectorBatch & keys_orc_column = *map_orc_column.keys; - auto key_type = map_type.getKeyType(); - writeColumn(keys_orc_column, *nested_columns[0], key_type, nullptr); + } - orc::ColumnVectorBatch & values_orc_column = *map_orc_column.elements; - auto value_type = map_type.getValueType(); - writeColumn(values_orc_column, *nested_columns[1], value_type, nullptr); - break; + /// Attach Iceberg field-id attributes so spec-compliant readers project columns by id. + if (column_mapper) + { + const auto & encoding = column_mapper->getStorageColumnEncoding(); + if (auto it = encoding.find(column_path); it != encoding.end()) + { + result->setAttribute("iceberg.id", std::to_string(it->second)); + result->setAttribute("iceberg.required", required ? "true" : "false"); } - default: - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); } + + return result; } void ORCBlockOutputFormat::consume(Chunk chunk) @@ -534,21 +303,13 @@ void ORCBlockOutputFormat::consume(Chunk chunk) if (!writer) prepareWriter(); - size_t columns_num = chunk.getNumColumns(); size_t rows_num = chunk.getNumRows(); - - std::unique_ptr batch = writer->createRowBatch(chunk.getNumRows()); - orc::StructVectorBatch & root = dynamic_cast(*batch); - auto columns = chunk.detachColumns(); for (auto & column : columns) column = recursiveRemoveLowCardinality(column); - for (size_t i = 0; i != columns_num; ++i) - writeColumn(*root.fields[i], *columns[i], data_types[i], nullptr); - - root.numElements = rows_num; - writer->add(*batch); + /// The values are encoded directly from the columns. + writer->add(columns, rows_num); } void ORCBlockOutputFormat::finalizeImpl() @@ -567,19 +328,22 @@ void ORCBlockOutputFormat::resetFormatterImpl() void ORCBlockOutputFormat::prepareWriter() { const Block & header = getPort(PortKind::Main).getHeader(); - schema = orc::createStructType(); - options.setMemoryPool(&getORCMemoryPool()); - options.setCompression(getORCCompression(format_settings.orc.output_compression_method)); - options.setRowIndexStride(format_settings.orc.output_row_index_stride); - options.setDictionaryKeySizeThreshold(format_settings.orc.output_dictionary_key_size_threshold); - options.setCompressionBlockSize(format_settings.orc.output_compression_block_size); - options.setTimezoneName(format_settings.orc.writer_time_zone_name); + schema = ORC::Type::createStructType(); + options.compression = getORCCompression(format_settings.orc.output_compression_method); + options.row_index_stride = format_settings.orc.output_row_index_stride; + options.dictionary_key_size_threshold = format_settings.orc.output_dictionary_key_size_threshold; + options.compression_block_size = format_settings.orc.output_compression_block_size; + options.timezone_name = format_settings.orc.writer_time_zone_name; size_t columns_count = header.columns(); for (size_t i = 0; i != columns_count; ++i) - schema->addStructField(header.safeGetByPosition(i).name, getORCType(recursiveRemoveLowCardinality(data_types[i]))); - writer = orc::createWriter(*schema, &output_stream, options); + { + const auto & column_name = header.safeGetByPosition(i).name; + schema->addStructField(column_name, getORCType(recursiveRemoveLowCardinality(data_types[i]), column_name)); + } + writer = std::make_unique(*schema, data_types, output_stream, options); } +void registerOutputFormatORC(FormatFactory & factory); void registerOutputFormatORC(FormatFactory & factory) { factory.registerOutputFormat("ORC", []( @@ -603,6 +367,7 @@ void registerOutputFormatORC(FormatFactory & factory) namespace DB { class FormatFactory; + void registerOutputFormatORC(FormatFactory &); void registerOutputFormatORC(FormatFactory &) { } diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h index 0e47f7333d9d..5c9ebc4da420 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h @@ -7,7 +7,8 @@ #include #include #include -#include +#include +#include namespace DB @@ -19,29 +20,22 @@ using DataTypes = std::vector; class WriteBuffer; -/// orc::Writer writes only in orc::OutputStream -class ORCOutputStream : public orc::OutputStream +class ORCOutputStream : public ORC::OutputStream { public: explicit ORCOutputStream(WriteBuffer & out_); - uint64_t getLength() const override; - uint64_t getNaturalWriteSize() const override; void write(const void * buf, size_t length) override; - void close() override {} - const std::string& getName() const override { return name; } - private: WriteBuffer & out; - std::string name = "ORCOutputStream"; }; -class ORCBlockOutputFormat : public IOutputFormat +class ORCBlockOutputFormat final : public IOutputFormat { public: - ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_); + ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_ = nullptr); String getName() const override { return "ORCBlockOutputFormat"; } @@ -50,37 +44,20 @@ class ORCBlockOutputFormat : public IOutputFormat void finalizeImpl() override; void resetFormatterImpl() override; - std::unique_ptr getORCType(const DataTypePtr & type); - - /// ConvertFunc is needed for type UInt8, because firstly UInt8 (char8_t) must be - /// converted to unsigned char (bugprone-signed-char-misuse in clang). - template - void writeNumbers(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, ConvertFunc convert); - - /// ConvertFunc is needed to convert ClickHouse Int128 to ORC Int128. - template - void writeDecimals(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, - const PaddedPODArray * null_bytemap, ConvertFunc convert); - - template - void writeStrings(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap); - - /// ORC column TimestampVectorBatch stores only seconds and nanoseconds, - /// GetSecondsFunc and GetNanosecondsFunc are needed to extract them from DateTime type. - template - void writeDateTimes(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, - GetSecondsFunc get_seconds, GetNanosecondsFunc get_nanoseconds); - - void writeColumn(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, const PaddedPODArray * null_bytemap); + /// For Iceberg writes, attaches the field-id `iceberg.id` type attribute so readers project + /// by id. `column_path` is the dotted name (`t.x`, `arr.element`) used to look the id up. + std::unique_ptr getORCType(const DataTypePtr & type, const String & column_path); void prepareWriter(); const FormatSettings format_settings; ORCOutputStream output_stream; DataTypes data_types; - std::unique_ptr writer; - std::unique_ptr schema; - orc::WriterOptions options; + std::unique_ptr writer; + std::unique_ptr schema; + ORC::WriterOptions options; + /// Non-null only for Iceberg writes; maps dotted column name -> Iceberg field-id. + ColumnMapperPtr column_mapper; }; } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.cpp b/src/Processors/Formats/Impl/Parquet/Decoding.cpp index 840abe3265b2..e52e24dce6a8 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp +++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp @@ -1676,6 +1676,8 @@ Int96Converter::Int96Converter() void Int96Converter::convertColumn(std::span data, size_t num_values, IColumn & col) const { + const bool saturate = overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate; + std::span to_span = col.insertRawUninitialized(num_values); Int64 * to = reinterpret_cast(to_span.data()); for (size_t i = 0; i < num_values; ++i) @@ -1700,16 +1702,17 @@ void Int96Converter::convertColumn(std::span data, size_t num_values /// This interpretation is consistent with the arrow reader code (DecodeInt96Timestamp in /// arrow/cpp/src/parquet/types.h) and with a test file written by spark /// (tests/queries/0_stateless/02998_native_parquet_reader.sh). - bool overflow = false; - Int64 x; - overflow |= common::subOverflow(julian_day, static_cast(2440588l), x); // unix day number - overflow |= common::mulOverflow(x, day_nanos, x); // unix nanoseconds - overflow |= common::addOverflow(x, nanos, x); - - if (overflow) - throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); - to[i] = x; + /// julian_day comes from Int32, so neither the subtraction nor the product can overflow Int128. + const Int128 total = Int128(julian_day - 2440588l) * day_nanos + nanos; + if (total < std::numeric_limits::min() || total > std::numeric_limits::max()) + { + if (!saturate) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); + to[i] = julian_day < 2440588l ? std::numeric_limits::min() : std::numeric_limits::max(); + } + else + to[i] = static_cast(total); } } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.h b/src/Processors/Formats/Impl/Parquet/Decoding.h index 05f6ef6a2e02..266176171e45 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.h +++ b/src/Processors/Formats/Impl/Parquet/Decoding.h @@ -298,6 +298,9 @@ extern template struct BigEndianDecimalStringConverter; struct Int96Converter : public FixedSizeConverter { + /// A value that does not fit into Int64 nanoseconds is clamped to the `DateTime64(9)` range with Saturate, otherwise throws. + FormatSettings::DateTimeOverflowBehavior overflow_behavior = FormatSettings::DateTimeOverflowBehavior::Ignore; + Int96Converter(); void convertColumn(std::span data, size_t num_values, IColumn & col) const override; diff --git a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp index 8053f644407c..b1633c13f7e2 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp @@ -1258,7 +1258,9 @@ void SchemaConverter::processPrimitiveColumn( case parq::Type::INT96: { out_inferred_type = std::make_shared(9, "UTC"); - out_decoder.fixed_size_converter = std::make_shared(); + auto converter = std::make_shared(); + converter->overflow_behavior = options.format.date_time_overflow_behavior; + out_decoder.fixed_size_converter = std::move(converter); /// (Leaving allow_stats == false because INT96 sort order is undefined.) return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp index 3e938fddea10..317478590c98 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp @@ -6,21 +6,17 @@ #include #include +#include #include #include +#include + #include #include #include -namespace CurrentMetrics -{ - extern const Metric ParquetEncoderThreads; - extern const Metric ParquetEncoderThreadsActive; - extern const Metric ParquetEncoderThreadsScheduled; -} - namespace DB { @@ -87,11 +83,10 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Custom parquet encoder doesn't support parquet versions < 2.6. Use output_format_parquet_use_custom_encoder = 0."); if (format_settings.parquet.parallel_encoding && format_settings.max_threads > 1) - pool = std::make_unique( - CurrentMetrics::ParquetEncoderThreads, - CurrentMetrics::ParquetEncoderThreadsActive, - CurrentMetrics::ParquetEncoderThreadsScheduled, - format_settings.max_threads); + { + getParquetEncoderThreadPool().initializeWithDefaultSettingsIfNotInitialized(); + pool = &getParquetEncoderThreadPool().get(); + } using C = FormatSettings::ParquetCompression; switch (format_settings.parquet.output_compression_method) @@ -130,10 +125,14 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea ParquetBlockOutputFormat::~ParquetBlockOutputFormat() { if (pool) - { - is_stopped = true; - pool->wait(); - } + stopThreads(); +} + +void ParquetBlockOutputFormat::stopThreads() +{ + is_stopped = true; + std::unique_lock lock(mutex); + condvar.wait(lock, [this] { return threads_running == 0; }); } void ParquetBlockOutputFormat::consume(Chunk chunk) @@ -279,8 +278,7 @@ void ParquetBlockOutputFormat::resetFormatterImpl() { if (pool) { - is_stopped = true; - pool->wait(); + stopThreads(); is_stopped = false; } @@ -497,17 +495,16 @@ void ParquetBlockOutputFormat::startMoreThreadsIfNeeded(const std::unique_locktrySchedule(job)) break; + ++threads_running; } } } -void ParquetBlockOutputFormat::threadFunction() +void ParquetBlockOutputFormat::threadFunction(ThreadGroupPtr & thread_group) { + std::optional switcher; + switcher.emplace(thread_group, ThreadName::PARQUET_ENCODER); + std::unique_lock lock(mutex); while (true) @@ -540,7 +541,12 @@ void ParquetBlockOutputFormat::threadFunction() { /// The check and the decrement need to be in the same critical section, to make sure /// we never get stuck with tasks but no threads. + /// Leave the query's thread group before stopThreads() can see the decrement. + switcher.reset(); + thread_group.reset(); --threads_running; + if (threads_running == 0) + condvar.notify_all(); return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h index f22447850e82..b553a00ba391 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h @@ -28,6 +28,9 @@ namespace DB class CHColumnToArrowColumn; +class ThreadGroup; +using ThreadGroupPtr = std::shared_ptr; + class ParquetBlockOutputFormat : public IOutputFormat { public: @@ -118,8 +121,9 @@ class ParquetBlockOutputFormat : public IOutputFormat void writeRowGroupInOneThread(Chunk chunk); void writeRowGroupInParallel(std::vector chunks); - void threadFunction(); + void threadFunction(ThreadGroupPtr & thread_group); void startMoreThreadsIfNeeded(const std::unique_lock & lock); + void stopThreads(); /// Called in single-threaded fashion. Writes to the file. void reapCompletedRowGroups(std::unique_lock & lock); @@ -140,13 +144,15 @@ class ParquetBlockOutputFormat : public IOutputFormat size_t base_offset = 0; // initial out.count(), just for assert std::mutex mutex; - std::condition_variable condvar; // wakes up consume() - std::unique_ptr pool; + std::condition_variable condvar; // wakes up consume() and stopThreads() + /// Shared by all Parquet writers of the process (`getParquetEncoderThreadPool`). + ThreadPool * pool = nullptr; std::atomic_bool is_stopped{false}; std::exception_ptr background_exception = nullptr; /// Invariant: if there's at least one task then there's at least one thread. + /// Counts the jobs scheduled on `pool` until they exit, queued ones included. size_t threads_running = 0; std::atomic bytes_in_flight{0}; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 5e9a4bfd7565..119112f9838a 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -56,9 +56,16 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat( format_filter_info = std::make_shared(); } -void ParquetV3BlockInputFormat::initializeIfNeeded() +void ParquetV3BlockInputFormat::prefetch() { - if (!reader) + if (need_only_count) + return; + readFileFooterIfNeeded(); +} + +void ParquetV3BlockInputFormat::readFileFooterIfNeeded() +{ + if (!reader && !reader_with_footer) { format_filter_info->initKeyConditionOnce(getPort().getHeader()); parser_shared_resources->initOnce([&] @@ -87,11 +94,24 @@ void ParquetV3BlockInputFormat::initializeIfNeeded() parser_shared_resources->opaque = ext; }); + auto new_reader = std::make_unique(); + new_reader->reader.prefetcher.init(in, read_options, parser_shared_resources); + new_reader->reader.file_metadata = getFileMetadata(new_reader->reader.prefetcher); + + std::lock_guard lock(reader_mutex); + reader_with_footer = std::move(new_reader); + } +} + +void ParquetV3BlockInputFormat::initializeIfNeeded() +{ + if (!reader) + { + readFileFooterIfNeeded(); + { std::lock_guard lock(reader_mutex); - reader.emplace(); - reader->reader.prefetcher.init(in, read_options, parser_shared_resources); - reader->reader.file_metadata = getFileMetadata(reader->reader.prefetcher); + reader = std::move(reader_with_footer); reader->reader.init(read_options, getPort().getHeader(), format_filter_info); reader->init(parser_shared_resources, buckets_to_read ? std::optional(buckets_to_read->row_group_ids) : std::nullopt); } @@ -169,6 +189,7 @@ void ParquetV3BlockInputFormat::resetReadBuffer() std::lock_guard lock(reader_mutex); if (reader) reader->shutdownTasks(); + reader_with_footer.reset(); } IInputFormat::resetReadBuffer(); } @@ -178,6 +199,7 @@ void ParquetV3BlockInputFormat::resetParser() { std::lock_guard lock(reader_mutex); reader.reset(); + reader_with_footer.reset(); } previous_block_missing_values.clear(); IInputFormat::resetParser(); diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h index a66ea4d97c2e..892771da231f 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h @@ -43,6 +43,8 @@ class ParquetV3BlockInputFormat : public IInputFormat private: Chunk read() override; + void prefetch() override; + void onCancel() noexcept override; const FormatSettings format_settings; @@ -52,17 +54,20 @@ class ParquetV3BlockInputFormat : public IInputFormat ParquetMetadataCachePtr metadata_cache; const std::optional object_with_metadata; - /// (This mutex is not important. It protects `reader.emplace` in a weird case where onCancel() + /// (This mutex is not important. It protects setting `reader` in a weird case where onCancel() /// may be called in parallel with first read(). ReadManager itself is thread safe for that, - /// but initializing vs checking the std::optional would race without this mutex.) + /// but initializing vs checking the pointer would race without this mutex.) std::mutex reader_mutex; - std::optional reader; + std::unique_ptr reader; + /// Has the file footer, but is not initialized: initializing it starts reading and decoding the column chunks. + std::unique_ptr reader_with_footer; bool reported_count = false; // if need_only_count BlockMissingValues previous_block_missing_values; size_t previous_approx_bytes_read_for_chunk = 0; + void readFileFooterIfNeeded(); void initializeIfNeeded(); std::shared_ptr buckets_to_read; diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp index a2c57cf0ed3a..48d880484d33 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include #include #include @@ -10,14 +12,24 @@ namespace DB RawBLOBRowOutputFormat::RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_) + SharedHeader header_, + const FormatSettings & format_settings_) : IRowOutputFormat(header_, out_) + , format_settings(format_settings_) { } -void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization &, size_t row_num) +void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) { + /// `getDataAt` of `ColumnAggregateFunction` returns the bytes of the pointer to the state, not the state itself. + /// Write the serialized state, the same as its conversion to `String`. + if (typeid_cast(&column)) + { + serialization.serializeBinary(column, row_num, out, format_settings); + return; + } + if (!column.isNullAt(row_num)) { auto value = column.getDataAt(row_num); @@ -31,10 +43,10 @@ void registerOutputFormatRawBLOB(FormatFactory & factory) factory.registerOutputFormat("RawBLOB", []( WriteBuffer & buf, const Block & sample, - const FormatSettings &, + const FormatSettings & settings, FormatFilterInfoPtr /*format_filter_info*/) { - return std::make_shared(buf, std::make_shared(sample)); + return std::make_shared(buf, std::make_shared(sample), settings); }); } diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h index e2afa209faaa..9418d3c33028 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h @@ -1,5 +1,6 @@ #pragma once +#include #include @@ -28,12 +29,15 @@ class RawBLOBRowOutputFormat final : public IRowOutputFormat public: RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_); + SharedHeader header_, + const FormatSettings & format_settings_); String getName() const override { return "RawBLOBRowOutputFormat"; } private: - void writeField(const IColumn & column, const ISerialization &, size_t row_num) override; + void writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) override; + + const FormatSettings format_settings; }; } diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp index 8fd5aba82710..005d5379243a 100644 --- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp +++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp @@ -49,7 +49,6 @@ #include #include #include -#include #include #include #include @@ -520,9 +519,7 @@ Pipe ReadFromMergeTree::readFromPoolParallelReplicas( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); pipes.emplace_back(std::move(source)); @@ -631,9 +628,7 @@ Pipe ReadFromMergeTree::readFromPool( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); @@ -750,9 +745,7 @@ Pipe ReadFromMergeTree::readInOrder( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); processor->addPartLevelToChunk(isQueryWithFinal()); diff --git a/src/Processors/Transforms/AddingDefaultsTransform.cpp b/src/Processors/Transforms/AddingDefaultsTransform.cpp index 9e0fe0f5c260..9650df7204bb 100644 --- a/src/Processors/Transforms/AddingDefaultsTransform.cpp +++ b/src/Processors/Transforms/AddingDefaultsTransform.cpp @@ -157,7 +157,8 @@ void AddingDefaultsTransform::transform(Chunk & chunk) return; const auto * block_missing_values = input_format.getMissingValues(); - if (!block_missing_values) + /// `BlockMissingValues::empty` is also true when the mask holds no columns at all, where the lookups below would be out of range. + if (!block_missing_values || block_missing_values->empty()) return; const auto & header = getOutputPort().getHeader(); diff --git a/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp new file mode 100644 index 000000000000..89e4391079a6 --- /dev/null +++ b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp @@ -0,0 +1,127 @@ +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, so a chunk holding more +/// than that becomes several record batches, each covering a row range. A range not starting at row 0 has +/// to rebase those offsets against the row before it. Reaching the real limit needs more than 2 GiB of +/// data, so these tests lower it. +/// +/// `CHColumnToArrowColumn` is the Apache Arrow library writer, used by the `Arrow` output format, +/// `ArrowFlight`, `StorageArrowFlight` and Delta Lake writes. + +namespace DB +{ + +namespace +{ + +constexpr size_t NUM_ROWS = 8; +constexpr size_t VALUE_SIZE = 16; + +std::string valueAt(size_t row) +{ + return std::string(VALUE_SIZE, static_cast('a' + row)); +} + +CHColumnToArrowColumn::Settings settingsWithLimit(UInt64 max_record_batch_bytes) +{ + CHColumnToArrowColumn::Settings settings; + settings.output_string_as_string = true; + settings.output_max_record_batch_bytes = max_record_batch_bytes; + return settings; +} + +std::shared_ptr convertToArrow(const DataTypePtr & type, MutableColumnPtr column, UInt64 max_record_batch_bytes) +{ + ColumnsWithTypeAndName header_columns{ColumnWithTypeAndName(type->createColumn(), type, "t")}; + + Columns columns; + columns.emplace_back(std::move(column)); + + std::vector chunks; + chunks.emplace_back(std::move(columns), NUM_ROWS); + + CHColumnToArrowColumn converter(header_columns, "Arrow", settingsWithLimit(max_record_batch_bytes)); + std::shared_ptr arrow_table; + converter.chChunkToArrowTable(arrow_table, chunks, 1); + return arrow_table; +} + +} + +TEST(CHColumnToArrowColumn, StringSplitAcrossRecordBatches) +{ + auto type = std::make_shared(); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(valueAt(row)); + + /// Two values per batch, so most batches start past row 0. + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & array = assert_cast(*chunked.chunk(chunk_i)); + /// Every batch addresses its own values from zero. + ASSERT_EQ(array.value_offset(0), 0); + for (int64_t i = 0; i < array.length(); ++i, ++row) + ASSERT_EQ(array.GetString(i), valueAt(row)); + } + ASSERT_EQ(row, NUM_ROWS); +} + +TEST(CHColumnToArrowColumn, ArraySplitAcrossRecordBatches) +{ + auto type = std::make_shared(std::make_shared()); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(Array{Field(valueAt(row)), Field(valueAt(row))}); + + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & list = assert_cast(*chunked.chunk(chunk_i)); + ASSERT_EQ(list.value_offset(0), 0); + for (int64_t i = 0; i < list.length(); ++i, ++row) + { + /// `value_slice` returns a new array by value: keep it alive while it is inspected. + const auto values_holder = list.value_slice(i); + const auto & values = assert_cast(*values_holder); + ASSERT_EQ(values.length(), 2); + ASSERT_EQ(values.GetString(0), valueAt(row)); + ASSERT_EQ(values.GetString(1), valueAt(row)); + } + } + ASSERT_EQ(row, NUM_ROWS); +} + +} + +#endif diff --git a/src/Server/HTTP/ReadHeaders.cpp b/src/Server/HTTP/ReadHeaders.cpp index 142b47a8d6d2..4a5ef642b68b 100644 --- a/src/Server/HTTP/ReadHeaders.cpp +++ b/src/Server/HTTP/ReadHeaders.cpp @@ -87,7 +87,12 @@ void readHeaders( skipToNextLineOrEOF(in); Poco::trimRightInPlace(value); - headers.add(name, Poco::Net::MessageHeader::decodeWord(value)); + std::string decoded_value = Poco::Net::MessageHeader::decodeWord(value); + /// RFC 2047 decoding can produce bytes that are forbidden in a field value (RFC 9110, section 5.5), + /// e.g. `=0D=0A` would become a line break that splits the header when it is written out again. + if (decoded_value.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Poco::Net::MessageException(fmt::format("Value of field \"{}\" contains CR, LF or NUL", name)); + headers.add(name, decoded_value); ++fields; } } diff --git a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp index f17e4f25ce44..d93ae95ec67b 100644 --- a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp +++ b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp @@ -59,6 +59,7 @@ namespace ErrorCodes extern const int WRONG_PASSWORD; extern const int REQUIRED_PASSWORD; extern const int AUTHENTICATION_FAILED; + extern const int REQUIRED_SECOND_FACTOR; extern const int SET_NON_GRANTED_ROLE; extern const int HTTP_LENGTH_REQUIRED; @@ -76,7 +77,8 @@ Poco::Net::HTTPResponse::HTTPStatus exceptionCodeToHTTPStatus(int exception_code return HTTPResponse::HTTP_UNAUTHORIZED; } if (exception_code == ErrorCodes::UNKNOWN_USER || exception_code == ErrorCodes::WRONG_PASSWORD - || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE) + || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE + || exception_code == ErrorCodes::REQUIRED_SECOND_FACTOR) { return HTTPResponse::HTTP_FORBIDDEN; } diff --git a/src/Server/PostgreSQLHandler.cpp b/src/Server/PostgreSQLHandler.cpp index c8e2fe902361..c49afe8df5cd 100644 --- a/src/Server/PostgreSQLHandler.cpp +++ b/src/Server/PostgreSQLHandler.cpp @@ -678,8 +678,8 @@ void PostgreSQLHandler::cancelRequest() inline std::unique_ptr PostgreSQLHandler::receiveStartupMessage(int payload_size) { /// The declared size is read from the wire before any authentication, and the message is read - /// into memory in full, so it has to be bounded. PostgreSQL uses the same limit. - static constexpr Int32 max_startup_message_size = 10000; + /// into memory in full, so it has to be bounded (`max_unauthenticated_message_size`). + static constexpr Int32 max_startup_message_size = PostgreSQLProtocol::Messaging::max_unauthenticated_message_size; std::unique_ptr message; try diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index 1d7b6d09bf16..92be0d801fac 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2525,8 +2525,10 @@ bool TCPHandler::processData(QueryState & state, bool scalar) if (scalar) { - /// Scalar value - state.query_context->addScalar(temporary_id.table_name, block); + /// Scalar value received from the client over the wire. It must not be trusted as a + /// server-computed scalar-subquery result (see Context::addClientScalar): otherwise a client + /// could name it with a row policy's scalar-subquery hash and forge the policy's result. + state.query_context->addClientScalar(temporary_id.table_name, block); } else if (!state.need_receive_data_for_insert && !state.need_receive_data_for_input) { diff --git a/src/Storages/AlterCommands.cpp b/src/Storages/AlterCommands.cpp index b1661cffc376..c026d44cb772 100644 --- a/src/Storages/AlterCommands.cpp +++ b/src/Storages/AlterCommands.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -1314,6 +1315,33 @@ bool AlterCommands::hasVectorSimilarityIndex(const StorageInMemoryMetadata & met return false; } +NameSet AlterCommands::getAddedIndexNames(const IndicesDescription & existing) const +{ + NameSet present; + for (const auto & index : existing) + present.insert(index.name); + + NameSet added; + for (const AlterCommand & command : *this) + { + if (command.ignore) + continue; + + if (command.type == AlterCommand::ADD_INDEX) + { + /// Otherwise `AlterCommand::apply` either skips it, with `IF NOT EXISTS`, or throws. + if (present.insert(command.index_name).second) + added.insert(command.index_name); + } + else if (command.type == AlterCommand::DROP_INDEX && !command.partition && !command.clear) + { + present.erase(command.index_name); + added.erase(command.index_name); + } + } + return added; +} + void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context) const { if (!prepared) @@ -1371,6 +1399,16 @@ void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context } } + /// Only the declared ones, and only now: the rebuild above resolves them against the schema every + /// command produced, which is what gets stored. Existing indices stay unauthorised on purpose. + const NameSet declared_indices = getAddedIndexNames(metadata.secondary_indices); + + for (const auto & index : metadata_copy.secondary_indices) + { + if (declared_indices.contains(index.name)) + checkTextIndexPreAndPostProcessorPermissions(index, context); + } + /// Changes in columns may lead to changes in projections ProjectionsDescription new_projections; for (const auto & projection : metadata_copy.projections) diff --git a/src/Storages/AlterCommands.h b/src/Storages/AlterCommands.h index 22a9253baa10..82501af8dd29 100644 --- a/src/Storages/AlterCommands.h +++ b/src/Storages/AlterCommands.h @@ -219,6 +219,9 @@ class AlterCommands : public std::vector /// Commands have to be prepared before apply. void apply(StorageInMemoryMetadata & metadata, ContextPtr context) const; + /// Indices the commands actually add: `ADD INDEX IF NOT EXISTS` of an existing name adds nothing. + NameSet getAddedIndexNames(const IndicesDescription & existing) const; + /// At least one command modify settings or comments. bool hasNonReplicatedAlterCommand() const; diff --git a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp index 7b54bd1a72fc..d2b3e89891d2 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp @@ -21,6 +21,7 @@ #include #include +#include #include namespace CurrentMetrics @@ -217,6 +218,11 @@ bool DistributedAsyncInsertBatch::recoverBatch() } files.erase(files.begin(), first_existing_file); + /// The batch is sent with the `ClientInfo` of its first file. Older servers could put files of different + /// users (or originating hosts) into one batch, so a restored batch of mixed identities must not be resent + /// as a whole: it is dropped, and its files are batched again by identity like any other pending files. + std::optional> batch_identity; + /// A missing file inside the surviving suffix cannot be recovered safely. for (const auto & file : files) { @@ -228,13 +234,25 @@ bool DistributedAsyncInsertBatch::recoverBatch() try { - ReadBufferFromFile header_buffer(files.back()); + ReadBufferFromFile header_buffer(file); const DistributedAsyncInsertHeader & header = DistributedAsyncInsertHeader::read(header_buffer, parent.log); if (header.rows) { total_rows += header.rows; total_bytes += header.bytes; } + + auto identity = getRemoteAuthenticationIdentity(header.client_info); + if (!batch_identity) + { + batch_identity = std::move(identity); + } + else if (identity != *batch_identity) + { + LOG_WARNING(parent.log, "File {} has a different user or originating host than the first file of the batch, " + "the files of the batch will be sent in new batches", file); + return false; + } } catch (Exception & e) { diff --git a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp index 172028d48813..c94608ea330d 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp @@ -494,8 +494,11 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader bool operator==(const BatchHeader & other) const { + /// The whole batch is sent with the `ClientInfo` of its first file, so files that the shard would + /// authenticate differently must never be merged into one batch. return std::tie(settings, query, client_info.query_kind) == std::tie(other.settings, other.query, other.client_info.query_kind) && + getRemoteAuthenticationIdentity(client_info) == getRemoteAuthenticationIdentity(other.client_info) && blocksHaveEqualStructure(header, other.header); } @@ -505,6 +508,9 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader { SipHash hash_state; hash_state.update(batch_header.query.data(), batch_header.query.size()); + const auto [initial_user, initial_host] = getRemoteAuthenticationIdentity(batch_header.client_info); + hash_state.update(initial_user.data(), initial_user.size()); + hash_state.update(initial_host.data(), initial_host.size()); batch_header.header.updateHash(hash_state); return hash_state.get64(); } diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp index e14d376583c7..ef6564f896e7 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp @@ -68,6 +68,14 @@ void writeAndConvert(RemoteInserter & remote, const DistributedAsyncInsertHeader } } +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info) +{ + String initial_host; + if (client_info.initial_address) + initial_host = client_info.initial_address->host().toString(); + return {client_info.initial_user, initial_host}; +} + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h index 202d9ff6fff8..3cc335c169f9 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h @@ -1,12 +1,16 @@ #pragma once #include +#include + +#include namespace DB { struct DistributedAsyncInsertHeader; +class ClientInfo; class ReadBufferFromFile; class RemoteInserter; @@ -23,6 +27,11 @@ class RemoteInserter; /// and mark batch as broken. bool isDistributedSendBroken(int code, bool remote_error); +/// The identity the shard authenticates a queued insert as (with the interserver ``): `initial_user` +/// and the host of `initial_address`, which is checked against the allowed hosts of that user. +/// A batch is sent with the `ClientInfo` of its first file, so all files of a batch must have the same identity. +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info); + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedSink.cpp b/src/Storages/Distributed/DistributedSink.cpp index dc3fa7f31036..b0d05d4d5ebb 100644 --- a/src/Storages/Distributed/DistributedSink.cpp +++ b/src/Storages/Distributed/DistributedSink.cpp @@ -864,17 +864,21 @@ void DistributedSink::writeToShard(const Cluster::ShardInfo & shard_info, const writeStringBinary(query_string, header_buf); context->getSettingsRef().write(header_buf); - if (OpenTelemetry::CurrentContext().isTraceEnabled()) { - // if the distributed tracing is enabled, use the trace context in current thread as parent of next span auto client_info = context->getClientInfo(); - client_info.client_trace_context = OpenTelemetry::CurrentContext(); + // if the distributed tracing is enabled, use the trace context in current thread as parent of next span + if (OpenTelemetry::CurrentContext().isTraceEnabled()) + client_info.client_trace_context = OpenTelemetry::CurrentContext(); + /// Background contexts (e.g. the ones of `Kafka` / `RabbitMQ` streaming into views) have + /// `query_kind = NO_QUERY`, for which `ClientInfo::write` stores nothing but the kind. The + /// replayed insert would then reach the shard with an empty `initial_user`, which a shard + /// accepting the interserver `` executes with full access, losing the identity + /// (e.g. the definer of a `SQL SECURITY DEFINER` view) that the query is bound to. + /// `RemoteInserter` sends the insert as a secondary query anyway, so persist it as such. + if (client_info.query_kind == ClientInfo::QueryKind::NO_QUERY) + client_info.query_kind = ClientInfo::QueryKind::SECONDARY_QUERY; client_info.write(header_buf, DBMS_TCP_PROTOCOL_VERSION); } - else - { - context->getClientInfo().write(header_buf, DBMS_TCP_PROTOCOL_VERSION); - } writeVarUInt(block.rows(), header_buf); writeVarUInt(block.bytes(), header_buf); diff --git a/src/Storages/Hive/HiveFile.cpp b/src/Storages/Hive/HiveFile.cpp index 18c9bf27a6f6..f2c467937ddb 100644 --- a/src/Storages/Hive/HiveFile.cpp +++ b/src/Storages/Hive/HiveFile.cpp @@ -8,12 +8,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -33,31 +33,16 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } -#define THROW_ARROW_NOT_OK(status) \ - do \ - { \ - if (const ::arrow::Status & _s = (status); !_s.ok()) \ - throw Exception::createDeprecated(_s.ToString(), ErrorCodes::BAD_ARGUMENTS); \ - } while (false) - - -template -Range createRangeFromOrcStatistics(const StatisticsType * stats) +template +Range createRangeFromOrcStatistics(const std::optional & minimum, const std::optional & maximum) { /// Null values or NaN/Inf values of double type. - if (stats->hasMinimum() && stats->hasMaximum()) - { - return Range(FieldType(stats->getMinimum()), true, FieldType(stats->getMaximum()), true); - } - if (stats->hasMinimum()) - { - return Range::createLeftBounded(FieldType(stats->getMinimum()), true); - } - if (stats->hasMaximum()) - { - return Range::createRightBounded(FieldType(stats->getMaximum()), true); - } - + if (minimum && maximum) + return Range(FieldType(*minimum), true, FieldType(*maximum), true); + if (minimum) + return Range::createLeftBounded(FieldType(*minimum), true); + if (maximum) + return Range::createRightBounded(FieldType(*maximum), true); return Range::createWholeUniverseWithoutNull(); } @@ -116,48 +101,40 @@ void IHiveFile::loadSplitMinMaxIndexes() split_minmax_idxes_loaded = true; } -Range HiveORCFile::buildRange(const orc::ColumnStatistics * col_stats) +Range HiveORCFile::buildRange(const ORC::Proto::ColumnStatistics * col_stats) { - if (!col_stats || col_stats->hasNull()) + /// A missing `has_null` means that the column may contain nulls. + if (!col_stats || col_stats->has_null.value_or(true)) return Range::createWholeUniverseWithoutNull(); - if (const auto * int_stats = dynamic_cast(col_stats)) + if (const auto & int_stats = col_stats->int_statistics) + return createRangeFromOrcStatistics(int_stats->minimum, int_stats->maximum); + if (const auto & double_stats = col_stats->double_statistics) + return createRangeFromOrcStatistics(double_stats->minimum, double_stats->maximum); + if (const auto & string_stats = col_stats->string_statistics) + return createRangeFromOrcStatistics(string_stats->minimum, string_stats->maximum); + if (const auto & bool_stats = col_stats->bucket_statistics) { - return createRangeFromOrcStatistics(int_stats); - } - if (const auto * double_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(double_stats); - } - if (const auto * string_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(string_stats); - } - if (const auto * bool_stats = dynamic_cast(col_stats)) - { - auto false_cnt = bool_stats->getFalseCount(); - auto true_cnt = bool_stats->getTrueCount(); + if (bool_stats->count.empty()) + return Range::createWholeUniverseWithoutNull(); + UInt64 true_cnt = bool_stats->count[0]; + UInt64 false_cnt = col_stats->number_of_values.value_or(0) - true_cnt; if (false_cnt && true_cnt) - { return Range(UInt8(0), true, UInt8(1), true); - } if (false_cnt) - { return Range::createLeftBounded(UInt8(0), true); - } if (true_cnt) - { return Range::createRightBounded(UInt8(1), true); - } - } - else if (const auto * timestamp_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(timestamp_stats); + return Range::createWholeUniverseWithoutNull(); } - else if (const auto * date_stats = dynamic_cast(col_stats)) + if (const auto & timestamp_stats = col_stats->timestamp_statistics) { - return createRangeFromOrcStatistics(date_stats); + /// The deprecated `minimum` and `maximum` are in the local time zone of the writer, which is + /// unknown for the statistics of the whole file, so only the UTC bounds are usable. + return createRangeFromOrcStatistics(timestamp_stats->minimum_utc, timestamp_stats->maximum_utc); } + if (const auto & date_stats = col_stats->date_statistics) + return createRangeFromOrcStatistics(date_stats->minimum, date_stats->maximum); return Range::createWholeUniverseWithoutNull(); } @@ -166,14 +143,12 @@ void HiveORCFile::prepareReader() in = std::make_unique(namenode_url, path, getContext()->getGlobalContext()->getConfigRef(), getContext()->getReadSettings()); auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; - auto result = arrow::adapters::orc::ORCFileReader::Open(asArrowFile(*in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(result.status()); - reader = std::move(result).ValueOrDie(); + reader = createORCReader(asORCInputStream(*in, format_settings, /*use_prefetch=*/false, is_stopped), ORC::ReaderOptions{}); } void HiveORCFile::prepareColumnMapping() { - const orc::Type & type = reader->GetRawORCReader()->getType(); + const ORC::Type & type = reader->getType(); size_t count = type.getSubtypeCount(); for (size_t pos = 0; pos < count; pos++) { @@ -190,7 +165,7 @@ bool HiveORCFile::useFileMinMaxIndex() const } -std::unique_ptr HiveORCFile::buildMinMaxIndex(const orc::Statistics * statistics) +std::unique_ptr HiveORCFile::buildMinMaxIndex(const std::vector * statistics) { if (!statistics) return nullptr; @@ -213,7 +188,7 @@ std::unique_ptr HiveORCFile::buildMinMaxIndex(c { size_t pos = it->second; /// Attention: column statistics start from 1. 0 has special purpose. - const orc::ColumnStatistics * col_stats = statistics->getColumnStatistics(static_cast(pos + 1)); + const ORC::Proto::ColumnStatistics * col_stats = pos + 1 < statistics->size() ? &(*statistics)[pos + 1] : nullptr; idx->hyperrectangle[i] = buildRange(col_stats); } ++i; @@ -230,8 +205,7 @@ void HiveORCFile::loadFileMinMaxIndexImpl() prepareColumnMapping(); } - auto statistics = reader->GetRawORCReader()->getStatistics(); - file_minmax_idx = buildMinMaxIndex(statistics.get()); + file_minmax_idx = buildMinMaxIndex(&reader->getStatistics()); } bool HiveORCFile::useSplitMinMaxIndex() const @@ -248,9 +222,10 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); auto stripe_num = raw_reader->getNumberOfStripes(); - auto stripe_stats_num = raw_reader->getNumberOfStripeStatistics(); + const auto & stripe_statistics = raw_reader->getMetadata().stripe_stats; + auto stripe_stats_num = stripe_statistics.size(); if (stripe_num != stripe_stats_num) throw Exception(ErrorCodes::BAD_ARGUMENTS, "orc file:{} has different strip num {} and strip statistics num {}", path, stripe_num, stripe_stats_num); @@ -258,8 +233,7 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() split_minmax_idxes.resize(stripe_num); for (size_t i = 0; i < stripe_num; ++i) { - auto stripe_stats = raw_reader->getStripeStatistics(i); - split_minmax_idxes[i] = buildMinMaxIndex(stripe_stats.get()); + split_minmax_idxes[i] = buildMinMaxIndex(&stripe_statistics[i].col_stats); } } @@ -271,7 +245,7 @@ std::optional HiveORCFile::getRowsImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); return raw_reader->getNumberOfRows(); } @@ -286,7 +260,8 @@ void HiveParquetFile::prepareReader() auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; auto open_file_res = parquet::arrow::OpenFile(asArrowFile(*in, format_settings, is_stopped, "Parquet", PARQUET_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(open_file_res.status()); + if (!open_file_res.ok()) + throw Exception::createDeprecated(open_file_res.status().ToString(), ErrorCodes::BAD_ARGUMENTS); reader = *std::move(open_file_res); } diff --git a/src/Storages/Hive/HiveFile.h b/src/Storages/Hive/HiveFile.h index 611302693b1d..50d9e0cbc6c2 100644 --- a/src/Storages/Hive/HiveFile.h +++ b/src/Storages/Hive/HiveFile.h @@ -5,9 +5,10 @@ #include #include +#include #include -#include +#include #include #include @@ -217,18 +218,18 @@ class HiveORCFile : public IHiveFile bool useSplitMinMaxIndex() const override; private: - static Range buildRange(const orc::ColumnStatistics * col_stats); + static Range buildRange(const ORC::Proto::ColumnStatistics * col_stats); void loadFileMinMaxIndexImpl() override; void loadSplitMinMaxIndexesImpl() override; - std::unique_ptr buildMinMaxIndex(const orc::Statistics * statistics); + std::unique_ptr buildMinMaxIndex(const std::vector * statistics); void prepareReader(); void prepareColumnMapping(); std::optional getRowsImpl() override; std::unique_ptr in; - std::unique_ptr reader; + std::unique_ptr reader; std::map orc_column_positions; }; diff --git a/src/Storages/Hive/StorageHive.cpp b/src/Storages/Hive/StorageHive.cpp index fccccb7c7fca..15e23429c5ad 100644 --- a/src/Storages/Hive/StorageHive.cpp +++ b/src/Storages/Hive/StorageHive.cpp @@ -608,6 +608,10 @@ HiveFiles StorageHive::collectHiveFilesFromPartition( throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, "Partition value size not match, expect {}, but got {}", partition_names.size(), partition.values.size()); + if (!partition_key_expr) + throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, + "Hive metastore returned a partition for table {}.{}, but the table has no partition key", hive_database, hive_table); + /// Join partition values in CSV format WriteBufferFromOwnString wb; for (size_t i = 0; i < partition.values.size(); ++i) diff --git a/src/Storages/IStorage.h b/src/Storages/IStorage.h index 8c58fa27b6a5..e10d484de8b3 100644 --- a/src/Storages/IStorage.h +++ b/src/Storages/IStorage.h @@ -167,6 +167,9 @@ class IStorage : public std::enable_shared_from_this, public TypePromo virtual bool supportsSubcolumns() const { return false; } /// Returns true if storage supports optimizations of functions by reading subcolumns. virtual bool supportsOptimizationToSubcolumns() const { return supportsSubcolumns(); } + /// Returns true if the storage writes `Map` columns with the bucketed serialization, where a single key + /// can be read without reading the whole column. Gates the `m['key']` -> `m.key_` rewrite. + virtual bool hasBucketedMapSerialization() const { return false; } /// Returns true if the storage supports transactions for SELECT, INSERT and ALTER queries. /// Storage may throw an exception later if some query kind is not fully supported. diff --git a/src/Storages/IndicesDescription.cpp b/src/Storages/IndicesDescription.cpp index 9d716df4428b..6bdb804cd4c6 100644 --- a/src/Storages/IndicesDescription.cpp +++ b/src/Storages/IndicesDescription.cpp @@ -1,12 +1,20 @@ #include #include +#include #include +#include #include +#include +#include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -25,6 +33,122 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } +namespace +{ + +/// Calls `fn` with the value of each `preprocessor` / `postprocessor` argument of a text index. +template +void forEachTransformArgument(const ASTPtr & arguments, F && fn) +{ + for (const auto & child : arguments->children) + { + auto * func = child->as(); + if (!func || func->name != "equals" || !func->arguments || func->arguments->children.size() != 2) + continue; + + const auto * key = func->arguments->children[0]->as(); + if (key && (key->name() == "preprocessor" || key->name() == "postprocessor")) + fn(func->arguments->children[1]); + } +} + +/// Resolving a name runs the function's `create`, where `checkAccess` lives. Names only: building the +/// expression would report its type errors from here, not from the validator. +/// +/// A transform is analysed under the global context, so reading a table or a dictionary during analysis +/// would happen with full access. Such access depends on the arguments, not the function name, so +/// authorizing names cannot cover it, and these constructs are refused. Only here, where a user declares +/// the index: metadata stored by an older version must still load and stay alterable. +void checkFunctionsAsUser(const ASTPtr & ast, const ContextPtr & context) +{ + if (ast->as() || ast->as() || ast->as() || ast->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, "A text index transform expression must not contain subqueries or table references"); + + if (const auto * function = ast->as()) + { + if (functionIsInOrGlobalInOperator(function->name) && function->arguments && function->arguments->children.size() == 2) + { + const auto & set = function->arguments->children[1]; + if (set->as() || set->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not use a table or a set as the right side of `{}`", function->name); + } + + /// Only the name, which for `dictGet` and the like does not touch the dictionary; analysis would. + if (auto resolver = FunctionFactory::instance().tryGet(function->name, context); resolver && !resolver->isDeterministic()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not contain non-deterministic functions. Got `{}`", function->name); + } + + for (const auto & child : ast->children) + checkFunctionsAsUser(child, context); +} + +void checkTransformPermissions(const ASTPtr & arguments, const ContextPtr & context) +{ + forEachTransformArgument(arguments, [&](ASTPtr & argument) + { + auto expression = argument->clone(); + /// Inlines SQL UDF bodies, as `TreeRewriter` does, so a function used only inside one is seen. + if (!UserDefinedSQLFunctionFactory::instance().empty()) + UserDefinedSQLFunctionVisitor::visit(expression, context); + + checkFunctionsAsUser(expression, context); + }); +} + +} + +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context) +{ + if (index.type == TEXT_INDEX_NAME && index.arguments) + checkTransformPermissions(index.arguments, context); +} + +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index) +{ + if (index.type != TEXT_INDEX_NAME || !index.arguments) + return false; + + bool found = false; + forEachTransformArgument(index.arguments, [&](ASTPtr &) { found = true; }); + return found; +} + +[[noreturn]] static void throwTransformNeedsInitiatorUser() +{ + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "A text index preprocessor or postprocessor is authorized on the host the query is submitted to, and the " + "other hosts resolve it against their own schema without that user. Let every host run the query as the " + "initiating user instead: enable the server setting distributed_ddl_use_initial_user_and_roles on every " + "host, and set distributed_ddl_entry_format_version to at least {}", + DDLLogEntry::INITIATOR_USER_VERSION); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration) +{ + if (hasTextIndexPreOrPostProcessor(declaration)) + throwTransformNeedsInitiatorUser(); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index) +{ + if (hasTextIndexPreOrPostProcessor(index)) + throwTransformNeedsInitiatorUser(); +} + +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration) +{ + const auto * type = declaration.getType() ? declaration.getType()->as() : nullptr; + if (!type || Poco::toLower(type->name) != TEXT_INDEX_NAME || !type->arguments) + return false; + + bool found = false; + forEachTransformArgument(type->arguments, [&](ASTPtr &) { found = true; }); + return found; +} + IndexDescription::IndexDescription(const IndexDescription & other) : definition_ast(other.definition_ast ? other.definition_ast->clone() : nullptr) , expression_list_ast(other.expression_list_ast ? other.expression_list_ast->clone() : nullptr) diff --git a/src/Storages/IndicesDescription.h b/src/Storages/IndicesDescription.h index 207e3c76b154..5d1daf8affaa 100644 --- a/src/Storages/IndicesDescription.h +++ b/src/Storages/IndicesDescription.h @@ -16,6 +16,7 @@ namespace DB class ExpressionActions; using ExpressionActionsPtr = std::shared_ptr; +class ASTIndexDeclaration; /// Description of non-primary index for Storage struct IndexDescription @@ -86,6 +87,20 @@ struct IndexDescription bool isSimpleSingleColumnIndex() const; }; +/// Checks that the functions referenced by the text index preprocessor and postprocessor expressions +/// may run with the permissions of `context`, and that they read no table, set or dictionary. Call only +/// where a user declares an index, on the node they submitted it to; elsewhere these resolve under the +/// global context, and stored metadata is not re-checked. +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context); + +/// Refuses a transform when the other hosts of an `ON CLUSTER` query do not run it as the initiator. +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration); +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index); + +/// Whether the declaration is a text index with a `preprocessor` or a `postprocessor` argument. +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration); +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index); + /// All secondary indices in storage struct IndicesDescription : public std::vector, IHints<> { diff --git a/src/Storages/MergeTree/KeyCondition.cpp b/src/Storages/MergeTree/KeyCondition.cpp index 2d6ff22b1111..1fb619b3cdc4 100644 --- a/src/Storages/MergeTree/KeyCondition.cpp +++ b/src/Storages/MergeTree/KeyCondition.cpp @@ -3775,6 +3775,11 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( DataTypePtr current_type, bool single_point) { + /// A bound where `isNull()` holds stands in for NULL or for an infinity, and is left untransformed below, + /// so no transformed value would remain to compare against an atom in the function's result domain. + if (single_point && (key_range.left.isNull() || key_range.right.isNull())) + return {}; + for (const auto & func : functions) { /// We check the monotonicity of each function on a specific range. @@ -3791,17 +3796,21 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( /// If we apply function to open interval, we can get empty intervals in result. /// E.g. for ('2020-01-03', '2020-01-20') after applying 'toYYYYMM' we will get ('202001', '202001'). /// To avoid this we make range left and right included. - /// Any function that treats NULL specially is not monotonic. - /// Thus we can safely use isNull() as an -Inf/+Inf indicator here. + /// A NULL bound is an -inf/+inf stand-in and is left as is. A function that returns NULL for a non-NULL + /// argument leaves a bound with no position in the `Range` order, so the range cannot be analyzed. if (!key_range.left.isNull()) { key_range.left = applyFunction(func, current_type, key_range.left); + if (key_range.left.isNull()) + return {}; key_range.left_included = true; } if (!key_range.right.isNull()) { key_range.right = applyFunction(func, current_type, key_range.right); + if (key_range.right.isNull()) + return {}; key_range.right_included = true; } diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp index 5b0543026617..b0cf4a2bb646 100644 --- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp +++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp @@ -540,8 +540,7 @@ MergeTreeReadTaskColumns getReadTaskColumns( index_read_tasks, actions_settings, reader_settings.enable_multiple_prewhere_read_steps, - reader_settings.force_short_circuit_execution, - &storage_snapshot->metadata->getColumns()); + reader_settings.force_short_circuit_execution); for (const auto & step : prewhere_actions.steps) add_step(*step); diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index fd61defc239a..7c8f71bd5502 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -293,6 +293,7 @@ namespace MergeTreeSetting extern const MergeTreeSettingsMergeTreeStringSerializationVersion string_serialization_version; extern const MergeTreeSettingsMergeTreeNullableSerializationVersion nullable_serialization_version; extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version; + extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version_for_zero_level_parts; extern const MergeTreeSettingsUInt32 min_level_for_wide_part; extern const MergeTreeSettingsBool propagate_types_serialization_versions_to_nested_types; } @@ -894,6 +895,14 @@ bool MergeTreeData::supportsFinal() const || merging_params.mode == MergingParams::VersionedCollapsing; } +bool MergeTreeData::hasBucketedMapSerialization() const +{ + /// Inserted parts use the zero-level setting, merged parts the other one. + auto settings = getSettings(); + return (*settings)[MergeTreeSetting::map_serialization_version] == MergeTreeMapSerializationVersion::WITH_BUCKETS + || (*settings)[MergeTreeSetting::map_serialization_version_for_zero_level_parts] == MergeTreeMapSerializationVersion::WITH_BUCKETS; +} + static void checkKeyExpression(const ExpressionActions & expr, const Block & sample_block, const String & key_name, bool allow_nullable_key) { if (expr.hasArrayJoin()) @@ -10134,7 +10143,7 @@ QueryPipeline MergeTreeData::updateLightweightImpl(const MutationCommands & comm if (it != commands.end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Got unexpected command with type {} in lightweight update", it->type); - LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.toString(false)); + LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.ast(false)->formatForLogging()); MutationCommands commands_to_run; const auto & system_columns = getPatchPartSystemColumns(); @@ -10665,6 +10674,16 @@ StorageSnapshotPtr MergeTreeData::getStorageSnapshot(const StorageMetadataPtr & return cache->emplace(this, createStorageSnapshot(metadata_snapshot, query_context, false)).first->second; } +void MergeTreeData::discardSharedStorageSnapshot(const ContextPtr & query_context) const +{ + auto query_metadata_cache = query_context->getQueryMetadataCache(); + if (!query_metadata_cache) + return; + + auto [cache, lock] = query_metadata_cache->getStorageSnapshotCache(); + cache->erase(this); +} + StorageSnapshotPtr MergeTreeData::getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const { diff --git a/src/Storages/MergeTree/MergeTreeData.h b/src/Storages/MergeTree/MergeTreeData.h index 24c347de459d..c19156cfd60f 100644 --- a/src/Storages/MergeTree/MergeTreeData.h +++ b/src/Storages/MergeTree/MergeTreeData.h @@ -548,6 +548,8 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; + bool supportsTTL() const override { return true; } bool supportsColumnsWithDynamicStructure() const override { return true; } @@ -648,6 +650,11 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr /// The same as above but does not hold vector of data parts. StorageSnapshotPtr getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const override; + /// Removes the snapshot of this table from the query-scoped snapshot cache of + /// `enable_shared_storage_snapshot_in_query`, so that the next `getStorageSnapshot` in the query + /// takes a fresh one. Holders of the removed snapshot keep it. + void discardSharedStorageSnapshot(const ContextPtr & query_context) const; + /// Load the set of data parts from disk. Call once - immediately after the object is created. void loadDataParts(bool skip_sanity_checks, std::optional> expected_parts); diff --git a/src/Storages/MergeTree/MergeTreeDataWriter.cpp b/src/Storages/MergeTree/MergeTreeDataWriter.cpp index 0eda0376f9db..94aa1b21eb17 100644 --- a/src/Storages/MergeTree/MergeTreeDataWriter.cpp +++ b/src/Storages/MergeTree/MergeTreeDataWriter.cpp @@ -514,6 +514,11 @@ Block MergeTreeDataWriter::mergeBlock( span.addAttribute("clickhouse.rows", block_size); span.addAttribute("clickhouse.columns", header->columns()); + /// The block can lose all its rows before this point, e.g. when insert deduplication removes + /// duplicate rows of a materialized view block. Merging algorithms do not expect an empty input. + if (block_size == 0) + return *header; + auto get_merging_algorithm = [&]() -> std::shared_ptr { switch (merging_params.mode) diff --git a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp index 8d0538e64453..1964c89f521f 100644 --- a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace DB @@ -28,6 +29,7 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int CORRUPTED_DATA; extern const int ILLEGAL_COLUMN; extern const int INCORRECT_QUERY; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; @@ -87,9 +89,22 @@ void MergeTreeIndexGranuleBloomFilter::deserializeBinary(ReadBuffer & istr, Merg throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown index version {}.", version); readVarUInt(total_rows, istr); + if (total_rows == 0) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Bloom filter index granule has zero rows"); - static size_t atom_size = 8; - size_t bytes_size = (bits_per_row * total_rows + atom_size - 1) / atom_size; + static constexpr size_t atom_size = 8; + size_t bits_size = 0; + if (common::mulOverflow(bits_per_row, total_rows, bits_size) + || common::addOverflow(bits_size, atom_size - 1, bits_size)) + { + throw Exception( + ErrorCodes::CORRUPTED_DATA, + "Bloom filter index granule size overflows for {} rows and {} bits per row", + total_rows, + bits_per_row); + } + + size_t bytes_size = bits_size / atom_size; size_t read_size = bytes_size; for (auto & filter : bloom_filters) { diff --git a/src/Storages/MergeTree/MergeTreeIndexSet.cpp b/src/Storages/MergeTree/MergeTreeIndexSet.cpp index 91ea8793399b..61443eea6299 100644 --- a/src/Storages/MergeTree/MergeTreeIndexSet.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexSet.cpp @@ -572,6 +572,21 @@ const ActionsDAG::Node & MergeTreeIndexConditionSet::traverseDAG(const ActionsDA { auto bit_wrapper_function = FunctionFactory::instance().get("__bitWrapperFunc", context); result_node = &result_dag.addFunction(bit_wrapper_function, {atom_node_ptr}, {}); + + /// A NULL atom value yields a NULL from `__bitWrapperFunc` rather than a BoolMask. + /// That NULL propagates through `__bitBoolMaskAnd`/`Or` and wrongly prunes a granule + /// the atom does not exclude. Map a NULL mask to `UNKNOWN_FIELD` (can be true or false). + if (isNullableOrLowCardinalityNullable(result_node->result_type)) + { + ColumnWithTypeAndName unknown_field_column_with_type; + unknown_field_column_with_type.name = calculateConstantActionNodeName(UNKNOWN_FIELD); + unknown_field_column_with_type.type = std::make_shared(); + unknown_field_column_with_type.column = unknown_field_column_with_type.type->createColumnConst(1, UNKNOWN_FIELD); + const auto & unknown_node = result_dag.addColumn(unknown_field_column_with_type); + + auto if_null_function = FunctionFactory::instance().get("ifNull", context); + result_node = &result_dag.addFunction(if_null_function, {result_node, &unknown_node}, {}); + } } else { diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp index db7da52fdaf7..a4e9b9a702a5 100644 --- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp +++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp @@ -1596,6 +1596,14 @@ void MergeTreeRangeReader::executePrewhereActionsAndFilterColumns(ReadResult & r /// Columns might be projected out. We need to store them here so that default columns can be evaluated later. Block additional_columns = block; + /// Carry over columns projected out at earlier steps: they may be needed + /// to evaluate defaults of columns missing in the part. + for (const auto & col : result.additional_columns) + { + if (!additional_columns.has(col.name)) + additional_columns.insert(col); + } + if (prewhere_info->actions) { const String dummy_column = addDummyColumnWithRowCount(block, result.num_rows); diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp index 147e7778daad..f20a455b4f2b 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp @@ -132,8 +132,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_, - LazyMaterializingRowsPtr lazy_materializing_rows_, - const ColumnsDescription * columns_) + LazyMaterializingRowsPtr lazy_materializing_rows_) : pool(std::move(pool_)) , algorithm(std::move(algorithm_)) , row_level_filter(row_level_filter_) @@ -145,8 +144,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( index_read_tasks_, actions_settings, reader_settings_.enable_multiple_prewhere_read_steps, - reader_settings_.force_short_circuit_execution, - columns_)) + reader_settings_.force_short_circuit_execution)) , reader_settings(reader_settings_) , result_header(transformHeader(pool->getHeader(), row_level_filter, prewhere_info)) , merge_tree_index_build_context(std::move(merge_tree_index_build_context_)) @@ -174,8 +172,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { PrewhereExprInfo prewhere_actions; @@ -208,7 +205,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( } if (prewhere_info && - (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution, columns))) + (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution))) { PrewhereExprStep prewhere_step { diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.h b/src/Storages/MergeTree/MergeTreeSelectProcessor.h index b044ff67fc1f..5909f164ed45 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.h +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.h @@ -108,8 +108,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_ = {}, - LazyMaterializingRowsPtr lazy_materializing_rows_ = {}, - const ColumnsDescription * columns_ = nullptr); + LazyMaterializingRowsPtr lazy_materializing_rows_ = {}); String getName() const; @@ -138,8 +137,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); void addPartLevelToChunk(bool add_part_level_) { add_part_level = add_part_level_; } diff --git a/src/Storages/MergeTree/MergeTreeSettings.cpp b/src/Storages/MergeTree/MergeTreeSettings.cpp index d6317adfe555..edb023a8c897 100644 --- a/src/Storages/MergeTree/MergeTreeSettings.cpp +++ b/src/Storages/MergeTree/MergeTreeSettings.cpp @@ -1171,7 +1171,7 @@ namespace ErrorCodes in the Keeper, the cache will update as soon as possible, so that we are able to filter the duplicated inserts in the memory. )", 0) \ - DECLARE(UInt64, max_replicated_logs_to_keep, 1000, R"( + DECLARE(NonZeroUInt64, max_replicated_logs_to_keep, 1000, R"( How many records may be in the ClickHouse Keeper log if there is inactive replica. An inactive replica becomes lost when when this number exceed. diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp index 52c20d4ee7d8..abf6b4c90f7e 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp @@ -1,8 +1,5 @@ #include -#include -#include - namespace DB { @@ -22,29 +19,10 @@ namespace struct NodeInfo { NameSet required_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column are placed into one step. - NameSet required_storage_columns; }; -/// Resolves a column name to its storage (physical) name. -/// For subcolumns like `map.key_k0`, returns `map`. -/// For regular columns, returns the name unchanged. -String resolveStorageColumnName(const String & column_name, const ColumnsDescription * columns) -{ - if (columns) - { - if (auto col = columns->tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, column_name)) - return col->getNameInStorage(); - } - return column_name; -} - /// Fills the list of required columns for a node in the DAG. -void fillRequiredColumns( - const ActionsDAG::Node * node, - std::unordered_map & nodes_info, - const ColumnsDescription * columns) +void fillRequiredColumns(const ActionsDAG::Node * node, std::unordered_map & nodes_info) { if (nodes_info.contains(node)) return; @@ -54,16 +32,14 @@ void fillRequiredColumns( if (node->type == ActionsDAG::ActionType::INPUT) { node_info.required_columns.insert(node->result_name); - node_info.required_storage_columns.insert(resolveStorageColumnName(node->result_name, columns)); return; } for (const auto & child : node->children) { - fillRequiredColumns(child, nodes_info, columns); + fillRequiredColumns(child, nodes_info); const auto & child_info = nodes_info[child]; node_info.required_columns.insert(child_info.required_columns.begin(), child_info.required_columns.end()); - node_info.required_storage_columns.insert(child_info.required_storage_columns.begin(), child_info.required_storage_columns.end()); } } @@ -226,8 +202,7 @@ bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { if (!prewhere_info) return true; @@ -243,37 +218,21 @@ bool tryBuildPrewhereSteps( std::unordered_map nodes_info; for (const auto & node : condition_nodes) { - fillRequiredColumns(node, nodes_info, columns); + fillRequiredColumns(node, nodes_info); } /// 3. Sort condition nodes by the number of columns used in them and the overall size of those columns /// TODO: not sorting for now because the conditions are already sorted by Where Optimizer - /// 4. Group adjacent conditions that read from the same set of physical storage columns into a single step. - /// Conditions on subcolumns of the same column (e.g. `map.key_k0` and `map.key_k1`) are placed into one group - /// when they appear next to each other in the condition list. - /// - /// Only adjacent conditions are merged to preserve the user's explicit PREWHERE evaluation order. - /// Non-adjacent conditions on the same storage column are kept in separate steps even though this - /// may cause redundant reads, because the user may have intentionally interleaved a guard predicate - /// (e.g. `PREWHERE tags['safe'] != '' AND value > 0 AND toUInt64(tags['unsafe']) > 0` — the - /// `value > 0` step must filter rows before evaluating the potentially-throwing conversion). - /// - /// For the WHERE-to-PREWHERE path this is not a problem: `MergeTreeWhereOptimizer` already groups - /// conditions by their physical storage columns, so subcolumns of the same column arrive here adjacent. + /// 4. Group conditions with the same set of columns into a single read/compute step std::vector> condition_groups; for (const auto & node : condition_nodes) { const auto & node_info = nodes_info[node]; - if (!condition_groups.empty() - && nodes_info[condition_groups.back().front()].required_storage_columns == node_info.required_storage_columns) - { - condition_groups.back().push_back(node); - } + if (!condition_groups.empty() && nodes_info[condition_groups.back().back()].required_columns == node_info.required_columns) + condition_groups.back().push_back(node); /// Add to the last group else - { - condition_groups.push_back({node}); - } + condition_groups.push_back({node}); /// Start new group } /// 5. Build DAGs for each step diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h index 4d3845a7e048..833e6f506992 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h @@ -13,13 +13,10 @@ namespace DB { -class ColumnsDescription; - bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index dbfc28547453..39df2ecbc8ef 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -338,17 +338,6 @@ void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const RPNBuilderTree cond.columns_size = getColumnsSize(cond.table_columns); - /// Resolve each column to its physical storage name so that subcolumns - /// of the same column (e.g. `map.key_k0`, `map.key_k1`) share one group. - const auto & storage_columns_description = storage_metadata->getColumns(); - for (const auto & col : cond.table_columns) - { - if (auto resolved = storage_columns_description.tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, col)) - cond.table_storage_columns.insert(resolved->getNameInStorage()); - else - cond.table_storage_columns.insert(col); - } - cond.viable = !has_invalid_column /// Condition depend on some column. Constant expressions are not moved. @@ -495,20 +484,17 @@ std::optional MergeTreeWhereOptimizer:: } }; - /// Move condition and all other conditions that depend on the same set of physical storage columns. - /// Grouping by storage columns (rather than the exact column set) keeps subcolumns of the - /// same column (e.g. `map.key_k0` and `map.key_k1`) in one group, so they are moved to - /// PREWHERE together and arrive adjacent for the prewhere-splitting step. + /// Move condition and all other conditions depend on the same set of columns. auto move_condition = [&](Conditions::iterator cond_it) { move_to_prewhere_conditions(cond_it); total_size_of_moved_conditions += cond_it->columns_size; total_number_of_moved_columns += cond_it->table_columns.size(); - /// Move all other viable conditions that depend on the same set of storage columns. + /// Move all other viable conditions that depend on the same set of columns. for (auto jt = where_conditions.begin(); jt != where_conditions.end();) { - if (jt->viable && jt->table_storage_columns == cond_it->table_storage_columns) + if (jt->viable && jt->columns_size == cond_it->columns_size && jt->table_columns == cond_it->table_columns) { move_to_prewhere_conditions(jt++); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h index bf2b97b3640d..b0a8bfdb2173 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h @@ -69,10 +69,6 @@ class MergeTreeWhereOptimizer : private boost::noncopyable UInt64 columns_size = 0; NameSet table_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column - /// (e.g. `map.key_k0` and `map.key_k1`) are grouped and moved to PREWHERE together. - NameSet table_storage_columns; /// Can condition be moved to prewhere? bool viable = false; diff --git a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp index 3f8edc6d4cc1..c94d1390bf19 100644 --- a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp +++ b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp @@ -144,7 +144,7 @@ ReplicatedMergeMutateTaskBase::PrepareResult MutateFromLogEntryTask::prepare() Strings mutation_ids; commands = std::make_shared(storage.queue.getMutationCommands(source_part, new_part_info.mutation, mutation_ids)); LOG_TRACE(log, "Mutating part {} with mutation commands from {} mutations ({}): {}", - entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->toString(true)); + entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->ast(true)->formatForLogging()); /// mutation_ids can be empty here. mutation_ids_for_log = mutation_ids; diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index 3735c427cffc..a2490c3ec29e 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -12,7 +12,7 @@ namespace MergeTreeSetting { extern const MergeTreeSettingsUInt64 finished_mutations_to_keep; extern const MergeTreeSettingsSeconds lock_acquire_timeout_for_background_operations; - extern const MergeTreeSettingsUInt64 max_replicated_logs_to_keep; + extern const MergeTreeSettingsNonZeroUInt64 max_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 min_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 replicated_deduplication_window; extern const MergeTreeSettingsUInt64 replicated_deduplication_window_for_async_inserts; diff --git a/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp new file mode 100644 index 000000000000..007d155521ef --- /dev/null +++ b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include +#include + +#include + +using namespace DB; + +namespace DB::ErrorCodes +{ + extern const int CORRUPTED_DATA; +} + +namespace +{ + +String encodeRowCount(size_t row_count) +{ + WriteBufferFromOwnString out; + writeVarUInt(row_count, out); + return out.str(); +} + +void expectCorruptedRowCount(size_t bits_per_row, size_t row_count) +{ + MergeTreeIndexGranuleBloomFilter granule(bits_per_row, 3, 1); + String encoded = encodeRowCount(row_count); + ReadBufferFromString in(encoded); + + try + { + granule.deserializeBinary(in, 1); + FAIL() << "Expected a corrupted Bloom-filter granule to be rejected"; + } + catch (const Exception & exception) + { + EXPECT_EQ(exception.code(), ErrorCodes::CORRUPTED_DATA); + } +} + +} + +TEST(MergeTreeIndexBloomFilterTest, DeserializesValidGranule) +{ + String encoded = encodeRowCount(1); + encoded.append(sizeof(BloomFilter::UnderType), '\0'); + + MergeTreeIndexGranuleBloomFilter granule(12, 3, 1); + ReadBufferFromString in(encoded); + + EXPECT_NO_THROW(granule.deserializeBinary(in, 1)); + EXPECT_FALSE(granule.empty()); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsZeroRowGranule) +{ + expectCorruptedRowCount(12, 0); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsFilterSizeOverflow) +{ + constexpr size_t bits_per_row = 12; + constexpr size_t overflowing_rows = std::numeric_limits::max() / bits_per_row + 1; + expectCorruptedRowCount(bits_per_row, overflowing_rows); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsRoundedFilterSizeOverflow) +{ + expectCorruptedRowCount(1, std::numeric_limits::max()); +} diff --git a/src/Storages/ObjectStorage/Azure/Configuration.cpp b/src/Storages/ObjectStorage/Azure/Configuration.cpp index 574921743d36..03767ddf2d66 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.cpp +++ b/src/Storages/ObjectStorage/Azure/Configuration.cpp @@ -44,7 +44,6 @@ namespace ErrorCodes { extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; - extern const int LOGICAL_ERROR; } const std::unordered_set required_configuration_keys = { @@ -69,7 +68,7 @@ const std::unordered_set optional_configuration_keys = { void StorageAzureConfiguration::check(ContextPtr context) { - auto url = Poco::URI(connection_params.getConnectionURL()); + auto url = Poco::URI(connection_params.getConnectionURLWithoutQuery()); context->getGlobalContext()->getRemoteHostFilter().checkURL(url); StorageObjectStorageConfiguration::check(context); } @@ -163,9 +162,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url if (pos_container != std::string::npos) { - String container_blob_path = connection_url.substr(pos_container+5); - connection_url = connection_url.substr(0,pos_container+4); - container_name = connection_url.substr(pos_container+4); + size_t host_end = pos_container + suffix.size(); + String container_blob_path = host_end < connection_url.size() ? connection_url.substr(host_end + 1) : ""; + connection_url.resize(host_end); auto pos_blob_path = container_blob_path.find('/'); if (pos_blob_path != std::string::npos) @@ -185,9 +184,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url auto pos_net = connection_url.find(suffix); if (pos_slash == std::string::npos || pos_at == std::string::npos|| pos_dot == std::string::npos || pos_net == std::string::npos - || pos_at-pos_slash-3 <= 0 || pos_dot-pos_at-1 <= 0) + || pos_at <= pos_slash + 3 || pos_dot <= pos_at + 1) { - throw Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect url format for a abfss url {}", connection_url); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Incorrect url format for a abfss url {}", connection_url); } auto container_name_abfss = connection_url.substr(pos_slash+3, pos_at-pos_slash-3); auto name = connection_url.substr(pos_at+1, pos_dot-pos_at-1); diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 3a346c1d28f2..08aa8818f4a3 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -106,7 +106,7 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration void setPaths(const Paths & paths) override { blobs_paths = paths; } String getNamespace() const override { return connection_params.getContainer(); } - String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURL()) / connection_params.getContainer(); } + String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURLWithoutQuery()) / connection_params.getContainer(); } StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; void check(ContextPtr context) override; diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp index e7b956fd20c6..28c9ba764fd3 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp @@ -51,6 +51,7 @@ try } metadata = manifest_file_reader->metadata(); + bytes_read = buffer->count(); parsed_column = std::move(columns[0]); parsed_column_data_type = std::dynamic_pointer_cast(data_type); parsed_manifest_file_entries.resize(parsed_column->size()); diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h index 2cf4c8a61d61..997c587f1880 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h @@ -45,6 +45,8 @@ class AvroForIcebergDeserializer std::map> metadata; + size_t bytes_read = 0; + /// Shared mutex to protect mutable cache members for thread safety mutable SharedMutex cache_mutex; @@ -71,6 +73,9 @@ class AvroForIcebergDeserializer size_t rows() const; + /// The constructor consumes the whole file, so this is its size on storage. + size_t bytesRead() const { return bytes_read; } + /// Allow to access avro paths like "a.b.c" bool hasPath(const std::string & path) const; DB::TypeIndex getTypeForPath(const std::string & path) const; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp index 3e9dd4058b3f..cac54224ac17 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp @@ -90,6 +90,30 @@ Field parseFieldFromString(const String & value, DB::DataTypePtr data_type) namespace DeltaLake { +namespace +{ + +/// A data file with the size its `add` action records. +struct DataObjectInfo : public DB::ObjectInfo +{ + DataObjectInfo(std::string path_, int64_t size_) + : DB::ObjectInfo(DB::RelativePathWithMetadata(std::move(path_))) + , size(size_) + { + } + + std::optional getFileSizeHint() const override + { + if (size > 0) + return static_cast(size); + return std::nullopt; + } + + const int64_t size; +}; + +} + class TableSnapshot::Iterator final : public DB::IObjectIterator { private: @@ -120,7 +144,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator const TableSchema & table_schema_, const DB::NameToNameMap & physical_names_map_, const DB::Names & partition_columns_, - DB::ObjectStoragePtr object_storage_, const DB::ActionsDAG * filter_, DB::IDataLakeMetadata::FileProgressCallback callback_, size_t list_batch_size_, @@ -135,7 +158,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator , read_schema(read_schema_) , expression_schema(table_schema_) , partition_columns(partition_columns_) - , object_storage(object_storage_) , callback(callback_) , list_batch_size(list_batch_size_) , log(log_) @@ -437,13 +459,9 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator } parseDVHandle(*scan_item, object); - object->setObjectMetadata(object_storage->getObjectMetadata(object->getPath(), /*with_tags=*/ false)); if (callback) - { - chassert(object->getObjectMetadata()); - callback(DB::FileProgress(0, object->getObjectMetadata()->size_bytes)); - } + callback(DB::FileProgress(0, object->getFileSizeHint().value_or(0))); return object; } } @@ -597,7 +615,7 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator std::string full_path = DB::resolvePathInsideTable( context->getDataPath(), DB::unescapeForFileName(KernelUtils::fromDeltaString(path))); - auto object = std::make_shared(DB::RelativePathWithMetadata(std::move(full_path))); + auto object = std::make_shared(std::move(full_path), size); object->data_lake_metadata.emplace(); LOG_TEST( @@ -641,7 +659,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator DB::NamesAndTypesList read_schema; DB::NamesAndTypesList expression_schema; DB::Names partition_columns; - const DB::ObjectStoragePtr object_storage; const DB::IDataLakeMetadata::FileProgressCallback callback; const size_t list_batch_size; const LoggerPtr log; @@ -966,7 +983,6 @@ DB::ObjectIterator TableSnapshot::iterate( schema->table_schema, schema->physical_names_map, schema->partition_columns, - object_storage, filter_dag, callback, list_batch_size, diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp index 94c263c0e7e7..dc22ef8c5954 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp @@ -45,18 +45,13 @@ UInt64 getCurrentTime() return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } -void exportTable( - std::shared_ptr table, +void exportRecordBatch( + const arrow::RecordBatch & batch, ffi::FFI_ArrowArray & array, ffi::FFI_ArrowSchema & schema) { - auto batch = table->CombineChunksToBatch(); - if (!batch.ok()) - throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, - "Failed to create chunks batch: {}", batch.status().ToString()); - arrow::Status status = arrow::ExportRecordBatch( - **batch, + batch, reinterpret_cast(&array), reinterpret_cast(&schema)); @@ -230,30 +225,61 @@ void WriteTransaction::commit(const std::vector & files) LOG_TEST(log, "Will commit {} files", files.size()); auto write_metadata = getWriteMetadata(files, log); - ffi::FFI_ArrowArray array; - ffi::FFI_ArrowSchema schema; - SCOPE_EXIT({ - if (schema.release) - schema.release(&schema); - }); - exportTable(write_metadata, array, schema); - - KernelEngineData engine_data; - try + /// Metadata too large for one Arrow record batch comes back as several table chunks. Recombining them + /// would hit the same 32-bit offset limit, so each record batch is added to the transaction on its own. + /// `TableBatchReader` yields nothing for an empty table, which still has to reach the kernel as before. + arrow::RecordBatchVector batches; + if (write_metadata->num_rows() == 0) { - /// Takes ownership of `array` (but not`schema`) if successfully called. - engine_data = DeltaLake::KernelUtils::unwrapResult( - ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), - "get_engine_data"); + auto empty_batch = arrow::RecordBatch::MakeEmpty(write_metadata->schema()); + if (!empty_batch.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to create an empty record batch: {}", empty_batch.status().ToString()); + batches.push_back(*std::move(empty_batch)); } - catch (...) + else { - if (array.release) - array.release(&array); - throw; + arrow::TableBatchReader batch_reader(*write_metadata); + while (true) + { + std::shared_ptr batch; + arrow::Status read_status = batch_reader.ReadNext(&batch); + if (!read_status.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to read a record batch: {}", read_status.ToString()); + if (!batch) + break; + batches.push_back(std::move(batch)); + } } - ffi::add_files(transaction.get(), engine_data.release()); + for (const auto & batch : batches) + { + ffi::FFI_ArrowArray array{}; + ffi::FFI_ArrowSchema schema{}; + SCOPE_EXIT({ + if (schema.release) + schema.release(&schema); + }); + exportRecordBatch(*batch, array, schema); + + KernelEngineData engine_data; + try + { + /// Takes ownership of `array` (but not`schema`) if successfully called. + engine_data = DeltaLake::KernelUtils::unwrapResult( + ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), + "get_engine_data"); + } + catch (...) + { + if (array.release) + array.release(&array); + throw; + } + + ffi::add_files(transaction.get(), engine_data.release()); + } auto version = DeltaLake::KernelUtils::unwrapResult(ffi::commit(transaction.release(), engine.get()), "commit"); LOG_TEST(log, "Commit version: {}", version); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp index c0072e3e576b..74fcc2accefb 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp @@ -182,8 +182,7 @@ std::optional SingleThreadIcebergKeysIterator::ne persistent_components, local_context, log, - mle.manifest_file_path, - mle.manifest_file_byte_size); + mle.manifest_file_path); current_manifest_file_iterator = Iceberg::ManifestFileIterator::create( manifest_file_cacheable_part.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h index 44309f94e60a..63479720f676 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h @@ -74,7 +74,7 @@ struct IcebergMetadataFilesCacheCell : private boost::noncopyable /// - manifest list consists of cache keys which will retrieve the manifest file from cache [file_path --> ManifestFileCacheKeys] /// - manifest file [file_path --> Iceberg::ManifestFileCacheableInfo] std::variant cached_element; - Int64 memory_bytes; + size_t memory_bytes; explicit IcebergMetadataFilesCacheCell(String && metadata_json_str) : cached_element(std::move(metadata_json_str)) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp index e8226dadcd76..fd279ca1936a 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp @@ -74,6 +74,9 @@ void MultipleFileWriter::finalize() output_format->finalize(); buffer->finalize(); total_bytes += buffer->count(); + + /// A finished format can still hold resources: a Parquet one keeps its idle encoder threads. + release(); } void MultipleFileWriter::release() diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp index 5039abab707a..859b46f2b219 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp @@ -259,6 +259,8 @@ static std::optional writeDataFiles( delete_data_writers[partition_key]->finalize(); delete_data_write_buffers[partition_key]->finalize(); delete_data_result[partition_key].total_bytes = static_cast(delete_data_write_buffers[partition_key]->count()); + delete_data_writers[partition_key].reset(); + delete_data_write_buffers[partition_key].reset(); } } @@ -317,6 +319,8 @@ static std::optional writeDataFiles( update_data_writers[partition_key]->finalize(); update_data_write_buffers[partition_key]->finalize(); update_data_result[partition_key].total_bytes = static_cast(update_data_write_buffers[partition_key]->count()); + update_data_writers[partition_key].reset(); + update_data_write_buffers[partition_key].reset(); } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp index b65109e9f697..d342906b3302 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp @@ -69,8 +69,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size) + const String & filename) { auto log_level = local_context->getSettingsRef()[Setting::iceberg_metadata_log_level].value; @@ -90,7 +89,8 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( auto manifest_file_deserializer = std::make_unique( std::move(buffer), filename, getFormatSettings(local_context)); - return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), bytes_size}; + const size_t manifest_file_bytes = manifest_file_deserializer->bytesRead(); + return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), manifest_file_bytes}; }; if (use_iceberg_metadata_cache && persistent_table_components.table_uuid.has_value()) @@ -115,8 +115,7 @@ Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesH persistent_table_components, local_context, log, - cache_key.manifest_file_path, - static_cast(cache_key.manifest_file_byte_size)); + cache_key.manifest_file_path); auto iterator = Iceberg::ManifestFileIterator::create( cacheable_info.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h index ac5a7f7bc06e..5df057a2bb49 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h @@ -28,8 +28,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size); + const String & filename); /// Creates a fully initialized ManifestFileIterator from a cache key. /// All entries are drained so that aggregate methods (e.g. getRowsCountInAllFilesExcludingDeleted) diff --git a/src/Storages/ObjectStorage/IObjectIterator.h b/src/Storages/ObjectStorage/IObjectIterator.h index 83c645e915fd..1b191139ce67 100644 --- a/src/Storages/ObjectStorage/IObjectIterator.h +++ b/src/Storages/ObjectStorage/IObjectIterator.h @@ -41,6 +41,7 @@ struct ObjectInfo virtual size_t fileSizeInArchive() const { throw Exception(ErrorCodes::LOGICAL_ERROR, "Not an archive"); } virtual std::string getPathOrPathToArchiveIfArchive() const; virtual std::optional getFileFormat() const { return std::nullopt; } + virtual std::optional getFileSizeHint() const { return std::nullopt; } std::optional getObjectMetadata() const { return relative_path_with_metadata.metadata; } void setObjectMetadata(const ObjectMetadata & metadata) { relative_path_with_metadata.metadata = metadata; } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp index 2acdbf6da675..1d4de8b623cd 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp @@ -95,6 +95,15 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + String getObjectStorageHash(const IObjectStorage & object_storage) + { + const String description = object_storage.getDescription(); + return sipHash128String(description.substr(0, description.find('?')) + '\0' + object_storage.getObjectsNamespace()); + } +} + StorageObjectStorageSource::StorageObjectStorageSource( String name_, ObjectStoragePtr object_storage_, @@ -536,7 +545,7 @@ void StorageObjectStorageSource::addNumRowsToCache(const ObjectInfo & object_inf schema_cache.addNumRows(cache_key, num_rows); } -StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader() +StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader(bool prefetch_input_format) { return createReader( 0, @@ -551,7 +560,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade max_block_size, parser_shared_resources, format_filter_info, - need_only_count); + need_only_count, + prefetch_input_format); } StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader( @@ -567,7 +577,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count) + bool need_only_count, + bool prefetch_input_format) { ObjectInfoPtr object_info; auto query_settings = configuration->getQuerySettings(context_); @@ -832,6 +843,9 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade if (need_only_count) input_format->needOnlyCount(); + if (prefetch_input_format) + input_format->prefetch(); + builder.init(Pipe(input_format)); configuration->addDeleteTransformers(object_info, builder, format_settings, parser_shared_resources, context_); @@ -977,7 +991,7 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade std::future StorageObjectStorageSource::createReaderAsync() { - return create_reader_scheduler([=, this] { return createReader(); }, Priority{}); + return create_reader_scheduler([=, this] { return createReader(/* prefetch_input_format */ true); }, Priority{}); } std::unique_ptr createReadBuffer( @@ -1099,6 +1113,7 @@ std::unique_ptr createReadBuffer( else { SipHash hash; + hash.update(getObjectStorageHash(*object_storage)); hash.update(object_info.getPath()); hash.update(object_info.metadata->etag); @@ -1147,7 +1162,9 @@ std::unique_ptr createReadBuffer( if (use_page_cache) { - PageCacheKey key = {.path = "s3:" + object_info.getPath(), .file_version = "etag:" + object_info.metadata->etag}; + PageCacheKey key = { + .path = fmt::format("s3:{}:{}", getObjectStorageHash(*object_storage), object_info.getPath()), + .file_version = "etag:" + object_info.metadata->etag}; impl = std::make_unique(key, effective_read_settings.page_cache, std::move(impl), modified_read_settings); } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.h b/src/Storages/ObjectStorage/StorageObjectStorageSource.h index 5cbe931a047e..375187276c51 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.h @@ -136,9 +136,10 @@ class StorageObjectStorageSource : public ISource size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count); + bool need_only_count, + bool prefetch_input_format = false); - ReaderHolder createReader(); + ReaderHolder createReader(bool prefetch_input_format = false); std::future createReaderAsync(); diff --git a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h index e9d9bd0f7414..a338ae7dead0 100644 --- a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h +++ b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h @@ -1,7 +1,7 @@ #pragma once #include #include -#include +#include #include namespace AzureQueue @@ -20,10 +20,7 @@ static inline std::unordered_map SETTINGS_TO_HIDE = std::string masked_value; if (!value.tryGet(masked_value)) return {}; - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - RE2::Replace(&masked_value, account_key_pattern, "AccountKey=[HIDDEN]\\1"); - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - RE2::Replace(&masked_value, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1"); + DB::maskAzureConnectionStringSecrets(masked_value); return fmt::format("'{}'", masked_value); }}, }; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp new file mode 100644 index 000000000000..e845fa34a6c0 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -0,0 +1,119 @@ +#include + +#include "config.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include + + +namespace DB +{ + +namespace +{ + +enum class MoveDestinationKind : uint8_t +{ + S3, + Azure, +}; + +std::optional getMoveDestinationKind(std::string_view name) +{ + /// The prefix is accepted for every queue setting, see `normalizeSetting` in `StorageObjectStorageQueue.cpp`. + static constexpr std::string_view legacy_prefix = "s3queue_"; + if (name.starts_with(legacy_prefix)) + name.remove_prefix(legacy_prefix.size()); + + if (name == "after_processing_move_uri") + return MoveDestinationKind::S3; + if (name == "after_processing_move_connection_string" || name == "after_processing_move_container") + return MoveDestinationKind::Azure; + return std::nullopt; +} + +AccessTypeObjects::Source getAccessSource(MoveDestinationKind kind) +{ + switch (kind) + { + case MoveDestinationKind::S3: + return AccessTypeObjects::Source::S3; + case MoveDestinationKind::Azure: + return AccessTypeObjects::Source::AZURE; + } +} + +/// A value that is not a `String` is never empty here: it is checked like a destination that cannot be parsed. +bool isEmptyValue(const Field & value) +{ + return value.getType() == Field::Types::String && value.safeGet().empty(); +} + +/// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +{ + const bool sets_destination = std::ranges::any_of( + changes, + [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); + if (!sets_destination) + return {}; + + /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only + /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against + /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). + const auto source = getAccessSource(table_kind); + AccessRightsElements res; + res.emplace_back(AccessType::WRITE, AccessTypeObjects::toStringSource(source)); + return res; +} + +} + +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::S3); +} + +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); +} + +void checkObjectStorageQueueS3MoveDestinationHost( + [[maybe_unused]] const String & move_uri, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AWS_S3 + if (!move_uri.empty()) + S3::URI(move_uri).checkRemoteHostFilter(filter); +#endif +} + +void checkObjectStorageQueueAzureMoveDestinationHost( + [[maybe_unused]] const String & move_connection_string, + [[maybe_unused]] const String & move_container, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AZURE_BLOB_STORAGE + if (!move_connection_string.empty()) + { + AzureBlobStorage::ConnectionParams connection_params; + AzureBlobStorage::processURL(move_connection_string, move_container, connection_params.endpoint, connection_params.auth_method); + /// Without the query: a connection string can carry a SAS, which the message of `checkURL` must not show. + String url = connection_params.getConnectionURL(); + url = url.substr(0, url.find_first_of("?#")); + filter.checkURL(Poco::URI(url)); + } +#endif +} + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h new file mode 100644 index 000000000000..40601b4b1145 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +namespace DB +{ + +class RemoteHostFilter; + +/// The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +/// `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads every processed file +/// with its own source credentials and writes it to the destination. So setting the destination needs +/// `WRITE` on the `S3` (or `AZURE`) source without a URL filter: the move writes keys built from +/// `after_processing_move_prefix` and the source keys, not from the URI, so a filtered grant cannot authorize them. +/// For `ALTER` it also needs `SELECT` on the table, because the creator of the table, not the user of the `ALTER`, +/// supplied the source and its credentials. + +/// The `StorageFactory::GetExportAccessFn` of `S3Queue` and `AzureQueue`: unfiltered `WRITE` if a setting moves files outside +/// the source bucket or container. Only these settings choose such a destination: `after_processing_move_uri` for S3, +/// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy +/// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. +/// An empty value disables the move destination, so it is not a destination and needs no grant. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); + +/// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. +/// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. +/// Does nothing when `move_uri` is empty. +void checkObjectStorageQueueS3MoveDestinationHost(const String & move_uri, const RemoteHostFilter & filter); + +/// The same for a move to another Azure container (see `StorageAzureConfiguration::check`). +/// Does nothing when `move_connection_string` is empty. +void checkObjectStorageQueueAzureMoveDestinationHost( + const String & move_connection_string, const String & move_container, const RemoteHostFilter & filter); + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp index cd48a45926ea..a89c5ec4923a 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,11 @@ namespace S3AuthSetting extern const S3AuthSettingsString secret_access_key; } +namespace S3RequestSetting +{ + extern const S3RequestSettingsBool allow_native_copy; +} + #endif namespace ErrorCodes @@ -285,6 +291,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move S3 objects"); } + /// The settings are checked at `CREATE` and `ALTER` too. This is defense in depth for a table that was created before + /// those checks existed, or before the list of allowed hosts was tightened. If it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueS3MoveDestinationHost(move_uri, getContext()->getRemoteHostFilter()); + if (auto * s3_storage = dynamic_cast(object_storage.get()); s3_storage != nullptr) { auto src_client = s3_storage->getS3StorageClient(); @@ -304,6 +314,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object /* for_disk_s3 */ false ); auto dst_uri = S3::URI(move_uri); + /// Native copy sends `CopyObject` through the source client, so it writes to the source endpoint. That is the checked + /// destination only if both clients use the same endpoint, otherwise use the buffered copy, which uploads with `dst_client`. + if (src_client->getInitialEndpoint() != dst_client->getInitialEndpoint()) + s3_settings->request_settings[S3RequestSetting::allow_native_copy] = false; auto read_settings = getReadSettings(); const auto read_settings_to_use = s3_storage->patchSettings(read_settings); auto scheduler = threadPoolCallbackRunnerUnsafe( @@ -391,6 +405,9 @@ void ObjectStorageQueuePostProcessor::moveAzureBlobs(const StoredObjects & objec throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move Azure blobs"); } + /// See the comment in `moveS3Objects`: if it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, getContext()->getRemoteHostFilter()); + if (auto * azure_storage = dynamic_cast(object_storage.get()); azure_storage != nullptr) { auto contextPtr = getContext(); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp index 643418d037d7..45987c8046d3 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp @@ -5,7 +5,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -58,14 +60,14 @@ namespace ErrorCodes DECLARE(String, partition_component, "", "Name of the capture group from partition_regex to use as partition key. Required when using partitioning_mode='regex'. Example: 'hostname'", 0) \ DECLARE(ObjectStorageQueueBucketingMode, bucketing_mode, ObjectStorageQueueBucketingMode::PATH, "Bucketing strategy for Ordered mode parallel processing: PATH (hash full file path, default), PARTITION (hash partition key, requires partitioning_mode != NONE)", 0) \ DECLARE(UInt32, after_processing_retries, 10, "Number of retries for the after_processing action before giving up", 0) \ - DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to", 0) \ + DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to. Setting it requires the `WRITE` grant on the `S3` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The URL must be allowed by `remote_url_allow_hosts`", 0) \ DECLARE(String, after_processing_move_prefix, "", "Path prefix to move processed files to", 0) \ DECLARE(String, after_processing_tag_key, "", "Tag key to tag processed files in the storage", 0) \ DECLARE(String, after_processing_tag_value, "", "Tag value to tag processed files in the storage", 0) \ DECLARE(String, after_processing_move_access_key_id, "", "S3 Access Key ID accompanying after_processing_move_uri", 0) \ DECLARE(String, after_processing_move_secret_access_key, "", "S3 Secret Access Key accompanying after_processing_move_uri", 0) \ - DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to", 0) \ - DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string", 0) \ + DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The endpoint must be allowed by `remote_url_allow_hosts`", 0) \ + DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table", 0) \ DECLARE(Bool, use_hive_partitioning, false, "DEPRECATED: Use partitioning_mode='hive' instead. Whether path contains hive partitioning and this engine should process such files with a separate processed files tracking per partition.", 0) \ #define LIST_OF_OBJECT_STORAGE_QUEUE_SETTINGS(M, ALIAS) \ @@ -107,7 +109,8 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const + const StorageObjectStorageQueue & storage, + bool display_secrets) const { MutableColumns & res_columns = params.res_columns; auto settings_changes_ast = storage.getInMemoryMetadataPtr()->settings_changes; @@ -127,6 +130,23 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( { return StorageObjectStorageQueue::isSettingChangeable(setting_name, (*this)[ObjectStorageQueueSetting::mode]); }; + /// Hides what `SHOW CREATE TABLE` hides. A secret is hidden whole, as its masker renders SQL. + auto render_value = [&](const std::string & setting_name, const Field & value) -> String + { + static constexpr std::string_view hidden_secret = "[HIDDEN]"; + if (!display_secrets) + { + for (const auto * settings_to_hide : {&S3Queue::SETTINGS_TO_HIDE, &AzureQueue::SETTINGS_TO_HIDE}) + { + auto it = settings_to_hide->find(setting_name); + if (it == settings_to_hide->end()) + continue; + if (auto masked = it->second(value); masked && masked->contains(hidden_secret)) + return String(hidden_secret); + } + } + return convertFieldToString(value); + }; for (const auto & change : impl->all()) { @@ -135,7 +155,7 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( res_columns[i++]->insert(database_name); res_columns[i++]->insert(table_name); res_columns[i++]->insert(name); - res_columns[i++]->insert(convertFieldToString(change.getValue())); + res_columns[i++]->insert(render_value(name, change.getValue())); res_columns[i++]->insert(change.getTypeName()); res_columns[i++]->insert(is_changed(name)); res_columns[i++]->insert(change.getDescription()); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h index dad7144540bc..37c784da6d07 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h @@ -61,7 +61,8 @@ struct ObjectStorageQueueSettings MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const; + const StorageObjectStorageQueue & storage, + bool display_secrets) const; void loadFromQuery(ASTStorage & storage_def, bool is_attach, const StorageID & storage_id); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 10e4f39ec00e..718da1abc8cf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include @@ -22,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -140,9 +144,26 @@ namespace ErrorCodes namespace { + /// The move uses only the destination of the storage type of the table, so only that one is checked. + void checkMoveDestinationHost( + ObjectStorageType type, + const String & move_uri, + const String & move_connection_string, + const String & move_container, + const RemoteHostFilter & filter) + { + if (type == ObjectStorageType::S3) + checkObjectStorageQueueS3MoveDestinationHost(move_uri, filter); + else if (type == ObjectStorageType::Azure) + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, filter); + } + void validateSettings( ObjectStorageQueueSettings & queue_settings, - bool is_attach) + ObjectStorageType type, + const RemoteHostFilter & remote_host_filter, + bool is_attach, + bool is_loading_from_existing_metadata) { if (!is_attach && !queue_settings[ObjectStorageQueueSetting::mode].changed) { @@ -201,6 +222,21 @@ namespace "Move of processed objects requires specifying target bucket/container or prefix"); } } + + /// The host filter of `configuration` covers the source only, so the move destination is checked here. + /// It is checked whenever it is set, not only for `after_processing = 'move'`: otherwise a table created with + /// `after_processing = 'keep'` and a destination that is not allowed could be switched to `move` by an `ALTER` + /// that does not change the destination. A table loaded from existing metadata must never fail to load. + if (!is_loading_from_existing_metadata) + { + checkMoveDestinationHost( + type, + queue_settings[ObjectStorageQueueSetting::after_processing_move_uri].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_connection_string].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_container].value, + remote_host_filter); + } + if (queue_settings[ObjectStorageQueueSetting::after_processing] == ObjectStorageQueueAction::TAG) { if (queue_settings[ObjectStorageQueueSetting::after_processing_tag_key].toString().empty()) @@ -307,7 +343,7 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( } const bool is_attach = mode > LoadingStrictnessLevel::CREATE; - validateSettings(*queue_settings_, is_attach); + validateSettings(*queue_settings_, type, context_->getRemoteHostFilter(), is_attach, isLoadingFromExistingMetadata(mode)); object_storage = configuration->createObjectStorage(context_, /* is_readonly */true, std::nullopt); FormatFactory::instance().checkFormatName(configuration->format); @@ -413,12 +449,18 @@ void StorageObjectStorageQueue::startup() /// Create metadata in keeper if it does not exits yet. /// Create a persistent node for the table under /registry node. bool created_new_metadata = false; - files_metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( + /// Keep a local handle: the factory call and the startup below do keeper I/O, which must not + /// run under `mutex`. + auto metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( zookeeper_name, zk_path, std::move(temp_metadata), getStorageID(), created_new_metadata); + { + std::lock_guard lock(mutex); + files_metadata = metadata; + } /// Register the metadata in startup(), unregister in shutdown. /// (If startup is never called, shutdown also won't be called.) @@ -435,6 +477,7 @@ void StorageObjectStorageQueue::startup() /* is_drop */created_new_metadata, /* keep_data_in_keeper */false); + std::lock_guard lock(mutex); files_metadata.reset(); } }); @@ -453,7 +496,7 @@ void StorageObjectStorageQueue::startup() }); /// Start background tasks. - files_metadata->startup(); + metadata->startup(); for (auto & task : streaming_tasks) task->activateAndSchedule(); @@ -496,11 +539,19 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) tryLogCurrentException(log); } - if (files_metadata) + /// Drop the handle before the keeper cleanup below, so a concurrent reader sees the + /// shut-down state. The local copy keeps the metadata alive for that cleanup. + std::shared_ptr metadata; + { + std::lock_guard lock(mutex); + metadata = std::move(files_metadata); + } + + if (metadata) { try { - files_metadata->unregisterActive(getStorageID()); + metadata->unregisterActive(getStorageID()); } catch (...) { @@ -508,8 +559,6 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) } ObjectStorageQueueMetadataFactory::instance().remove(zookeeper_name, zk_path, getStorageID(), is_drop, keep_data_in_keeper); - - files_metadata.reset(); } LOG_TRACE(log, "Shut down storage"); } @@ -1316,6 +1365,35 @@ void StorageObjectStorageQueue::checkAlterIsPossible(const AlterCommands & comma } } } + + /// The host filter of `configuration` covers the source only, so a new move destination is checked here. + /// `checkAlterIsPossible` runs on every host and the check depends only on the server config, so it is correct everywhere. + static constexpr std::array move_destination_settings{ + "after_processing_move_uri", "after_processing_move_connection_string", "after_processing_move_container"}; + + auto get_move_destination_value = [](const SettingsChanges * settings, std::string_view name) -> String + { + const Field * value = settings ? settings->tryGet(name) : nullptr; + return value ? convertFieldToString(*value) : String{}; + }; + + const bool move_destination_changed = std::ranges::any_of( + move_destination_settings, + [&](std::string_view name) + { return get_move_destination_value(old_settings, name) != get_move_destination_value(&new_settings, name); }); + + if (move_destination_changed) + { + const String move_connection_string = get_move_destination_value(&new_settings, "after_processing_move_connection_string"); + const String move_container = get_move_destination_value(&new_settings, "after_processing_move_container"); + + checkMoveDestinationHost( + type, + get_move_destination_value(&new_settings, "after_processing_move_uri"), + move_connection_string, + move_container, + local_context->getRemoteHostFilter()); + } } void StorageObjectStorageQueue::alter( @@ -1532,6 +1610,12 @@ const ObjectStorageQueueTableMetadata & StorageObjectStorageQueue::getTableMetad return files_metadata->getTableMetadata(); } +std::shared_ptr StorageObjectStorageQueue::tryGetFilesMetadata() const +{ + std::lock_guard lock(mutex); + return files_metadata; +} + std::shared_ptr StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate) { @@ -1571,11 +1655,16 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), /// so let's reconstruct. ObjectStorageQueueSettings settings; - /// If startup() for a table was not called, just use the default queue settings + /// If startup() for a table was not called, just use the default queue settings. + /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. if (!startup_finished) return settings; - const auto & table_metadata = getTableMetadata(); + auto metadata = tryGetFilesMetadata(); + if (!metadata) + return settings; + + const auto & table_metadata = metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) @@ -1591,12 +1680,12 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const settings[ObjectStorageQueueSetting::tracked_files_limit] = table_metadata.tracked_files_limit; settings[ObjectStorageQueueSetting::buckets] = table_metadata.buckets; - auto cleanup_interval_ms = files_metadata->getCleanupIntervalMS(); + auto cleanup_interval_ms = metadata->getCleanupIntervalMS(); settings[ObjectStorageQueueSetting::cleanup_interval_min_ms] = static_cast(cleanup_interval_ms.first); settings[ObjectStorageQueueSetting::cleanup_interval_max_ms] = static_cast(cleanup_interval_ms.second); - settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(files_metadata->getPersistentProcessingNodeTTLSeconds()); - settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = files_metadata->usePersistentProcessingNode(); - const auto & file_statuses_cache = files_metadata->getFileStatusesCache(); + settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(metadata->getPersistentProcessingNodeTTLSeconds()); + settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = metadata->usePersistentProcessingNode(); + const auto & file_statuses_cache = metadata->getFileStatusesCache(); settings[ObjectStorageQueueSetting::metadata_cache_size_bytes] = file_statuses_cache.maxSizeInBytes(); settings[ObjectStorageQueueSetting::metadata_cache_size_elements] = file_statuses_cache.maxCount(); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index 5a251e7b7e16..902ec55b54bf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -147,6 +147,8 @@ class StorageObjectStorageQueue : public IStorage, WithContext bool supportsColumnsWithDynamicStructure() const override { return true; } const ObjectStorageQueueTableMetadata & getTableMetadata() const; + /// Returns nullptr if the table is not started up or is already shut down. + std::shared_ptr tryGetFilesMetadata() const; std::shared_ptr createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate); std::shared_ptr createSource( diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 27f3c6004559..d7ddf6e5d128 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -143,6 +144,7 @@ void registerStorageS3Queue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::S3, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getS3QueueMoveDestinationAccess, }); } #endif @@ -161,6 +163,7 @@ void registerStorageAzureQueue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::AZURE, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getAzureQueueMoveDestinationAccess, }); } #endif diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp index f5e81a4a4843..ec0c6ea0433a 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp @@ -275,6 +275,14 @@ void StorageMaterializedPostgreSQL::dropInnerTableIfAny(bool sync, ContextPtr lo } +bool StorageMaterializedPostgreSQL::hasBucketedMapSerialization() const +{ + if (auto nested = tryGetNested()) + return nested->hasBucketedMapSerialization(); + return false; +} + + bool StorageMaterializedPostgreSQL::needRewriteQueryWithFinal(const Names & column_names) const { return needRewriteQueryWithFinalForStorage(column_names, getNested()); diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h index 0933a2772d9d..c133fee077bf 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h @@ -91,6 +91,8 @@ class StorageMaterializedPostgreSQL final : public IStorage, WithContext bool needRewriteQueryWithFinal(const Names & column_names) const override; + bool hasBucketedMapSerialization() const override; + void read( QueryPlan & query_plan, const Names & column_names, diff --git a/src/Storages/StorageAlias.cpp b/src/Storages/StorageAlias.cpp index eb8bc370f85a..5160352e3432 100644 --- a/src/Storages/StorageAlias.cpp +++ b/src/Storages/StorageAlias.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -15,6 +16,9 @@ #include #include #include +#include +#include +#include namespace DB @@ -31,6 +35,7 @@ namespace ErrorCodes extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int BAD_ARGUMENTS; extern const int SUPPORT_IS_DISABLED; + extern const int NOT_IMPLEMENTED; } StorageAlias::StorageAlias( @@ -171,6 +176,26 @@ SinkToStoragePtr StorageAlias::write( return std::make_shared(*this, local_context, target_metadata); } +void StorageAlias::checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const +{ + /// `InterpreterAlterQuery` checks the export grants (`SELECT` on the table and its row policy) on the name in the query, + /// which is the alias, not the target. The refusal does not need the user, so it also holds on the hosts of `ON CLUSTER`. + for (const auto & command : commands) + { + if (command.type == AlterCommand::MODIFY_SETTING && !StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes).empty()) + { + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Changing the settings that send the data of a table elsewhere through an alias is not supported. " + "Execute the ALTER directly on the target table: {}.{}", + backQuoteIfNeed(target_database), + backQuoteIfNeed(target_table)); + } + } + + getTargetTable()->checkAlterIsPossible(commands, local_context); +} + void StorageAlias::alter( const AlterCommands & params, ContextPtr local_context, diff --git a/src/Storages/StorageAlias.h b/src/Storages/StorageAlias.h index 0753decac7e5..99a9167dd58d 100644 --- a/src/Storages/StorageAlias.h +++ b/src/Storages/StorageAlias.h @@ -55,7 +55,7 @@ class StorageAlias final : public IStorage, WithContext /// Distributed write to target table std::optional distributedWrite(const ASTInsertQuery & query, ContextPtr local_context) override; - void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override { getTargetTable()->checkAlterIsPossible(commands, local_context); } + void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override; /// Alter target table void alter( @@ -143,6 +143,7 @@ class StorageAlias final : public IStorage, WithContext std::optional supportedPrewhereColumns() const override { return getTargetTable()->supportedPrewhereColumns(); } bool canMoveConditionsToPrewhere() const override { return getTargetTable()->canMoveConditionsToPrewhere(); } bool supportsOptimizationToSubcolumns() const override { return getTargetTable()->supportsOptimizationToSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsDeduplication() const override { return getTargetTable()->supportsDeduplication(); } bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageBuffer.cpp b/src/Storages/StorageBuffer.cpp index 090058a95a95..2993357d6658 100644 --- a/src/Storages/StorageBuffer.cpp +++ b/src/Storages/StorageBuffer.cpp @@ -887,6 +887,13 @@ bool StorageBuffer::supportsPrewhere() const return false; } +bool StorageBuffer::hasBucketedMapSerialization() const +{ + if (auto destination = getDestinationTable()) + return destination->hasBucketedMapSerialization(); + return false; +} + bool StorageBuffer::checkThresholds(const Buffer & buffer, bool direct, time_t current_time, size_t additional_rows, size_t additional_bytes) const { time_t time_passed = 0; diff --git a/src/Storages/StorageBuffer.h b/src/Storages/StorageBuffer.h index 481647a89625..8da3169b9b2f 100644 --- a/src/Storages/StorageBuffer.h +++ b/src/Storages/StorageBuffer.h @@ -91,6 +91,7 @@ friend class BufferSink; bool supportsParallelInsert() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } diff --git a/src/Storages/StorageDistributed.cpp b/src/Storages/StorageDistributed.cpp index 478abb8530f7..2bdf34ab918b 100644 --- a/src/Storages/StorageDistributed.cpp +++ b/src/Storages/StorageDistributed.cpp @@ -1,5 +1,10 @@ #include +#include +#include +#include +#include + #include #include @@ -179,6 +184,7 @@ namespace Setting extern const SettingsBool prefer_global_in_and_join; extern const SettingsBool skip_unavailable_shards; extern const SettingsBool enable_global_with_statement; + extern const SettingsMap additional_table_filters; } namespace DistributedSetting @@ -1364,6 +1370,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser auto & select = query.select->as(); StoragePtr src_storage; + bool src_is_table_function = false; /// Distributed write only works in the most trivial case INSERT ... SELECT /// without any unions or joins on the right side @@ -1380,6 +1387,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (joined_tables.tablesCount() == 1) { src_storage = joined_tables.getLeftTableStorage(); + src_is_table_function = joined_tables.isLeftTableFunction(); } } } @@ -1387,6 +1395,19 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (!src_storage) return {}; + /// This is the only place source SELECT access is enforced in this case + /// (table functions have been already checked in ITableFunction::execute) + const auto src_id = src_storage->getStorageID(); + if (!src_is_table_function + && !local_context->getAccess()->isGranted(AccessType::SELECT, src_id.database_name, src_id.table_name)) + return {}; + if (auto row_policy_filter = local_context->getRowPolicyFilter(src_id.database_name, src_id.table_name, RowPolicyFilterType::SELECT_FILTER); + row_policy_filter && !row_policy_filter->isAlwaysTrue()) + return {}; + /// It is not easy to match this table only, analyzer also do not do it + if (!settings[Setting::additional_table_filters].value.empty()) + return {}; + if (auto src_distributed = std::dynamic_pointer_cast(src_storage)) { return distributedWriteBetweenDistributedTables(*src_distributed, query, local_context); diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 0cc905ab1d3c..4ced2fa21aa6 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -1,9 +1,12 @@ #include +#include #include #include #include #include +#include #include +#include #include #include #include @@ -267,4 +270,37 @@ const StorageFactory::StorageFeatures & StorageFactory::getStorageFeatures(const return it->second.features; } +AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & create) const +{ + AccessRightsElements res; + auto add = [&](const ASTStorage & storage) + { + if (!storage.engine || !storage.settings) + return; + auto it = storages.find(storage.engine->name); + if (it != storages.end() && it->second.features.get_export_access_fn) + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + }; + + if (create.storage) + add(*create.storage); + if (create.targets) + { + for (const ASTStorage * inner_engine : create.targets->getInnerEngines()) + add(*inner_engine); + } + return res; +} + +AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const +{ + AccessRightsElements res; + for (const auto & [_, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes)); + } + return res; +} + } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index d3e4ccc969d4..6babf823c358 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -16,6 +16,8 @@ namespace DB class Context; class ASTCreateQuery; class ASTStorage; +class AccessRightsElements; +class SettingsChanges; struct StorageID; struct ConstraintsDescription; @@ -33,6 +35,10 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// Used to validate if table settings belong to the engine or the query before the start of the query interpretation using HasBuiltinSettingFn = bool(std::string_view); + /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. + /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + struct Arguments { const String & engine_name; @@ -76,6 +82,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> std::optional source_access_type = std::nullopt; HasBuiltinSettingFn * has_builtin_setting_fn = nullptr; + GetExportAccessFn * get_export_access_fn = nullptr; }; using CreatorFn = std::function; @@ -111,6 +118,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> .supports_schema_inference = false, .source_access_type = std::nullopt, .has_builtin_setting_fn = nullptr, + .get_export_access_fn = nullptr, }); const Storages & getAllStorages() const @@ -140,6 +148,13 @@ class StorageFactory : private boost::noncopyable, public IHints<> const StorageFeatures & getStorageFeatures(const String & storage_name) const; + /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` + /// table. An unknown engine needs nothing here: creating it fails later. + AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, + /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. + AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; + private: Storages storages; }; diff --git a/src/Storages/StorageInMemoryMetadata.cpp b/src/Storages/StorageInMemoryMetadata.cpp index 7982f7de575a..f99761a93ff7 100644 --- a/src/Storages/StorageInMemoryMetadata.cpp +++ b/src/Storages/StorageInMemoryMetadata.cpp @@ -20,6 +20,8 @@ #include #include +#include + namespace DB { @@ -198,6 +200,47 @@ ContextMutablePtr StorageInMemoryMetadata::getSQLSecurityOverriddenContext(Conte new_context->setUser(getDefinerID(context)); + /// `Context::setUser` only sets the access-control identity (`user_id`); it does not touch the + /// user names in `ClientInfo`. That is harmless when there is an invoker whose names were copied + /// above, but a scheduled refresh of a refreshable materialized view builds its context from the + /// global context, where `current_user`, `initial_user` and `authenticated_user` are empty. + /// `RemoteQueryExecutor` sends the names as-is, and a shard that accepts the interserver + /// `` treats an empty `initial_user` as "interserver mode": it skips authentication + /// (see `TCPHandler::receiveQuery`) and executes the query with full access + /// (see `Context::getAccess`, `full_access = !user_id`). Stamp the definer into the empty fields + /// so the remote leg of the query is bounded by the same identity as the local one. Non-empty + /// fields are left alone so `currentUser` inside an ordinary `DEFINER` view still returns the + /// invoker. `AsynchronousInsertQueue` and `InterpreterExecuteAsQuery` do the same. + { + const auto & new_client_info = new_context->getClientInfo(); + const bool current_user_empty = new_client_info.current_user.empty(); + const bool initial_user_empty = new_client_info.initial_user.empty(); + const bool authenticated_user_empty = new_client_info.authenticated_user.empty(); + + if (current_user_empty || initial_user_empty || authenticated_user_empty) + { + const auto definer_name = new_context->getUserName(); + if (current_user_empty) + new_context->setCurrentUserName(definer_name); + if (initial_user_empty) + { + new_context->setInitialUserName(definer_name); + /// The shard authenticates the definer by `initial_user` and checks `initial_address` + /// against the allowed hosts of that user. Without an invoker, the address is the + /// unspecified `0.0.0.0`, which only matches users with `HOST ANY`. The query is + /// produced by this server itself, so present it as coming from the local host. + if (!new_client_info.initial_address || new_client_info.initial_address->host().isWildcard()) + new_context->setInitialAddress(Poco::Net::SocketAddress(Poco::Net::IPAddress("127.0.0.1"), 0)); + } + if (authenticated_user_empty) + { + ClientInfo client_info_with_definer = new_context->getClientInfo(); + client_info_with_definer.authenticated_user = definer_name; + new_context->setClientInfo(client_info_with_definer); + } + } + } + new_context->clampToSettingsConstraints(changed_settings, SettingSource::QUERY); new_context->applySettingsChanges(changed_settings); new_context->setSetting("allow_ddl", 1); diff --git a/src/Storages/StorageMaterializedView.cpp b/src/Storages/StorageMaterializedView.cpp index cd9b89b12c7b..05223ca73bf7 100644 --- a/src/Storages/StorageMaterializedView.cpp +++ b/src/Storages/StorageMaterializedView.cpp @@ -559,10 +559,19 @@ ContextMutablePtr StorageMaterializedView::createRefreshContext(const String & l { ContextPtr table_context = getContext(); ClientInfo client_info = table_context->getClientInfo(); - client_info.interface = ClientInfo::Interface::BACKGROUND; - client_info.client_name = "refreshable materialized view"; - auto refresh_context = getInMemoryMetadataPtr()->getSQLSecurityOverriddenContext(table_context, &client_info); - refresh_context->setClientInfo(client_info); + auto view_metadata = getInMemoryMetadataPtr(); + auto refresh_context = view_metadata->getSQLSecurityOverriddenContext(table_context, &client_info); + /// For `SQL SECURITY DEFINER`, `getSQLSecurityOverriddenContext` fills the empty user names in + /// the context's `ClientInfo` with the definer. Do not assign the local `client_info` copy to + /// the context: `setClientInfo` replaces the whole struct and would wipe that identity out. + /// Re-read it instead, so that a view without SQL security (which gets a plain copy) also gets + /// these fields. + { + ClientInfo refresh_client_info = refresh_context->getClientInfo(); + refresh_client_info.interface = ClientInfo::Interface::BACKGROUND; + refresh_client_info.client_name = "refreshable materialized view"; + refresh_context->setClientInfo(refresh_client_info); + } refresh_context->setSetting("database_replicated_allow_replicated_engine_arguments", 3); refresh_context->setSetting("log_comment", log_comment); refresh_context->setQueryKind(ClientInfo::QueryKind::INITIAL_QUERY); diff --git a/src/Storages/StorageMaterializedView.h b/src/Storages/StorageMaterializedView.h index 62331b24f329..a4d72e909292 100644 --- a/src/Storages/StorageMaterializedView.h +++ b/src/Storages/StorageMaterializedView.h @@ -36,6 +36,7 @@ class StorageMaterializedView final : public IStorage, WithMutableContext bool supportsFinal() const override { return getTargetTable()->supportsFinal(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsSubcolumns() const override { return getTargetTable()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override; bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageMerge.cpp b/src/Storages/StorageMerge.cpp index 202aae98818e..a70dd5e4659b 100644 --- a/src/Storages/StorageMerge.cpp +++ b/src/Storages/StorageMerge.cpp @@ -318,6 +318,12 @@ bool StorageMerge::supportsPrewhere() const return traverseTablesUntil([](const auto & table) { return !table->supportsPrewhere(); }) == nullptr; } +bool StorageMerge::hasBucketedMapSerialization() const +{ + /// The rewritten query is sent to every underlying table, so all of them must benefit from it. + return traverseTablesUntil([](const auto & table) { return !table->hasBucketedMapSerialization(); }) == nullptr; +} + bool StorageMerge::canMoveConditionsToPrewhere() const { /// NOTE: This check and the above check are used during query analysis as condition for applying diff --git a/src/Storages/StorageMerge.h b/src/Storages/StorageMerge.h index 2c1eafc7f808..948a5f50694f 100644 --- a/src/Storages/StorageMerge.h +++ b/src/Storages/StorageMerge.h @@ -51,6 +51,7 @@ class StorageMerge final : public IStorage, WithContext bool supportsSampling() const override { return true; } bool supportsFinal() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } bool supportsPrewhere() const override; std::optional supportedPrewhereColumns() const override; diff --git a/src/Storages/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index 8419b2aea6c2..cecedf79cca5 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -1114,6 +1114,11 @@ QueryPipeline StorageMergeTree::updateLightweight(const MutationCommands & comma /// Updates currently don't work with parallel replicas. context_copy->setSetting("max_parallel_replicas", Field(1)); + /// A snapshot cached by `enable_shared_storage_snapshot_in_query` before the wait for committing + /// inserts above (e.g. by the validation of `IN` operands in `InterpreterUpdateQuery`) would hide + /// the parts committed during the wait from the update. See `StorageReplicatedMergeTree::updateLightweight`. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); auto sink = std::make_shared(*this, std::move(patch_metadata), std::move(update_holder), context_copy); @@ -2800,25 +2805,24 @@ void StorageMergeTree::replacePartitionFrom(const StoragePtr & source_table, con String partition_id; + /// The merges_blocker must live until the end of the function to prevent background mutations + /// from starting on parts in the target partition between when we stop waiting and when we + /// actually remove old parts via removePartsInRangeFromWorkingSet. Without this, a mutation + /// could "resurrect" old data by completing on an already-removed part and adding a new version + /// of it back to the working set. + ActionLock merges_blocker; if (is_all) { if (replace) throw DB::Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Only support DROP/DETACH/ATTACH PARTITION ALL currently"); + merges_blocker = stopMergesAndWait(); } else { partition_id = getPartitionIDFromQuery(partition, local_context); + merges_blocker = stopMergesAndWaitForPartition(partition_id); } - /// We use the global `stopMergesAndWait` (not the per-partition variant) because the - /// per-partition blocker check in `scheduleDataProcessingJob` happens outside - /// `currently_processing_in_background_mutex`, creating a race window where a mutation - /// can be selected inside the mutex, pass the per-partition check outside the mutex, - /// and get scheduled after the blocker was set but before we call - /// `removePartsInRangeFromWorkingSet`, "resurrecting" old data. - /// The global blocker is checked inside the mutex, eliminating this race. - ActionLock merges_blocker = stopMergesAndWait(); - auto source_metadata_snapshot = source_table->getInMemoryMetadataPtr(); auto my_metadata_snapshot = getInMemoryMetadataPtr(); diff --git a/src/Storages/StorageMongoDB.cpp b/src/Storages/StorageMongoDB.cpp index 6a6fbeca720e..e4dff78729a2 100644 --- a/src/Storages/StorageMongoDB.cpp +++ b/src/Storages/StorageMongoDB.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -36,6 +37,7 @@ #include #include +#include #include using bsoncxx::builder::basic::document; @@ -49,6 +51,7 @@ namespace DB namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int NOT_IMPLEMENTED; @@ -78,6 +81,53 @@ void MongoDBConfiguration::checkCollection() const throw Exception(ErrorCodes::BAD_ARGUMENTS, "MongoDB collection name must be non-empty and must not contain NUL characters"); } +namespace +{ + +void throwIfServerCredentials(const mongocxx::uri & uri, std::string_view remedy) +{ + /// Only these take the credentials from the connection string; `MONGODB-OIDC`, `MONGODB-AWS`, `GSSAPI` and + /// `MONGODB-X509` use the server's. Without a mechanism the driver uses SCRAM or no authentication. Names are case-insensitive. + static constexpr std::string_view allowed_mechanisms[] = {"SCRAM-SHA-1", "SCRAM-SHA-256", "PLAIN"}; + + const String mechanism = uri.auth_mechanism(); + const bool is_allowed_mechanism = mechanism.empty() + || std::ranges::any_of(allowed_mechanisms, [&](std::string_view allowed) { return equalsCaseInsensitive(mechanism, allowed); }); + + if (!is_allowed_mechanism) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB authentication mechanism '{}' is not allowed, because it authenticates with " + "credentials of the server process. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a password " + "in the connection string{}.", + mechanism, remedy); + + /// The driver stores the deprecated `sslClientCertificateKeyFile` under the canonical name, so this covers both. + if (uri.tls_certificate_key_file()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB connection option `tlsCertificateKeyFile` is not allowed, because it makes the server present a " + "client certificate from its own filesystem. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a " + "password in the connection string{}.", + remedy); +} + +} + +void MongoDBConfiguration::checkServerCredentialsForTable(const ContextPtr & context) const +{ + /// In `clickhouse-local` the user is the operator, so the credentials of the process are theirs to use. + if (context->getApplicationType() != Context::ApplicationType::SERVER) + return; + + throwIfServerCredentials(*uri, ""); +} + +void MongoDBConfiguration::checkServerCredentialsForDictionary() const +{ + throwIfServerCredentials(*uri, ", or define the dictionary in the server configuration files"); +} + StorageMongoDB::StorageMongoDB( const StorageID & table_id_, MongoDBConfiguration configuration_, @@ -104,6 +154,9 @@ Pipe StorageMongoDB::read( size_t max_block_size, size_t /*num_streams*/) { + /// Checked per read, with the query's settings: a table created with `mongodb(...)` is built with the global context. + configuration.checkServerCredentialsForTable(context); + storage_snapshot->check(column_names); Block sample_block; diff --git a/src/Storages/StorageMongoDB.h b/src/Storages/StorageMongoDB.h index 5d436a874803..ee514c16762a 100644 --- a/src/Storages/StorageMongoDB.h +++ b/src/Storages/StorageMongoDB.h @@ -53,6 +53,9 @@ struct MongoDBConfiguration void checkHosts(const ContextPtr & context) const; void checkCollection() const; + void checkServerCredentialsForTable(const ContextPtr & context) const; + void checkServerCredentialsForDictionary() const; + bool isOidColumn(const std::string & name) const { return oid_fields.contains(name); diff --git a/src/Storages/StorageProxy.h b/src/Storages/StorageProxy.h index 57c14568e56d..aa24e39addb6 100644 --- a/src/Storages/StorageProxy.h +++ b/src/Storages/StorageProxy.h @@ -38,6 +38,7 @@ class StorageProxy : public IStorage bool noPushingToViewsOnInserts() const override { return getNested()->noPushingToViewsOnInserts(); } bool hasEvenlyDistributedRead() const override { return getNested()->hasEvenlyDistributedRead(); } bool supportsSubcolumns() const override { return getNested()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getNested()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override { return getNested()->supportsColumnsWithDynamicStructure(); } ColumnSizeByName getColumnSizes() const override { return getNested()->getColumnSizes(); } diff --git a/src/Storages/StorageReplicatedMergeTree.cpp b/src/Storages/StorageReplicatedMergeTree.cpp index 853396096da3..9707592466a1 100644 --- a/src/Storages/StorageReplicatedMergeTree.cpp +++ b/src/Storages/StorageReplicatedMergeTree.cpp @@ -249,6 +249,7 @@ namespace FailPoints extern const char rmt_merge_selecting_task_no_free_threads[]; extern const char rmt_merge_selecting_task_max_part_size[]; extern const char rmt_delay_execute_drop_range[]; + extern const char rmt_restore_replica_pause_before_metadata_version_raise[]; } namespace ErrorCodes @@ -7069,6 +7070,7 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( createReplica(metadata_snapshot, zookeeper_retries_info); createNewZooKeeperNodes(zookeeper_retries_info); + FailPointInjection::pauseFailPoint(FailPoints::rmt_restore_replica_pause_before_metadata_version_raise); /// Bump the /metadata ZNode version to match the max parts metadata version. /// The table's in-memory metadata_version is derived from the /metadata ZNode stat.version @@ -7076,12 +7078,41 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( if (max_parts_metadata_version > 0) { auto zookeeper = getZooKeeper(); - String metadata_str = zookeeper->get(zookeeper_path + "/metadata"); - for (int32_t i = 0; i < max_parts_metadata_version; ++i) - zookeeper->set(zookeeper_path + "/metadata", metadata_str); - zookeeper->set(replica_path + "/metadata_version", std::to_string(max_parts_metadata_version)); + /// Each batch logs an ALTER_METADATA entry of the version it reaches, so a replica that cloned an earlier one catches up. + Coordination::Stat metadata_stat; + Coordination::Stat columns_stat; + String metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + String columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + while (metadata_stat.version < max_parts_metadata_version) + { + const auto target = static_cast(std::min( + max_parts_metadata_version, Int64{metadata_stat.version} + static_cast(zkutil::MULTI_BATCH_SIZE))); + + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(zookeeper_path + "/columns", columns_stat.version)); + for (int32_t version = metadata_stat.version; version < target; ++version) + ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/metadata", version + 1 == target ? metadata_str : "", version)); + + ReplicatedMergeTreeLogEntryData entry; + entry.type = LogEntry::ALTER_METADATA; + entry.source_replica = replica_name; + entry.metadata_str = metadata_str; + entry.columns_str = columns_str; + entry.alter_version = target; + entry.create_time = time(nullptr); + entry.have_mutation = false; + ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/log/log-", entry.toString(), zkutil::CreateMode::PersistentSequential)); - LOG_INFO(log, "Bumped metadata version to {} to match parts", max_parts_metadata_version); + Coordination::Responses responses; + const Coordination::Error code = zookeeper->tryMulti(ops, responses); + if (code != Coordination::Error::ZOK && code != Coordination::Error::ZBADVERSION) + zkutil::KeeperMultiException::check(code, ops, responses); + + metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + } + + LOG_INFO(log, "Raised metadata version to {} to match parts", metadata_stat.version); } LOG_INFO(log, "Created ZK nodes for table"); @@ -8433,6 +8464,13 @@ QueryPipeline StorageReplicatedMergeTree::updateLightweight(const MutationComman waitForCommittingOpsToFinish(zookeeper, context_copy->getPartitionIdToMaxBlock(getStorageID().uuid), ops, backoff_ms, sync_timeout); } + /// With `enable_shared_storage_snapshot_in_query` the update reads with the snapshot of this table + /// cached for the whole query. Anything analyzed before this point may have cached one, e.g. the + /// validation of `IN` operands in `InterpreterUpdateQuery`. Such a snapshot predates the wait for committing inserts above, so the + /// parts that arrived during the wait would be invisible to the update and their rows would stay + /// unchanged. Discard it, so that the update and its subqueries share a snapshot taken now. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); diff --git a/src/Storages/System/StorageSystemMutations.cpp b/src/Storages/System/StorageSystemMutations.cpp index 7514ed309af7..b3b65c6003ed 100644 --- a/src/Storages/System/StorageSystemMutations.cpp +++ b/src/Storages/System/StorageSystemMutations.cpp @@ -10,14 +10,67 @@ #include #include #include +#include #include #include #include +#include +#include +#include namespace DB { +namespace Setting +{ + extern const SettingsUInt64 max_parser_depth; + extern const SettingsUInt64 max_parser_backtracks; +} + +namespace ErrorCodes +{ + extern const int SYNTAX_ERROR; + extern const int TOO_DEEP_RECURSION; + extern const int TOO_SLOW_PARSING; +} + +/// The mutation entry keeps the real text of the command, because the mutation is executed from it +/// (on every replica, for replicated tables). Hide the secrets on the way out instead, the way +/// `system.distributed_ddl_queue` does. The command is formatted the same way as the stored text, +/// so only the secrets differ from it. +static String hideSecretsInCommand(const ContextPtr & context, const String & command) +{ + /// Nothing to parse, see `MutationCommand::ast`. + if (command.empty()) + return command; + + const auto & settings = context->getSettingsRef(); + ParserAlterCommandList parser; + ASTPtr ast; + try + { + ast = parseQuery(parser, command, 0, settings[Setting::max_parser_depth], settings[Setting::max_parser_backtracks]); + } + catch (const Exception & e) + { + /// The text may be unparseable on another server version, so hide the whole command instead of failing the table. + if (e.code() != ErrorCodes::SYNTAX_ERROR + && e.code() != ErrorCodes::TOO_DEEP_RECURSION + && e.code() != ErrorCodes::TOO_SLOW_PARSING) + throw; + return "[HIDDEN]"; + } + + return ast->formatWithPossiblyHidingSensitiveData( + /*max_length=*/0, + /*one_line=*/true, + /*show_secrets=*/false, + /*print_pretty_type_names=*/false, + /*identifier_quoting_rule=*/IdentifierQuotingRule::WhenNecessary, + /*identifier_quoting_style=*/IdentifierQuotingStyle::Backticks); +} + ColumnsDescription StorageSystemMutations::getColumnsDescription() { @@ -65,10 +118,11 @@ Block StorageSystemMutations::getFilterSampleBlock() const }; } -void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const +void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const { const auto access = context->getAccess(); const bool check_access_for_databases = !access->isGranted(AccessType::SHOW_TABLES); + const bool show_secrets = canDisplaySecrets(context); /// Collect a set of *MergeTree tables. std::map> merge_tree_tables; @@ -169,25 +223,43 @@ void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr c parts_postpone_reasons_map.emplace_back(std::move(key_value)); } - size_t col_num = 0; - res_columns[col_num++]->insert(database); - res_columns[col_num++]->insert(table); - - res_columns[col_num++]->insert(status.id); - res_columns[col_num++]->insert(status.command); - res_columns[col_num++]->insert(UInt64(status.create_time)); - res_columns[col_num++]->insert(block_partition_ids); - res_columns[col_num++]->insert(block_numbers); - res_columns[col_num++]->insert(parts_in_progress_names); - res_columns[col_num++]->insert(parts_to_do_names); - res_columns[col_num++]->insert(parts_to_do_names.size()); - res_columns[col_num++]->insert(parts_postpone_reasons_map); - res_columns[col_num++]->insert(status.is_done); - res_columns[col_num++]->insert(status.is_killed); - res_columns[col_num++]->insert(status.latest_failed_part); - res_columns[col_num++]->insert(UInt64(status.latest_fail_time)); - res_columns[col_num++]->insert(status.latest_fail_reason); - res_columns[col_num++]->insert(status.latest_fail_error_code_name); + size_t src_index = 0; + size_t res_index = 0; + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(database); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(table); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.id); + /// Parsing the command costs much more than everything else here, so it is done only when the column is queried. + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(show_secrets ? status.command : hideSecretsInCommand(context, status.command)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.create_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_partition_ids); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_numbers); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_in_progress_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names.size()); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_postpone_reasons_map); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_done); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_killed); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_failed_part); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.latest_fail_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_reason); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_error_code_name); } } } diff --git a/src/Storages/System/StorageSystemMutations.h b/src/Storages/System/StorageSystemMutations.h index 5341838a65e3..c3f897491fc7 100644 --- a/src/Storages/System/StorageSystemMutations.h +++ b/src/Storages/System/StorageSystemMutations.h @@ -21,8 +21,9 @@ class StorageSystemMutations final : public IStorageSystemOneBlock protected: using IStorageSystemOneBlock::IStorageSystemOneBlock; - void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const override; + void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const override; Block getFilterSampleBlock() const override; + bool supportsColumnsMask() const override { return true; } }; } diff --git a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp index b573828ddee1..444e3d74a08b 100644 --- a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp +++ b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( const ActionsDAG::Node *, std::vector) const { + const bool display_secrets = canDisplaySecrets(context); auto add_table = [&]( const DatabaseTablesIteratorPtr & it, StorageObjectStorageQueue & storage) { @@ -52,7 +54,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( auto constraints_and_current_profiles = context->getSettingsConstraintsAndCurrentProfiles(); const auto & constraints = constraints_and_current_profiles->constraints; MutableColumnsAndConstraints params(res_columns, constraints); - storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage); + storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage, display_secrets); }; const auto access = context->getAccess(); diff --git a/src/TableFunctions/ITableFunction.cpp b/src/TableFunctions/ITableFunction.cpp index fcd19f5b5408..9624c7464e48 100644 --- a/src/TableFunctions/ITableFunction.cpp +++ b/src/TableFunctions/ITableFunction.cpp @@ -55,11 +55,22 @@ void ITableFunction::checkEngineAccess(ContextPtr context) const context->checkAccess(AccessType::TABLE_ENGINE, engine); } +void ITableFunction::checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const +{ + auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); + if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) + context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); +} + ColumnsDescription ITableFunction::getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const { /// Resolving table structure is always a read operation. checkSourceAccess(context, /*is_insert_query*/ false); checkEngineAccess(context); + /// Resolving the structure may access the source (e.g. schema inference fetches a URL), so it must be + /// gated in the same way as `execute`: otherwise `DESCRIBE TABLE url(...)` would let a user who cannot + /// run the table function (e.g. under `readonly = 1`) make the server request an endpoint. + checkCreateTemporaryTableAccess(context, /*is_insert_query*/ false); return getActualTableStructure(context, is_insert_query); } @@ -73,9 +84,7 @@ StoragePtr ITableFunction::execute(const ASTPtr & ast_function, ContextPtr conte /// Deliberately not under `check_source_access`: no caller takes over the engine check. checkEngineAccess(context); - auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); - if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) - context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); + checkCreateTemporaryTableAccess(context, is_insert_query); auto context_to_use = use_global_context ? context->getGlobalContext() : context; diff --git a/src/TableFunctions/ITableFunction.h b/src/TableFunctions/ITableFunction.h index 0aeb1d497e1a..6579ff2ce25a 100644 --- a/src/TableFunctions/ITableFunction.h +++ b/src/TableFunctions/ITableFunction.h @@ -88,8 +88,9 @@ class ITableFunction : public std::enable_shared_from_this StoragePtr execute(const ASTPtr & ast_function, ContextPtr context, const std::string & table_name, ColumnsDescription cached_columns_ = {}, bool use_global_context = false, bool is_insert_query = false) const; - /// Returns actual table structure after enforcing source access checks. - /// Use this instead of getActualTableStructure() from outside execute(). + /// Returns actual table structure after enforcing the same access checks as `execute`: source, engine, + /// and `CREATE TEMPORARY TABLE` (for table functions not allowed in readonly mode). + /// Use this instead of `getActualTableStructure` from outside `execute`. ColumnsDescription getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const; /// Check that the user has the required source access (e.g. READ ON MYSQL, WRITE ON S3). @@ -98,6 +99,10 @@ class ITableFunction : public std::enable_shared_from_this /// Check the `TABLE ENGINE` grant, for engines that opt in via `requiresTableEngineGrant`. void checkEngineAccess(ContextPtr context) const; + /// Check the `CREATE TEMPORARY TABLE` grant, required to use a table function unless it is allowed + /// in readonly mode and the query is not an insert. + void checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const; + virtual ~ITableFunction() = default; protected: diff --git a/src/configure_config.cmake b/src/configure_config.cmake index 39b16eeebbe7..0d3a4da3abaa 100644 --- a/src/configure_config.cmake +++ b/src/configure_config.cmake @@ -150,6 +150,9 @@ endif() if (TARGET ch_contrib::parquet) set(USE_PARQUET 1) set(USE_ARROW 1) +endif() +# The ORC reader and writer are implemented in ClickHouse and need only the compression libraries. +if (TARGET ch_contrib::snappy) set(USE_ORC 1) endif() if (TARGET ch_contrib::liburing) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 26adc0ca8970..08f04e9081b2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -59,8 +59,38 @@ def tune_local_port_range(): ) +def is_xdist_replacement_worker(): + """True when this worker was spawned to replace one that died mid-run. + + `pytest-xdist` numbers a replacement past the size of the original pool, so `gw8` in a pool of + eight (`gw0`..`gw7`) is a replacement. A replacement starts a fresh pytest *session*, which + re-runs every session-scoped fixture - and `cleanup_environment` kills every container on the + host, including the ones the workers that are still running own. One worker dying, from an OOM + kill for instance, would otherwise take the containers of the whole job with it. + """ + worker = os.environ.get("PYTEST_XDIST_WORKER", "") + count = os.environ.get("PYTEST_XDIST_WORKER_COUNT", "") + if not worker.startswith("gw") or not count.isdigit(): + return False + + index = worker.removeprefix("gw") + if not index.isdigit(): + return False + + return int(index) >= int(count) + + @pytest.fixture(autouse=True, scope="session") def cleanup_environment(): + if is_xdist_replacement_worker(): + logging.info( + "Worker %s replaces a worker that died, so the containers of the workers which are " + "still running are not ours to clean up. Skipping the environment cleanup.", + os.environ["PYTEST_XDIST_WORKER"], + ) + yield + return + try: result = run_and_check(["docker ps | wc -l"], shell=True) if int(result) > 1: diff --git a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml index d4ac4986c22d..ad199feefc1e 100644 --- a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml +++ b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml @@ -2,6 +2,7 @@ host:80 ^[a-z]*\.ru$ + .*\.allowed\.example diff --git a/tests/integration/test_allowed_url_from_config/test.py b/tests/integration/test_allowed_url_from_config/test.py index 78ff4b22d321..b43422300bba 100644 --- a/tests/integration/test_allowed_url_from_config/test.py +++ b/tests/integration/test_allowed_url_from_config/test.py @@ -72,6 +72,43 @@ def test_azure_host_filter_before_client_creation(start_cluster, query): assert node5.query(container_requests) == before +def test_object_storage_queue_move_destination_host_filter(start_cluster): + # The source is on an allowed host (`host:80`), so only the move destination can be rejected. `node1` has no + # Keeper, so a rejection with "not allowed" must come from the settings validation, which runs before any + # Keeper access. + s3_queue = ( + "CREATE TABLE s3queue_move_host (x UInt8) " + "ENGINE = S3Queue('http://host:80/bucket/data/', 'key', 'secret', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_uri = '{}', " + "after_processing_move_access_key_id = 'key', after_processing_move_secret_access_key = 'secret'" + ) + azure_queue = ( + "CREATE TABLE azurequeue_move_host (x UInt8) " + "ENGINE = AzureQueue('http://host:80', 'container', '*', 'account', 'YQ==', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_connection_string = " + "'DefaultEndpointsProtocol=http;AccountName=account;AccountKey=YQ==;BlobEndpoint=http://host:123/account;', " + "after_processing_move_container = 'dst'" + ) + + try: + error = node1.query_and_get_error(s3_queue.format("http://host:123/bucket/")) + assert "not allowed" in error, error + + error = node1.query_and_get_error( + azure_queue, settings={"azure_sdk_max_retries": 0} + ) + assert "not allowed" in error, error + + # Control: an allowed destination passes the host check and only fails later, on the missing Keeper. + error = node1.query_and_get_error(s3_queue.format("http://host:80/bucket/")) + assert "not allowed" not in error, error + finally: + node1.query("DROP TABLE IF EXISTS s3queue_move_host SYNC") + node1.query("DROP TABLE IF EXISTS azurequeue_move_host SYNC") + + def test_config_with_only_primary_hosts(start_cluster): assert ( node2.query( @@ -217,6 +254,34 @@ def test_mysql_dictionary_host_filter(start_cluster): node5.query("DROP DICTIONARY IF EXISTS default.test_mysql_host_filter") +def test_mysql_database_host_filter(start_cluster): + # node5 denies all hosts; the check runs before any connection attempt. + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('10.0.0.1:3306', 'db', 'u', 'p')" + ) + node5.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nc AS " + "host = '10.0.0.1', port = 3306, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nc)" + ) + node5.query("DROP NAMED COLLECTION test_mysql_db_filter_nc") + + # node1's suffix rule would match the whole string, but the connector stops at the NUL; reject it. + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('127.0.0.1\\0.allowed.example:1', 'db', 'u', 'p')" + ) + node1.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nul_nc AS " + "host = '127.0.0.1\\0.allowed.example', port = 1, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nul_nc)" + ) + node1.query("DROP NAMED COLLECTION test_mysql_db_filter_nul_nc") + + def test_mysql_dictionary_replica_host_filter(start_cluster): """MySQL dictionary source with REPLICA(...) syntax should respect RemoteHostFilter.""" # Covers the replica branch: if (config.has(settings_config_prefix + ".replica")) @@ -335,3 +400,58 @@ def test_table_function_remote(start_cluster): "SELECT * FROM remote('localhost:800', system, metrics)" ) ) + + +# The catalog is built lazily on first use, so a query on a table connects to the metastore. +def hive_catalog_error(node, database, url): + node.query( + f"CREATE DATABASE {database} ENGINE = DataLakeCatalog('{url}') " + "SETTINGS catalog_type = 'hive', warehouse = 'test_warehouse'", + settings={"allow_experimental_database_hms_catalog": 1}, + ) + return node.query_and_get_error(f"SELECT * FROM {database}.`ns.tbl`") + + +def test_hive_catalog_host_filter(start_cluster): + url = "thrift://localhost:1" + try: + # Control first: `node4` declares no `remote_url_allow_hosts` at all, so its filter stays + # uninitialized and allows everything - the same statement gets past the check and fails at + # the network instead. Without this arm, a filter that rejected everything would also pass. + error = hive_catalog_error(node4, "test_hive_host_filter", url) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + + # `node5` declares an empty `remote_url_allow_hosts`, which allows nothing. + error = hive_catalog_error(node5, "test_hive_host_filter", url) + assert "UNACCEPTABLE_URL" in error, error + # The check must run before the connect, so the refusal carries no connection error. + assert "Connection refused" not in error, error + finally: + node4.query("DROP DATABASE IF EXISTS test_hive_host_filter") + node5.query("DROP DATABASE IF EXISTS test_hive_host_filter") + + +def test_hive_catalog_host_filter_rejects_nul(start_cluster): + try: + # Control: the suffix rule in `config_with_hosts.xml` admits this host, so it gets past the + # filter and fails at name resolution instead. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://hms.allowed.example:1" + ) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + node1.query("DROP DATABASE test_hive_host_filter_nul") + + # The same rule matches the whole string including the NUL, but `getaddrinfo` would stop at the + # NUL and connect to 127.0.0.1. The host must be refused before any connection attempt. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://127.0.0.1\\0.allowed.example:1" + ) + assert "BAD_ARGUMENTS" in error, error + assert "Unexpected character" in error, error + assert "Connection refused" not in error, error + finally: + node1.query("DROP DATABASE IF EXISTS test_hive_host_filter_nul") diff --git a/tests/integration/test_arrowflight_interface/test.py b/tests/integration/test_arrowflight_interface/test.py index 634ade912d13..4a1c124f986e 100644 --- a/tests/integration/test_arrowflight_interface/test.py +++ b/tests/integration/test_arrowflight_interface/test.py @@ -519,6 +519,43 @@ def test_doget_multiple_chunks(): assert actual[1].column("name").equals(pa.chunked_array([pa.array(["cde"], type=pa.string())])) +# A result is split across several Arrow arrays only when it exceeds the 32-bit offsets of the +# String/Binary/List buffers, so a small one must arrive as a single chunk per column for every type. +def test_doget_single_chunk_per_column(): + node.query( + """ + CREATE TABLE mytable ( + id Int64, + s String, + ns Nullable(String), + lc LowCardinality(String), + arr Array(String), + m Map(String, String), + t Tuple(String, String), + fs FixedString(3) + ) ORDER BY id + """ + ) + node.query( + """ + INSERT INTO mytable SELECT + number, toString(number), if(number % 2, NULL, toString(number)), toString(number % 2), + [toString(number)], map('k', toString(number)), (toString(number), 'x'), toFixedString('abc', 3) + FROM numbers(4) + """ + ) + + client, options = get_client() + + descriptor = flight.FlightDescriptor.for_command("SELECT * FROM mytable ORDER BY id") + flight_info = client.get_flight_info(descriptor, options) + table = client.do_get(flight_info.endpoints[0].ticket, options).read_all() + + assert table.num_rows == 4 + for name, column in zip(table.schema.names, table.columns): + assert column.num_chunks == 1, f"column {name} was split into {column.num_chunks} chunks" + + # We don't support any formats different from "Arrow". def test_doget_cmd_select_invalid_format(): node.query("CREATE TABLE mytable (id Int64, name String) ORDER BY id") diff --git a/tests/integration/test_backup_restore_new/test.py b/tests/integration/test_backup_restore_new/test.py index d317a99a0b49..0df792a10ecc 100644 --- a/tests/integration/test_backup_restore_new/test.py +++ b/tests/integration/test_backup_restore_new/test.py @@ -1474,6 +1474,131 @@ def test_system_users_required_privileges(): instance.query("DROP USER u2") +# Access backups include every entity of a type, so these checks need this module's isolated server. +def test_restore_row_policy_replace_requires_scoped_drop(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROW POLICY ON test.table TO u2") + instance.query( + "CREATE ROW POLICY rowpol1 ON test.table AS RESTRICTIVE USING 1 TO ALL" + ) + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.row_policies TO {backup_name}") + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + + restore = f"RESTORE TABLE system.row_policies FROM {backup_name}" + select_filter = "SELECT select_filter FROM system.row_policies WHERE short_name = 'rowpol1' AND database = 'test' AND table = 'table'" + instance.query(f"{restore} SETTINGS create_access='if-not-exists'", user="u2") + assert instance.query(select_filter) == "owner = 1\n" + + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("GRANT DROP ROW POLICY ON test.another_table TO u2") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("DROP ROW POLICY rowpol1 ON test.table") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "" + + instance.query(f"{restore} SETTINGS create_access='create'", user="u2") + assert instance.query(select_filter) == "1\n" + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + instance.query("GRANT DROP ROW POLICY ON test.table TO u2") + instance.query(f"{restore} SETTINGS create_access='replace'", user="u2") + assert instance.query(select_filter) == "1\n" + + +@pytest.mark.parametrize( + "kind,system_table,target", [("USER", "users", "u1"), ("ROLE", "roles", "r1")] +) +def test_restore_access_partial_revoke_cannot_cancel_drop(kind, system_table, target): + instance.query(f"CREATE {kind} {target} SETTINGS max_threads = 1") + instance.query(f"GRANT DROP {kind} ON * TO {target}") + instance.query(f"REVOKE DROP {kind} ON {target} FROM {target}") + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.{system_table} TO {backup_name}") + instance.query(f"ALTER {kind} {target} SETTINGS max_threads = 2") + + # Create the actor after the backup so its grants cannot mask the target's partial revoke. + instance.query("CREATE USER u2") + instance.query(f"GRANT CREATE {kind} ON {target} TO u2") + instance.query(f"GRANT DROP {kind} ON * TO u2 WITH GRANT OPTION") + instance.query(f"REVOKE DROP {kind} ON {target} FROM u2") + restore = f"RESTORE TABLE system.{system_table} FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert f"DROP {kind}" in error + assert "max_threads = 2" in instance.query(f"SHOW CREATE {kind} {target}") + + # Ordinary `DROP` is sufficient; the target's grants exclude `DROP` on itself. + instance.query(f"GRANT DROP {kind} ON {target} TO u2") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query(f"SHOW CREATE {kind} {target}") + + +def test_restore_access_partial_revokes_preserve_grant_and_table_requirements(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("INSERT INTO test.table VALUES (1)") + instance.query("CREATE ROLE r1 SETTINGS max_threads = 1") + instance.query("GRANT SELECT, INSERT ON test.* TO r1 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM r1") + instance.query("REVOKE INSERT ON test.table FROM r1") + backup_name = new_backup_name() + backup_tables = "TABLE system.roles, TABLE test.table" + instance.query(f"BACKUP {backup_tables} TO {backup_name}") + instance.query("ALTER ROLE r1 SETTINGS max_threads = 2") + + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROLE, DROP ROLE ON r1 TO u2") + instance.query("GRANT CREATE TABLE ON test.table TO u2") + instance.query("GRANT SELECT, INSERT ON test.* TO u2 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM u2") + restore = f"RESTORE TABLE system.roles FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert "SELECT" in error + assert "WITH GRANT OPTION" in error + assert "max_threads = 2" in instance.query("SHOW CREATE ROLE r1") + + instance.query("GRANT SELECT ON test.table TO u2 WITH GRANT OPTION") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query("SHOW CREATE ROLE r1") + + instance.query("TRUNCATE TABLE test.table") + instance.query("REVOKE INSERT ON test.table FROM u2") + restore_with_table = ( + f"RESTORE {backup_tables} FROM {backup_name} SETTINGS create_access='replace'" + ) + error = instance.query_and_get_error(restore_with_table, user="u2") + assert "ACCESS_DENIED" in error + assert "INSERT" in error + assert instance.query("SELECT count() FROM test.table") == "0\n" + + instance.query("GRANT INSERT ON test.table TO u2") + instance.query(restore_with_table, user="u2") + assert instance.query("SELECT * FROM test.table") == "1\n" + + def test_system_users_async(): instance.query("CREATE USER u1 IDENTIFIED BY 'qwe123' SETTINGS custom_c = 3") diff --git a/tests/integration/test_crash_log/test.py b/tests/integration/test_crash_log/test.py index 3c11c28add8e..9990917c913c 100644 --- a/tests/integration/test_crash_log/test.py +++ b/tests/integration/test_crash_log/test.py @@ -55,9 +55,14 @@ def test_crash_log_synchronous(started_node): wait_for_clickhouse_stop(started_node) started_node.restart_clickhouse() crashes_count += 1 + # Report the rows that are there. Without them a lost row leaves only `'1' == '2'` behind, + # which says nothing about which of the two crashes failed to record itself. assert ( started_node.query("SELECT COUNT(*) FROM system.crash_log") == f"{crashes_count}\n" + ), started_node.query( + "SELECT event_time_microseconds, signal, signal_description, query " + "FROM system.crash_log ORDER BY event_time_microseconds FORMAT Vertical" ) diff --git a/tests/integration/test_database_glue/test.py b/tests/integration/test_database_glue/test.py index 585fe2899b5c..eac84dd81389 100644 --- a/tests/integration/test_database_glue/test.py +++ b/tests/integration/test_database_glue/test.py @@ -588,6 +588,62 @@ def test_timestamps(started_cluster): assert node.query(f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}`") == "2024-01-01 12:00:00.000000\t2024-01-01 12:00:00.000000\n" +def test_timestamp_types_cache_does_not_keep_metadata(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_ts_cache_{uuid.uuid4().hex}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + database_name = f"db_{test_ref}" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + schema = Schema( + NestedField(field_id=1, name="timestamp", field_type=TimestampType(), required=False), + NestedField(field_id=2, name="timestamptz", field_type=TimestamptzType(), required=False), + ) + table = create_table(catalog, root_namespace, table_name, schema, dir=test_ref) + + create_clickhouse_glue_database(started_cluster, node, database_name) + + def cache_metrics(): + return [ + int(value) + for value in node.query( + "SELECT value FROM system.metrics " + "WHERE metric IN ('GlueCatalogSchemaCacheBytes', 'GlueCatalogSchemaCacheEntries') ORDER BY metric" + ).split() + ] + + bytes_before, entries_before = cache_metrics() + + row = pa.Table.from_pylist( + [{"timestamp": datetime(2024, 1, 1, 12), "timestamptz": datetime(2024, 1, 1, 12, tzinfo=pytz.UTC)}] + ) + versions = 30 + for _ in range(versions): + table.append(row) + description = node.query(f"DESCRIBE TABLE {database_name}.`{root_namespace}.{table_name}`") + assert [line.split("\t")[1] for line in description.splitlines()] == [ + "Nullable(DateTime64(6))", + "Nullable(DateTime64(6, \\'UTC\\'))", + ] + + bytes_after, entries_after = cache_metrics() + assert entries_after - entries_before == versions + + metadata_size = int( + node.query( + f"SELECT max(_size) FROM s3('http://minio1:9001/warehouse-glue/{test_ref}/metadata/*.metadata.json', " + f"'{minio_access_key}', '{minio_secret_key}', 'One')" + ) + ) + assert bytes_after - bytes_before < metadata_size + + node.query(f"DROP DATABASE {database_name}") + + def test_insert(started_cluster): node = started_cluster.instances["node1"] diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index e979a99c18b8..fcdcf17d2989 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -806,3 +806,500 @@ def test_invalid_auth_header_format(started_cluster): """ ) assert "Invalid auth header format" in str(err.value) + + +def test_writes_mutate_update(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_update_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String, y Int32)") + + node.query(f"INSERT INTO {table_ref} VALUES ('123', 1);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456', 2);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('999', 3);", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\t1\n456\t2\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = '777' WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n777\t1\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'goshan dr' WHERE x = '777';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n999\t3\ngoshan dr\t1\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'pudge1000-7' WHERE y = 2;", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "999\t3\ngoshan dr\t1\npudge1000-7\t2\n" + + +def test_writes_mutate_delete(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_delete_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String)") + + # DELETE on empty table is a no-op. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "" + + node.query(f"INSERT INTO {table_ref} VALUES ('123');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('789'), ('890'), ('999');", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + # No-match DELETE keeps the table intact. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '789';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n890\n999\n" + + # Lightweight DELETE syntax should work identically against catalog tables. + node.query(f"DELETE FROM {table_ref} WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '999';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n" + + +def test_iceberg_file_progress_callback(started_cluster): + """ + Regression test for the `IcebergIterator::next` file-progress callback wiring (PR #105413). + + `IcebergIterator` stored a `FileProgressCallback` but never invoked it, so the + per-query `Progress.total_bytes_to_read` stayed at zero for Iceberg scans and + the progress bar showed no estimate. The fix invokes the callback with the data + file size for every object info returned. The assertion below uses the + `FileProgressCallbackInvocations` ProfileEvent, which is incremented inside the + callback lambda installed by `TCPHandler::setFileProgressCallback`, so removing + the `callback(...)` call in `IcebergIterator::next` makes this event stay at + zero for the test query. + """ + node = started_cluster.instances["node1"] + + test_ref = f"test_progress_callback_{uuid.uuid4().hex[:8]}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + table = create_table( + catalog, + root_namespace, + table_name, + DEFAULT_SCHEMA, + PartitionSpec(), + DEFAULT_SORT_ORDER, + ) + + # Append a small but non-empty batch so the iterator returns a data-file entry. + num_rows = 50 + data = [generate_record() for _ in range(num_rows)] + df = pa.Table.from_pylist(data) + table.append(df) + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + # `node.query` uses native TCP, the only protocol path where + # `setFileProgressCallback` is currently wired. `SELECT *` with `FORMAT Null` + # forces a full scan: the metadata-only `SELECT count()` path resolves the row + # count from manifest statistics and bypasses the data-file iterator. + query_id = f"iceberg_progress_callback_{uuid.uuid4().hex}" + node.query( + f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}` FORMAT Null", + query_id=query_id, + ) + + node.query("SYSTEM FLUSH LOGS") + + # `FileProgressCallbackInvocations` is incremented inside the lambda installed + # by `TCPHandler::setFileProgressCallback`. For an Iceberg-table scan it can + # only fire from `IcebergIterator::next` (the generic + # `StorageObjectStorageSource::KeysIterator` path is replaced by + # `IcebergIterator` for Iceberg storage), so a non-zero value proves the + # iterator's `callback(FileProgress(...))` invocation was executed. + profile_event_value = node.query( + f""" + SELECT ProfileEvents['FileProgressCallbackInvocations'] + FROM system.query_log + WHERE query_id = '{query_id}' AND type = 'QueryFinish' + ORDER BY event_time_microseconds DESC + LIMIT 1 + """ + ).strip() + assert profile_event_value, ( + f"`system.query_log` has no `QueryFinish` row for query_id={query_id}." + ) + file_progress_callback_invocations = int(profile_event_value) + assert file_progress_callback_invocations > 0, ( + f"Expected `FileProgressCallbackInvocations` > 0 from the Iceberg scan, " + f"got {file_progress_callback_invocations}. " + f"`IcebergIterator::next` did not invoke the file-progress callback " + f"(regression of PR #105413 wiring)." + ) + + +def test_alter_database_settings_not_supported(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"iceberg_alter_settings_{uuid.uuid4().hex}" + create_clickhouse_iceberg_database(started_cluster, node, db_name) + + fake_token = f"fake_secret_token_{uuid.uuid4().hex}" + + qid_alter = uuid.uuid4().hex + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = '{fake_token}'", + query_id=qid_alter, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING no_such_setting = 1" + ) + assert "BAD_ARGUMENTS" in error or "UNKNOWN_SETTING" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "other_warehouse" not in show_result + assert "onelake_bearer_token" not in show_result + node.query( + f"SELECT name FROM system.tables WHERE database = '{db_name}' SETTINGS show_data_lake_catalogs_in_system_tables = true" + ) + + node.query("SYSTEM FLUSH LOGS system.query_log") + logged_query = node.query( + f"SELECT arrayStringConcat(groupArray(query), '\\n') FROM system.query_log WHERE query_id = '{qid_alter}'" + ) + assert fake_token not in logged_query + assert "[HIDDEN]" in logged_query + + node.query(f"DROP DATABASE {db_name}") + + glue_db_name = f"glue_alter_settings_{uuid.uuid4().hex}" + node.query( + f""" + ATTACH DATABASE {glue_db_name} ENGINE = DataLakeCatalog('http://fake-glue:1') + SETTINGS catalog_type = 'glue', region = 'us-east-1', storage_endpoint = 'http://fake-glue:1/x' + """ + ) + error = node.query_and_get_error( + f"ALTER DATABASE {glue_db_name} MODIFY SETTING region = 'eu-west-1'" + ) + assert "NOT_IMPLEMENTED" in error + node.query(f"DROP DATABASE {glue_db_name}") + + +def test_alter_database_settings_rest_auth_header(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"rest_alter_auth_header_{uuid.uuid4().hex}" + old_header = f"Authorization: Bearer old_{uuid.uuid4().hex}" + new_header = f"Authorization: Bearer new_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-rest:1/api') + SETTINGS catalog_type = 'rest', warehouse = 'wh', auth_header = '{old_header}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING auth_header = '{new_header}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING catalog_credential = 'id:secret'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_header not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_header in engine_full_with_secrets + assert old_header not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_persistence(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_alter_persist_{uuid.uuid4().hex}" + old_token = f"secret_token_{uuid.uuid4().hex}" + new_token = f"secret_token_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-0', onelake_tenant_id = 'tenant-1', onelake_bearer_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_tenant_id = 'tenant-2', onelake_bearer_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_client_id = 'client-1'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = ''" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert new_token not in show_result + assert old_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert "tenant-2" in engine_full_with_secrets + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.restart_clickhouse() + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert "tenant-0" not in show_result + assert "tenant-1" not in show_result + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert "tenant-2" in engine_full + assert "tenant-0" not in engine_full + assert "tenant-1" not in engine_full + assert new_token not in engine_full + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_refresh_token(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_refresh_token_{uuid.uuid4().hex}" + old_token = f"refresh_token_{uuid.uuid4().hex}" + new_token = f"refresh_token_{uuid.uuid4().hex}" + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_refresh_token = '{old_token}' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', oauth_server_use_request_body = 0 + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "oauth_server_use_request_body" in error + + # In refresh-token mode the catalog access token is reused for Azure storage, + # so a non-storage auth_scope is rejected at CREATE time. + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', auth_scope = 'api://my-catalog/.default' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "auth_scope" in error + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_refresh_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = 'token'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert new_token not in engine_full + + node.query(f"DROP DATABASE {db_name}") + + +def test_catalog_listing_error_surfaces_in_system_tables(started_cluster): + """ + Regression test: an error from the catalog while listing tables (e.g. expired + catalog credentials) must not be silently turned into an empty listing when the + user explicitly opted into showing datalake catalogs in system tables with + show_data_lake_catalogs_in_system_tables=1. Without the opt-in the old tolerant + behaviour is kept (system tables must not fail because of one broken catalog). + """ + node = started_cluster.instances["node1"] + + root_namespace = f"clickhouse_{uuid.uuid4()}" + namespace = f"{root_namespace}_test_listing_error" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(namespace) + create_table(catalog, namespace, "table_x") + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + node.query("SYSTEM ENABLE FAILPOINT datalake_get_tables_throw") + try: + assert ( + node.query( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}'" + ).strip() + == "0" + ) + + error = node.query_and_get_error( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name, engine FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + finally: + node.query("SYSTEM DISABLE FAILPOINT datalake_get_tables_throw") + + result = node.query( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "table_x" in result + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") + + +def test_catalog_commit_conflict_reaches_caller_at_once(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_catalog_commit_conflict_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node, root_namespace, table_name, "(x UInt64)" + ) + + # Every sink reads the branch tip in its constructor, and all `max_insert_threads` sinks are + # constructed before the pipeline starts, so all but one of them commit against a stale parent + # and are refused with `409`. That makes the conflict a property of the plan rather than a race. + num_writers = 4 + query_id = uuid.uuid4().hex + node.query( + f"INSERT INTO {table_ref} SELECT number FROM numbers_mt(4000000)", + query_id=query_id, + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + "max_insert_threads": num_writers, + "max_threads": num_writers, + }, + ) + + node.query("SYSTEM FLUSH LOGS system.text_log") + + conflicts, http_requests = map( + int, + node.query( + f""" + SELECT + countIf(logger_name LIKE 'RestCatalog%' AND message LIKE '%updateMetadata conflict%'), + countIf(logger_name = 'ReadWriteBufferFromHTTP') + FROM system.text_log + WHERE query_id = '{query_id}' AND message LIKE '%409%' + """ + ).split(), + ) + + assert conflicts, ( + "no writer was refused, so nothing about conflict handling was exercised" + ) + assert http_requests == conflicts, ( + f"{conflicts} refused commit(s) cost {http_requests} catalog requests, so a conflict is " + f"resent with backoff instead of being handed back to the sink at once" + ) + + assert int(node.query(f"SELECT count() FROM {table_ref}")) == 4000000 + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") diff --git a/tests/integration/test_dotnet_client/test.py b/tests/integration/test_dotnet_client/test.py index 76778a84edbd..80fea52d791a 100644 --- a/tests/integration/test_dotnet_client/test.py +++ b/tests/integration/test_dotnet_client/test.py @@ -54,11 +54,14 @@ def test_dotnet_client(started_cluster, dotnet_container): reference = fp.read() code, (stdout, stderr) = dotnet_container.exec_run( - "dotnet run --host {host} --port {port} --user default --password 123 --database default".format( + "dotnet /client/out/clickhouse.test.dll --host {host} --port {port} --user default --password 123 --database default".format( host=started_cluster.get_instance_ip("node"), port=8123 ), demux=True, ) - assert code == 0 - assert stdout == reference + # These two streams exist nowhere else: the client runs in its own container and nothing in the + # job collects its output. Reporting them here is what makes a client that died on a signal + # diagnosable at all, instead of leaving a bare exit code behind. + assert code == 0, f"stdout:\n{stdout!r}\nstderr:\n{stderr!r}" + assert stdout == reference, f"stderr:\n{stderr!r}" diff --git a/tests/integration/test_git_import/test.py b/tests/integration/test_git_import/test.py index 13c76498e0a5..e1c6fc623d29 100644 --- a/tests/integration/test_git_import/test.py +++ b/tests/integration/test_git_import/test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import logging +import re import time import pytest @@ -40,8 +41,24 @@ def clone_git_repository(repo, dir, commit=None): time.sleep(1) +# `ClickHouseCluster` gives the whole container the running server's profraw merge pool +# (`LLVM_PROFILE_FILE=/debug/it-%c%4m.profraw`), which every `docker exec`-ed process inherits. +# A second writer cannot merge into a continuous-mode profile - it records its own writer's counter +# bias - so in a coverage build the profiling runtime writes +# `LLVM Profile Warning: Unable to merge profile data: source profile file is not compatible.` and +# two `File exists` errors to stderr. Give this one-shot process a file of its own: its coverage is +# still collected and it no longer touches the server's pool. +GIT_IMPORT_PROFILE_FILE = "/debug/git-import-%p.profraw" + +# One progress line per processed commit, which `git-import` writes to stderr. +COMMIT_PROGRESS_RE = re.compile(r"^\d+% \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [0-9a-f]{40} ") + + def run_git_import(dir): - command = f"cd {dir} && /usr/bin/clickhouse git-import 2>&1" + command = ( + f"cd {dir} && LLVM_PROFILE_FILE={GIT_IMPORT_PROFILE_FILE} " + "/usr/bin/clickhouse git-import 2>&1" + ) return node.exec_in_container(["bash", "-c", command]) @@ -176,7 +193,15 @@ def test_git_import(): create_tables() insert_into_tables(dir) - assert output.count("\n") == 26 + # `git-import` prints the `git log` command it runs and the commit count to stdout, and one + # progress line per commit to stderr, which the `2>&1` above merges into the same stream. Match + # those shapes instead of counting every newline, so that a line written by anything other than + # `git-import` - a profiling or sanitizer runtime, a loader warning - fails the thing it + # actually broke rather than this count. + lines = output.splitlines() + assert "git log --reverse --no-merges --pretty=%H" in lines, output + assert "Total 24 commits to process." in lines, output + assert sum(1 for line in lines if COMMIT_PROGRESS_RE.match(line)) == 24, output assert node.query("SELECT count() FROM commits") == "24\n" assert node.query("SELECT count() FROM file_changes") == "35\n" assert node.query("SELECT count(), round(avg(indent), 1) FROM line_changes") == TSV( diff --git a/tests/integration/test_keeper_remove_rejoin_leader/test.py b/tests/integration/test_keeper_remove_rejoin_leader/test.py index 8cb03c599d26..e51bbbdc7041 100644 --- a/tests/integration/test_keeper_remove_rejoin_leader/test.py +++ b/tests/integration/test_keeper_remove_rejoin_leader/test.py @@ -28,6 +28,7 @@ import json import os +import re import time import uuid from typing import NamedTuple @@ -132,6 +133,46 @@ def started_cluster(): pass +def _relax_timeouts_for_sanitizer(config_path): + """Rewrite a keeper config with relaxed Raft timeouts for sanitizer builds. + + Under sanitizers (ASan, MSan, TSan) CPU overhead can delay Raft + heartbeats enough to trigger spurious leader elections. This bumps + the heartbeat interval and election timeout so the cluster stays + stable even with 3-5x slowdown. + """ + with open(config_path) as f: + content = f.read() + + content = re.sub( + r"\d+", + "2000", + content, + ) + content = re.sub( + r"\d+", + "5000", + content, + ) + content = re.sub( + r"\d+", + "10000", + content, + ) + # Configs for nodes 1/2/3 omit election timeouts — add them. + if "" not in content: + content = re.sub( + r"([ \t]*)", + r"\g<1> 5000\n" + r"\g<1> 10000\n" + r"\g<1>", + content, + ) + + with open(config_path, "w") as f: + f.write(content) + + def send_rcfg(cluster, node, command, timeout_sec=60): result_str = keeper_utils.send_4lw_cmd( cluster, @@ -183,6 +224,30 @@ def test_leader_election_after_rolling_membership_change(started_cluster): for n in [node1, node2, node3]: keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Under sanitizers, Raft heartbeats can be delayed enough to trigger + # spurious leader elections. Detect and relax timeouts if needed. + if node1.is_built_with_sanitizer(): + # Patch all 6 config files on disk. Nodes 4/5/6 will pick them + # up later when start_keeper copies them into the container. + for i in range(1, 7): + _relax_timeouts_for_sanitizer( + os.path.join(CONFIG_DIR, _get_generated_cfg(node_names, i)) + ) + + # Rolling-restart nodes 1/2/3 so they pick up the relaxed + # timeouts. Only one node is down at a time, so quorum is kept. + for node_obj in [node1, node2, node3]: + cfg_name = _get_generated_cfg(node_names, node_id(node_obj)) + node_obj.stop_clickhouse() + node_obj.copy_file_to_container( + os.path.join(CONFIG_DIR, cfg_name), + "/etc/clickhouse-server/config.d/" + cfg_name, + ) + node_obj.start_clickhouse() + + for n in [node1, node2, node3]: + keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Identify the current leader and the two followers dynamically so the # test does not depend on which node wins the initial election. leader = keeper_utils.get_leader(cluster, [node1, node2, node3]) diff --git a/tests/integration/test_mask_sensitive_info/test.py b/tests/integration/test_mask_sensitive_info/test.py index 83dd82d92c8b..7f17c145e335 100644 --- a/tests/integration/test_mask_sensitive_info/test.py +++ b/tests/integration/test_mask_sensitive_info/test.py @@ -725,13 +725,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"icebergAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] # DeltaLake table functions are not available under Memory Sanitizer (Rust code is not instrumented) @@ -742,9 +742,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: @@ -764,13 +764,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"icebergAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_delta_lake: @@ -780,9 +780,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..362c39c90ed8 --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,11 @@ + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py new file mode 100644 index 000000000000..3996927d149f --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py @@ -0,0 +1,102 @@ +import pytest + +from helpers.cluster import ClickHouseCluster, QueryRuntimeException + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) + +TENANT = {"user": "tenant", "password": "tpass"} + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def test_scheduled_refresh_of_definer_view_carries_definer_to_remote_shard( + started_cluster, +): + # Protected data lives only on node2. The tenant exists on both nodes but has no grant on it. + node2.query( + """ + CREATE DATABASE lab; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + CREATE TABLE lab.secrets (id UInt64, payload String) ENGINE = MergeTree ORDER BY id; + INSERT INTO lab.secrets VALUES (1, 'a'), (2, 'b'), (3, 'c'); + """ + ) + # With `table_engines_require_grant = false`, `TABLE ENGINE ON Distributed` is revoked unless the + # user also has `READ` and `WRITE` on the `REMOTE` source. + node1.query( + """ + CREATE DATABASE tenant_db; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT CREATE TABLE, SELECT, INSERT ON tenant_db.* TO tenant; + GRANT TABLE ENGINE ON Distributed TO tenant; + GRANT READ, WRITE ON REMOTE TO tenant; + """ + ) + + node1.query( + """ + CREATE TABLE tenant_db.dist (id UInt64, payload String) + ENGINE = Distributed('secure', 'lab', 'secrets', rand()); + CREATE TABLE tenant_db.target + (id UInt64, payload String, current_user String, authenticated_user String) + ENGINE = MergeTree ORDER BY id; + """, + **TENANT, + ) + + # A direct read through the Distributed table is denied on the remote shard. + assert "ACCESS_DENIED" in node1.query_and_get_error( + "SELECT * FROM tenant_db.dist", **TENANT + ) + + # The shard also checks the allowed hosts of the definer against `initial_address`. A scheduled + # refresh has no client, so it must present itself as coming from the local host of the + # initiator rather than from the unspecified address, which only `HOST ANY` users accept. + node2.query("ALTER USER tenant HOST LOCAL") + + # The refresh runs under the definer's identity and must be denied on the remote shard too. + # Before the fix, the refresh query was sent with an empty `initial_user`, which the remote + # shard treated as interserver mode and executed without any access checks. + node1.query( + """ + CREATE MATERIALIZED VIEW tenant_db.rmv REFRESH EVERY 1 YEAR APPEND TO tenant_db.target + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT id, payload, currentUser() AS current_user, authenticatedUser() AS authenticated_user + FROM tenant_db.dist; + """, + **TENANT, + ) + + with pytest.raises(QueryRuntimeException, match="ACCESS_DENIED"): + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT count() FROM tenant_db.target") == "0\n" + assert "ACCESS_DENIED" in node1.query( + "SELECT exception FROM system.view_refreshes WHERE database = 'tenant_db' AND view = 'rmv'" + ) + + # Once the definer is granted access on the remote shard, the refresh succeeds and the remote + # shard sees the definer as the current and authenticated user. + node2.query("GRANT SELECT ON lab.secrets TO tenant") + node1.query("SYSTEM REFRESH VIEW tenant_db.rmv") + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT * FROM tenant_db.target ORDER BY id", **TENANT) == ( + "1\ta\ttenant\ttenant\n2\tb\ttenant\ttenant\n3\tc\ttenant\ttenant\n" + ) diff --git a/tests/integration/test_restore_replica_metadata_version/test.py b/tests/integration/test_restore_replica_metadata_version/test.py index b35af4075c11..4fc23ce116ae 100644 --- a/tests/integration/test_restore_replica_metadata_version/test.py +++ b/tests/integration/test_restore_replica_metadata_version/test.py @@ -36,6 +36,79 @@ def start_cluster(): cluster.shutdown() +def test_alter_after_concurrent_restore(start_cluster): + zk = cluster.get_kazoo_client("zoo1") + table = "test_concurrent_restore" + zk_path = f"/clickhouse/tables/{table}" + failpoint = "rmt_restore_replica_pause_before_metadata_version_raise" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + for node in [node_1, node_2]: + node.query( + f"CREATE TABLE {table} (n UInt32) " + f"ENGINE = ReplicatedMergeTree('{zk_path}/', '{node.name}') ORDER BY n" + ) + + # Two ALTERs bring the metadata version of the table, and of the part inserted after them, to 2 + for column in ["a", "b"]: + node_1.query( + f"ALTER TABLE {table} ADD COLUMN {column} UInt32", + settings={"alter_sync": 2}, + ) + node_1.query(f"INSERT INTO {table} VALUES (1, 1, 1)") + node_2.query(f"SYSTEM SYNC REPLICA {table}") + for node in [node_1, node_2]: + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + zk_rmr_with_retries(zk, zk_path) + for node in [node_1, node_2]: + node.query(f"SYSTEM RESTART REPLICA {table}") + + # Restore both replicas at the same time, as ON CLUSTER does: node_1 stops after it has + # restored the table in Keeper, before it raises the metadata version to the one of its part, + # and node_2 restores in the meantime by copying node_1 + node_1.query(f"SYSTEM ENABLE FAILPOINT {failpoint}") + restore = node_1.get_query_request(f"SYSTEM RESTORE REPLICA {table}") + node_1.query(f"SYSTEM WAIT FAILPOINT {failpoint} PAUSE") + node_2.query(f"SYSTEM RESTORE REPLICA {table}") + assert ( + node_2.query(f"SELECT is_readonly FROM system.replicas WHERE table = '{table}'") + == "0\n" + ) + node_1.query(f"SYSTEM DISABLE FAILPOINT {failpoint}") + restore.get_answer() + + for node in [node_1, node_2]: + node.query(f"SYSTEM SYNC REPLICA {table}") + + _, stat = zk.get(f"{zk_path}/metadata") + assert stat.version == 2 + for node in [node_1, node_2]: + version, _ = zk.get(f"{zk_path}/replicas/{node.name}/metadata_version") + assert version == b"2" + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + # A replica left below the metadata version of the table rejects every ALTER with CANNOT_ASSIGN_ALTER + node_2.query(f"ALTER TABLE {table} ADD COLUMN c UInt32", settings={"alter_sync": 2}) + node_1.query(f"ALTER TABLE {table} ADD COLUMN d UInt32", settings={"alter_sync": 2}) + for node in [node_1, node_2]: + assert node.query(f"SELECT n, a, b, c, d FROM {table}") == "1\t1\t1\t0\t0\n" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + + def test_fix_metadata_version_on_attach_part_after_restore(start_cluster): zk = cluster.get_kazoo_client("zoo1") diff --git a/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py new file mode 100644 index 000000000000..d90720f797bd --- /dev/null +++ b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py @@ -0,0 +1,99 @@ +""" +An Iceberg manifest-list entry may declare any `manifest_length`. Reading such a table must not +depend on that number: it used to become the metadata cache cell weight and terminate the server. +""" +import os +import shutil +import tempfile + +from helpers.iceberg_utils import get_uuid_str +from test_storage_iceberg_no_spark.test_local_path_traversal import ( + _download_table_from_container, + _get_manifest_paths_from_chain, + _modify_avro_file, +) + +NOCACHE = { + "use_iceberg_metadata_files_cache": False, + "use_parquet_metadata_cache": False, +} +CACHE = {"use_iceberg_metadata_files_cache": True} +HUGE_MANIFEST_LENGTH = 2**62 + + +def _make_table_with_manifest_length(instance, table_name, table_path, new_length): + """Build a well-formed IcebergLocal table with the cache off, then rewrite every + manifest-list entry's `manifest_length`. new_length=None rewrites the file without + changing the value. Returns the manifest files' real total size on disk.""" + instance.query( + f"CREATE TABLE {table_name} (c0 Int) ENGINE = IcebergLocal('{table_path}/', 'Parquet');", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + instance.query( + f"INSERT INTO {table_name} VALUES (1), (2), (3)", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + assert instance.query(f"SELECT count() FROM {table_name}", settings=NOCACHE).strip() == "3" + instance.query(f"DROP TABLE {table_name}") + + temp_dir = tempfile.mkdtemp() + try: + host_path = os.path.join(temp_dir, table_name) + os.makedirs(host_path, exist_ok=True) + _download_table_from_container(instance, table_path, host_path) + manifest_list_rel, manifest_rels = _get_manifest_paths_from_chain(host_path, table_path) + local_manifest_list = os.path.join(host_path, manifest_list_rel) + _modify_avro_file( + local_manifest_list, + ["manifest_length"], + (lambda v: v) if new_length is None else (lambda _: new_length), + ) + instance.copy_file_to_container(local_manifest_list, f"{table_path}/{manifest_list_rel}") + return sum(os.path.getsize(os.path.join(host_path, rel)) for rel in manifest_rels) + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + + +def _read_back(instance, table_path): + """Read with the metadata cache ON, from a cold cache: the cache-miss path is the only + one that builds the cell whose weight the declared length used to set. Returns the + query results plus the cache weight those reads produced.""" + instance.query("SYSTEM DROP ICEBERG METADATA CACHE") + count = instance.query(f"SELECT count() FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + total = instance.query(f"SELECT sum(c0) FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + weight = instance.query( + "SELECT value FROM system.metrics WHERE metric = 'IcebergMetadataFilesCacheBytes'" + ).strip() + return count, total, int(weight) + + +def _assert_weighed_by_real_size(weight, manifest_bytes): + """A manifest is charged three times its size on storage, so the total must clear that + bound. Reading the size from the file rather than hardcoding it keeps this stable while + still failing if the weight ever comes from something other than the real size.""" + assert weight >= 3 * manifest_bytes, f"weight {weight} < 3 * {manifest_bytes}" + + +def test_iceberg_rewritten_manifest_list_is_readable(started_cluster_iceberg_no_spark): + """Control for the test below: the same Avro round-trip with the declared length + untouched. It runs first so that a regression of the fix, which aborts the server and + makes every later query in the package fail to connect, cannot mask this result.""" + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_manifest_list_roundtrip" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length(instance, table_name, table_path, None) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) + + +def test_iceberg_huge_manifest_length_is_readable(started_cluster_iceberg_no_spark): + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_huge_manifest_length" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length( + instance, table_name, table_path, HUGE_MANIFEST_LENGTH + ) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) diff --git a/tests/integration/test_storage_s3/test.py b/tests/integration/test_storage_s3/test.py index eb975f052251..be913f27a387 100644 --- a/tests/integration/test_storage_s3/test.py +++ b/tests/integration/test_storage_s3/test.py @@ -2683,6 +2683,41 @@ def test_page_cache(started_cluster): assert 0 < int(gets) +def test_cache_key_includes_storage(started_cluster): + # The same key with the same content, so the same ETag, in another bucket or behind another endpoint: + # the filesystem cache and the page cache must not serve it the entry filled by the first object. + instance = started_cluster.instances["dummy"] + table_name = f"test_cache_key_includes_storage-{uuid.uuid4()}" + host = f"{started_cluster.minio_host}:{started_cluster.minio_port}" + ip = f"{started_cluster.minio_ip}:{started_cluster.minio_port}" + + for bucket in [started_cluster.minio_bucket, started_cluster.minio_bucket_2]: + instance.query( + f"insert into function s3('http://{host}/{bucket}/{table_name}.tsv', auto, 'x UInt64') select number from numbers(100) SETTINGS s3_truncate_on_insert=1" + ) + + urls = [ + f"http://{host}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{ip}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{host}/{started_cluster.minio_bucket_2}/{table_name}.tsv", + ] + for settings in ["filesystem_cache_name = 'cache1', enable_filesystem_cache=1", "use_page_cache_for_object_storage=1"]: + for url in urls: + query_id = f"{table_name}-{uuid.uuid4()}" + assert "100\n" == instance.query( + f"select sum(ignore(*) + 1) from s3('{url}', 'TSV', 'x UInt64') SETTINGS {settings}", + query_id=query_id, + ) + + instance.query("SYSTEM FLUSH LOGS") + + assert 0 < int( + instance.query( + f"SELECT ProfileEvents['S3GetObject'] FROM system.query_log WHERE query_id = '{query_id}' AND type = 'QueryFinish'" + ) + ) + + def test_archive(started_cluster): id = uuid.uuid4() bucket = started_cluster.minio_bucket diff --git a/tests/integration/test_storage_url/test.py b/tests/integration/test_storage_url/test.py index 8c7bc908f932..fa68686b1f67 100644 --- a/tests/integration/test_storage_url/test.py +++ b/tests/integration/test_storage_url/test.py @@ -115,7 +115,8 @@ def test_table_function_url_access_rights(): f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1" ) - node1.query("GRANT READ ON URL TO u1") + # Like `SELECT`, `DESCRIBE` of a table function also needs `CREATE TEMPORARY TABLE`. + node1.query("GRANT READ ON URL, CREATE TEMPORARY TABLE ON *.* TO u1") assert node1.query( f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1", diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py b/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml new file mode 100644 index 000000000000..0b5411455b46 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml @@ -0,0 +1,6 @@ + + + root + clickhouse + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..af0b7ad21cab --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,14 @@ + + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml new file mode 100644 index 000000000000..ae00b3b543f9 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + ::/0 + + default + default + 1 + + + + + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/test.py b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py new file mode 100644 index 000000000000..f14f501904b5 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py @@ -0,0 +1,299 @@ +# pylint: disable=unused-argument +# pylint: disable=redefined-outer-name +# pylint: disable=line-too-long + +""" +Pushes from streaming engines into a `Distributed` table must reach the shard under the definer. + +`Kafka`, `RabbitMQ` and the other streaming engines never write anywhere themselves: a consumed +batch is pushed only into the dependent materialized views, from a copy of the global context that +has no user. A view with `SQL SECURITY DEFINER` switches that push to the definer. When the view's +target is a `Distributed` table over a cluster with an interserver ``, the definer's name +must travel with the query: before the fix `Context::setUser` left the `ClientInfo` user names +empty, the shard received an empty `initial_user`, treated the query as interserver mode and +executed it with full access. A tenant that could create tables only in its own database could +chain `Kafka -> MATERIALIZED VIEW -> Distributed('secure', default, secret_data)` and write into +a table on the shard it had no `INSERT` grant on. + +The `secure` cluster consists of `node2` only, so a table on `node1` can reach `default.secret_data` +solely over the interserver connection. Every pipeline is built twice with the same statements: by +`tenant`, who has no grants on `node2` and whose rows must be rejected there, and by `writer`, who +has `INSERT` on the target and whose rows must arrive. In both cases the shard must see the +definer's name in `system.query_log`. + +The push is also checked with `distributed_foreground_insert = 0`, where the rows go through the +background directory queue of the `Distributed` table: the persisted insert must keep the definer's +name, although the streaming context has `query_kind = NO_QUERY`. +""" + +import json +import time + +import pika +import pytest + +import helpers.kafka.common as k +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml", "configs/rabbitmq.xml"], + user_configs=["configs/users.xml"], + with_kafka=True, + with_rabbitmq=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + user_configs=["configs/users.xml"], +) + +WRITER = "writer" +TENANT = "tenant" +CREDENTIALS = { + WRITER: {"user": WRITER, "password": "wpass"}, + TENANT: {"user": TENANT, "password": "tpass"}, +} +ROWS_PER_PIPELINE = 2 + +# How long a streaming engine gets to consume the messages and push them to the shard. Consumer +# group setup in Kafka alone can take several seconds. +DELIVERY_WAIT_SECONDS = 60 + +users = pytest.mark.parametrize("user", [WRITER, TENANT]) + + +def database(user): + return f"{user}_db" + + +def query_as(user, sql): + return node1.query(sql, **CREDENTIALS[user]) + + +def remote_rows(): + return int(node2.query("SELECT count() FROM default.secret_data")) + + +def shard_inserts(user, condition): + """Number of `INSERT` queries into the protected table that the shard executed under `user`.""" + node2.query("SYSTEM FLUSH LOGS") + return int( + node2.query( + f""" + SELECT count() FROM system.query_log + WHERE user = '{user}' AND query LIKE 'INSERT INTO default.secret_data%' AND {condition} + """ + ) + ) + + +def shard_finished_inserts(user): + return shard_inserts(user, "type = 'QueryFinish'") + + +def shard_denied_inserts(user): + # The access check happens before the pipeline starts, so the shard logs the denial as + # `ExceptionBeforeStart`. + return shard_inserts( + user, + "type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing') AND exception_code = 497", + ) + + +def wait_until(condition, timeout=DELIVERY_WAIT_SECONDS): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(1) + return False + + +@pytest.fixture(scope="module", autouse=True) +def started_cluster(): + try: + cluster.start() + + # The protected table lives on the shard only. Both users exist on both nodes, but on + # the shard only `writer` may insert into it. + node2.query( + """ + CREATE TABLE default.secret_data (key Int) ENGINE = MergeTree ORDER BY key; + CREATE USER writer IDENTIFIED WITH plaintext_password BY 'wpass'; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT INSERT ON default.secret_data TO writer; + """ + ) + for user in (WRITER, TENANT): + db = database(user) + # Send to the shard synchronously by default, so that a push either delivers the rows + # or fails right away, without a background directory queue in between. + # With `table_engines_require_grant = false`, `TABLE ENGINE` on a source engine is + # revoked unless the user also has `READ` and `WRITE` on its source. + node1.query( + f""" + CREATE USER {user} IDENTIFIED WITH plaintext_password BY '{CREDENTIALS[user]["password"]}' + SETTINGS distributed_foreground_insert = 1; + CREATE DATABASE {db}; + GRANT ALL ON {db}.* TO {user}; + GRANT TABLE ENGINE ON Distributed, TABLE ENGINE ON Kafka, TABLE ENGINE ON RabbitMQ TO {user}; + GRANT READ, WRITE ON REMOTE, READ, WRITE ON KAFKA, READ, WRITE ON RABBITMQ TO {user}; + """ + ) + query_as( + user, + f"CREATE TABLE {db}.dist (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + + yield cluster + finally: + cluster.shutdown() + + +@pytest.fixture(autouse=True) +def clean_remote_table(): + node2.query("TRUNCATE TABLE default.secret_data") + yield + + +def drop_pipeline(user, source): + """Stop the streaming table, so that a rejected push is not retried into the next test.""" + db = database(user) + query_as(user, f"DROP TABLE {db}.{source}_to_dist") + query_as(user, f"DROP TABLE {db}.{source} SYNC") + + +def create_definer_view(user, source, target="dist"): + """A view owned by `user` that pushes the source rows into the user's `Distributed` table.""" + db = database(user) + query_as( + user, + f""" + CREATE MATERIALIZED VIEW {db}.{source}_to_dist TO {db}.{target} + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT key FROM {db}.{source} + """, + ) + + +def check_delivery(user, finished_before, denied_before): + """The shard must have executed the push under the user's name, with the outcome the user's + grants dictate: the rows arrive for `writer` and are rejected for `tenant`.""" + if user == WRITER: + assert wait_until(lambda: remote_rows() == ROWS_PER_PIPELINE) + assert shard_finished_inserts(WRITER) > finished_before + else: + assert wait_until( + lambda: shard_denied_inserts(TENANT) > denied_before or remote_rows() > 0 + ) + assert remote_rows() == 0 + assert shard_denied_inserts(TENANT) > denied_before + + +def check_direct_insert(user): + """The control case: a direct `INSERT` carries the user's name to the shard, where it is checked. + + It passes without the fix as well, so it is not a separate test: bugfix validation requires every + new test to fail on the unfixed binary. It runs before a streaming pipeline instead.""" + db = database(user) + if user == WRITER: + query_as(WRITER, f"INSERT INTO {db}.dist VALUES (1)") + assert remote_rows() == 1 + else: + error = node1.query_and_get_error( + f"INSERT INTO {db}.dist VALUES (1)", **CREDENTIALS[TENANT] + ) + assert "ACCESS_DENIED" in error + assert remote_rows() == 0 + node2.query("TRUNCATE TABLE default.secret_data") + + +@users +@pytest.mark.parametrize("foreground", [1, 0]) +def test_kafka(user, foreground): + db = database(user) + topic = f"definer_interserver_{user}_{foreground}" + k.kafka_create_topic(k.get_admin_client(cluster), topic) + + query_as( + user, + f""" + CREATE TABLE {db}.kafka (key Int) ENGINE = Kafka + SETTINGS kafka_broker_list = 'kafka1:19092', + kafka_topic_list = '{topic}', + kafka_group_name = '{topic}', + kafka_format = 'JSONEachRow', + kafka_flush_interval_ms = 1000 + """, + ) + # A separate `Distributed` table per mode, so that a rejected file left in the background queue + # is dropped together with the table and is not retried into the next test. + target = f"dist_{foreground}" + query_as( + user, + f"CREATE TABLE {db}.{target} (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + # The definer's settings apply to the push. It is not set in the server's profile, because the + # settings of the context the push starts from would override the definer's ones. + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = {foreground}") + create_definer_view(user, "kafka", target) + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + k.kafka_produce( + cluster, topic, [json.dumps({"key": i}) for i in range(ROWS_PER_PIPELINE)] + ) + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "kafka") + query_as(user, f"DROP TABLE {db}.{target} SYNC") + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = 1") + + +@users +def test_rabbitmq(user): + check_direct_insert(user) + db = database(user) + exchange = f"definer_interserver_{user}" + + query_as( + user, + f""" + CREATE TABLE {db}.rabbitmq (key Int) ENGINE = RabbitMQ + SETTINGS rabbitmq_host_port = 'rabbitmq1:5672', + rabbitmq_exchange_name = '{exchange}', + rabbitmq_format = 'JSONEachRow', + rabbitmq_flush_interval_ms = 1000, + rabbitmq_max_block_size = 100 + """, + ) + create_definer_view(user, "rabbitmq") + + # The exchange and the queue are declared by the table in the background; messages + # published before that are dropped by RabbitMQ. + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: RabbitMQ setup completed") + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: Queue .* is declared") + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + + credentials = pika.PlainCredentials("root", "clickhouse") + parameters = pika.ConnectionParameters( + cluster.rabbitmq_ip, cluster.rabbitmq_port, "/", credentials + ) + connection = pika.BlockingConnection(parameters) + channel = connection.channel() + for i in range(ROWS_PER_PIPELINE): + channel.basic_publish( + exchange=exchange, routing_key="", body=json.dumps({"key": i}) + ) + connection.close() + + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "rabbitmq") diff --git a/tests/integration/test_totp_auth/test_totp.py b/tests/integration/test_totp_auth/test_totp.py index d682ecf94848..7aa30c96a53c 100644 --- a/tests/integration/test_totp_auth/test_totp.py +++ b/tests/integration/test_totp_auth/test_totp.py @@ -98,9 +98,37 @@ def test_one_time_password(started_cluster): query_text, user="totuser", password=f"aa+bb+{old_password}" ) - assert "REQUIRED_SECOND_FACTOR" in node.query_and_get_error( - query_text, user="totuser", password=f"aa+bb" + # Without a code the response does not depend on the password, so the error REQUIRED_SECOND_FACTOR + # does not confirm a guessed password: a wrong or an empty password gets exactly the same error + error_without_code = node.query_and_get_error( + query_text, user="totuser", password="aa+bb" ) + assert "REQUIRED_SECOND_FACTOR" in error_without_code + for password in ["wrongpwd", ""]: + assert error_without_code == node.query_and_get_error( + query_text, user="totuser", password=password + ) + + http_responses = [ + node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": password}, + ) + for password in ["aa+bb", "wrongpwd"] + ] + for response in http_responses: + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "767" + assert http_responses[0].text == http_responses[1].text + + response = node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": "aa+bb+000000000"}, + ) + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "516" assert "totuser42\n" == node.query( query_text, user="totuser", password=f"aa+bb+{get_otp('totuser')}" @@ -196,13 +224,17 @@ def test_interactive_totp_authentication(started_cluster): # Then enter wrong TOTP when prompted c.expect("TOTP.*:") - c.send(f"000000", eol="\r") + c.send("000000000", eol="\r") c.expect(expected_error) - with client(command=f"{client_command(user0)} --password aa+bb+000000") as c: + # A wrong code of the configured length (9 digits); a suffix of another length counts as no code + with client(command=f"{client_command(user0)} --password aa+bb+000000000") as c: c.expect(expected_error) + # A wrong password without a code is asked for the code like a right one, and fails only after that with client(command=f"{client_command(user0)} --password wrongpwd") as c: + c.expect("TOTP.*:") + c.send(get_otp(user0), eol="\r") c.expect(expected_error) with client( @@ -370,7 +402,10 @@ def test_one_time_only_no_password(started_cluster): assert f"{user0}42\n" == node.query(query_text, user=user0, password=get_otp(user0)) + # The client cannot know that the account has no password: it asks for the password first with client(command=f"{client_command(user0)}") as c: + c.expect("Password.*:") + c.send("", eol="\r") c.expect("TOTP.*:") c.send(get_otp(user0, offset_steps=1), eol="\r") c.expect(prompt) diff --git a/tests/performance/map_bucketed_serialization.xml b/tests/performance/map_bucketed_serialization.xml index d86c681a4f3b..e5016ad60d46 100644 --- a/tests/performance/map_bucketed_serialization.xml +++ b/tests/performance/map_bucketed_serialization.xml @@ -1,6 +1,6 @@ @@ -107,7 +107,7 @@ CREATE TABLE map_subcol_pw_mixed (id UInt64, tags Map(String, String), value UInt32) @@ -126,7 +126,7 @@ OPTIMIZE TABLE map_subcol_pw_mixed FINAL SETTINGS mutations_sync=1 - diff --git a/tests/performance/prewhere_subcolumn_read_steps.xml b/tests/performance/prewhere_subcolumn_read_steps.xml new file mode 100644 index 000000000000..04cb68d9dd07 --- /dev/null +++ b/tests/performance/prewhere_subcolumn_read_steps.xml @@ -0,0 +1,19 @@ + + + 0 + + + CREATE TABLE t_prewhere_json (id UInt64, j JSON(max_dynamic_paths = 0)) ENGINE = MergeTree ORDER BY id + CREATE TABLE t_prewhere_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0 + + INSERT INTO t_prewhere_json SELECT number, concat('{{"kind":"a","n":', toString(number), ',"payload":"', repeat('x', 2000), '"}}') FROM numbers_mt(3000000) + INSERT INTO t_prewhere_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> repeat('v', 60), range(16))) FROM numbers_mt(10000000) + + + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j)) > 10 + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 + SELECT count() FROM t_prewhere_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 + + DROP TABLE IF EXISTS t_prewhere_json + DROP TABLE IF EXISTS t_prewhere_map + diff --git a/tests/queries/0_stateless/00900_long_parquet_load_2.sh b/tests/queries/0_stateless/00900_long_parquet_load_2.sh index dc8d68888463..b58b54143176 100755 --- a/tests/queries/0_stateless/00900_long_parquet_load_2.sh +++ b/tests/queries/0_stateless/00900_long_parquet_load_2.sh @@ -47,6 +47,10 @@ EXCLUDE=( # malformed on purpose, so loading it here would print an exception. 05035_delta_byte_array_zero_values.parquet 05035_delta_byte_array_decimal.parquet + # `INT96` timestamps outside the `DateTime64(9)` range (throws with the default `date_time_overflow_behavior`), tested by 05443. + 05443_int96_out_of_range.parquet + # `INT96` timestamp on the lower boundary day of the `DateTime64(9)` range, tested by 05444. + 05444_int96_lower_boundary.parquet ) for NAME in $(find "$DATA_DIR" -type f \( -iname '*.parquet' -o -iname '*.parquet.gz' \) -print0 | xargs -0 -n 1 basename | LC_ALL=C sort | grep -vFf <(printf '%s\n' "${EXCLUDE[@]}")); do diff --git a/tests/queries/0_stateless/01035_avg.reference b/tests/queries/0_stateless/01035_avg.reference index 1f47b3a8b7ea..192bceec0560 100644 --- a/tests/queries/0_stateless/01035_avg.reference +++ b/tests/queries/0_stateless/01035_avg.reference @@ -1,6 +1,6 @@ nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan --0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.493856 32355.57552 499999.5 499999.5 499999.5 499999.5 499999.5 499999.5 -0.000500002 0.49999949943727 -0.000005 -0.000004999999999999992 --2767.546272 -999999 --0.50000449943727 +-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.467744 31470.715104 124999.5 124999.5 124999.5 124999.5 124999.5 124999.5 -0.0005000056 0.12499949943764 -0.000005000000000000001 -0.0000050000000000000334 +-3182.944672 +249999 +-0.12500449943764 1 1 \N \N 1 1 diff --git a/tests/queries/0_stateless/01035_avg.sql b/tests/queries/0_stateless/01035_avg.sql index 0f7baddaec57..a8aae4480e66 100644 --- a/tests/queries/0_stateless/01035_avg.sql +++ b/tests/queries/0_stateless/01035_avg.sql @@ -27,7 +27,7 @@ SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(f32), avg(f64), avg(d32), avg(d64), avg(d128), avg(d256) FROM test_01035_avg; -INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 1000000; +INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 250000; SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(u8), avg(u16), avg(u32), avg(u64), avg(u128), avg(u256), diff --git a/tests/queries/0_stateless/01252_weird_time_zone.reference b/tests/queries/0_stateless/01252_weird_time_zone.reference index 90f5bf0e30dd..a93b19a6dd70 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.reference +++ b/tests/queries/0_stateless/01252_weird_time_zone.reference @@ -5,3 +5,41 @@ Pacific/Kwajalein 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Apia 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Enderbury 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Fakaofo 2020-01-02 03:04:05 2020-01-02 00:00:00 3 +--- offset of zones that crossed the international date line +Pacific/Kiritimati 50400 +Pacific/Apia 46800 +Pacific/Fakaofo 46800 +Pacific/Enderbury 46800 +Pacific/Kanton 46800 +Pacific/Kwajalein 43200 +Kwajalein 43200 +--- the same zones before their jump, and a +13:45 zone, must not move +Pacific/Apia -39600 +Pacific/Fakaofo -39600 +Pacific/Chatham 49500 +Pacific/Chatham 45900 +--- negative offsets before the epoch +Africa/Abidjan -968 +Africa/Accra -52 +Africa/Addis_Ababa 9320 +Europe/Moscow 9017 +--- parseDateTime agrees with toDateTime on an affected zone +1 +1 +1 +1 +1 +1 +--- other consumers of the offset ++1400 +2025-06-14 22:00:00 2025-06-16 02:00:00 +2025-06-14 22:00:00.500 2025-06-16 02:00:00.500 +--- consumers that reduce the offset modulo a day must be unaffected +12:00:00 12:00:00.500 +1970-01-02 12:00:00 2025-06-15 00:00:00 12 2025-06-15 +--- daylight saving transitions keep their sub-day offset +-18000 -14400 -18000 +--- inside and outside the lookup table window report the same offset +1 +--- every zone agrees with rendering the instant as local text and reading it back as UTC +0 diff --git a/tests/queries/0_stateless/01252_weird_time_zone.sql b/tests/queries/0_stateless/01252_weird_time_zone.sql index c4919ca4fe01..729eea83216d 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.sql +++ b/tests/queries/0_stateless/01252_weird_time_zone.sql @@ -13,3 +13,56 @@ SELECT 'Pacific/Kwajalein', rand() as r, toHour(toDateTime(r, 'Pacific/Kwajalein SELECT 'Pacific/Apia', rand() as r, toHour(toDateTime(r, 'Pacific/Apia') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Enderbury', rand() as r, toHour(toDateTime(r, 'Pacific/Enderbury') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Fakaofo', rand() as r, toHour(toDateTime(r, 'Pacific/Fakaofo') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; + +-- timezoneOffset must report the true UTC offset, including its whole-day component (issue #115281). +SELECT '--- offset of zones that crossed the international date line'; +SELECT 'Pacific/Kiritimati', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Enderbury', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Enderbury')); +SELECT 'Pacific/Kanton', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kanton')); +SELECT 'Pacific/Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kwajalein')); +SELECT 'Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Kwajalein')); + +SELECT '--- the same zones before their jump, and a +13:45 zone, must not move'; +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Chatham')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Chatham')); + +SELECT '--- negative offsets before the epoch'; +SELECT 'Africa/Abidjan', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Abidjan')); +SELECT 'Africa/Accra', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Accra')); +SELECT 'Africa/Addis_Ababa', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Addis_Ababa')); +SELECT 'Europe/Moscow', timeZoneOffset(toDateTime64(-1900000000, 0, 'Europe/Moscow')); + +SELECT '--- parseDateTime agrees with toDateTime on an affected zone'; +SELECT toUnixTimestamp(parseDateTime('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeOrNull('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTime64('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00', 'yyyy-MM-dd HH:mm:ss', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeBestEffort('2025-06-15 12:00:00', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00 Pacific/Kiritimati', 'yyyy-MM-dd HH:mm:ss z')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- other consumers of the offset'; +SELECT formatDateTime(toDateTime64(1750000000, 0, 'UTC'), '%z', 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'); + +SELECT '--- consumers that reduce the offset modulo a day must be unaffected'; +SELECT CAST(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati') AS Time), CAST(toDateTime64('2025-06-15 12:00:00.5', 3, 'Pacific/Kiritimati') AS Time64(3)); +SELECT toTime(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toStartOfDay(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toHour(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toDate(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- daylight saving transitions keep their sub-day offset'; +SELECT timeZoneOffset(toDateTime('2025-03-09 01:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-03-09 03:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-11-02 03:00:00', 'America/New_York')); + +SELECT '--- inside and outside the lookup table window report the same offset'; +SELECT timeZoneOffset(toDateTime64(1750000000, 0, 'Pacific/Kiritimati')) = timeZoneOffset(toDateTime64(90000000000, 0, 'Pacific/Kiritimati')); + +SELECT '--- every zone agrees with rendering the instant as local text and reading it back as UTC'; +WITH + arrayJoin([toDateTime64(1262347200, 0, 'UTC'), toDateTime64(1750000000, 0, 'UTC'), toDateTime64(2000000000, 0, 'UTC')]) AS ts, + formatDateTime(ts, '%z', time_zone) AS z, + (toInt64(substring(z, 2, 2)) * 3600 + toInt64(substring(z, 4, 2)) * 60) * multiIf(substring(z, 1, 1) = '-', -1, 1) AS reported, + toInt64(toDateTime(formatDateTime(ts, '%Y-%m-%d %H:%i:%S', time_zone), 'UTC')) - toInt64(ts) AS expected +SELECT count() FROM system.time_zones WHERE reported != expected; diff --git a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference index d771371b2644..0eb78aef3648 100644 --- a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference +++ b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference @@ -1 +1 @@ -0bedc9eaf0b07ce14f59ffd25e1a6df6 - +75b5b0cbd2734c37f4f02bd726c4ea60 - diff --git a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh index a44ae6f1e95a..960f2f03174f 100755 --- a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh +++ b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash -# Tags: distributed +# Tags: distributed, no-llvm-coverage +# no-llvm-coverage: the test needs the shard accumulating `repeat('a', 100000)` per row to hit +# `max_memory_usage=1G` and emit `Query memory limit exceeded` before the other shard cancels. +# LLVM source-based coverage instrumentation perturbs this memory-tracking cadence, so the +# expected exception sometimes does not surface on `127.3` before cancellation, leaving an empty +# `grep` match and a flaky FAIL. CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -9,7 +14,11 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # 1 on 127.2 # 2 on 127.3 # max_block_size to fail faster -# max_memory_usage/_shard_num/repeat() will allow failure on the first shard earlier. +# `groupArrayIf` on `_shard_num` makes `127.3` the only shard that can run out of memory: on +# `127.2` the condition is false for every row, so its aggregate states never grow and it just +# streams `system.numbers` until the initiator cancels it. Before this, `127.2` accumulated +# one-byte strings and reached the same `max_memory_usage` only about 20% later than `127.3`, so +# which shard failed first was a race. opts=( "--max_memory_usage=1G" "--max_block_size=50" @@ -17,9 +26,30 @@ opts=( "--max_distributed_connections=2" "--max_bytes_before_external_group_by=0" "--max_bytes_ratio_before_external_group_by=0" + # The query reads `system.numbers` until a shard runs out of memory, so `max_memory_usage` + # has to be the only limit that can stop it. The test profile of the CI configuration + # (tests/config/users.d/limits.yaml) sets `max_rows_to_read = 20000000`, which `127.2` and + # the initiator reach at about the same time as `127.3` reaches `max_memory_usage`; the query + # then fails with `TOO_MANY_ROWS` instead of `MEMORY_LIMIT_EXCEEDED` and the `grep` below + # finds nothing. + "--max_rows_to_read=0" + # `127.2` now never fails on its own, so if the cancellation this test is about ever breaks, + # the query would stream forever and the test would be killed by the runner's timeout with no + # output. Fail it with `TIMEOUT_EXCEEDED` instead, far above the ~1s the expected exception + # needs. + "--max_execution_time=100" ) -${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArray(repeat('a', if(_shard_num == 2, 100000, 1))), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" |& { - # the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. - grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" - # while if this will not correctly then it will got the exception from the 127.2:9000 and fail -} +LOG="$CLICKHOUSE_TMP/err-$CLICKHOUSE_DATABASE" +trap 'rm -f "$LOG"' EXIT + +${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArrayIf(repeat('a', 100000), _shard_num == 2), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" > "$LOG" 2>&1 +CODE=$? + +# the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. +# while if this will not correctly then it will got the exception from the 127.2:9000 and fail +if ! grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" "$LOG"; then + # stderr only on the failing path: a test that writes there and exits 0 is a FAIL for the runner. + echo "Fail, Code: $CODE, client output:" >&2 + cat "$LOG" >&2 + exit 1 +fi diff --git a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 index 2b1dc6c1c781..89f267e614a3 100644 --- a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 +++ b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 @@ -1,4 +1,8 @@ --- Tags: long +-- Tags: long, no-msan +-- no-msan: 5 join algorithms x ~78 statements, several of them deliberately spilling, average +-- ~183s under MSan against ~4s in a release build; the p99 is 73% of the 600s per-test budget, so +-- a run that gets killed on the timeout is an ordinary tail event. Join implicit-cast semantics +-- get no MSan-specific coverage, and the test still runs under ASan, UBSan and TSan. SET enable_analyzer = 1; DROP TABLE IF EXISTS t1; diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference index 9942759a9480..2d3bd2d2ebfd 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference @@ -1,3 +1,5 @@ 1 10 42 53 1 10 42 53 1 10 42 53 +1 +1 0 0 0 diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql index c49bf392895b..31bf6c5e6524 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql @@ -6,3 +6,13 @@ insert into function file(currentDatabase() || '_data_02302.orc') select 1 as x, select * from file(currentDatabase() || '_data_02302.orc', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_orc_allow_missing_columns=1; insert into function file(currentDatabase() || '_data_02302.arrow') select 1 as x, null::Nullable(UInt8) as xx settings engine_file_truncate_on_insert=1; select * from file(currentDatabase() || '_data_02302.arrow', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_arrow_allow_missing_columns=1; + +-- The next two queries test the native Parquet reader, so they pin it (some release branches still randomize it off). +-- A count-only read reads just the single smallest declared column, so `d` must stay strictly +-- narrower than every other column for this to exercise a defaulted one. The count cache would +-- answer before a reader exists, and the two count-only optimizations are randomized off in some runs, so all three are pinned. +-- Missing columns are rejected so that a read which is not count-only fails here instead of +-- synthesizing `d` into a correctly sized mask and returning the same count with no guard in place. +select count() from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt64, d UInt8 default 10') settings use_cache_for_count_from_files = 0, optimize_count_from_files = 1, optimize_trivial_count_query = 1, input_format_parquet_allow_missing_columns = 0, input_format_parquet_use_native_reader_v3 = 1; +-- With the setting off no `default` expression is applied, so the columns keep their type defaults. +select * from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_parquet_allow_missing_columns=1, input_format_defaults_for_omitted_fields=0, input_format_parquet_use_native_reader_v3=1; diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference new file mode 100644 index 000000000000..0f9d2713f87d --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference @@ -0,0 +1 @@ +idx text diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql new file mode 100644 index 000000000000..a629b362ee8e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql @@ -0,0 +1,24 @@ +-- An `ALTER` that adds an index is authorized against the schema the whole statement produces. +-- That must not skip the validation of its other commands and run into an exception. + +SET enable_full_text_index = 1; + +DROP TABLE IF EXISTS tab; +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab + RENAME COLUMN missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 1; -- { serverError NOT_FOUND_COLUMN_IN_BLOCK } + +ALTER TABLE tab + RENAME COLUMN val TO a, + RENAME COLUMN a TO b, + ADD INDEX idx(id) TYPE minmax GRANULARITY 1; -- { serverError NOT_IMPLEMENTED } + +ALTER TABLE tab + RENAME COLUMN IF EXISTS missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1; + +SELECT name, type FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab'; + +DROP TABLE tab; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.reference b/tests/queries/0_stateless/02346_text_index_transform_access.reference new file mode 100644 index 000000000000..1c382f1ae6da --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.reference @@ -0,0 +1,19 @@ +1. Direct call denied. +2. Denied in a preprocessor. +3. Denied when nested under a String result. +4. Denied via ALTER ADD INDEX. +5. Unprivileged expression unaffected. +1 +6. Accepted with the privilege, so not a blocklist. +1 +7. Existing index stays readable without the privilege. +1 +8. Unrelated ALTER does not re-authorize. +1 +9. Neither does DETACH/ATTACH. +1 +10. Redeclaring with a privileged function is denied. +11. The transform preflight does not reject what a plain ALTER accepts. +idx_pre +12. A statement without a transform is not analyzed at all. +idx_minmax diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.sql b/tests/queries/0_stateless/02346_text_index_transform_access.sql new file mode 100644 index 000000000000..62903e79d44b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.sql @@ -0,0 +1,124 @@ +-- Text index `preprocessor` expressions must only use functions the user declaring +-- the index is permitted to run. +-- +-- The test needs a function the current user may not run. Introspection functions fit: they are +-- refused both without the grant and, as here, with `allow_introspection_functions = 0`. Using the +-- setting keeps the test in plain SQL, with no second user to create. + +DROP TABLE IF EXISTS tab; + +-- The test configuration sets this to 1. +SET allow_introspection_functions = 0; + +SELECT '1. Direct call denied.'; + +SELECT demangle('_ZNK2DB7Context9getAccessEv'); -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. Denied in a preprocessor.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Denied when nested under a String result.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, demangle(val))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '4. Denied via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)); -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '5. Unprivileged expression unaffected.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'Hello World'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; + +SELECT '6. Accepted with the privilege, so not a blocklist.'; + +SET allow_introspection_functions = 1; + +-- `demangle` returns a non-mangled argument unchanged. +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'hello world'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '7. Existing index stays readable without the privilege.'; + +SET allow_introspection_functions = 0; + +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '8. Unrelated ALTER does not re-authorize.'; + +ALTER TABLE tab ADD COLUMN extra UInt8 DEFAULT 0; +ALTER TABLE tab RENAME COLUMN val TO val2; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '9. Neither does DETACH/ATTACH.'; + +DETACH TABLE tab; +ATTACH TABLE tab; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '10. Redeclaring with a privileged function is denied.'; + +ALTER TABLE tab DROP INDEX idx, + ADD INDEX idx(val2) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val2)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '11. The transform preflight does not reject what a plain ALTER accepts.'; + +CREATE TABLE tab_preflight (id UInt64, val String, num UInt64) +ENGINE = MergeTree ORDER BY id SETTINGS auto_statistics_types = 'minmax'; + +-- The preflight must drop implicit statistics too, or `ADD STATISTICS` looks like a duplicate. +ALTER TABLE tab_preflight ADD INDEX idx_pre(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1, + ADD STATISTICS num TYPE minmax; + +SELECT name FROM system.data_skipping_indices +WHERE database = currentDatabase() AND table = 'tab_preflight' ORDER BY name; + +DROP TABLE tab_preflight; + +SELECT '12. A statement without a transform is not analyzed at all.'; + +SET allow_statistics = 1; +CREATE TABLE tab_plain (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS auto_statistics_types = 'minmax'; + +ALTER TABLE tab_plain ADD INDEX idx_minmax(x) TYPE minmax GRANULARITY 1, ADD STATISTICS x TYPE minmax; + +SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab_plain'; + +DROP TABLE tab_plain; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference new file mode 100644 index 000000000000..8a97bd9c341e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference @@ -0,0 +1,3 @@ +1. ALTER ADD INDEX is denied. +2. CREATE TABLE is denied. +3. Accepted with the privilege. diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql new file mode 100644 index 000000000000..67ca0d15dcdc --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql @@ -0,0 +1,40 @@ +-- Tags: zookeeper, no-replicated-database +-- no-replicated-database: the test creates its own Replicated database + +-- A Replicated database hands the DDL to replicas that apply it without the submitting user, so the +-- permission check happens on the node it was submitted to. See 02346_text_index_transform_access +-- for the checks themselves, and 02346_text_index_transform_on_cluster for `ON CLUSTER`. + +SET allow_introspection_functions = 0; + +-- {CLICKHOUSE_DATABASE_1} may be left over from a previous run, hence the DROP. +DROP DATABASE IF EXISTS {CLICKHOUSE_DATABASE_1:Identifier}; +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} +ENGINE = Replicated('/clickhouse/02346_text_index_transform_access/{database}', 'shard1', 'replica1') FORMAT Null; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab (id UInt64, val String) +ENGINE = MergeTree ORDER BY id FORMAT Null; + +SELECT '1. ALTER ADD INDEX is denied.'; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. CREATE TABLE is denied.'; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab_denied +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Accepted with the privilege.'; + +SET allow_introspection_functions = 1; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1 FORMAT Null; + +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} FORMAT Null; diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.reference b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference new file mode 100644 index 000000000000..3954d852fafa --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference @@ -0,0 +1,6 @@ +1. A set from a table. +2. A subquery. +3. A dictionary lookup. +4. The same via ALTER ADD INDEX. +5. A literal set is still accepted. +1 diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.sql b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql new file mode 100644 index 000000000000..9d785850ee83 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql @@ -0,0 +1,68 @@ +-- Text index transforms are analysed under the global context, so anything that reads a table or a +-- dictionary while being analysed would do it with full access, and constant folding could reveal +-- what it read. A transform must be a pure function of the indexed value, so these are rejected +-- before any analysis. See 02346_text_index_transform_access for the function permission checks. + +DROP TABLE IF EXISTS tab; +DROP TABLE IF EXISTS set_source; +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dict_source; + +CREATE TABLE set_source (x String) ENGINE = Set; +INSERT INTO set_source VALUES ('secret'); + +CREATE TABLE dict_source (id UInt64, value String) ENGINE = MergeTree ORDER BY id; +INSERT INTO dict_source VALUES (1, 'secret'); +CREATE DICTIONARY dict (id UInt64, value String) PRIMARY KEY id +SOURCE(CLICKHOUSE(TABLE 'dict_source')) LAYOUT(FLAT()) LIFETIME(0); + +SELECT '1. A set from a table.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '2. A subquery.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, (SELECT any(value) FROM dict_source))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '3. A dictionary lookup.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '4. The same via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN (SELECT x FROM set_source), val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))); -- { serverError INCORRECT_QUERY } + +SELECT '5. A literal set is still accepted.'; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN ('hello', 'world'), val, val)); +INSERT INTO tab VALUES (1, 'hello there'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; +DROP DICTIONARY dict; +DROP TABLE dict_source; +DROP TABLE set_source; diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference new file mode 100644 index 000000000000..91fa6db49214 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference @@ -0,0 +1,14 @@ +1. ALTER ADD INDEX with a transform is refused. +1 +2. CREATE with a transform is refused. +1 +3. Refused on the legacy entry-format path too, which normalizes on the host. +1 +4. Indices inherited by CREATE AS on the legacy path are refused. +1 +5. An index without a transform is unaffected. +idx_plain +6. CREATE AS with an explicit engine and no privilege on the source. +SHOW COLUMNS ON default.tab +7. The same for a source that does not exist. +SHOW COLUMNS ON default.missing diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh new file mode 100755 index 000000000000..15b49c8bf03b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database +# no-replicated-database: ON CLUSTER is not allowed for a Replicated database + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The hosts of an `ON CLUSTER` query resolve a text index transform against their own schema and +# without the submitting user, so it is refused unless they run as that user. + +USER="user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER IF EXISTS $USER; + CREATE TABLE tab (id UInt64, val String, lowered String ALIAS lower(val)) ENGINE = MergeTree ORDER BY id; +" + +echo '1. ALTER ADD INDEX with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lowered) +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '2. CREATE with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_transform ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '3. Refused on the legacy entry-format path too, which normalizes on the host.' +$CLICKHOUSE_CLIENT --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_legacy ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '4. Indices inherited by CREATE AS on the legacy path are refused.' +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.src_transform (id UInt64, val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val))) ENGINE = MergeTree ORDER BY id" +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_inherited ON CLUSTER test_shard_localhost + AS ${CLICKHOUSE_DATABASE}.src_transform ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '5. An index without a transform is unaffected.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx_plain(val) TYPE text(tokenizer = 'splitByNonAlpha') +" +$CLICKHOUSE_CLIENT -q "SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab' ORDER BY name" + +# With an explicit engine `setEngine` does not look at `AS src`, and the inherited indices are inspected +# on the initiator, so describing the source has to be authorized first. +$CLICKHOUSE_CLIENT -n -q " + CREATE USER $USER; + GRANT CREATE TABLE ON ${CLICKHOUSE_DATABASE}.dst TO $USER; + GRANT TABLE ENGINE ON MergeTree TO $USER; +" + +echo '6. CREATE AS with an explicit engine and no privilege on the source.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.tab ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.tab" + +echo '7. The same for a source that does not exist.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.missing ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.missing" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER $USER; + DROP TABLE tab; + DROP TABLE src_transform; +" diff --git a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 index 45c6b5fe5f3f..d05007d356e4 100644 --- a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 +++ b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 @@ -1,4 +1,4 @@ --- Tags: long +-- Tags: long, no-msan SET enable_analyzer = 1; SET single_join_prefer_left_table = 0; diff --git a/tests/queries/0_stateless/02426_orc_bug.reference b/tests/queries/0_stateless/02426_orc_bug.reference index 4f76072e70d1..d5f93b43aa8d 100644 --- a/tests/queries/0_stateless/02426_orc_bug.reference +++ b/tests/queries/0_stateless/02426_orc_bug.reference @@ -1 +1 @@ -64a50db9526e0e3aa8c969939922658d - +f8d66b83061a9b0ce960c0b9ce32a64c - diff --git a/tests/queries/0_stateless/02884_authentication_quota.reference b/tests/queries/0_stateless/02884_authentication_quota.reference index d8ed6d97b505..c41269381185 100644 --- a/tests/queries/0_stateless/02884_authentication_quota.reference +++ b/tests/queries/0_stateless/02884_authentication_quota.reference @@ -6,7 +6,7 @@ > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -18,9 +18,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login @@ -32,7 +32,7 @@ QUOTA_EXCEEDED > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -44,9 +44,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login diff --git a/tests/queries/0_stateless/02884_authentication_quota.sh b/tests/queries/0_stateless/02884_authentication_quota.sh index bca24bf6cc27..b092e0b35359 100755 --- a/tests/queries/0_stateless/02884_authentication_quota.sh +++ b/tests/queries/0_stateless/02884_authentication_quota.sh @@ -18,7 +18,7 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Quota is exceeded 1 >= 1. Login with correct password should fail." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" @@ -37,10 +37,10 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' - ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Also try to login with correct password. Quota should stay exceeded." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference new file mode 100644 index 000000000000..8c21354a38e1 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference @@ -0,0 +1,6 @@ +1 +0 +0 +1 +0 +0 diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh new file mode 100755 index 000000000000..bc088b046271 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel, no-replicated-database, no-shared-merge-tree +# no-parallel: uses a global failpoint and two replicas with stopped replication queues. +# no-fasttest: a test that arms a global failpoint must run alone, and such tests are kept out of the fast test. +# no-replicated-database: the test controls replication queues of individual tables. +# no-shared-merge-tree: the failpoint is in the `ReplicatedMergeTree` block allocation path. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -e + +function cleanup_tables() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R2" 2>/dev/null || true + wait || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R2 SYNC" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R1 SYNC" 2>/dev/null || true +} + +function cleanup() +{ + cleanup_tables +} +trap cleanup EXIT + +# Runs a lightweight update of partition 2 whose rows arrive from the other replica while the update +# waits for committing inserts, and checks that the update has patched all of them. +function run_case() +{ + local name=$1 + local assignment=$2 + R1=t_lwu_prune_empty_03100_58_${name}_r1 + R2=t_lwu_prune_empty_03100_58_${name}_r2 + + $CLICKHOUSE_CLIENT --query " + SET insert_keeper_fault_injection_probability = 0.0; + + DROP TABLE IF EXISTS $R2 SYNC; + DROP TABLE IF EXISTS $R1 SYNC; + + CREATE TABLE $R1 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r1') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + CREATE TABLE $R2 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r2') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + INSERT INTO $R1 SELECT 1, number, 1 FROM numbers(50); + INSERT INTO $R1 SELECT 2, number, 1 FROM numbers(50); + SYSTEM SYNC REPLICA $R2; + + ALTER TABLE $R1 DELETE WHERE p = 2 SETTINGS mutations_sync = 2; + + SYSTEM STOP REPLICATION QUEUES $R1; + + SELECT count() FROM system.parts + WHERE database = currentDatabase() AND table = '$R1' AND partition_id = '2' AND active AND rows = 0; + " + + $CLICKHOUSE_CLIENT --query "INSERT INTO $R2 SELECT 2, 1000000 + number, 1 FROM numbers(30)" + + block_numbers_path="/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name/block_numbers/2" + block_count_before=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + + $CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" + + $CLICKHOUSE_CLIENT --query "UPDATE $R1 SET v = $assignment WHERE p = 2 SETTINGS enable_lightweight_update = 1, enable_shared_storage_snapshot_in_query = 1" & + + for _ in {0..300}; do + sleep 0.3 + block_count_after=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + if [[ "$block_count_after" -gt "$block_count_before" ]]; then + break + fi + done + + if [[ "$block_count_after" -le "$block_count_before" ]]; then + echo "Failed to observe a new block allocation for lightweight update at $block_numbers_path" >&2 + exit 2 + fi + + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" + + wait + + + result=$($CLICKHOUSE_CLIENT --query " + SYSTEM SYNC REPLICA $R1; + SYSTEM SYNC REPLICA $R2; + + SELECT count() FROM $R1 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1; + SELECT count() FROM $R2 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1") + + if [[ "$result" != $'0\n0' ]]; then + echo "Unexpected unpatched-row counts in case $name:" >&2 + echo "$result" >&2 + $CLICKHOUSE_CLIENT --query " + SELECT 'patch parts', name, rows FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND startsWith(name, 'patch') + ORDER BY table, name; + SELECT 'partition 2 parts', table, name, rows, min_block_number, max_block_number FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND partition_id = '2' + ORDER BY table, name; + SELECT 'frozen mutation version', table, mutation_id, block_numbers.partition_id, block_numbers.number + FROM system.mutations + WHERE database = currentDatabase() AND table = '$R1' + ORDER BY create_time DESC;" >&2 + exit 1 + fi + + echo "$result" + + cleanup_tables +} + +run_case plain 999 +# The `IN` operand names the updated table, so validating it in `InterpreterUpdateQuery` takes a storage +# snapshot of the table before the update waits for committing inserts. +run_case in_assignment "if((p, x, v) IN t_lwu_prune_empty_03100_58_in_assignment_r1, 999, 998)" diff --git a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh index 6819deea1fc1..35498f567da2 100755 --- a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh +++ b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh @@ -15,7 +15,7 @@ ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} SYNC" ${CLICKHOUSE_CLIENT} --query "CREATE TABLE ${TABLE_NAME} (c0 Int) ENGINE = File(ORC, '${USER_FILES_PATH}/${TEST_FILE}')" ${CLICKHOUSE_CLIENT} --query "INSERT INTO TABLE ${TABLE_NAME} (c0) VALUES (1),(2),(3),(5.4)" -${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx SETTINGS input_format_orc_use_fast_decoder = 0" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} sync" diff --git a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference index 2217316a750e..8f35989d78b9 100644 --- a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference +++ b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference @@ -10,6 +10,8 @@ Expression Name: v Description: set GRANULARITY 1 Condition: true - Parts: 0/1 - Granules: 0/1 - Ranges: 0 + Parts: 1/1 + Granules: 1/1 + Ranges: 1 +1 +1 diff --git a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql index c799670ca5db..d3a92f2e129a 100644 --- a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql +++ b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql @@ -13,3 +13,8 @@ ORDER BY (ts); INSERT INTO test (v) FORMAT Values ('VALUE1'); EXPLAIN indexes = 1, description=0 SELECT CAST(NULL, 'Nullable(String)') AS source, v AS v FROM test WHERE (source = 'VALUE1') OR (v ILIKE 'VALUE1'); + +-- The row matches via the second disjunct, so the granule must not be pruned: the set +-- index must return the same rows as a scan with skip indexes disabled. +SELECT count() FROM test WHERE (CAST(NULL, 'Nullable(String)') = 'VALUE1') OR (v ILIKE 'VALUE1'); +SELECT count() FROM test WHERE (CAST(NULL, 'Nullable(String)') = 'VALUE1') OR (v ILIKE 'VALUE1') SETTINGS use_skip_indexes = 0; diff --git a/tests/queries/0_stateless/03784_bad_base_backup.sh b/tests/queries/0_stateless/03784_bad_base_backup.sh index ef0cdd18a110..6ac1401f2fea 100755 --- a/tests/queries/0_stateless/03784_bad_base_backup.sh +++ b/tests/queries/0_stateless/03784_bad_base_backup.sh @@ -48,3 +48,15 @@ thread & thread & wait + +# The databases are created outside of the test database, so they must be dropped here: +# leftover `Replicated` databases break tests that enumerate all `Replicated` databases of the server, +# such as `05061_system_drop_database_replica_access`. Wait for the `ASYNC` backups to finish first. +for _ in $(seq 1 600) +do + [[ $($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.backups WHERE status = 'CREATING_BACKUP' AND name LIKE '%${CLICKHOUSE_DATABASE}%'") == 0 ]] && break + sleep 0.1 +done + +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d1_$CLICKHOUSE_DATABASE SYNC" +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d2_$CLICKHOUSE_DATABASE SYNC" diff --git a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh index 6db574849a79..6548e86729d7 100755 --- a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh +++ b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh @@ -16,7 +16,7 @@ EOF (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; -${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user"; +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE, CREATE TEMPORARY TABLE ON *.* TO $user"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "FILE_DOESNT_EXIST") >= 1 )) && echo "FILE_DOESNT_EXIST" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "CANNOT_STAT") >= 1 )) && echo "CANNOT_STAT" || echo "UNEXPECTED"; diff --git a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh index 3e4c623ee8e6..8caf9b22b41b 100755 --- a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh +++ b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh @@ -30,7 +30,7 @@ $CLICKHOUSE_CLIENT --allow_experimental_kafka_offsets_storage_in_keeper 1 -q " kafka_format = 'JSONEachRow', kafka_max_block_size = 100, kafka_keeper_path = '$KEEPER_PATH', - kafka_replica_name = 'r1'; + kafka_replica_name = '{replica}'; " # Create destination table diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference index 491b7765b057..7d4cda3c2395 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference @@ -16,7 +16,7 @@ 1 1 1 --- Optimization also works with basic (non-bucketed) serialization +-- No optimization with basic (non-bucketed) serialization 1 -- Correctness: results with optimization 7 7 70 diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql index c9eaddb60218..e161a47a3cfa 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql @@ -150,20 +150,19 @@ SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHE -- ========================================== -- Section 8: basic serialization (not with_buckets) --- The optimization still applies because DataTypeMap exposes dynamic subcolumns --- regardless of serialization version. With basic serialization, the whole map is --- read and the key is extracted; with_buckets reads only the relevant bucket. +-- The rewrite is not applied: with basic serialization the key subcolumn reads the whole map anyway. -- ========================================== DROP TABLE t_map_subcolumns; CREATE TABLE t_map_subcolumns (id UInt64, m Map(String, UInt64)) -ENGINE = MergeTree ORDER BY id; +ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; INSERT INTO t_map_subcolumns SELECT number, map('key1', number) FROM numbers(10); -SELECT '-- Optimization also works with basic (non-bucketed) serialization'; -SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; +SELECT '-- No optimization with basic (non-bucketed) serialization'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; -- ========================================== -- Section 9: Correctness - verify actual query results after optimization diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference index 89024e17dd7f..a108bf0eea76 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference @@ -54,7 +54,7 @@ 98 98 2 99 99 1 -- Section 4: PREWHERE with basic serialization --- Optimization still rewrites to subcolumn +-- No rewrite to subcolumn 1 -- Correctness: PREWHERE with basic serialization 96 96 960 diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql index a3594aff2a1b..db0474ce8c2a 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql @@ -133,7 +133,7 @@ DROP TABLE t_map_prewhere; -- ========================================== -- Section 4: PREWHERE with basic serialization (non-bucketed) --- Optimization still applies, but reads the whole map internally. +-- No rewrite to the key subcolumn, it would read the whole map anyway. -- ========================================== DROP TABLE IF EXISTS t_map_prewhere; @@ -141,14 +141,15 @@ CREATE TABLE t_map_prewhere (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'basic', + map_serialization_version_for_zero_level_parts = 'basic', min_bytes_for_wide_part = 1, min_rows_for_wide_part = 1; INSERT INTO t_map_prewhere SELECT number, map('key1', number, 'key2', number * 10) FROM numbers(100); SELECT '-- Section 4: PREWHERE with basic serialization'; -SELECT '-- Optimization still rewrites to subcolumn'; -SELECT count() > 0 FROM ( +SELECT '-- No rewrite to subcolumn'; +SELECT count() = 0 FROM ( EXPLAIN actions = 1 SELECT id, m FROM t_map_prewhere PREWHERE m['key1'] > 95 ) WHERE explain LIKE '%m.key_key1%'; diff --git a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql index 05fe94c220e0..d0a35aacb003 100644 --- a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql +++ b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql @@ -1,7 +1,7 @@ -- Tags: no-random-settings -- Tests that text indexes built on mapValues(m) work correctly when the analyzer --- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form. +-- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form, which it does only for bucketed Maps. SET enable_analyzer = 1; @@ -16,7 +16,8 @@ CREATE TABLE tab ) ENGINE = MergeTree ORDER BY id -SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0; +SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; INSERT INTO tab VALUES (0, {'service':'web-api'}), (1, {'service':'backend'}), (2, {'service':'frontend'}); diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference new file mode 100644 index 000000000000..e99e8dbc05e4 --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference @@ -0,0 +1,8 @@ +1 +0 +1 +0 +1 +0 +1 +0 diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql new file mode 100644 index 000000000000..0965065b3bbe --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql @@ -0,0 +1,9 @@ +SELECT hasSubsequenceUTF8('', ''); +SELECT hasSubsequenceUTF8('', 'a'); +SELECT hasSubsequenceCaseInsensitiveUTF8('', ''); +SELECT hasSubsequenceCaseInsensitiveUTF8('', 'A'); + +SELECT hasSubsequenceUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceUTF8(materialize(''), materialize('a')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('A')); diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference new file mode 100644 index 000000000000..382c328e0874 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference @@ -0,0 +1,3 @@ +2 20 +2 20 +2099-01-01 00:00:00 20 diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql new file mode 100644 index 000000000000..06a0cd88ef07 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql @@ -0,0 +1,34 @@ +SET mutations_sync = 1; + +-- Test that TTL expressions referencing subcolumns work correctly. +-- Previously, executeExpressionAndGetColumn used getByName which failed +-- for subcolumns not present as top-level columns in the block. +-- We test both INSERT (updateTTL in MergeTreeDataWriter) and merge +-- (TTL algorithms in the merge pipeline) paths. + +-- Case 1: Tuple subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol; +CREATE TABLE t_ttl_subcol (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL t.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol VALUES ((1, '2000-01-01'), 10); +INSERT INTO t_ttl_subcol VALUES ((2, '2099-01-01'), 20); +OPTIMIZE TABLE t_ttl_subcol FINAL; +SELECT t.a, val FROM t_ttl_subcol ORDER BY val; +DROP TABLE t_ttl_subcol; + +-- Case 2: Tuple subcolumn with function in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol_func; +CREATE TABLE t_ttl_subcol_func (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL toDate(t.d) + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol_func VALUES ((1, '2000-01-01 12:00:00'), 10); +INSERT INTO t_ttl_subcol_func VALUES ((2, '2099-01-01 12:00:00'), 20); +OPTIMIZE TABLE t_ttl_subcol_func FINAL; +SELECT t.a, val FROM t_ttl_subcol_func ORDER BY val; +DROP TABLE t_ttl_subcol_func; + +-- Case 3: JSON subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_json_subcol; +CREATE TABLE t_ttl_json_subcol (json JSON(d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL json.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2000-01-01"}', 10); +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2099-01-01"}', 20); +OPTIMIZE TABLE t_ttl_json_subcol FINAL; +SELECT json.d, val FROM t_ttl_json_subcol ORDER BY val; +DROP TABLE t_ttl_json_subcol; diff --git a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh index 6dfb8038211b..1639da5845ab 100755 --- a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh +++ b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh @@ -7,10 +7,9 @@ # grind (and could overflow the native stack), uncancellable. It must now be rejected as # TOO_DEEP_RECURSION once the nesting exceeds max_parser_depth. # -# 2. The Apache ORC C++ library (convertType) builds its own orc::Type tree by recursing over the -# file footer before any ClickHouse code runs. A pathologically deep file used to overflow the -# native stack there (crashing the process / triggering the OOM killer). The library now bounds -# the nesting depth and rejects such a file instead of crashing. +# 2. The ORC reader builds its type tree by recursing over the file footer before the schema +# inference runs. A pathologically deep file must not overflow the native stack there: the +# reader bounds the nesting depth and rejects such a file. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -55,18 +54,24 @@ orc.write_table(pa.table({'x': pa.array([], type=t)}), '$2') " } -# (1) A moderate file (200 levels) that the ORC library builds fine, with max_parser_depth lowered +# (1) A moderate file (200 levels) that the ORC reader builds fine, with max_parser_depth lowered # below the nesting so parseORCType rejects it deterministically and build-independently. gen_orc 200 "${TMP_DIR}/moderate.orc" $CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/moderate.orc', ORC) SETTINGS max_parser_depth = 100" 2>&1 \ | expect_contains parser_depth_limit TOO_DEEP_RECURSION -# (2) A file nested past the ORC library's own limit. Even with max_parser_depth raised so high that -# parseORCType would accept it, the library must reject it (without crashing). The library throws +# (2) A file nested past the ORC reader's own limit. Even with max_parser_depth raised so high that +# parseORCType would accept it, the reader must reject it (without crashing). The reader throws # before recursing past its limit, so this is safe to run. gen_orc 3000 "${TMP_DIR}/deep.orc" -$CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1 \ - | expect_contains orc_library_depth_limit "nesting depth exceeds the limit" +# Under TSan the stack size check allows only 5% of the stack, so it can reject the file before the depth limit. +out=$($CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1) +if printf '%s\n' "$out" | grep -qF -e "nesting depth exceeds the limit" -e "TOO_DEEP_RECURSION"; then + echo "orc_library_depth_limit: nesting depth exceeds the limit" +else + echo "orc_library_depth_limit: expected 'nesting depth exceeds the limit', got:" + printf '%s\n' "$out" | head -3 +fi # (3) max_parser_depth=0 means unlimited (matching the SQL parser), so a moderately nested file must # still be inferred normally rather than rejected by the explicit limit. diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.reference b/tests/queries/0_stateless/04338_async_insert_current_user.reference new file mode 100644 index 000000000000..161fe963e5bf --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.reference @@ -0,0 +1,6 @@ +1 1 1 +2 1 1 +1 1 1 +2 1 1 +10 1 1 +20 1 1 diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.sql b/tests/queries/0_stateless/04338_async_insert_current_user.sql new file mode 100644 index 000000000000..5a04881f9670 --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.sql @@ -0,0 +1,43 @@ +-- Regression test for issue #107530: context-dependent functions such as currentUser() +-- must evaluate to the inserting user (not an empty string) on the async_insert flush path, +-- both in DEFAULT/MATERIALIZED column expressions and in materialized views. + +DROP TABLE IF EXISTS t_async_user; +DROP TABLE IF EXISTS t_async_user_src; +DROP TABLE IF EXISTS t_async_user_dst; +DROP VIEW IF EXISTS t_async_user_mv; + +-- DEFAULT / MATERIALIZED column expressions calling currentUser(). +CREATE TABLE t_async_user +( + x Int32, + u_default String DEFAULT currentUser(), + u_materialized String MATERIALIZED currentUser() +) +ENGINE = MergeTree ORDER BY x; + +INSERT INTO t_async_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1); +INSERT INTO t_async_user (x) SETTINGS async_insert = 0 VALUES (2); + +-- The async row (x=1) and the sync row (x=2) must both record the inserting user. +-- Before the fix the async row recorded an empty string. +SELECT x, u_default = currentUser() AS default_matches, length(u_default) > 0 AS default_non_empty +FROM t_async_user ORDER BY x; +SELECT x, u_materialized = currentUser() AS materialized_matches, length(u_materialized) > 0 AS materialized_non_empty +FROM t_async_user ORDER BY x; + +-- Materialized view selecting currentUser(). +CREATE TABLE t_async_user_src (x Int32) ENGINE = MergeTree ORDER BY x; +CREATE TABLE t_async_user_dst (x Int32, u String) ENGINE = MergeTree ORDER BY x; +CREATE MATERIALIZED VIEW t_async_user_mv TO t_async_user_dst AS SELECT x, currentUser() AS u FROM t_async_user_src; + +INSERT INTO t_async_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10); +INSERT INTO t_async_user_src SETTINGS async_insert = 0 VALUES (20); + +SELECT x, u = currentUser() AS mv_matches, length(u) > 0 AS mv_non_empty +FROM t_async_user_dst ORDER BY x; + +DROP VIEW t_async_user_mv; +DROP TABLE t_async_user_dst; +DROP TABLE t_async_user_src; +DROP TABLE t_async_user; diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference new file mode 100644 index 000000000000..697f9b3fa30a --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference @@ -0,0 +1,3 @@ +1 1 1 1 +2 1 1 1 +10 1 1 1 diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh new file mode 100755 index 000000000000..b457807b3384 --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Regression test for issue #107530: authenticatedUser() must evaluate to the +# originally authenticated user (not an empty string, and not currentUser()) on the +# async_insert flush path. Uses EXECUTE AS so currentUser() and authenticatedUser() +# diverge: the test then fails if setAuthenticatedUserName is removed (au becomes empty) +# or wired to the wrong value (au becomes the impersonated user). + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +AUTH_USER="auth_user_${CLICKHOUSE_DATABASE}" +APP_USER="app_user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${APP_USER}" +$CLICKHOUSE_CLIENT --query "CREATE USER ${AUTH_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "CREATE USER ${APP_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "GRANT IMPERSONATE ON ${APP_USER} TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${APP_USER}" + +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP VIEW IF EXISTS t_auth_user_mv" + +# DEFAULT columns: currentUser() = impersonated user, authenticatedUser() = original user. +$CLICKHOUSE_CLIENT --query " +CREATE TABLE t_auth_user +( + x Int32, + cu String DEFAULT currentUser(), + au String DEFAULT authenticatedUser() +) +ENGINE = MergeTree ORDER BY x" + +# Async insert (x=1) and sync insert (x=2), both under EXECUTE AS the impersonated user. +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1)" +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 0 VALUES (2)" + +# The async row (x=1) and the sync row (x=2) must both record currentUser()=impersonated +# and authenticatedUser()=originally authenticated. Before the fix the async row recorded +# an empty authenticatedUser(). cu_ne_au proves the two ClientInfo fields are restored +# independently (it would be false if authenticatedUser were mis-wired to currentUser). +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user ORDER BY x" + +# Materialized view selecting authenticatedUser() under EXECUTE AS on the async path. +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_src (x Int32) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_dst (x Int32, cu String, au String) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE MATERIALIZED VIEW t_auth_user_mv TO t_auth_user_dst AS SELECT x, currentUser() AS cu, authenticatedUser() AS au FROM t_auth_user_src" + +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10)" + +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user_dst ORDER BY x" + +$CLICKHOUSE_CLIENT --query "DROP VIEW t_auth_user_mv" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP USER ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER ${APP_USER}" diff --git a/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference new file mode 100644 index 000000000000..add40c4db3ca --- /dev/null +++ b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference @@ -0,0 +1,14 @@ +50 +50 +50 +50 +50 +50 +50 +50 +50 +33 +50 +50 +1 +1 diff --git a/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql new file mode 100644 index 000000000000..c653a112c5f6 --- /dev/null +++ b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql @@ -0,0 +1,50 @@ +-- Regression test for https://github.com/ClickHouse/ClickHouse/issues/103103 +-- A NULL-valued atom (e.g. toInt64OrNull('x')) reaching the set skip index was bit-wrapped by +-- __bitWrapperFunc and propagated NULL instead of the UNKNOWN mask, so the granule check wrongly +-- pruned matching granules and the query returned fewer rows than with skip indexes disabled. + +DROP TABLE IF EXISTS t_null_const_set_index; + +CREATE TABLE t_null_const_set_index (v Int64, lc LowCardinality(String), INDEX i lc TYPE set(64) GRANULARITY 1) +ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 32; + +INSERT INTO t_null_const_set_index SELECT number, toString(number % 3) FROM numbers(100); + +-- Disable the query condition cache so every query below is analyzed by the index, not served +-- from a cached verdict, and both granule-filtering paths are exercised deterministically: +-- secondary_indices_enable_bulk_filtering = 1 -> getPossibleGranules, 0 -> mayBeTrueOnGranule. +SET use_query_condition_cache = 0; + +-- All of the following match 50 rows via the second disjunct and must not be pruned. +-- Before the fix they returned 0 with the index. Run each under both granule paths. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 1; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 0; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND nullIf(1, 1)) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 1; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND nullIf(1, 1)) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 0; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND CAST(NULL AS Nullable(Int64))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toUInt8OrNull('x')) OR v < 50; +-- The NULL value may be hidden behind a function that suppresses constant folding, so the atom +-- is not a folded ColumnConst; identity() and materialize() must be handled the same way. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND identity(toInt64OrNull('x'))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND materialize(toInt64OrNull('x'))) OR v < 50; +-- NULL value next to a predicate on the indexed column itself, and under NOT. +SELECT count() FROM t_null_const_set_index WHERE (lc = '1' AND toInt64OrNull('x')) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE NOT ((lc = '1' AND toInt64OrNull('x')) OR v >= 50); +-- Non-integer typed NULL and bare NULL route to UNKNOWN already; must stay 50. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND CAST(NULL AS Nullable(Float64))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND NULL) OR v < 50; + +-- The NULL atom must not disable pruning: the index still prunes a granule it can legitimately +-- exclude. `lc = '999'` matches nothing, so every granule is skipped (`Granules: 0/`, +-- asserted format-agnostically since the total depends on the randomized part type). +SELECT count() > 0 AS prunes_nonmatching_granules +FROM (EXPLAIN indexes = 1 SELECT count() FROM t_null_const_set_index WHERE lc = '999') +WHERE explain ILIKE '%Granules: 0/%'; + +-- With the NULL atom present, a matching disjunct must still keep its granules: the index is +-- analyzed (the UNKNOWN atom does not disable it) and does not prune to zero. +SELECT count() = 0 AS null_atom_keeps_matching_granules +FROM (EXPLAIN indexes = 1 SELECT count() FROM t_null_const_set_index WHERE (lc = '1' AND toInt64OrNull('x')) OR lc = '2') +WHERE explain ILIKE '%Granules: 0/%'; + +DROP TABLE t_null_const_set_index; diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference new file mode 100644 index 000000000000..f693c2c0ae49 --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference @@ -0,0 +1,9 @@ +345 +11400 +168 5800 +[0,1,2,3,4,5,6,7,8,9,10,11,12] +3 3 +10 10 +17 4 +24 11 +1152 71944 diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql new file mode 100644 index 000000000000..4ce81b48033e --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql @@ -0,0 +1,23 @@ +-- Multi-step PREWHERE must keep columns needed to evaluate `DEFAULT`s of columns missing in the part. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default; + +CREATE TABLE t_multistep_prewhere_default (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple(); +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default ADD COLUMN v Int64 DEFAULT k % 13; +ALTER TABLE t_multistep_prewhere_default ADD COLUMN w Int64 DEFAULT k + length(s); + +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +SELECT sum(v) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3' AND k % 2 = 1; +SELECT arraySort(groupUniqArray(v)) FROM (SELECT DISTINCT v FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'); +SELECT k, v FROM t_multistep_prewhere_default WHERE k <= 30 AND s = '3' ORDER BY k; + +-- Parts written after the ALTER store v and w physically. +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7), 42, 43 FROM numbers(1000, 100); +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 1050 AND s = '3'; + +DROP TABLE t_multistep_prewhere_default; diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference new file mode 100644 index 000000000000..22b6a5ac9c04 --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference @@ -0,0 +1,6 @@ +350 +350 +4 4 +11 11 +18 5 +25 12 diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql new file mode 100644 index 000000000000..46e95b8cd3dd --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql @@ -0,0 +1,25 @@ +-- Multi-step PREWHERE must see patched values of the columns it carries over to evaluate `DEFAULT`s. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default_patch; + +SET enable_lightweight_update = 1, apply_patch_parts = 1; +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +CREATE TABLE t_multistep_prewhere_default_patch (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple() +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1; + +SYSTEM STOP MERGES t_multistep_prewhere_default_patch; + +INSERT INTO t_multistep_prewhere_default_patch SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default_patch ADD COLUMN v Int64 DEFAULT k % 13; + +UPDATE t_multistep_prewhere_default_patch SET k = k + 1 WHERE 1; + +-- Both queries must agree: `v` is missing in the part, so it is evaluated from the patched `k`. +SELECT sum((k % 13)::Int64) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; +SELECT sum(v) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; + +SELECT k, v FROM t_multistep_prewhere_default_patch WHERE k <= 30 AND s = '3' ORDER BY k; + +DROP TABLE t_multistep_prewhere_default_patch; diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference new file mode 100644 index 000000000000..7bed391e68f3 --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference @@ -0,0 +1,4 @@ +INCORRECT_DATA +0 0 +1 1 +2 2 diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh new file mode 100755 index 000000000000..57a8727696be --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The stripe footer of this blob is truncated, so reading it must fail with a regular +# INCORRECT_DATA exception. +BLOB='4f52431100000a061204080150005500000a280a06000000000000121e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc1550000f0000780039604d293e0b00006e0007dda36300f00a0608061000180b0a0608061001182d0a0608011001180a0a060805100118081204080010001204080210001a03474d545100000a260a04080150000a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc155000b500000803107e1a0a08031038181220342801220f080c1201011a0263302000280030002208080920002800300030013a04080150003a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc15500040904e48016200085d1005188080102202000c282b300682f403034f524317' + +# The fixture must stay pure even-length lowercase hex: unhex's result for a non-hex character is +# implementation-defined, so one invalid character makes the corrupt footer decoder-dependent and +# this test silently stops asserting anything. +if [[ ! $BLOB =~ ^[0-9a-f]+$ ]] || (( ${#BLOB} % 2 )); then + echo "BLOB must be an even-length string of [0-9a-f]" >&2 + exit 1 +fi + +$CLICKHOUSE_LOCAL -q "SELECT c0 FROM format(ORC, 'c0 DateTime64(3)', unhex('$BLOB'));" 2>&1 \ + | grep -oE "INCORRECT_DATA" \ + | sort -u + +# Well-formed ORC must still read back unchanged. +DATA_FILE="$CLICKHOUSE_TMP/04856_orc_control_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_LOCAL -q "SELECT number AS a, toString(number) AS b FROM numbers(3) FORMAT ORC" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT a, b FROM file('$DATA_FILE', ORC) ORDER BY a" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference new file mode 100644 index 000000000000..1f714f4b2082 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference @@ -0,0 +1,14 @@ +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +1 +2 diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh new file mode 100755 index 000000000000..dd54288e64f9 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Truncating this fixture to 289 bytes leaves byte 6 in the postscript's compression field. Codec 6 +# is BROTLI, which the ORC format declares but this reader does not implement. The reader rejects it +# with a NOT_IMPLEMENTED exception; it must never be a logical error, which aborts in debug and +# sanitizer builds. +DATA_FILE="$CLICKHOUSE_TMP/05036_orc_codec6_${CLICKHOUSE_DATABASE}.orc" +head -c 289 "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$DATA_FILE" + +# Both the schema-inference path and the explicit-structure path reach the reader, so both are +# asserted here. Match on the error text, never on the exit status: ClickHouse exits with the error +# code truncated to a byte, so 636 and 124 are the same outcome. +for query in \ + "SELECT * FROM file('$DATA_FILE', ORC) FORMAT Null" \ + "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" \ + "SELECT count() FROM file('$DATA_FILE', ORC, 'x Int32')" \ + "DESCRIBE file('$DATA_FILE', ORC)" \ + "SELECT * FROM format(ORC, 'x Int32', (SELECT * FROM file('$DATA_FILE', RawBLOB))) FORMAT Null" +do + # An abort prints nothing at all, so classify explicitly rather than letting the arm go silent: + # a missing line is much harder to read in a diff than a named verdict. + OUT=$($CLICKHOUSE_LOCAL --query "$query" 2>&1) + if [ -z "$OUT" ]; then + echo "no output at all" + else + echo "$OUT" | grep -o -m1 'BROTLI compression in ORC files is not supported\|Logical error' || echo "unexpected: $OUT" + fi +done + +# The message must name the codec, and must not call the file corrupt: a well-formed +# Brotli-compressed ORC file takes this same path. +$CLICKHOUSE_LOCAL --query "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" 2>&1 \ + | grep -o -m1 'BROTLI compression in ORC files is not supported\|CORRUPTED\|INCORRECT_DATA' + +# Neighbouring truncations are genuinely corrupt and must keep reporting corruption rather than the +# codec gap. Schema inference wraps every non-retryable cause in one outer code, so that arm alone +# cannot tell the two apart; the explicit-structure arm bypasses the wrapper and surfaces the inner +# classification, and counting the codec error there pins them apart. +for length in 200 400 +do + NEIGHBOUR="$CLICKHOUSE_TMP/05036_orc_${length}_${CLICKHOUSE_DATABASE}.orc" + head -c $length "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$NEIGHBOUR" + $CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC) FORMAT Null" 2>&1 \ + | grep -o -m1 'CANNOT_EXTRACT_TABLE_STRUCTURE\|Logical error' + EXPLICIT=$($CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC, 'x Int32') FORMAT Null" 2>&1) + echo "$EXPLICIT" | grep -o -m1 'INCORRECT_DATA\|Logical error' || echo "unexpected: $EXPLICIT" + echo "$EXPLICIT" | grep -c 'BROTLI compression' + rm "$NEIGHBOUR" +done + +# Well-formed ORC must still read back unchanged. +$CLICKHOUSE_LOCAL --query "SELECT i FROM file('$CUR_DIR/data_orc/orc_union_type.orc', ORC) ORDER BY i" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference new file mode 100644 index 000000000000..98fb6a686563 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference @@ -0,0 +1,4 @@ +1 +1 +1 +1 diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh new file mode 100755 index 000000000000..0e451abc8151 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: zookeeper, replica, no-shared-merge-tree, no-replicated-database +# no-shared-merge-tree: the setting bounds the ReplicatedMergeTree log, which SharedMergeTree does not have +# no-replicated-database: the ZooKeeper path and the replica name are literal, so they collide between the hosts of the database + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# The oldest kept log record names the threshold that log pointers of inactive replicas are compared +# with, so a window that keeps no records at all has no meaning. +ERR="A setting's value has to be greater than 0" + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs_zero (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# An ATTACH that carries a full definition is user input too, and reaches the same check. +uuid=$($CLICKHOUSE_CLIENT --query "SELECT generateUUIDv4()") +$CLICKHOUSE_CLIENT --query " + ATTACH TABLE max_logs_zero UUID '$uuid' (x UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r2', '1') ORDER BY x; +" +$CLICKHOUSE_CLIENT --query " + ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# A positive value is still accepted and stored. +$CLICKHOUSE_CLIENT --query "ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 1;" +$CLICKHOUSE_CLIENT --query " + SELECT count() FROM system.tables + WHERE database = currentDatabase() AND name = 'max_logs' + AND engine_full LIKE '%max_replicated_logs_to_keep = 1%'; +" + +$CLICKHOUSE_CLIENT --query "DROP TABLE max_logs SYNC" diff --git a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference index ec35dc29b3b4..6be1fa0c53ad 100644 --- a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference +++ b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference @@ -1,5 +1,9 @@ SASL mechanism longer than the message: error response password without a terminator: error response +password message at the Int32 maximum: error response +password message above the limit: error response +SASL initial response at the Int32 maximum: error response +SASL final response at the Int32 maximum: error response well-formed exchange: query result received query with a smuggled tail: error response query shorter than declared: error response diff --git a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh index e5fd34c2db3f..b5d3e9b7acef 100755 --- a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh +++ b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh @@ -32,6 +32,32 @@ def connect(): return sock +def connect_short(): + """A connection whose client timeout is well below the server's `handshake_timeout_milliseconds` (30 + seconds by default), so a message the server waits for shows up as a client timeout. With a timeout + at or above the handshake timeout the server would answer the same error response on its own, and a + regression that only makes the server wait would not be noticed.""" + sock = socket.create_connection(("127.0.0.1", port), timeout=5) + sock.settimeout(5) + return sock + + +def read_message(sock): + """Reads one backend message: a type byte, a length that counts itself, and the body.""" + def recv_exactly(size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise AssertionError("the connection closed before a complete message") + data += chunk + return data + + message_type = recv_exactly(1) + (length,) = struct.unpack(">i", recv_exactly(4)) + return message_type, recv_exactly(length - 4) + + def startup(sock, user): payload = ("user\x00" + user + "\x00\x00").encode() sock.sendall(struct.pack(">ii", 8 + len(payload), 196608) + payload) @@ -93,6 +119,46 @@ except (BrokenPipeError, ConnectionResetError, socket.timeout): print("password without a terminator:", outcome(sock)) sock.close() +# The declared length of a message that is parsed before authentication is bounded by the server, because +# the client that declares it is not trusted yet. Otherwise the client declares the Int32 maximum and the +# server buffers up to 2 GiB of payload that never completes. +sock = connect_short() +startup(sock, user_plain) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("password message at the Int32 maximum:", outcome(sock)) +sock.close() + +# The same for a length just above the limit, which pins the boundary itself. +sock = connect_short() +startup(sock, user_plain) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 10001)) +print("password message above the limit:", outcome(sock)) +sock.close() + +# The same for a `SASLInitialResponse`. +sock = connect_short() +startup(sock, user_scram) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("SASL initial response at the Int32 maximum:", outcome(sock)) +sock.close() + +# The same for a `SASLResponse`, the second SCRAM message. A well-formed client-first message is needed +# to get there, and its own declared lengths stay small. +sock = connect_short() +startup(sock, user_scram) +read_message(sock) +client_first = b"n,,n=,r=abcdefghijklmnopqrstuvwx" +body = b"SCRAM-SHA-256\x00" + struct.pack(">i", len(client_first)) + client_first +sock.sendall(b"p" + struct.pack(">i", 4 + len(body)) + body) +message_type, body = read_message(sock) +assert message_type == b"R" and struct.unpack(">i", body[:4])[0] == 11, body +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("SASL final response at the Int32 maximum:", outcome(sock)) +sock.close() + # A well-formed exchange still works: authenticate and run a query. def read_until_ready(sock): data = b"" diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference new file mode 100644 index 000000000000..743f61f80a90 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference @@ -0,0 +1,9 @@ +String: batches>1=1 64 2016 1 +Nullable(String): batches>1=1 64 2016 1 +LowCardinality: batches>1=1 64 2016 4 +Array(String): batches>1=1 64 2016 1 +Map: batches>1=1 64 2016 1 +Tuple: batches>1=1 64 2016 1 +FixedString: batches>1=1 64 2016 1 +FixedString fixed-width: batches>1=0 64 2016 1 +UInt64: batches>1=0 64 2016 64 diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh new file mode 100755 index 000000000000..695c740a9cd8 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Arrow offsets its String/Binary/List buffers with 32-bit integers, so a block holding more than that has +# to be written as several record batches. `output_format_arrow_max_record_batch_size_bytes` lowers the +# bound, which exercises the same splitting with kilobytes instead of the 2 GiB a real overflow needs. +# +# Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_split.arrows" +trap 'rm -f "$FILE"' EXIT + +batches() { + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY +} + +run() { + local label="$1" expr="$2" limit="$3" extra="${4:-}" + $CLICKHOUSE_LOCAL --allow_suspicious_fixed_string_types 1 --query " + SELECT number AS n, ${expr} AS v + FROM numbers(64) + SETTINGS max_block_size = 64, + output_format_arrow_compression_method = 'none', + output_format_arrow_max_record_batch_size_bytes = ${limit}${extra} + FORMAT ArrowStream + " > "$FILE" + echo -n "${label}: batches>1=$([ "$(batches)" -gt 1 ] && echo 1 || echo 0) " + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(n), uniqExact(v) FROM file('$FILE', ArrowStream)" +} + +# One block of 64 rows against a small bound, so each shape must split. +run "String" "repeat('x', 64)" 512 +run "Nullable(String)" "if(number % 3 = 0, NULL, repeat('y', 64))::Nullable(String)" 512 +run "LowCardinality" "toLowCardinality(repeat(toString(number % 4), 64))" 512 +run "Array(String)" "[repeat('z', 64)]" 512 +run "Map" "map('k', repeat('m', 64))" 512 +run "Tuple" "(repeat('p', 64), repeat('q', 64))" 512 +# Only the offsets mode gives `FixedString` a buffer the bound applies to; the default maps it to a +# fixed-width Arrow type instead. +run "FixedString" "toFixedString(repeat('f', 64), 64)" 512 ", output_format_arrow_fixed_string_as_fixed_byte_array = 0" + +# A fixed-width column has no offsets buffer to overflow, so the bound leaves it in one batch. +run "FixedString fixed-width" "toFixedString(repeat('f', 64), 64)" 512 +run "UInt64" "number" 64 diff --git a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh index ff237fd5db5b..20fc7c819b31 100755 --- a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh +++ b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh @@ -14,7 +14,7 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) BG_MESSAGE="M_bg_${CLICKHOUSE_DATABASE}" FG_MESSAGE="M_fg_${CLICKHOUSE_DATABASE}" -START=$(${CLICKHOUSE_CLIENT} --query "SELECT toString(now64(6))") +START=$(${CLICKHOUSE_CLIENT} --query "SELECT toUnixTimestamp64Micro(now64(6))") ${CLICKHOUSE_CLIENT} --query " CREATE TABLE dest_bg (s String) ENGINE = File(ProtobufSingle) @@ -33,10 +33,11 @@ do ${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS text_log" # The logger is checked too because this query is itself written to the text log, so otherwise # an iteration would match the previous one instead of the background exception. + # `event_date` is in the server time zone, and the session one is randomized. refused=$(${CLICKHOUSE_CLIENT} --query " SELECT count() > 0 FROM system.text_log - WHERE event_date >= toDate('${START}') - AND event_time_microseconds >= toDateTime64('${START}', 6) + WHERE event_date >= yesterday() + AND event_time_microseconds >= fromUnixTimestamp64Micro(${START}) AND logger_name LIKE '%StorageBuffer%' AND message LIKE '%can only be executed on behalf of a user%'") [ "$refused" = "1" ] && break diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference new file mode 100644 index 000000000000..5567708ffa73 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference @@ -0,0 +1,2 @@ +HTTP status code: 409 +requests: 1 diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh new file mode 100755 index 000000000000..1a260ca3f719 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +# `409 Conflict` reports a state mismatch on the server, so resending the same bytes cannot succeed. +# Retrying it only postpones the error the caller has to act on: an Iceberg REST catalog commit +# refused with `409` was resent `http_max_tries` times with backoff, adding ~32 seconds per conflict. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HTTP_PORT=$(python3 -c " +import socket +s = socket.socket() +s.bind(('127.0.0.1', 0)) +print(s.getsockname()[1]) +s.close() +") + +python3 -c " +import threading +from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + +requests = 0 +lock = threading.Lock() + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + global requests + if self.path == '/requests': + with lock: + body = str(requests).encode() + self.send_response(200) + else: + with lock: + requests += 1 + body = b'{\"error\": \"conflict\"}' + self.send_response(409) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + +ThreadingHTTPServer(('127.0.0.1', $HTTP_PORT), Handler).serve_forever() +" & +HTTP_PID=$! + +trap 'kill $HTTP_PID 2>/dev/null' EXIT + +for _ in {1..100}; do + if [ "$(${CLICKHOUSE_CURL} -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${HTTP_PORT}/requests")" = "200" ]; then + break + fi + sleep 0.1 +done + +${CLICKHOUSE_CLIENT} --query "SELECT * FROM url('http://127.0.0.1:${HTTP_PORT}/data', JSONEachRow, 'x Int32')" 2>&1 | grep -o "HTTP status code: 409" | head -n 1 + +echo "requests: $(${CLICKHOUSE_CURL} -s "http://127.0.0.1:${HTTP_PORT}/requests")" diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference new file mode 100644 index 000000000000..fe1489a7d47e --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference @@ -0,0 +1,4 @@ +low_cardinality_as_dictionary=0 record batches for 3 blocks: 3 +6 15 +low_cardinality_as_dictionary=1 record batches for 3 blocks: 3 +6 15 diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh new file mode 100755 index 000000000000..bff3fc53e4fa --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The writer splits a chunk across record batches only when it exceeds the 32-bit offsets of the Arrow +# buffers, so a small result must give exactly one batch per block for every type shape. A wrong row +# count from the split logic shows up only here: the data reads back correctly either way. +# +# `FORMAT ArrowStream` into a file rather than `INSERT INTO FUNCTION file`, whose path squashes the +# blocks into one. Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +GEN="SELECT + toString(number) AS s, + if(number % 3 = 0, NULL, toString(number))::Nullable(String) AS ns, + toLowCardinality(toString(number % 2)) AS lc, + arrayMap(x -> toString(x), range(number % 3)) AS arr, + arrayMap(y -> arrayMap(x -> toString(x), range(y)), range(number % 3)) AS arr2, + map(toString(number), toString(number % 2)) AS m, + (toString(number), toString(number % 2)) AS t, + toFixedString(toString(number), 3) AS fs, + number AS u +FROM numbers(6)" + +for lc_as_dict in 0 1; do + $CLICKHOUSE_LOCAL --query "${GEN} SETTINGS + max_block_size = 2, + output_format_arrow_compression_method = 'none', + output_format_arrow_fixed_string_as_fixed_byte_array = 0, + output_format_arrow_low_cardinality_as_dictionary = ${lc_as_dict} + FORMAT ArrowStream" > "$FILE" + + echo -n "low_cardinality_as_dictionary=${lc_as_dict} record batches for 3 blocks: " + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY + + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(u) FROM file('$FILE', ArrowStream)" +done diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference new file mode 100644 index 000000000000..15e7d3a0e939 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference @@ -0,0 +1,22 @@ +-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs +3 +-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs +3 +-- a nested unknown setting still throws +1 +-- a nested value the setting cannot take still throws +1 +-- a nested clause forwarded to the shards carries the clamped value +1 +-- the same query for an unconstrained user reads both shards +6 +-- a view with an invalid nested setting in its stored body fails on a direct read +1 +-- and on a remote shard through Distributed +1 +-- a parameterized view with an invalid nested setting fails on a direct read +1 +-- and on a remote shard +1 +-- the session settings are untouched +false diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh new file mode 100755 index 000000000000..f05616c8d829 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer +# (the clamp is analyzer-path behaviour; the legacy interpreter throws on such a nested clause) +# A nested `SETTINGS` clause is clamped to the session's settings constraints, and the clamped clause is +# what the query node keeps. So a shard receives the clamped clause, and an +# unknown name or an uncastable value in a nested clause throws, as it does in a top-level clause - also +# when the clause sits in a view's stored body and the view is read on a remote shard. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Users and settings profiles are server-global, so their names carry the test database to keep this +# test safe against a concurrent copy of itself - which is how the flaky check runs it. +SUFFIX="05141_${CLICKHOUSE_DATABASE}" +CONST_USER="user_const_${SUFFIX}" +CONST_PROFILE="profile_const_${SUFFIX}" +RO_USER="user_ro_${SUFFIX}" +RO_PROFILE="profile_ro_${SUFFIX}" +FREE_USER="user_free_${SUFFIX}" +DIST_USER="user_dist_${SUFFIX}" +DIST_PROFILE="profile_dist_${SUFFIX}" +TABLE="t_05141" +DIST_TABLE="dist_05141" +VIEW="v_05141" +DIST_VIEW="dist_v_05141" +PARAM_VIEW="pv_05141" + +${CLICKHOUSE_CLIENT} --query " +DROP USER IF EXISTS ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE IF EXISTS ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; + +CREATE TABLE ${CLICKHOUSE_DATABASE}.${TABLE} (id UInt32, s String) ENGINE = MergeTree ORDER BY id; +INSERT INTO ${CLICKHOUSE_DATABASE}.${TABLE} VALUES (1, 'a'), (2, 'b'), (3, 'c'); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE} AS ${CLICKHOUSE_DATABASE}.${TABLE} + ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${TABLE}); + +CREATE SETTINGS PROFILE ${CONST_PROFILE} SETTINGS use_query_cache = 0 CONST; +CREATE SETTINGS PROFILE ${RO_PROFILE} SETTINGS readonly = 1 CONST; +CREATE SETTINGS PROFILE ${DIST_PROFILE} SETTINGS max_rows_to_read MAX 2; +CREATE USER ${CONST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${CONST_PROFILE}; +CREATE USER ${RO_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${RO_PROFILE}; +CREATE USER ${FREE_USER} IDENTIFIED WITH no_password; +CREATE USER ${DIST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${DIST_PROFILE}; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.* TO ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +" + +# `CREATE` does not analyze the body of a view with an explicit column list nor of a parameterized view, so +# such definitions can carry an invalid nested setting. +${CLICKHOUSE_CLIENT} --query " +CREATE VIEW ${CLICKHOUSE_DATABASE}.${VIEW} (x UInt8) AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW} (x UInt8) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${VIEW}); +CREATE VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW} AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1) WHERE x = {p:UInt8}; +" + +# The bare binary, not ${CLICKHOUSE_CLIENT}: the harness's randomized settings would be rejected for the readonly user. +RESTRICTED_CLIENT="${CLICKHOUSE_CLIENT_BINARY} --host=${CLICKHOUSE_HOST} --port=${CLICKHOUSE_PORT_TCP} --database=${CLICKHOUSE_DATABASE}" +CONST="${RESTRICTED_CLIENT} --user=${CONST_USER}" +RO="${RESTRICTED_CLIENT} --user=${RO_USER}" +FREE="${RESTRICTED_CLIENT} --user=${FREE_USER}" +DIST="${RESTRICTED_CLIENT} --user=${DIST_USER}" + +echo "-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs" +${RO} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- a nested unknown setting still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threds = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a nested value the setting cannot take still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threads = 'abc')" 2>&1 | grep -c -F "CANNOT_PARSE_INPUT_ASSERTION_FAILED" + +# The IN subquery runs on the shards, whose user has no constraints. It must arrive with the value the +# initiator clamped (2, so reading 3 rows fails there), not with the value as written. +echo "-- a nested clause forwarded to the shards carries the clamped value" +${DIST} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" 2>&1 | grep -c -F "TOO_MANY_ROWS" + +echo "-- the same query for an unconstrained user reads both shards" +${FREE} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" + +# The bare binary again: `${CLICKHOUSE_CLIENT}` adds `--send_logs_level`, so the server's error log line would +# be printed too and `grep -c` would count two lines. +echo "-- a view with an invalid nested setting in its stored body fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${VIEW}" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# `prefer_localhost_replica = 0` is explicit: the local shard is analyzed under the initiator's query kind +# and already throws, so only the remote path exercises the fix, and the harness randomizes this setting. +echo "-- and on a remote shard through Distributed" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${DIST_VIEW} SETTINGS prefer_localhost_replica = 0" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a parameterized view with an invalid nested setting fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${PARAM_VIEW}(p = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# 127.0.0.2 is the non-local shard of `test_cluster_two_shards`; the port is explicit so the test runs on +# a non-default port; the database is qualified because the remote session does not inherit the test database. +echo "-- and on a remote shard" +${RESTRICTED_CLIENT} --query "SELECT * FROM remote('127.0.0.2:${CLICKHOUSE_PORT_TCP}', view(SELECT * FROM ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}(p = 1)))" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- the session settings are untouched" +${CONST} --query "SELECT getSetting('use_query_cache')" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; +DROP USER ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +" diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference new file mode 100644 index 000000000000..6ee89cf48413 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference @@ -0,0 +1,18 @@ +-- control: the setting is not changed in the session +0 1 +-- control: compatibility = '26.1' in a nested clause moves the setting to its old default +1 0 +-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level +1 1 +-- and stays on the query node +1 +-- same clause: an equal assignment before compatibility keeps the current value +1 1 +-- same clause: an equal assignment before a profile that carries compatibility keeps the current value +1 1 +-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one +1 +-- child scope: the same with a profile that carries compatibility in the inner one +1 +-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery +1 diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh new file mode 100755 index 000000000000..03ce5a1eebc0 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer + +# A nested `SETTINGS` change equal to the current value is applied and marks the setting as changed +# in the subquery's context, as at the top level. That flag is what `compatibility` respects +# ("changed manually" settings are left alone), also when `compatibility` sits in a profile or in +# a nested query, so the flag must not be dropped as a "no-op". + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Settings profiles are server-global, so the name carries the test database. +PROFILE="p_compat_05175_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE IF EXISTS ${PROFILE}" +${CLICKHOUSE_CLIENT} --query "CREATE SETTINGS PROFILE ${PROFILE} SETTINGS compatibility = '26.1'" + +Q="SELECT changed, value FROM system.settings WHERE name = 'ignore_format_null_for_explain'" + +echo "-- control: the setting is not changed in the session" +${CLICKHOUSE_CLIENT} --query "${Q}" + +echo "-- control: compatibility = '26.1' in a nested clause moves the setting to its old default" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS compatibility = '26.1')" + +echo "-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- and stays on the query node" +${CLICKHOUSE_CLIENT} --query "EXPLAIN QUERY TREE SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" | grep -c "SETTINGS ignore_format_null_for_explain=" + +echo "-- same clause: an equal assignment before compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, compatibility = '26.1')" + +echo "-- same clause: an equal assignment before a profile that carries compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, profile = '${PROFILE}')" + +echo "-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- child scope: the same with a profile that carries compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS profile = '${PROFILE}') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery" +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "SELECT value FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE ${PROFILE}" diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference new file mode 100644 index 000000000000..06604339ef49 --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference @@ -0,0 +1,7 @@ +ACCESS_DENIED: necessary to have the grant READ, WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +ACCESS_DENIED: Missing permissions: WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +424242 diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh new file mode 100755 index 000000000000..1fa58284b9aa --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Tags: no-object-storage, no-replicated-database +# no-object-storage: the query attaches a directory on the local disk, and there the table data lives on +# object storage. +# no-replicated-database: a Replicated database enqueues the query before the path is resolved against +# `user_files`, and the DDL worker then rejects the path as outside of `user_files`. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the data of the new table and moves it to +# the data path of the table, so it needs `READ ON FILE` like the `file` function and `WRITE ON FILE` like +# renaming files after processing. Without that check `CREATE TABLE` on a table of their own is enough for a +# user to read and consume data that somebody else staged in `user_files`. + +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +staged_root="${CLICKHOUSE_TEST_UNIQUE_NAME}_staged" +staged_table_dir="${staged_root}/data/staging/protected" + +# Stage a MergeTree table directory in `user_files` with clickhouse-local, as an admin or a migration +# workflow would do. An Ordinary database keeps the table directory at a known place. +${CLICKHOUSE_LOCAL} --path "${USER_FILES_PATH}/${staged_root}" --allow_deprecated_database_ordinary=1 --query " + CREATE DATABASE staging ENGINE = Ordinary; + CREATE TABLE staging.protected (id UInt64, secret UInt64) ENGINE = MergeTree ORDER BY id; + INSERT INTO staging.protected VALUES (1, 424242); +" + +${CLICKHOUSE_CLIENT} <&1 | grep -qF "$1"; then + echo "ACCESS_DENIED: $1" + else + echo "UNEXPECTED: the attach was not denied with: $1" + fi + ${CLICKHOUSE_CLIENT} --query "SELECT 'tables named stolen:', count() FROM system.tables WHERE database = currentDatabase() AND name = 'stolen'" + if [ -d "${USER_FILES_PATH}/${staged_table_dir}" ]; then + echo "staged directory is still in place" + else + echo "UNEXPECTED: the staged directory is gone" + fi +} +check_denied_and_untouched "necessary to have the grant READ, WRITE ON FILE" +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user" +check_denied_and_untouched "Missing permissions: WRITE ON FILE" + +# With both grants the same query attaches the data. +${CLICKHOUSE_CLIENT} --query "GRANT WRITE ON FILE TO $user" +${CLICKHOUSE_CLIENT} --user "$user" --query "$attach_query" +${CLICKHOUSE_CLIENT} --user "$user" --query "SELECT secret FROM stolen" + +${CLICKHOUSE_CLIENT} <&1 \ + | tr '\t' ' ' | grep -oE "QUOTA_REQUIRES_CLIENT_KEY|^[[:alnum:]_]+ [[:digit:]]+$" +} + +echo "1. warm two cached quota contexts of the same user, without and with a quota key" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "2. a tightening that keeps the key type reaches the warm context" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} FOR INTERVAL 100 YEAR MAX queries = 900" +usage --user "${user}" + +echo "3. switching the key type to client_key must reach both warm contexts" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY client_key FOR INTERVAL 100 YEAR MAX queries = 800" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "4. a user whose context was never cached is rejected the same way" +usage --user "${control_user}" + +echo "5. reverting the key type lets the never-detached context resume" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY user_name FOR INTERVAL 100 YEAR MAX queries = 700" +usage --user "${user}" + +${CLICKHOUSE_CLIENT} -q "DROP QUOTA ${quota}" +${CLICKHOUSE_CLIENT} -q "DROP USER ${user}, ${control_user}" diff --git a/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference new file mode 100644 index 000000000000..08c55835830b --- /dev/null +++ b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference @@ -0,0 +1,43 @@ +the reported oracle mismatch: count(p) + count(not p) + count(p is null) = count(*) +1 +predicate, row-level truth, answer over the partitioned table +assumeNotNull(c0) = 0 3 3 +assumeNotNull(c0) < 3 4 4 +NOT (assumeNotNull(c0) > 0) 3 3 +assumeNotNull(c0) >= 0 5 5 +assumeNotNull(c0) IN (0) 3 3 +isNull and isNotNull compared with a constant +(c0 IS NULL) >= true 2 2 +(c0 IS NOT NULL) < true 2 2 +not(1 < (c0 IS NULL)) 5 5 +the partition step is the sole pruner here, and it now keeps the NULL partition +MinMax +Condition: true +Parts: 4/4 +Partition +Condition: (isNull(c0) in [1, +Inf)) +Parts: 1/4 +ifNull and coalesce reach the same chain once the rewrite that usually hides them is off +ifNull(c0, 0) = 0 3 3 +coalesce(c0, 0) = 0 3 3 +NOT (ifNull(c0, 0) >= 7) 5 5 +NOT (coalesce(nullIf(c0, 5), 0) = 1) 4 4 +MinMax +Parts: 4/4 +Partition +Parts: 3/4 +reverse key 3 3 +LowCardinality(Nullable) key 3 3 +SummingMergeTree, the query the fuzzer reported +1 +control: with no NULL row the partition step is the only pruner and still prunes +isZeroOrNull(c0) >= true 1 +MinMax +Parts: 3/3 +Partition +Parts: 1/3 +control: the primary-key path already rejected the chain and is unchanged +assumeNotNull(c0) = 0 3 3 +control: a NULL-preserving wrapper maps the NULL row to NULL and still answers correctly +c0 + 1 = 1 1 1 +round(c0) = 0 1 1 diff --git a/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql new file mode 100644 index 000000000000..58bcbf7cc70d --- /dev/null +++ b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql @@ -0,0 +1,112 @@ +-- Tags: no-replicated-database, no-parallel-replicas +-- no-replicated-database: EXPLAIN output differs for replicated database. +-- no-parallel-replicas: EXPLAIN output differs for parallel replicas. +-- Test for https://github.com/ClickHouse/ClickHouse/issues/121133, https://github.com/ClickHouse/ClickHouse/issues/126369 and https://github.com/ClickHouse/ClickHouse/issues/127755 + +-- Randomized to 0 or 1, and the value changes the plan the EXPLAIN blocks below print. +SET parallel_replicas_local_plan = 1; +-- Statistics are a part-pruning source of their own; pinning it off keeps the Min-Max and +-- Partition steps the only pruners the EXPLAIN blocks below can attribute a Parts: count to. +SET use_statistics = 0; + +DROP TABLE IF EXISTS t_part; +DROP TABLE IF EXISTS t_flat; + +-- `t_flat` holds the same rows behind an unprunable key, so its answer is the row-level truth +-- that every other table below must reproduce. +CREATE TABLE t_part (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +CREATE TABLE t_flat (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY tuple() ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_part VALUES (NULL), (0), (1), (5), (NULL); +INSERT INTO t_flat VALUES (NULL), (0), (1), (5), (NULL); + +SELECT 'the reported oracle mismatch: count(p) + count(not p) + count(p is null) = count(*)'; +SELECT (SELECT count() FROM t_part WHERE assumeNotNull(c0) = 0) + + (SELECT count() FROM t_part WHERE NOT (assumeNotNull(c0) = 0)) + + (SELECT count() FROM t_part WHERE (assumeNotNull(c0) = 0) IS NULL) + = (SELECT count() FROM t_part) AS tlp_identity_holds; + +SELECT 'predicate, row-level truth, answer over the partitioned table'; +SELECT 'assumeNotNull(c0) = 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_part WHERE assumeNotNull(c0) = 0); +SELECT 'assumeNotNull(c0) < 3', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) < 3), (SELECT count() FROM t_part WHERE assumeNotNull(c0) < 3); +SELECT 'NOT (assumeNotNull(c0) > 0)', (SELECT count() FROM t_flat WHERE NOT (assumeNotNull(c0) > 0)), (SELECT count() FROM t_part WHERE NOT (assumeNotNull(c0) > 0)); +SELECT 'assumeNotNull(c0) >= 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) >= 0), (SELECT count() FROM t_part WHERE assumeNotNull(c0) >= 0); +-- A set atom carries its own copy of the chain and is applied by MergeTreeSetIndex, not by KeyCondition. +SELECT 'assumeNotNull(c0) IN (0)', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) IN (0)), (SELECT count() FROM t_part WHERE assumeNotNull(c0) IN (0)); + +SELECT 'isNull and isNotNull compared with a constant'; +SELECT '(c0 IS NULL) >= true', (SELECT count() FROM t_flat WHERE (c0 IS NULL) >= true), (SELECT count() FROM t_part WHERE (c0 IS NULL) >= true); +SELECT '(c0 IS NOT NULL) < true', (SELECT count() FROM t_flat WHERE (c0 IS NOT NULL) < true), (SELECT count() FROM t_part WHERE (c0 IS NOT NULL) < true); +SELECT 'not(1 < (c0 IS NULL))', (SELECT count() FROM t_flat WHERE not(1 < (c0 IS NULL))), (SELECT count() FROM t_part WHERE not(1 < (c0 IS NULL))); + +-- `isNull` reports no monotonicity, so only the single-point Partition step can use it: it is the sole +-- pruner and its Parts: denominator is the table's part count. +SELECT 'the partition step is the sole pruner here, and it now keeps the NULL partition'; +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_part WHERE (c0 IS NULL) >= true + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0 +) WHERE explain LIKE '%Condition%' OR explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +SELECT 'ifNull and coalesce reach the same chain once the rewrite that usually hides them is off'; +SELECT 'ifNull(c0, 0) = 0', (SELECT count() FROM t_flat WHERE ifNull(c0, 0) = 0), (SELECT count() FROM t_part WHERE ifNull(c0, 0) = 0); +SELECT 'coalesce(c0, 0) = 0', (SELECT count() FROM t_flat WHERE coalesce(c0, 0) = 0), (SELECT count() FROM t_part WHERE coalesce(c0, 0) = 0); +-- The rewrite applies only to a non-negated condition, so a negated one reaches the chain with the rewrite on. +SELECT 'NOT (ifNull(c0, 0) >= 7)', (SELECT count() FROM t_flat WHERE NOT (ifNull(c0, 0) >= 7)), (SELECT count() FROM t_part WHERE NOT (ifNull(c0, 0) >= 7)); + +-- An inner link can also produce a real NULL: `nullIf` maps the exact point 5 to one, and the chain +-- leaves it untransformed just like an infinity bound. Such a bound compares as both inside and +-- outside every range, so the negated atom is the form that can wrongly prune it; keep it negated. +SELECT 'NOT (coalesce(nullIf(c0, 5), 0) = 1)', (SELECT count() FROM t_flat WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1)), (SELECT count() FROM t_part WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1)); +-- Partition 1 is still pruned, so such a bound costs its own partition and no other. +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_part WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1) + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0, use_skip_indexes = 0 +) WHERE explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +DROP TABLE IF EXISTS t_rev; +CREATE TABLE t_rev (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY (c0 DESC) +SETTINGS allow_nullable_key = 1, allow_experimental_reverse_key = 1; +INSERT INTO t_rev VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'reverse key', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_rev WHERE assumeNotNull(c0) = 0); + +DROP TABLE IF EXISTS t_lc; +SET allow_suspicious_low_cardinality_types = 1; +CREATE TABLE t_lc (c0 LowCardinality(Nullable(Int))) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_lc VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'LowCardinality(Nullable) key', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_lc WHERE assumeNotNull(c0) = 0); + +DROP TABLE IF EXISTS t_smt; +CREATE TABLE t_smt (c0 Nullable(Int)) ENGINE = SummingMergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_smt VALUES (NULL), (0), (1), (NULL); +SELECT 'SummingMergeTree, the query the fuzzer reported'; +SELECT (SELECT count() FROM t_smt WHERE assumeNotNull(t_smt.c0) = false) + + (SELECT count() FROM t_smt WHERE NOT (assumeNotNull(t_smt.c0) = false)) + + (SELECT count() FROM t_smt WHERE (assumeNotNull(t_smt.c0) = false) IS NULL) + = (SELECT count() FROM t_smt) AS tlp_identity_holds; + +SELECT 'control: with no NULL row the partition step is the only pruner and still prunes'; +DROP TABLE IF EXISTS t_nonull; +CREATE TABLE t_nonull (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_nonull VALUES (0), (1), (5); +SELECT 'isZeroOrNull(c0) >= true', count() FROM t_nonull WHERE isZeroOrNull(c0) >= true; +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_nonull WHERE isZeroOrNull(c0) >= true + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0 +) WHERE explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +SELECT 'control: the primary-key path already rejected the chain and is unchanged'; +DROP TABLE IF EXISTS t_pk; +CREATE TABLE t_pk (c0 Nullable(Int)) ENGINE = MergeTree ORDER BY c0 SETTINGS allow_nullable_key = 1, index_granularity = 1; +INSERT INTO t_pk VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'assumeNotNull(c0) = 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_pk WHERE assumeNotNull(c0) = 0); + +SELECT 'control: a NULL-preserving wrapper maps the NULL row to NULL and still answers correctly'; +SELECT 'c0 + 1 = 1', (SELECT count() FROM t_flat WHERE c0 + 1 = 1), (SELECT count() FROM t_part WHERE c0 + 1 = 1); +SELECT 'round(c0) = 0', (SELECT count() FROM t_flat WHERE round(c0) = 0), (SELECT count() FROM t_part WHERE round(c0) = 0); + +DROP TABLE t_part; +DROP TABLE t_flat; +DROP TABLE t_rev; +DROP TABLE t_lc; +DROP TABLE t_smt; +DROP TABLE t_nonull; +DROP TABLE t_pk; diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference new file mode 100644 index 000000000000..c9a233584ace --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference @@ -0,0 +1,5 @@ +t_05291 (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE v = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE _row_exists = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291_replicated (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +0 diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql new file mode 100644 index 000000000000..58aa5021b160 --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql @@ -0,0 +1,47 @@ +-- Tags: no-fasttest +-- no-fasttest: the `s3` table function is not in the fast test build. + +-- A mutation entry keeps the real text of its commands, because the mutation is executed from it (on every +-- replica, for replicated tables). `system.mutations.command` must still hide the credentials of the table +-- functions in the mutation subqueries, the way the query log does. + +SET mutations_sync = 0; +SET lightweight_deletes_sync = 0; +SET allow_nondeterministic_mutations = 1; + +DROP TABLE IF EXISTS t_05291; +DROP TABLE IF EXISTS t_05291_replicated; + +CREATE TABLE t_05291 (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id; +CREATE TABLE t_05291_replicated (id UInt64, v UInt64) +ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/t_05291_replicated', 'r1') ORDER BY id; + +INSERT INTO t_05291 SELECT number, number FROM numbers(10); +INSERT INTO t_05291_replicated SELECT number, number FROM numbers(10); + +-- Keep the mutations pending, so that they stay in `system.mutations`. +SYSTEM STOP MERGES t_05291; +SYSTEM STOP MERGES t_05291_replicated; + +ALTER TABLE t_05291 DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291DELETE', 'CSV', 'c1 String')); +ALTER TABLE t_05291 UPDATE v = 0 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291UPDATE', 'CSV', 'c1 String')); +DELETE FROM t_05291 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291LIGHTWEIGHT', 'CSV', 'c1 String')); +ALTER TABLE t_05291_replicated DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291REPLICATED', 'CSV', 'c1 String')); + +-- The replica loads the mutations from ZooKeeper asynchronously; `PULL` fetches them synchronously. +SYSTEM SYNC REPLICA t_05291_replicated PULL; + +SELECT table, command FROM system.mutations WHERE database = currentDatabase() ORDER BY table, mutation_id; + +-- A secret cannot be probed with a filter on the column either. +SELECT count() FROM system.mutations WHERE database = currentDatabase() AND position(command, 'SECRET05291') > 0; + +-- `KILL MUTATION` parses the command that it reads from `system.mutations` to check the access rights. +KILL MUTATION WHERE database = currentDatabase() AND table = 't_05291' FORMAT Null; + +DROP TABLE t_05291; +DROP TABLE t_05291_replicated; diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference new file mode 100644 index 000000000000..a685fc6d0653 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference @@ -0,0 +1,6 @@ +-- baseline: the policy confines the user to its single tenant (1) +1 +-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards) +8 +-- and the shards consumed it through an explicit __getScalar reference (1) +1 diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh new file mode 100755 index 000000000000..add1062cda49 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# A row policy whose USING expression contains a scalar subquery (here `has((SELECT [2]), tenant_id)`) +# is resolved through the analyzer's scalar-subquery cache, which lives in the same `Context::scalars` +# map that a client can write to with a `Scalar` packet (the `clickhouse-client --external ... --scalar` +# feature). A restricted user could therefore name a client scalar with the policy subquery's query-tree +# hash and forge its result, replacing `(SELECT [2])` with an attacker-chosen array and reading every +# tenant's rows. On 26.3 `clickhouse-client` cannot send scalars (no `--external ... --scalar`), so the +# forged-scalar cases are left out and this test only pins the policy baseline and that scalars shipped +# to shards in distributed queries still resolve. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# User and policy names are server-global, so suffix them with the (unique) test database. +user="u_scalar_rlp_${CLICKHOUSE_DATABASE}" +policy="rp_scalar_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE IF EXISTS docs; +CREATE TABLE docs (id UInt64, tenant_id UInt8, secret String) ENGINE = MergeTree ORDER BY id; +INSERT INTO docs SELECT number, number, 'secret-' || toString(number) FROM numbers(1, 8); + +CREATE USER ${user} NOT IDENTIFIED; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.docs TO ${user}; +-- The policy confines ${user} to tenant 2 only, via a scalar subquery. +CREATE ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING has((SELECT [2]), tenant_id) TO ${user}; +-- Once a table has any policy, \`throw_on_unmatched_row_policies\` (on in the test config) rejects +-- reads by users no policy matches, so the default user needs a permissive one of its own. +CREATE ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING 1 TO ALL EXCEPT ${user}; +" + +echo "-- baseline: the policy confines the user to its single tenant (1)" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SELECT count() FROM ${CLICKHOUSE_DATABASE}.docs SETTINGS enable_scalar_subquery_optimization = 1" + +# Marking wire scalars as client-supplied must not disturb distributed queries: the initiator computes +# an array-returning scalar subquery once and ships the result to the shards in the same `Scalar` packet, +# where it arrives through `addClientScalar`. The shard consumes it through the explicit `__getScalar` +# reader, which still reads client-supplied entries, rather than through the narrowed subquery cache. +log_comment="scalar_rlp_dist_${CLICKHOUSE_DATABASE}" + +echo "-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards)" +${CLICKHOUSE_CLIENT} --log_comment "${log_comment}" --query " +SELECT count() FROM cluster('test_cluster_two_shards', '${CLICKHOUSE_DATABASE}', docs) +WHERE has((SELECT [2, 3, 4, 5]), tenant_id) +SETTINGS prefer_localhost_replica = 0, enable_scalar_subquery_optimization = 1" + +echo "-- and the shards consumed it through an explicit __getScalar reference (1)" +# The secondary queries log `current_database = 'default'` rather than the test database, so they are +# selected by the id of the initial query, which does carry it. +${CLICKHOUSE_CLIENT} --query " +SYSTEM FLUSH LOGS query_log; +SELECT count() > 0 FROM system.query_log +WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 0 + AND query LIKE '%__getScalar%' + AND initial_query_id IN ( + SELECT query_id FROM system.query_log + WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 1 + AND current_database = currentDatabase() AND log_comment = '${log_comment}')" + +${CLICKHOUSE_CLIENT} --query " +DROP ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs; +DROP ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs; +DROP TABLE docs; +" +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference new file mode 100644 index 000000000000..88b9566a6b12 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference @@ -0,0 +1,3 @@ +column 20 is out of range, the file has 5 columns +column 20 is out of range, the file has 5 columns +100 4950 diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh new file mode 100755 index 000000000000..27b41467be72 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: Depends on S3 + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A 569-byte ORC file (id Int64, name String, v Float64, part Int32) with one row, whose stripe footer declares a +# row index stream for column 20, but the file has 5 columns. Two readers indexed the selected-column mask with +# that id and aborted the server; both must report a malformed file instead: +# - remote reads prebuffer stripes (`ORC::Reader::preBuffer`), so the file is read through s3; +# - predicate pushdown loads the row indexes (`ORC::RowReader::loadStripeIndex`), also for local files. The +# predicate must keep the stripe (`id >= 0`; the row has id 1), or the stripe statistics skip it first. +ORC_B64=$(tr -d '\n' <<'B64' +T1JDEQAACgYSBAgBUAArAAAKEwoDAAAAEgwIARIGCAIQAhgCUAAzAAAKFwoFAAAAAAASDggBIggKAWESAWEYAlAAUwAACicKAgAA +EiEIARobCQAAAAAAAPg/EQAAAAAAAPg/GQAAAAAAAPg/UAArAAAKEwoDAAAAEgwIARIGCAAQABgAUAAHAABCAIADAABhBwAAQACA +EQAAAAAAAAAA+D8HAABAAACuAAAotS/9IGR1AgCEAwoGCAYQABgLCgYIBhABGBgCGBwDGCwUARABGAYCGAQKBggCEAIDARAEGAYS +AggAEgIIAgASAggCCAB7/hAam+nkirydJ0AbQIZdZQm6AAAotS/9IF+lAgBEBApdCgQIAVAACg4IARIGCAIQAhgCUABYBgoQCAEi +CAoBYRIBYQoKIwgBGhsJAPg/EQD4PxkA+D9QAFgLABAAGABQAFgGBQBKyAIaAUJwd1jtfAJ4AQAotS/9IOydBQBCyiYskLc5//// +///w6acgxiIELbemIDUZs4IjVzcRUBwT/pE0KZF9o02pZZNSphSQJ3okw0BbBghYiEDLlRuOvFiuU8aKKePElHHiyPYGVW7/bcVn +e6TQcm1Ni83htzOUa/ujDT2c/5Sg/4wO/hPqp6rnKrCqiyUKQ5//PDC42JMILQmsez1JVU0+1/o9wp3ZDoEFo2mF6HyRLSE6DwgA +SsgCGgFCcHdas32g06DT47p5Bgi/ARAFGICAECICAAwoYDAJgvQDA09SQxg= +B64 +) +FILE="05317_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$FILE', format='RawBLOB') SELECT base64Decode('$ORC_B64')" + +# Stripes are prebuffered only with `remote_filesystem_read_prefetch`, which CI randomizes. +$CLICKHOUSE_CLIENT --remote_filesystem_read_prefetch 1 \ + --query "SELECT * FROM s3(s3_conn, filename='$FILE', format='ORC') FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' + +# Predicate pushdown (on by default) on a local file, which is never prebuffered. +LOCAL_FILE="05317_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --engine_file_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION file('$LOCAL_FILE', 'RawBLOB') SELECT base64Decode('$ORC_B64')" +$CLICKHOUSE_CLIENT --input_format_orc_filter_push_down 1 \ + --query "SELECT * FROM file('$LOCAL_FILE', 'ORC') WHERE id >= 0 FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' +rm -f "${USER_FILES_PATH:?}/$LOCAL_FILE" + +# The server is still alive, and a valid ORC file is still read through the same path. +VALID="05317_valid_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$VALID', format='ORC') SELECT number AS id, toString(number) AS s FROM numbers(100)" +$CLICKHOUSE_CLIENT --query "SELECT count(), sum(id) FROM s3(s3_conn, filename='$VALID', format='ORC')" diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference new file mode 100644 index 000000000000..21113e5c614b --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference @@ -0,0 +1,18 @@ +-- Q-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded LF +contains CR, LF or NUL +400 +-- B-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded NUL +contains CR, LF or NUL +400 +-- Encoded word in the middle of the value +contains CR, LF or NUL +400 +-- Other encoded words are still decoded +café au lait +café diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh new file mode 100755 index 000000000000..ef96f960e4b3 --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# An RFC 2047 encoded word must not decode into CR, LF or NUL inside a header value: +# such a value could split the header when it is forwarded (e.g. to an HTTP authentication server). + +function check_rejected() +{ + local header="$1" + ${CLICKHOUSE_CURL} -sS -H "$header" -w '%{http_code}\n' "${CLICKHOUSE_URL}&query=SELECT+1" | grep -o -F -e 'contains CR, LF or NUL' -e '400' +} + +echo "-- Q-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?Q?x=0D=0AInjected:_1?=' +echo "-- Q-encoded LF" +check_rejected 'X-Test: =?UTF-8?Q?x=0AInjected:_1?=' +echo "-- B-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?B?eA0KSW5qZWN0ZWQ6IDE=?=' +echo "-- Q-encoded NUL" +check_rejected 'X-Test: =?UTF-8?Q?x=00y?=' +echo "-- Encoded word in the middle of the value" +check_rejected 'X-Test: prefix =?UTF-8?Q?=0D=0A?= suffix' + +echo "-- Other encoded words are still decoded" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?Q?caf=C3=A9_au_lait?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?B?Y2Fmw6k=?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference new file mode 100644 index 000000000000..7a770acba3a2 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference @@ -0,0 +1,7 @@ +json_whole 1 +json_whole_prewhere 1 +json_other_path 1 +tuple_whole 1 +map_size_and_key 1 +maps_other_map 1 +map_key_and_whole 1 diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql new file mode 100644 index 000000000000..a87623566a81 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql @@ -0,0 +1,79 @@ +-- Tags: no-parallel-replicas +-- no-parallel-replicas: read_bytes in the initiator's query_log does not include the replicas' reads. + +-- A condition on a cheap subcolumn gets its own PREWHERE read step, so the column it is combined with is read +-- only for the rows it keeps. No row passes the first condition, so a case reads about the bytes of that one alone. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; +SET optimize_move_to_prewhere = 1; +SET query_plan_optimize_prewhere = 1; +SET move_all_conditions_to_prewhere = 1; +SET enable_multiple_prewhere_read_steps = 1; +SET use_query_condition_cache = 0; + +DROP TABLE IF EXISTS t_json; +DROP TABLE IF EXISTS t_tuple; +DROP TABLE IF EXISTS t_map; +DROP TABLE IF EXISTS t_maps; + +CREATE TABLE t_json (id UInt64, j JSON) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_tuple (id UInt64, t Tuple(kind String, payload String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +-- Bucketed, with as many buckets as keys, so that `m['k1']` reads one bucket and not the whole Map. +CREATE TABLE t_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', + map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0; +CREATE TABLE t_maps (id UInt64, c Tuple(left Map(String, String), right Map(String, String))) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +-- Random values, so that the size of a column on disk, by which the conditions are ordered, reflects the cost of reading it. +INSERT INTO t_json SELECT number, concat('{"kind":"a","payload":"', hex(randomString(500)), '"}') FROM numbers(20000); +INSERT INTO t_tuple SELECT number, tuple('a', hex(randomString(500))) FROM numbers(20000); +INSERT INTO t_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> hex(randomString(30)), range(16))) FROM numbers(20000); +INSERT INTO t_maps SELECT number, tuple(map('k', 'a'), map('k', hex(randomString(500)))) FROM numbers(20000); + +SELECT count() FROM t_json WHERE j.kind = 'b' FORMAT Null SETTINGS log_comment = 'json_cheap'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' FORMAT Null SETTINGS log_comment = 'tuple_cheap'; +SELECT count() FROM t_map WHERE length(m) = 3 FORMAT Null SETTINGS log_comment = 'map_cheap'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' FORMAT Null SETTINGS log_comment = 'map_key_cheap'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' FORMAT Null SETTINGS log_comment = 'maps_cheap'; + +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole'; +SELECT count() FROM t_json PREWHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole_prewhere'; +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 FORMAT Null SETTINGS log_comment = 'json_other_path'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' AND length(toString(t)) > 10 FORMAT Null SETTINGS log_comment = 'tuple_whole'; +-- PREWHERE keeps the written order, which the WHERE optimizer may change based on the column sizes. +SELECT count() FROM t_map PREWHERE length(m) = 3 AND m['k1'] != '' FORMAT Null SETTINGS log_comment = 'map_size_and_key'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' AND c.right['k'] != '' FORMAT Null SETTINGS log_comment = 'maps_other_map'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 FORMAT Null SETTINGS log_comment = 'map_key_and_whole'; + +SYSTEM FLUSH LOGS query_log; + +SELECT c.case_name, q.bytes < 2 * base.bytes +FROM VALUES('idx UInt8, case_name String, base_name String', + (1, 'json_whole', 'json_cheap'), + (2, 'json_whole_prewhere', 'json_cheap'), + (3, 'json_other_path', 'json_cheap'), + (4, 'tuple_whole', 'tuple_cheap'), + (5, 'map_size_and_key', 'map_cheap'), + (6, 'maps_other_map', 'maps_cheap'), + (7, 'map_key_and_whole', 'map_key_cheap')) AS c +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS q ON q.log_comment = c.case_name +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS base ON base.log_comment = c.base_name +ORDER BY c.idx; + +DROP TABLE t_json; +DROP TABLE t_tuple; +DROP TABLE t_map; +DROP TABLE t_maps; diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference new file mode 100644 index 000000000000..fcc2c16d9ebd --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference @@ -0,0 +1,30 @@ +bucketed MergeTree +1 +MergeTree with bucketed zero-level parts +1 +basic MergeTree +1 +Memory +1 +explicit key subcolumn of a basic Map +8 8 +9 9 +results +8 8 +9 9 +8 8 +9 9 +8 8 +9 9 +Merge over a bucketed table +1 +MaterializedView with a bucketed target +1 +Buffer with a bucketed destination +1 +Merge over a bucketed and a basic table +1 +8 8 +8 8 +9 9 +9 9 diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql new file mode 100644 index 000000000000..cd62f633bf69 --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql @@ -0,0 +1,75 @@ +-- `m['key']` is rewritten to the Map key subcolumn `m.key_` only when the table serializes Maps +-- with buckets, because only then can a single key be read without the whole Map. +-- Both serialization settings are named in every table, clickhouse-test randomizes them. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; + +DROP TABLE IF EXISTS t_map_buffer; +DROP TABLE IF EXISTS t_map_mv; +DROP TABLE IF EXISTS t_map_merge; +DROP TABLE IF EXISTS t_map_memory; +DROP TABLE IF EXISTS t_map_basic; +DROP TABLE IF EXISTS t_map_zero_level_bucketed; +DROP TABLE IF EXISTS t_map_bucketed; + +CREATE TABLE t_map_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_zero_level_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_basic (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; +CREATE TABLE t_map_memory (id UInt64, m Map(String, UInt64)) ENGINE = Memory; + +INSERT INTO t_map_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_zero_level_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_basic SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_memory SELECT number, map('k', number) FROM numbers(10); + +SELECT 'bucketed MergeTree'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MergeTree with bucketed zero-level parts'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_zero_level_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'basic MergeTree'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_basic WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Memory'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_memory WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +SELECT 'explicit key subcolumn of a basic Map'; +SELECT id, m.key_k FROM t_map_basic WHERE m.key_k > 7 ORDER BY id; + +SELECT 'results'; +SELECT id, m['k'] FROM t_map_bucketed WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_basic WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_memory WHERE m['k'] > 7 ORDER BY id; + +-- Engines that pass the analyzed query to other tables answer for those tables. +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_bucketed$'); +CREATE MATERIALIZED VIEW t_map_mv (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets' +AS SELECT id, m FROM t_map_bucketed; +CREATE TABLE t_map_buffer (id UInt64, m Map(String, UInt64)) +ENGINE = Buffer(currentDatabase(), t_map_bucketed, 1, 10, 100, 10000, 1000000, 10000000, 100000000); + +SELECT 'Merge over a bucketed table'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MaterializedView with a bucketed target'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_mv WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Buffer with a bucketed destination'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_buffer WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +-- The query is sent to every table of a Merge, so all of them must be bucketed. +DROP TABLE t_map_merge; +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_(bucketed|basic)$'); + +SELECT 'Merge over a bucketed and a basic table'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT id, m['k'] FROM t_map_merge WHERE m['k'] > 7 ORDER BY id; + +DROP TABLE t_map_buffer; +DROP TABLE t_map_mv; +DROP TABLE t_map_merge; +DROP TABLE t_map_memory; +DROP TABLE t_map_basic; +DROP TABLE t_map_zero_level_bucketed; +DROP TABLE t_map_bucketed; diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference new file mode 100644 index 000000000000..dfd940ddad71 --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference @@ -0,0 +1,3 @@ +3000 30 +3000 4501500 +1000 499500 diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh new file mode 100755 index 000000000000..f36ec224287c --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires `IcebergLocal` (USE_AVRO build option) + +# Each finished Iceberg data file used to keep its Parquet encoder threads until the commit, so writing +# 30 partitions with `max_threads = 16` needed 480 threads of the 300-thread global pool. +# https://github.com/ClickHouse/ClickHouse/issues/126508 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 16); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 16); do printf ', number * %d' "$i"; done) +SETTINGS="SET allow_insert_into_iceberg = 1, max_insert_threads = 1, max_threads = 16, output_format_parquet_parallel_encoding = 1" + +# INSERT, then ALTER TABLE ... UPDATE, which writes one position delete file and one data file per partition. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32 ${COLS}) ENGINE = IcebergLocal('${TABLE_DIR}/update/') PARTITION BY p; + INSERT INTO t SELECT number % 30 ${EXPRS} FROM numbers(3000); + SELECT count(), uniqExact(_path) FROM t; + ALTER TABLE t UPDATE c1 = c1 + 1 WHERE 1; + SELECT count(), sum(c1) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 + +# ALTER TABLE ... DELETE writes two-column position delete files, so it needs more partitions to fill the pool. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32, x Int64) ENGINE = IcebergLocal('${TABLE_DIR}/delete/') PARTITION BY p; + INSERT INTO t SELECT number % 80, number FROM numbers(2000); + ALTER TABLE t DELETE WHERE x >= 1000; + SELECT count(), sum(x) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference new file mode 100644 index 000000000000..636bda45df5e --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference @@ -0,0 +1,4 @@ +[[[[NULL]]],[[[NULL]]]] +[NULL,NULL] +4 2 +server is alive diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh new file mode 100755 index 000000000000..81d6382e1910 --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# The fast-test build is unoptimized and re-runs a new test several times under a 60s cap, while +# materializing a deeply nested Dynamic value whose operation does not trip the recursion guard takes +# superlinear time. The optimized stateless configurations run it within budget. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Each repetition of 1E2B0801 is a value of type Array(Dynamic(max_types=8)) with one element, so the +# nesting depth of the Dynamic value comes from the data, not from the declared type. The second row is NULL. +nested_value() { echo "format(RowBinary, 'd Dynamic', unhex(concat(repeat('1E2B0801', $1), '0000')))"; } + +$CLICKHOUSE_CLIENT -q "SELECT arraySort([d, d]) FROM $(nested_value 3)" + +# Depending on the build and the stack size, a deep value is either processed or rejected with +# TOO_DEEP_RECURSION, but it must never crash the server or use memory quadratic in the depth. +# Parsing a value takes time quadratic in its depth (every level has a longer type name), so the deepest value, +# which exhausts the stack in the release build, is only used for the operations that recurse into the nested +# columns: `index`, `compareAt`, and `filter`. +check_query() { + out=$($CLICKHOUSE_CLIENT -q "$1 FORMAT Null" 2>&1) + [[ -z "$out" || "$out" == *TOO_DEEP_RECURSION* ]] || echo "$1: $out" +} +table=$(nested_value 1000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d, arrayJoin([1, 2]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done +table=$(nested_value 9000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done + +# Writing a part and merging parts go through the dynamic structure helpers of the column. +# Writing a part takes time quadratic in the nesting depth (every level adds substreams with longer names), +# so a depth that exhausts the stack takes tens of seconds; use a small depth that checks the normal path +# and stays far from the stack limit in sanitizer builds, where depth 300 already hits it. +# The substream names of a deep value exceed the file name length limit of the filesystem in a wide part, +# so they must be replaced with hashes regardless of the randomized MergeTree settings. +$CLICKHOUSE_CLIENT -q "CREATE TABLE deep_dynamic (d Dynamic) ENGINE = MergeTree ORDER BY tuple() SETTINGS replace_long_file_name_to_hash = 1, max_file_name_length = 127" +table=$(nested_value 64) +for query in "INSERT INTO deep_dynamic SELECT d FROM $table" "INSERT INTO deep_dynamic SELECT d FROM $table" "OPTIMIZE TABLE deep_dynamic FINAL"; do + out=$($CLICKHOUSE_CLIENT -q "$query" 2>&1) + [[ -z "$out" ]] || echo "$query: $out" +done +$CLICKHOUSE_CLIENT -q "SELECT count(), countIf(d IS NULL) FROM deep_dynamic" +$CLICKHOUSE_CLIENT -q "DROP TABLE deep_dynamic" + +$CLICKHOUSE_CLIENT -q "SELECT 'server is alive'" diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference new file mode 100644 index 000000000000..fcc653eab3e4 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference @@ -0,0 +1,5 @@ +writer: time zone is rejected +reader: time zone is rejected +reader file: time zone is rejected +--- stateless server is still alive --- +1 diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh new file mode 100755 index 000000000000..f8e04add8d56 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e + +# A malformed ORC timezone name used to reach an empty TZif file outside TZDIR and abort +# inside libc++. The time zones are now resolved only from the embedded time zone database, +# so such a name must be rejected without touching the file system. Keep each attempt in a child clickhouse-local process and disable core dumps. +ulimit -c 0 + +WORK_DIR="${CLICKHOUSE_TMP}/orc_timezone_traversal_${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${WORK_DIR}" +mkdir -p "${WORK_DIR}" +trap 'rm -rf "${WORK_DIR}"' EXIT + +regression_status=0 +python3 - "${WORK_DIR}" <<'PY' || regression_status=$? +import os +import pathlib +import shlex +import shutil +import subprocess +import sys + +work_dir = pathlib.Path(sys.argv[1]) +tz_dir = work_dir / "zoneinfo" / "a" / "b" +tz_dir.mkdir(parents=True) + +# Use real, minimal zone files so the valid setup and the ORC fixture can be loaded while +# TZDIR points at this private directory. The traversal resolves to this test's empty file. +system_zoneinfo = pathlib.Path("/usr/share/zoneinfo") +for zone in ("UTC", "America/Vancouver"): + source = system_zoneinfo / zone + if not source.is_file(): + raise SystemExit(f"required time zone file not found: {source}") + target = tz_dir / zone + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + +(work_dir / "outside").write_bytes(b"") +if (tz_dir / "../../../outside").resolve() != (work_dir / "outside").resolve(): + raise SystemExit("private timezone traversal fixture is misconfigured") +(work_dir / "dev").mkdir() +(work_dir / "dev" / "null").write_bytes(b"") +if (tz_dir / "../../../dev/null").resolve() != (work_dir / "dev" / "null").resolve(): + raise SystemExit("private ORC metadata traversal fixture is misconfigured") + +env = os.environ.copy() +env["TZDIR"] = str(tz_dir) +env["TZ"] = "UTC" +local_command = shlex.split(env["CLICKHOUSE_LOCAL"]) + + +def run_local(path, *args, query=None, input_data=None): + path.mkdir(parents=True, exist_ok=True) + command = local_command + ["--path", str(path), *args] + if query is not None: + command += ["--query", query] + return subprocess.run( + command, + input=input_data, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + + +safe_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='America/Vancouver', " + "output_format_orc_compression_method='none'" +) +fixture = run_local(work_dir / "safe", query=safe_query) +if fixture.returncode != 0 or not fixture.stdout.startswith(b"ORC"): + diagnostic = (fixture.stderr + fixture.stdout).decode(errors="replace") + raise SystemExit(f"could not create valid ORC fixture: {diagnostic[:1000]}") + +# Preserve the ORC file's byte lengths while replacing its writer timezone metadata +# with the path from the customer reproducer. This exercises a file supplied by a +# reader, without requiring a malicious query setting. +safe_name = b"America/Vancouver" +unsafe_name = b"../../../dev/null" +if len(safe_name) != len(unsafe_name) or fixture.stdout.count(safe_name) != 1: + raise SystemExit("valid ORC fixture has unexpected timezone metadata") +malicious_file = fixture.stdout.replace(safe_name, unsafe_name, 1) + +malicious_writer_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='../../../outside', " + "output_format_orc_compression_method='none'" +) +writer = run_local(work_dir / "writer", query=malicious_writer_query) +reader = run_local( + work_dir / "reader", + "--input-format=ORC", + "--input_format_orc_reader_time_zone_name=../../../outside", + query="SELECT * FROM table", + input_data=fixture.stdout, +) +reader_file = run_local( + work_dir / "reader_file", + "--input-format=ORC", + query="SELECT * FROM table", + input_data=malicious_file, +) + +failed = False +for label, result in (("writer", writer), ("reader", reader), ("reader file", reader_file)): + if result.returncode < 0: + print(f"{label}: terminated by signal {-result.returncode}") + failed = True + elif result.returncode == 0: + print(f"{label}: malformed timezone unexpectedly succeeded") + failed = True + elif any( + message in result.stdout + result.stderr + for message in (b"is not supported. Use a name from `system.time_zones`", b"Cannot load time zone ../../../") + ): + print(f"{label}: time zone is rejected") + else: + diagnostic = (result.stderr + result.stdout).decode(errors="replace") + first_line = next((line for line in diagnostic.splitlines() if line), "no diagnostic") + print(f"{label}: unexpected error: {first_line[:300]}") + failed = True + +if failed: + raise SystemExit(1) +PY + +echo '--- stateless server is still alive ---' +${CLICKHOUSE_CLIENT} --query "SELECT 1" +exit "${regression_status}" diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference b/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql new file mode 100644 index 000000000000..329dfc62bcda --- /dev/null +++ b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql @@ -0,0 +1,9 @@ +-- Tags: no-fasttest +-- no-fasttest: needs Azure Blob Storage support, which is not built in the fast test. + +-- The (url, sas_token) form of the Azure table functions parses a URL that ends right after the host like the same URL +-- with a trailing slash (both then fail at format detection), and rejects a malformed abfss URL with BAD_ARGUMENTS. +SELECT * FROM azureBlobStorage('https://acc.blob.core.windows.net', 'sv=2022'); -- { serverError CANNOT_DETECT_FORMAT } +SELECT * FROM azureBlobStorage('abfss://foo.net', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://foo.net/c/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://c.x@acc.dfs.core.windows.net/p/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference new file mode 100644 index 000000000000..e838531bffe0 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference @@ -0,0 +1,51 @@ +LIKE `t0` +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(KEY `k` (`x`)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +LIKE `t0` +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(KEY `k` (`x`)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(`x` int, `y` varchar(10)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh new file mode 100755 index 000000000000..ab7e6079e829 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `CREATE TABLE` in a MySQL dump without column definitions (`CREATE TABLE ... LIKE`, or only indexes or constraints) +# gives no structure, so the structure is inferred from the data of the `INSERT`. + +function dump() +{ + printf 'CREATE TABLE `t1` %s;\n/*!40101 SET character_set_client = @saved_cs_client */;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB'; do + echo "$create" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "DESCRIBE TABLE table" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" +done + +# The `INSERT` immediately following the `CREATE TABLE` must not be skipped. + +function dump_single_insert() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +function dump_multiple_inserts() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"');\nINSERT INTO `t1` VALUES (2,'"'"'b'"'"');\nINSERT INTO `t1` VALUES (3,'"'"'c'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB' '(`x` int, `y` varchar(10)) ENGINE=InnoDB'; do + echo "$create" + dump_single_insert "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --structure 'x UInt32, y String' --query "SELECT * FROM table" +done diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference new file mode 100644 index 000000000000..5453565c8dd8 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference @@ -0,0 +1,3 @@ +BAD_ARGUMENTS +x UInt32 +supported_values Map(String, UInt32) diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh new file mode 100755 index 000000000000..e551cdbc6837 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `map` whose value type is unsupported is skipped in schema inference with +# `input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1`. + +SCHEMADIR="$CUR_DIR/format_schemas" +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 0" 2>&1 | grep -o -m1 -F 'BAD_ARGUMENTS' +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1" diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference new file mode 100644 index 000000000000..739d1f2b1342 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference @@ -0,0 +1,4 @@ +Map(Int64, Nullable(Int64)) {1:1} +Map(Int64, Nullable(Int64)) {0:1} +Map(Int64, Nullable(Int64)) {2:3} +Map(Int64, Int64) {0:1} diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql new file mode 100644 index 000000000000..fb99be351299 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest +-- no-fasttest: MsgPack format is not available in the fasttest environment + +-- A MsgPack map whose first key has no inferable type (nil, empty array, empty map, nested map with a nil key) +-- must be reported as "cannot determine type", not dereferenced. + +SET input_format_msgpack_number_of_columns = 1; + +-- {1: 1} +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\x01\x01'); + +-- {nil: 1}, {[]: 1}, {{}: 1}, {{nil: 1}: 1} +DESC format(MsgPack, '\x81\xc0\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x90\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x80\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x81\xc0\x01\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- {nil: 1}, {2: 3}: the type is taken from the second row. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01\x81\x02\x03'); + +-- {nil: 1} with schema_inference_hints, which the error message suggests. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01') SETTINGS schema_inference_hints = 'c1 Map(Int64, Int64)'; diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference new file mode 100644 index 000000000000..98c80be8e58b --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference @@ -0,0 +1,5 @@ +0300000000000000 +c9b15b7fd5143f1d8f677be3dc4daab9 - +c9b15b7fd5143f1d8f677be3dc4daab9 - +9038957ba26f89fe09ee1964aad98576 - +9038957ba26f89fe09ee1964aad98576 - diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh new file mode 100755 index 000000000000..d6493c3c6808 --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# `RawBLOB` must write the serialized state of an aggregate function, the same as its conversion to `String`, +# not the pointer to the state in memory. + +$CLICKHOUSE_CLIENT -q "SELECT sumState(number) FROM numbers(3) FORMAT RawBLOB" | od -An -tx1 | tr -d ' \n' +echo + +$CLICKHOUSE_CLIENT -q "SELECT quantileState(number) FROM numbers(100000) FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(quantileState(number) AS String) FROM numbers(100000) FORMAT RawBLOB" | md5sum + +$CLICKHOUSE_CLIENT -q "SELECT uniqExactState(number) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(uniqExactState(number) AS String) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference new file mode 100644 index 000000000000..e5046dab0a10 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -0,0 +1,35 @@ +table created +-- ALTER with only ALTER SETTINGS +settings that are not a destination: allowed +-- ALTER with SELECT on the table, but no WRITE on S3 +-- ALTER ON CLUSTER is rejected by the initiator +-- ALTER ON CLUSTER of a table that does not exist on the initiator +-- ALTER with WRITE on S3 limited by a URL filter +-- ALTER with WRITE on S3 +destination with WRITE on S3: allowed +empty destination without WRITE on S3: allowed +-- ALTER with WRITE on S3, restricted by a row policy +empty destination with a row policy: allowed +-- ALTER through an Alias +settings that are not a destination through an alias: allowed +-- CREATE without WRITE on S3 or AZURE +table without a destination: created +-- CREATE AS with a destination, without WRITE on S3 +-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3 +-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3 +-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3 +-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3 +-- ATTACH with a full definition and a destination, without WRITE on S3 +-- RESTORE of a queue with a destination, without WRITE on S3 +0 +0 +0 +-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 +CREATE AS with WRITE on S3: created +materialized view with WRITE on S3: created +RESTORE with WRITE on S3: restored +RESTORE ON CLUSTER with WRITE on S3: restored +CREATE ON CLUSTER with WRITE on S3: created +CREATE AS ON CLUSTER with WRITE on S3: created +ATTACH with WRITE on S3: attached +RESTORE TEMPORARY with WRITE on S3: restored 1 diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh new file mode 100755 index 000000000000..5699f7262195 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -0,0 +1,377 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, zookeeper, no-replicated-database +# Tag no-fasttest: the `S3Queue` and `AzureQueue` engines are not built into the fast test build. +# Tag zookeeper: `S3Queue` keeps its state in Keeper, and `ON CLUSTER` queries use the distributed DDL queue. +# Tag no-replicated-database: with `access_control_improvements.enable_read_write_grants` disabled (the default), +# a replicated access storage round-trips the user through serialized SQL, which rewrites `WRITE ON S3('')` +# into the old-style whole-source `S3` grant without the filter. + +# The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +# `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads the processed files with its +# own credentials and writes them to the destination. So setting `after_processing_move_uri`, +# `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) +# source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. +# `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +db="${CLICKHOUSE_DATABASE}" +user_alter="s3queue_move_alter_${db}" +user_create="s3queue_move_create_${db}" +keeper_path="/s3queue_move_destination_access_${db}" +src="http://localhost:11111/test/${db}_move_src/" +dst="http://localhost:11111/test/${db}_move_dst/" +backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" +backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" +attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") +azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}', after_processing = 'keep' +" +echo "table created" + +$CLICKHOUSE_CLIENT -q " + CREATE USER ${user_alter}; + GRANT ALTER SETTINGS ON ${db}.t TO ${user_alter}; + CREATE USER ${user_create}; + GRANT CREATE TABLE ON ${db}.* TO ${user_create}; + GRANT TABLE ENGINE ON S3Queue TO ${user_create}; + GRANT TABLE ENGINE ON AzureQueue TO ${user_create}; +" + +echo "-- ALTER with only ALTER SETTINGS" + +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container redirects the move to another container of the same account. +# The check reads only the query, so it fails before the storage is involved, although `t` is an `S3Queue`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# Settings that do not choose a destination need only ALTER SETTINGS. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING polling_max_timeout_ms = 20000, after_processing_move_prefix = 'prefix_${db}' +" && echo "settings that are not a destination: allowed" + +echo "-- ALTER with SELECT on the table, but no WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${db}.t TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container is a destination change that needs `WRITE` on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER is rejected by the initiator" + +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" + +# The grants come from the settings in the query, not from the table, so the initiator checks them without the table. +# With the grant, the query reaches the host and fails there. +$CLICKHOUSE_CLIENT -q "GRANT ALTER SETTINGS, SELECT ON ${db}.t_missing TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError UNKNOWN_TABLE } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3 limited by a URL filter" + +# The move writes keys built from the prefix and the source keys, so a URL filter cannot authorize them. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3('${dst}.*') TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3('${dst}.*') FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} +" && echo "destination with WRITE on S3: allowed" + +# Resetting the destination disables the move, so it needs no grant for a destination. +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination without WRITE on S3: allowed" + +echo "-- ALTER with WRITE on S3, restricted by a row policy" + +# The move copies whole files, so a user whose row policy hides rows of the table cannot set a destination. +$CLICKHOUSE_CLIENT -q " + GRANT WRITE ON S3 TO ${user_alter}; + CREATE ROW POLICY p_${db} ON ${db}.t USING x = 1 TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +# Turning the move off needs no check. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination with a row policy: allowed" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY p_${db} ON ${db}.t; + REVOKE WRITE ON S3 FROM ${user_alter}; +" + +echo "-- ALTER through an Alias" + +# The export checks see only the name in the query, which is the alias, so the change is refused for every user. +$CLICKHOUSE_CLIENT --allow_experimental_alias_table_engine 1 -q "CREATE TABLE ${db}.t_alias ENGINE = Alias('${db}', 't')" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError NOT_IMPLEMENTED } +" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 +" && echo "settings that are not a destination through an alias: allowed" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_alias SYNC" + +echo "-- CREATE without WRITE on S3 or AZURE" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# The same CREATE without a destination, or with an empty one, needs no grant for it. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'keep', + after_processing_move_uri = '' +" && echo "table without a destination: created" + +echo "-- CREATE AS with a destination, without WRITE on S3" + +# The engine and the settings of `AS` are inherited after the query is parsed, so the check has to see the final definition. +# `AS` inherits the definition only when the query has no storage clause (with `SETTINGS`, the engine is +# `default_table_engine`), so the destination comes from the source table. +# The source has no `keeper_path`, so each copy gets its own default path from its `UUID`. +# `SELECT` is required because the definition of the source has secret parts. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_as_src (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', after_processing = 'move', after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "GRANT SHOW COLUMNS, SELECT ON ${db}.t_as_src TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3" + +# The engine is an inner engine of the view, and the inner table is created as an internal query, which checks nothing. +$CLICKHOUSE_CLIENT -q "GRANT CREATE VIEW ON ${db}.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3" + +# This format ships the query as written and the workers resolve `AS` with no user. +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_entry_format_version 2 -q " + CREATE TABLE ${db}.t_as_cluster ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3" + +# This format builds the definition on the initiator. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ATTACH with a full definition and a destination, without WRITE on S3" + +# A full definition in `ATTACH` is a new definition, like `CREATE`. An `Atomic` database needs a `UUID` for it. +# The server warns that a full definition in `ATTACH` is not recommended, so only errors are sent to the client. +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- RESTORE of a queue with a destination, without WRITE on S3" + +# The restored definition comes from the backup, and the table is created by an internal query, +# so the restore has to authorize the destination before it creates anything. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "BACKUP TABLE ${db}.t_backup TO ${backup} FORMAT Null" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_backup SYNC" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup'" + +# The hosts create the tables with no user, so the initiator must authorize the destination. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup_cluster'" + +# A temporary table keeps its engine, even with `restore_replace_external_engines_to_null`, so the same check applies. +# Temporary tables live in a session, so the table is created and backed up in one client. +$CLICKHOUSE_CLIENT -m -q " + CREATE TEMPORARY TABLE t_tmp_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_tmp_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys}; + BACKUP TEMPORARY TABLE t_tmp_backup TO ${backup_tmp} FORMAT Null; +" +$CLICKHOUSE_CLIENT -q "GRANT CREATE TEMPORARY TABLE ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} + SETTINGS structure_only = 1, restore_replace_external_engines_to_null = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" + +# The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src +" && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x +" && echo "materialized view with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE ON CLUSTER with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "CREATE ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src +" && echo "CREATE AS ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "ATTACH with WRITE on S3: attached" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; + SELECT 'RESTORE TEMPORARY with WRITE on S3: restored', count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference new file mode 100644 index 000000000000..1ee31d8b5520 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference @@ -0,0 +1,3 @@ +src 0 1 +src 1 2 +tgt 0 1 diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql new file mode 100644 index 000000000000..71c125e9ef63 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql @@ -0,0 +1,39 @@ +-- Two async inserts with the same `insert_deduplication_token` but different data are coalesced +-- into one batch. In the materialized view target, the rows of the two tokens land in different +-- partitions. For the partition of the second (duplicate) token, self-deduplication removes all +-- rows, and the recalculated block for that partition is empty. The empty block used to reach +-- `MergeTreeDataWriter::mergeBlock` and trigger the "Required source after the first merge is +-- not 0" logical error with `optimize_on_insert` enabled and a `ReplacingMergeTree` target. + +DROP TABLE IF EXISTS mv_dedup_empty; +DROP TABLE IF EXISTS tgt_dedup_empty; +DROP TABLE IF EXISTS src_dedup_empty; + +CREATE TABLE src_dedup_empty (p UInt64, v UInt64) ENGINE = MergeTree ORDER BY v; +CREATE TABLE tgt_dedup_empty (p UInt64, v UInt64) ENGINE = ReplacingMergeTree PARTITION BY p ORDER BY v + SETTINGS non_replicated_deduplication_window = 100; +CREATE MATERIALIZED VIEW mv_dedup_empty TO tgt_dedup_empty AS SELECT p, v FROM src_dedup_empty; + +SET async_insert = 1; +SET wait_for_async_insert = 0; +SET async_insert_deduplicate = 1; +SET deduplicate_blocks_in_dependent_materialized_views = 1; +SET optimize_on_insert = 1; +-- Prevent an automatic flush between the two inserts; the flush below is explicit. +SET async_insert_busy_timeout_min_ms = 600000; +SET async_insert_busy_timeout_max_ms = 600000; +SET async_insert_use_adaptive_busy_timeout = 0; + +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (0, 1); +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (1, 2); + +SYSTEM FLUSH ASYNC INSERT QUEUE src_dedup_empty; + +-- The source table has no deduplication window, so it keeps both rows. In the target table the +-- second insert is a duplicate of the first by token, so only the first row survives. +SELECT 'src', p, v FROM src_dedup_empty ORDER BY v; +SELECT 'tgt', p, v FROM tgt_dedup_empty ORDER BY v; + +DROP TABLE mv_dedup_empty; +DROP TABLE tgt_dedup_empty; +DROP TABLE src_dedup_empty; diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference new file mode 100644 index 000000000000..f7068f2917b6 --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference @@ -0,0 +1,7 @@ +parallel_distributed_insert_select=0 ACCESS_DENIED +parallel_distributed_insert_select=1 ACCESS_DENIED +parallel_distributed_insert_select=2 ACCESS_DENIED +0 +1 +row policy on source FALLBACK +additional_table_filters 0 diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh new file mode 100755 index 000000000000..1c39f64182cf --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="user_$CLICKHOUSE_DATABASE" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE secret_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + CREATE TABLE copy_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + INSERT INTO secret_local VALUES (1, 'secret'); + + CREATE TABLE src_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), secret_local, id); + CREATE TABLE dst_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), copy_local, id); + + DROP USER IF EXISTS $user; + CREATE USER $user IDENTIFIED WITH no_password; + GRANT SELECT, INSERT ON $CLICKHOUSE_DATABASE.dst_dist TO $user; +" + +# The cluster has no interserver secret, so the shard runs the forwarded query under the credentials +# from the cluster configuration rather than as the caller. +client=($CLICKHOUSE_CLIENT --user "$user" --prefer_localhost_replica 0) + +for setting in 0 1 2; do + echo -n "parallel_distributed_insert_select=$setting " + "${client[@]}" --parallel_distributed_insert_select "$setting" -q "INSERT INTO dst_dist SELECT * FROM src_dist" |& + grep -o -m1 'ACCESS_DENIED' || echo 'NOT DENIED' +done + +# Read the destination directly: resolving `dst_dist` also authorizes `copy_local` once the shard +# query is planned on the initiator, which depends on the distributed plan settings. +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# With the grant in place the optimized path must still work. +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON $CLICKHOUSE_DATABASE.src_dist TO $user" +"${client[@]}" --parallel_distributed_insert_select 2 -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# A row policy on the source table cannot be applied by the optimized rewrite (it ships the query +# to the shards, where the policy on the Distributed table never applies), so it must fall back to +# the regular path. The regular path reads `src_dist` with a `SELECT` sent to the shard, while the +# optimized rewrite sends only an `INSERT ... SELECT` there, so the fallback is detected by the +# kind of the secondary queries in `system.query_log`. (The regular path of this branch does not +# enforce a row policy on a Distributed table, so the result of the copy itself is not checked.) +# +# The two fallback cases below pin serialize_query_plan = 0: with plan serialization the initiator +# plans the read of the underlying table itself and requires the caller's own SELECT on it, which +# these cases do not grant. +$CLICKHOUSE_CLIENT -q "CREATE ROW POLICY policy_05443 ON src_dist USING id != 1 TO $user" +query_id="05443_row_policy_${CLICKHOUSE_DATABASE}_$RANDOM" +"${client[@]}" --parallel_distributed_insert_select 2 --enable_analyzer 1 --enable_parallel_replicas 0 \ + --serialize_query_plan 0 --query_id "$query_id" \ + -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY policy_05443 ON src_dist; + SYSTEM FLUSH DISTRIBUTED dst_dist; + TRUNCATE TABLE copy_local; + SYSTEM FLUSH LOGS query_log; + SELECT + 'row policy on source', + if(countIf(query_kind = 'Select') > 0 AND countIf(query_kind = 'Insert' AND query ILIKE '%SELECT%') = 0, + 'FALLBACK', 'OPTIMIZED') + FROM system.query_log + WHERE event_date >= yesterday() AND initial_query_id = '$query_id' AND NOT is_initial_query AND type = 'QueryFinish' +" + +# additional_table_filters is keyed by the source table name, which the optimized rewrite would +# drop, so it must fall back to the regular path, which applies the filter: the only row has +# id = 1, nothing is copied and the destination stays empty. +echo -n "additional_table_filters " +"${client[@]}" --parallel_distributed_insert_select 2 --enable_parallel_replicas 0 --serialize_query_plan 0 \ + --additional_table_filters "{'src_dist' : 'id != 1'}" -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH DISTRIBUTED dst_dist; SELECT count() FROM copy_local" + +$CLICKHOUSE_CLIENT -q "DROP USER $user" diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference new file mode 100644 index 000000000000..aca8188dbcd7 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference @@ -0,0 +1,13 @@ +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +0 1900-01-01 00:00:00.145224192 Nullable(DateTime64(9, \'UTC\')) +1 1900-01-01 00:00:00.000000000 Nullable(DateTime64(9, \'UTC\')) +2 2020-05-17 10:20:30.123456000 Nullable(DateTime64(9, \'UTC\')) +3 2262-04-11 23:47:16.854775807 Nullable(DateTime64(9, \'UTC\')) +4 \N Nullable(DateTime64(9, \'UTC\')) +0 1900-01-01 00:00:00.145225 Nullable(DateTime64(6, \'UTC\')) +1 1900-01-01 00:00:00.000000 Nullable(DateTime64(6, \'UTC\')) +2 2020-05-17 10:20:30.123456 Nullable(DateTime64(6, \'UTC\')) +3 2262-04-11 23:47:16.854775 Nullable(DateTime64(6, \'UTC\')) +4 \N Nullable(DateTime64(6, \'UTC\')) +2 diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh new file mode 100755 index 000000000000..184859b09430 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# INT96 timestamps 0001-01-01, 1800-01-01 12:30, 2020-05-17 10:20:30.123456, 9999-12-31 23:59:59 and NULL, written by +# pyarrow with `use_deprecated_int96_timestamps=True`. The first and the fourth do not fit into Int64 nanoseconds. +DATA_FILE="${CUR_DIR}/data_parquet/05443_int96_out_of_range.parquet" + +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'throw'" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet, 'id Int32, ts Nullable(DateTime64(6, \'UTC\'))') ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT count() FROM file('${DATA_FILE}', Parquet) WHERE ts > '2000-01-01' SETTINGS date_time_overflow_behavior = 'saturate';" diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference new file mode 100644 index 000000000000..0b775a99cb4f --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference @@ -0,0 +1,2 @@ +0 1900-01-01 00:00:00.000000000 -9223329600000000000 +0 1900-01-01 00:00:00.000000000 -9223329600000000000 diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh new file mode 100755 index 000000000000..39e02424f38a --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A single INT96 timestamp 1677-09-21 12:00:00 (julian day 2333836, time of day 43200000000000 ns), written by pyarrow +# with `use_deprecated_int96_timestamps=True`. Midnight of that day does not fit into Int64 nanoseconds, but the full value +# -9223329600000000000 does, so it must be read exactly instead of being saturated to the Int64 minimum or rejected. +DATA_FILE="${CUR_DIR}/data_parquet/05444_int96_lower_boundary.parquet" + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'throw';" diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference new file mode 100644 index 000000000000..aa20b4a60886 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference @@ -0,0 +1 @@ +ACCESS_DENIED diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh new file mode 100755 index 000000000000..71282f1c8437 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tags: distributed, no-fasttest +# Tag no-fasttest: the interserver `` requires SSL, which the fast test build does not have. + +# Queued `Distributed` inserts of different users must not be sent in one batch: the batch is sent with +# the `ClientInfo` of its first file, and over a cluster with an interserver `` the shard +# authenticates the whole batch as that file's `initial_user`. Before the fix, rows of a user without +# the remote `INSERT` grant were delivered under the identity of a user that had it. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Flushing the rejected file (also when the table is dropped) logs the error on the server. +CLICKHOUSE_CLIENT=$(echo "$CLICKHOUSE_CLIENT" | sed "s/--send_logs_level=${CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL:-none}/--send_logs_level=none/g") + +WRITER="writer_${CLICKHOUSE_DATABASE}" +TENANT="tenant_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${WRITER}, ${TENANT}; + CREATE TABLE target (key Int) ENGINE = MergeTree ORDER BY key; + CREATE TABLE dist (key Int) ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), target, 0) + SETTINGS background_insert_batch = 1; + SYSTEM STOP DISTRIBUTED SENDS dist; + CREATE USER ${WRITER} IDENTIFIED WITH no_password; + CREATE USER ${TENANT} IDENTIFIED WITH no_password; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.dist TO ${WRITER}, ${TENANT}; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.target TO ${WRITER}; +" + +${CLICKHOUSE_CLIENT} --user "${WRITER}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (1)" +${CLICKHOUSE_CLIENT} --user "${TENANT}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (2)" + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH DISTRIBUTED dist" 2>&1 | grep -o -m1 "ACCESS_DENIED" +${CLICKHOUSE_CLIENT} -q "SELECT key FROM target WHERE key = 2" + +${CLICKHOUSE_CLIENT} -m -q " + DROP TABLE dist; + DROP USER ${WRITER}, ${TENANT}; +" diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference new file mode 100644 index 000000000000..65bc13dc12ac --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference @@ -0,0 +1,13 @@ +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', '[HIDDEN]', 'container', 'blob') +SELECT * FROM icebergAzure('[HIDDEN]', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = '[HIDDEN]', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +HIDDEN +0 1 +0 1 diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh new file mode 100755 index 000000000000..8ef143807a79 --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no `azureBlobStorage` table function + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A storage account url carrying a credential of its own (a SAS `?sig=...`, `user:key@`), or a value that is +# not a plain string literal, is hidden whole in the Azure table functions, positional or as a named-collection +# override, as the `AzureBlobStorage` engine and the backup destination already do. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('https://user:plain_password@account.blob.core.windows.net', 'container', 'blob') +SELECT * FROM azureBlobStorage(concat('https://account.blob.core.windows.net/?sig=', 'plain_sas_signature'), 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +EOF + +# `SELECT` on a view implies `SHOW COLUMNS`, so a user granted only that sees the view definition through +# `SHOW CREATE TABLE` and `system.tables`, but not the SAS in it. +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +$CLICKHOUSE_CLIENT -q "DROP USER IF EXISTS ${user}" +$CLICKHOUSE_CLIENT -q "CREATE VIEW ${CLICKHOUSE_DATABASE}.v_sas AS SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'file.csv', 'CSV', 'none', 'id UInt8')" +$CLICKHOUSE_CLIENT -q "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'hello'" +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.v_sas TO ${user}" + +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SHOW CREATE TABLE ${CLICKHOUSE_DATABASE}.v_sas" | grep -o -e 'plain_sas_signature' -e 'HIDDEN' +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SELECT countIf(create_table_query LIKE '%plain_sas_signature%'), countIf(create_table_query LIKE '%[HIDDEN]%') FROM system.tables WHERE database = '${CLICKHOUSE_DATABASE}' AND name = 'v_sas'" + +# `EXPLAIN AST optimize = 1` expands the view, which executes the table function and needs more than `SELECT` +# on the view, so it is run as the default user, who sees no secrets either without +# `format_display_secrets_in_show_and_select`. +$CLICKHOUSE_CLIENT --format_display_secrets_in_show_and_select 0 -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN AST optimize = 1 SELECT * FROM ${CLICKHOUSE_DATABASE}.v_sas)" + +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.reference b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference new file mode 100644 index 000000000000..a46fd0469968 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference @@ -0,0 +1,14 @@ +1900-06-01 00:01:41.000007000 -2195942298999993 +1900-06-01 00:01:41.000000000 -2195942299000000 +1960-06-01 00:01:41.000007000 -302486298999993 +2000-06-01 00:01:41.000007000 959817701000007 +none 25000 609103159500350648 +zstd 25000 609103159500350648 +lz4 25000 609103159500350648 +snappy 25000 609103159500350648 +zlib 25000 609103159500350648 +expected 25000 609103159500350648 +1001 4500 5500 +1923 +['a','b','a','b'] +['a','b','a','b'] Array(LowCardinality(String)) diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.sh b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh new file mode 100755 index 000000000000..bee99fd05840 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The Arrow ORC adapter stores negative nanoseconds for the timestamps before the epoch, +# and the reader must decode them as the reference implementation does. +$CLICKHOUSE_LOCAL -q "SELECT t, toUnixTimestamp64Micro(t) FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_arrow.orc', ORC) SETTINGS session_timezone = 'UTC'" + +DATA_FILE="$CLICKHOUSE_TMP/05447_${CLICKHOUSE_DATABASE}.orc" + +# Dictionary encoding of strings (with the row index and several row groups), a non-GMT writer time +# zone, and the values that need all integer encodings: repeats, deltas, outliers. +QUERY="SELECT number AS n, + toString(number % 13) AS low_cardinality, + if(number % 5 = 0, NULL, concat('value_', toString(number))) AS high_cardinality, + toDateTime64(1700000000 + number * 37, 3, 'UTC') AS ts, + if(number % 1000 = 0, 1000000000000, number % 7) AS outliers, + intDiv(number, 100) AS runs, + toDecimal128(number, 10) * -3 AS dec +FROM numbers(25000)" + +for compression in none zstd lz4 snappy zlib +do + $CLICKHOUSE_LOCAL -q "$QUERY FORMAT ORC SETTINGS output_format_orc_compression_method = '$compression', + output_format_orc_dictionary_key_size_threshold = 0.5, output_format_orc_row_index_stride = 1000, + output_format_orc_writer_time_zone_name = 'America/Los_Angeles'" > "$DATA_FILE" + $CLICKHOUSE_LOCAL -q "SELECT '$compression', count(), sum(cityHash64(*)) FROM file('$DATA_FILE', ORC, + 'n UInt64, low_cardinality String, high_cardinality Nullable(String), ts DateTime64(3, \'UTC\'), outliers UInt64, runs UInt64, dec Decimal(38, 10)') + SETTINGS input_format_orc_reader_time_zone_name = 'America/Los_Angeles'" +done +$CLICKHOUSE_LOCAL -q "SELECT 'expected', count(), sum(cityHash64(*)) FROM ($QUERY)" + +# Filter pushdown skips the row groups by the statistics in the row index. +$CLICKHOUSE_LOCAL -q "SELECT count(), min(n), max(n) FROM file('$DATA_FILE', ORC) WHERE n BETWEEN 4500 AND 5500 SETTINGS input_format_orc_filter_push_down = 1" +$CLICKHOUSE_LOCAL -q "SELECT count() FROM file('$DATA_FILE', ORC) WHERE low_cardinality = '12' SETTINGS input_format_orc_filter_push_down = 1" + +# The dictionary of a string column nested in an array can have more entries than the stripe has rows. +$CLICKHOUSE_LOCAL -q "SELECT ['a', 'b', 'a', 'b'] AS arr FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 0.5" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT arr FROM file('$DATA_FILE', ORC, 'arr Array(String)')" +$CLICKHOUSE_LOCAL -q "SELECT arr, toTypeName(arr) FROM file('$DATA_FILE', ORC, 'arr Array(LowCardinality(String))')" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.reference b/tests/queries/0_stateless/05448_orc_date_after_2059.reference new file mode 100644 index 000000000000..62cea6b447e4 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.reference @@ -0,0 +1,12 @@ +0 1970-01-01 Nullable(Date32) +1 2059-09-17 Nullable(Date32) +2 2059-09-18 Nullable(Date32) +3 2100-01-01 Nullable(Date32) +4 2149-06-06 Nullable(Date32) +0 1970-01-01 +1 2059-09-17 +2 2059-09-18 +3 2100-01-01 +4 2149-06-06 +3 +4 diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.sh b/tests/queries/0_stateless/05448_orc_date_after_2059.sh new file mode 100755 index 000000000000..8cc480ff4b24 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `Date` is the unsigned number of days, and the dates after 2059-09-18 (more than 32767 days) used +# to be written to ORC as negative numbers, which read back as the dates before 1970. +DATA_FILE="$CLICKHOUSE_TMP/05448_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q "SELECT number AS n, toDate(d) AS d FROM values('number UInt64, d String', (0, '1970-01-01'), (1, '2059-09-17'), (2, '2059-09-18'), (3, '2100-01-01'), (4, '2149-06-06')) FORMAT ORC" > "$DATA_FILE" + +$CLICKHOUSE_LOCAL -q "SELECT n, d, toTypeName(d) FROM file('$DATA_FILE', ORC) ORDER BY n" +$CLICKHOUSE_LOCAL -q "SELECT n, d FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') ORDER BY n" + +# The statistics are correct as well, so the filter pushdown keeps the rows. +$CLICKHOUSE_LOCAL -q "SELECT n FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') WHERE d > '2060-01-01' ORDER BY n SETTINGS input_format_orc_filter_push_down = 1" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference new file mode 100644 index 000000000000..d5d2e9dad4f1 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference @@ -0,0 +1,5 @@ +-- page cache, prefetching read +0 0 +1 10 +2 20 +1 diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh new file mode 100755 index 000000000000..8b52986339b5 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: S3 (MinIO) is not available in the fast test. + +# Parsing a short CSV object through the userspace page cache with a prefetching read must not read past the end of the +# page cache cell that holds it. A sanitizer build aborts on such a read. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}/data.csv" + +CONFIG_FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_page_cache.yaml" +echo "page_cache_max_size: 134217728" > "${CONFIG_FILE}" + +# A 14-byte object: "0,0\n1,10\n2,20\n". +${CLICKHOUSE_CLIENT} --query " + INSERT INTO FUNCTION s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a UInt32, b UInt32') + SELECT number, number * 10 FROM numbers(3) SETTINGS s3_truncate_on_insert = 1" + +echo "-- page cache, prefetching read" +${CLICKHOUSE_LOCAL} --config-file "${CONFIG_FILE}" --query " + SELECT * FROM s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a String, b UInt32') ORDER BY b + SETTINGS input_format_parallel_parsing = 0, use_page_cache_for_object_storage = 1, + remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1; + SELECT value > 0 FROM system.metrics WHERE metric = 'PageCacheBytes'" + +rm "${CONFIG_FILE}" diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference new file mode 100644 index 000000000000..a4a9c43f01b2 --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference @@ -0,0 +1,8 @@ +1.6.0 0 18000000000 Mike +1.6.0 0 1 +1.6.0 1 18000000000 Mike +1.6.0 1 1 +1.6.11 0 18000000000 Mike +1.6.11 0 1 +1.6.11 1 18000000000 Mike +1.6.11 1 1 diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh new file mode 100755 index 000000000000..30badff1fa0d --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# The bloom filters written by the C++ writer of ORC 1.6.0 - 1.6.11 and 1.7.0 use incorrect hashing (ORC-1024) +# and must be ignored, otherwise the filter pushdown skips the matching rows. +for version in 1.6.0 1.6.11 +do + for push_down in 0 1 + do + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, id, name + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id = 18000000000 + SETTINGS input_format_orc_filter_push_down = $push_down" + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, count() + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id IN (18000000000, 18000000001) + SETTINGS input_format_orc_filter_push_down = $push_down" + done +done diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference new file mode 100644 index 000000000000..cf669808c66d --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference @@ -0,0 +1,39 @@ +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +SELECT * FROM azureBlobStorage('[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('[HIDDEN]', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=[HIDDEN]', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = '[HIDDEN]', storage_account_url = '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', connection_string = '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('[HIDDEN]', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]' +0 1 +0 1 +0 1 +0 1 +0 1 diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh new file mode 100755 index 000000000000..6246ea1d8cb3 --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Azure table functions and engines, whose arguments it then hides whole + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `clickhouse-format` hides the credentials in the arguments of the Azure table functions and engines and in the +# `SETTINGS` clause of `AzureQueue`, wherever the parser reads them from. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id', tenant_id = 'tid'), 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id'), extra_credentials(tenant_id = 'tid'), 'plain_account_key', 'CSV') +SELECT * FROM azureBlobStorageCluster(extra_credentials(client_id = 'id'), 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')) +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;SharedAccessSignature=sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=https://account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('HTTPS://user:plain_password=x@account.blob.core.windows.net/', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, client_secret = 'plain_client_secret', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = headers('Authorization' = 'plain_header_secret'), blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', storage_account_url = 'AccountName=account;AccountKey=plain_account_key_2') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = concat('AccountName=account;AccountKey=', 'plain_account_key'), connection_string = 'AccountName=account;AccountKey=plain_account_key_2') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage(azure_conf, sas_token = 'plain_sas_signature') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', 'plain_account_key' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'HTTPS://account.blob.core.windows.net/?sig=plain_sas_signature' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'https://user:plain_password=x@account.blob.core.windows.net/' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2' +EOF + +# The query tree hides an argument masked whole, not only the right side of a comparison. +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x'))" +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage(azure_conf, 'sp=r&sig=plain_sas_signature' = 'x'))" + +# Nothing inside an Azure `extra_credentials(...)` is dumped, keys included. +for explain in "AST" "QUERY TREE run_passes = 0"; do + $CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_client_%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN $explain SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')))" +done + +# The statement is logged with the credential hidden. +$CLICKHOUSE_CLIENT -q "EXPLAIN AST SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_logged')" > /dev/null +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS query_log" +$CLICKHOUSE_CLIENT -q "SELECT countIf(query LIKE '%plain_sas_logged%'), countIf(query LIKE '%[HIDDEN]%') FROM system.query_log WHERE current_database = currentDatabase() AND query LIKE 'EXPLAIN AST%azureBlobStorage%' AND type = 'QueryFinish' AND is_initial_query" diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.reference b/tests/queries/0_stateless/05473_orc_footer_content_length.reference new file mode 100644 index 000000000000..ae5399ce4997 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.reference @@ -0,0 +1,2 @@ +1 True True +1 True True diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.sh b/tests/queries/0_stateless/05473_orc_footer_content_length.sh new file mode 100755 index 000000000000..78921273f950 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. +# The `content_length` in the ORC footer covers only the stripes, not the metadata section with the stripe statistics. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +check() +{ + $CLICKHOUSE_LOCAL --query "$1" | python3 -c ' +import sys + +data = sys.stdin.buffer.read() + +def varint(buf, pos): + result = shift = 0 + while True: + byte = buf[pos] + pos += 1 + result |= (byte & 0x7f) << shift + shift += 7 + if byte < 0x80: + return result, pos + +def fields(buf): + pos = 0 + while pos < len(buf): + key, pos = varint(buf, pos) + if key & 7 == 0: + value, pos = varint(buf, pos) + elif key & 7 == 2: + length, pos = varint(buf, pos) + value = buf[pos:pos + length] + pos += length + else: + raise Exception("unexpected wire type") + yield key >> 3, value + +postscript_length = data[-1] +postscript = dict(fields(data[-1 - postscript_length:-1])) +footer_length = postscript[1] +footer = list(fields(data[-1 - postscript_length - footer_length:-1 - postscript_length])) +content_length = next(v for f, v in footer if f == 2) +stripes = [dict(fields(v)) for f, v in footer if f == 3] +stripes_length = sum(s.get(2, 0) + s.get(3, 0) + s.get(4, 0) for s in stripes) +print(len(stripes), content_length == stripes_length, postscript[5] > 0) +' +} + +check "SELECT number FROM numbers(3) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" +check "SELECT number, toString(number) FROM numbers(100000) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.reference b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference new file mode 100644 index 000000000000..754cd5dae768 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference @@ -0,0 +1,20 @@ +a Nullable(Int64) +b Nullable(Decimal(12, 0)) +c Nullable(Decimal(20, 2)) +d Nullable(Decimal(12, 2)) +e Nullable(Decimal(2, 2)) +17292380420 24 36164.16 0.03 0.01 +17292380421 38 63351.7 0.08 0.01 +17292380421 28 42673.96 0.09 0.06 +17292380421 40 76677.6 0.05 0.04 +17292380421 2 2096.48 0.07 0.07 +17292380421 42 45284.82 0.07 0.05 +17292380421 10 18572.9 0.01 0.08 +17292380422 12 14836.8 0.09 0.06 +17292380422 41 82152.52 0.07 0.02 +17292380422 38 47240.84 0.1 0 +38 0.08 +40 0.05 +42 0.07 +41 0.07 +38 0.1 diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.sh b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh new file mode 100755 index 000000000000..94e31bf56154 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `decimal64_v2.orc` from the examples of apache/orc has the format version 1.9999 (`UNSTABLE_PRE_2_0`), +# where the DECIMAL columns with the precision up to 18 are signed RLEv2 integers without the SECONDARY stream. +$CLICKHOUSE_LOCAL -q "DESCRIBE file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT * FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT b, d FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC) WHERE b > 30 SETTINGS input_format_orc_filter_push_down = 1" diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference new file mode 100644 index 000000000000..8588a3ce6bb6 --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference @@ -0,0 +1,4 @@ +400 79800 0 399 +58 11571 +INCORRECT_DATA +1 diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh new file mode 100755 index 000000000000..b0ebdedb176d --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: needs MinIO + +# A source of an object storage reads the Parquet footer of its next file in the background, while it reads the current one. +# One stream (`max_threads = 1`) reads all files, so every file but the first one is read through a prefetched footer. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +DIR="${CLICKHOUSE_TEST_UNIQUE_NAME}" +Q="${CLICKHOUSE_TEST_UNIQUE_NAME}_" + +for i in 0 1 2 3; do + ${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/good/${i}.parquet', format = Parquet) SELECT number + ${i} * 100 AS x FROM numbers(100)" +done +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/0.parquet', format = Parquet) SELECT number AS x FROM numbers(100)" +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/1.parquet', format = RawBLOB) SELECT 'not a parquet file'" + +# The footer is read in advance only by the native Parquet reader, which CI randomizes on this branch. +SETTINGS="--max_threads 1 --use_parquet_metadata_cache 1 --input_format_parquet_use_native_reader_v3 1" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}1" --query "SELECT count(x), sum(x), min(x), max(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet')" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}2" --query "SELECT count(x), sum(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet') WHERE x % 7 = 0" + +# The file that is not Parquet fails the query as it did before the footer was read in advance. +${CLICKHOUSE_CLIENT} $SETTINGS --query "SELECT sum(x) FROM s3(s3_conn, filename = '${DIR}/bad/*.parquet')" 2>&1 | grep -o -m1 "INCORRECT_DATA" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" + +# The second query finds all footers in the Parquet metadata cache. +# With parallel replicas, `s3` is rewritten to `s3Cluster` and the files are read by secondary queries, +# which run with `current_database = 'default'`, so the hits are summed over `initial_query_id`. +${CLICKHOUSE_CLIENT} --query " + SELECT sum(ProfileEvents['ParquetMetadataCacheHits']) >= 4 + FROM system.query_log + WHERE initial_query_id = '${Q}2' AND type = 'QueryFinish' + AND (current_database = currentDatabase() OR NOT is_initial_query) +" diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference new file mode 100644 index 000000000000..f23520f0dbfc --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference @@ -0,0 +1,2 @@ +batches: 4096 row counts: [64] +262144 1000 16777216 diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh new file mode 100755 index 000000000000..e71fb6e12721 --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# ^ pyarrow is not available in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One large block split by a small `output_format_arrow_max_record_batch_size_bytes` into thousands of +# record batches. The `LowCardinality` column never needs a split itself, but measuring it is linear in +# the rows given, so this is the shape where measuring the whole remainder of the block +# for every batch would be quadratic. Every batch is bounded by the `String` column: 64 rows of 64 bytes. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_many_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +$CLICKHOUSE_LOCAL --query " + SELECT + toLowCardinality(toString(number % 1000)) AS lc, + repeat('x', 64) AS s + FROM numbers(262144) + SETTINGS + max_block_size = 262144, + output_format_arrow_max_record_batch_size_bytes = 4096, + output_format_arrow_compression_method = 'none' + FORMAT ArrowStream" > "$FILE" + +python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + batches = list(ipc.open_stream(src)) +print("batches:", len(batches), "row counts:", sorted({batch.num_rows for batch in batches})) +PY + +$CLICKHOUSE_LOCAL --query " + SELECT count(), uniqExact(lc), sum(length(s)) + FROM file('$FILE', ArrowStream)" diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference new file mode 100644 index 000000000000..d00491fd7e5b --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference @@ -0,0 +1 @@ +1 diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh new file mode 100755 index 000000000000..eec443dcca49 --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Tags: zookeeper + +# `SYSTEM RESTORE DATABASE REPLICA` stops and replaces the DDL worker of a `Replicated` database. +# A DDL query that was concurrently waiting in the worker used to keep a raw pointer to it +# and dereference the destroyed worker (segmentation fault). Now such a query either succeeds +# or fails with an exception, and the server stays alive. + +# The racing queries fail with various errors by design; they are not interesting. +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=none + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +TIMEOUT=10 + +function ddl_thread() +{ + local i=0 + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + i=$((i + 1)) + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_${1}_${i} (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS ${DB}.t_${1}_${i} SYNC" >/dev/null 2>&1 + done +} + +function sync_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +function restore_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +ddl_thread 1 & +ddl_thread 2 & +ddl_thread 3 & +sync_thread & +restore_thread & +restore_thread & +wait + +# The server is alive and the database still accepts DDL. +for _ in $(seq 1 60); do + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_final (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 && break + sleep 1 +done +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t_final" + +$CLICKHOUSE_CLIENT --query "DROP DATABASE ${DB} SYNC" diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference new file mode 100644 index 000000000000..587aee15552b --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference @@ -0,0 +1,5 @@ +restore is waiting 1 +create succeeded +restore finished +1 +0 diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh new file mode 100755 index 000000000000..6ef139d50d2d --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# An initial DDL query of a `Replicated` database executes and commits on the submitting thread. +# `SYSTEM RESTORE DATABASE REPLICA` must wait for such a query that was already admitted by the old +# DDL worker before the new worker recovers the replica. Otherwise the query could commit its metadata +# while the recovery compares the Keeper snapshot with the local tables, and the recovery would move +# the just created table to the `_broken_replicated_tables` database. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +# Hold the initial `CREATE TABLE` after the DDL worker has admitted it, before it executes and commits. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = MergeTree ORDER BY x" & +create_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore stops the old DDL worker and then has to wait for the paused `CREATE TABLE`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $create_pid && echo "create succeeded" +# The restore proceeds only after the query has committed. The replica is not lost then (its digest is not empty), +# so the restore may refuse with `REPLICA_ALREADY_EXISTS`; either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +# The table created by the successful query is still there after the recovery of the replica. +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference new file mode 100644 index 000000000000..799f581f2dea --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference @@ -0,0 +1,6 @@ +d_complex LOADED +d_simple LOADED +1 1 +alive +4 +0 diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh new file mode 100755 index 000000000000..aa8ddefa8372 --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-llvm-coverage +# no-fasttest: waits 7 s for the update backoff; no-llvm-coverage: the file size limit below would also cut the coverage profile. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ssd_cache` dictionaries whose cache file cannot grow for the next partition stay usable after the failed update, +# and the next update fails the same way. The file size limit lets the first 64 KiB of each cache file be allocated, +# but not the next 64 KiB, while 100 values of 1.2 KB need more than that. + +dir="${CLICKHOUSE_USER_FILES_UNIQUE:?}" +rm -rf "${dir:?}" +mkdir -p "$dir" +trap 'rm -rf "${dir:?}"' EXIT + +query=" +CREATE TABLE src (k UInt64, v String) ENGINE = Memory; +INSERT INTO src SELECT number, toString(number) || ':' || repeat('x', 1200) FROM numbers(100); + +CREATE DICTIONARY d_simple (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_simple')); + +CREATE DICTIONARY d_complex (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(COMPLEX_KEY_SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_complex')); + +-- Both updates fail, because the cache files cannot grow. +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +-- Wait for the 5-6 s backoff after a failed update, so that the next lookups update the dictionaries again. +SELECT sleep(3) FORMAT Null; +SELECT sleep(3) FORMAT Null; +SELECT sleep(1) FORMAT Null; + +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +SELECT name, status FROM system.dictionaries ORDER BY name; +SELECT dictGet('d_simple', 'v', toUInt64(0)) = '0:' || repeat('x', 1200), dictGet('d_complex', 'v', tuple(toUInt64(0))) = '0:' || repeat('x', 1200); +SELECT 'alive'; +" + +( + cd "$dir" || exit 1 + ulimit -c 0 + trap '' XFSZ + ulimit -f 100 + $CLICKHOUSE_LOCAL --ignore-error --send_logs_level=error --query "$query" 2>"$dir/stderr" +) + +# Each of the four failed updates reports the failed allocation, and none of them was refused by the backoff. +grep -o -F 'Cannot preallocate space' "$dir/stderr" | wc -l +grep -o -F 'nearest update is scheduled' "$dir/stderr" | wc -l diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference new file mode 100644 index 000000000000..350939450c19 --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference @@ -0,0 +1,25 @@ +--- readonly_1 +READONLY +READONLY +READONLY +READONLY +READONLY +OK +--- readonly_2 +OK +OK +OK +OK +OK +--- readonly_0 +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +OK +--- requests to the endpoint +readonly_2_cluster 1 +readonly_2_describe 1 +readonly_2_remote 1 +readonly_2_select 1 diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh new file mode 100755 index 000000000000..621fcc5b8a8b --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Resolving the structure of a table function (`DESCRIBE TABLE url(...)`, or a table function nested in +# `cluster`) must require the same `CREATE TEMPORARY TABLE` grant as reading from it, and must be refused +# before the source is contacted. Otherwise a user who cannot run `url` (e.g. under `readonly = 1`) can make +# the server request an arbitrary endpoint and read the response from the schema inference error. + +USER_READONLY_1="readonly_1_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_2="readonly_2_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_0="readonly_0_${CLICKHOUSE_TEST_UNIQUE_NAME}" +TEMP_CREDENTIALS="unknown" + +# Create users with different readonly settings. +function create_users() { + ${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + CREATE USER ${USER_READONLY_1} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 1; + CREATE USER ${USER_READONLY_2} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 2; + -- \`readonly = 0\`, but without the \`CREATE TEMPORARY TABLE\` grant. + CREATE USER ${USER_READONLY_0} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}'; + GRANT SELECT ON *.*, READ ON URL, READ ON REMOTE TO ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${USER_READONLY_1}, ${USER_READONLY_2}; + " +} + +function drop_users() { + ${CLICKHOUSE_CLIENT} -q "DROP USER ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}" +} + +# Instead of a mock server, use this server's HTTP interface: every request to it is logged in `system.query_log` +# with the marker given as the argument, so `check_endpoint_requests` can tell whether the source was contacted. +# It always responds in `JSONEachRow`, like the JSON metadata service in the original report: the format passed +# to `url` is how the response is parsed, so `Values` fails to parse it and would echo the body in the error. +function endpoint() { + local marker="$1" + echo "${CLICKHOUSE_PORT_HTTP_PROTO}://${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?database=${CLICKHOUSE_DATABASE}&query=SELECT+1+AS+x,+%27marker_${marker}%27+AS+m+FORMAT+JSONEachRow" +} + +# Run a query as the given user and print `READONLY`, `ACCESS_DENIED`, `OK`, or the full unexpected error. +# `CLICKHOUSE_CLIENT` passes randomized settings, which a `readonly = 1` user is not allowed to change. +function run() { + local user="$1" + local query="$2" + local output + output=$(${CLICKHOUSE_CLIENT_BINARY} --host "${CLICKHOUSE_HOST}" --port "${CLICKHOUSE_PORT_TCP}" \ + --user "${user}" --password "${TEMP_CREDENTIALS}" -q "${query}" 2>&1) + if [[ "${output}" =~ \((READONLY|ACCESS_DENIED)\) ]]; then + echo "${BASH_REMATCH[1]}" + elif [[ "${output}" == *Exception* ]]; then + echo "${output}" + else + echo "OK" + fi +} + +# Run all the queries as one user. The user name without the unique suffix (e.g. `readonly_1`) +# labels the output and the endpoint markers. +function check_user() { + local user="$1" + local label="${user%_"${CLICKHOUSE_TEST_UNIQUE_NAME}"}" + echo "--- ${label}" + run "${user}" "SELECT * FROM url('$(endpoint "${label}_select")', 'JSONEachRow')" + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_describe")', 'JSONEachRow')" + # With a format that fails to parse the response, the schema inference error would contain the response body. + # It is skipped for `readonly_2`, which is allowed to read the URL: its error text depends on the server version. + if [[ "${label}" != "readonly_2" ]]; then + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_values")', 'Values')" + fi + + # `remote` is not allowed in readonly mode, so it is refused before the nested `url` is resolved. + run "${user}" "DESCRIBE TABLE remote('127.0.0.1', url('$(endpoint "${label}_remote")', 'JSONEachRow'))" + # `cluster` is allowed in readonly mode, but it resolves the structure of the nested `url` on the local shard. + run "${user}" "DESCRIBE TABLE cluster('test_shard_localhost', url('$(endpoint "${label}_cluster")', 'JSONEachRow'))" + + # Table functions allowed in readonly mode stay available without the grant. + run "${user}" "DESCRIBE TABLE numbers(1)" +} + +# Print the markers of the requests that reached the endpoint, i.e. which queries contacted the source. +# Only the queries of the `readonly = 2` user may appear: a marker without requests has no row. +function check_endpoint_requests() { + echo "--- requests to the endpoint" + ${CLICKHOUSE_CLIENT} -m -q " + SYSTEM FLUSH LOGS query_log; + SELECT extract(query, 'marker_([a-z0-9_]+)') AS marker, count() > 0 + FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE 'SELECT 1 AS x, %marker_%' + GROUP BY marker + ORDER BY marker; + " +} + +create_users +for user in "${USER_READONLY_1}" "${USER_READONLY_2}" "${USER_READONLY_0}"; do + check_user "${user}" +done +check_endpoint_requests +drop_users diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference new file mode 100644 index 000000000000..2e0aea006e63 --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference @@ -0,0 +1,6 @@ +1 +2 +3 +4 +1 [1,2,3] +1 [1,2,3] diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh new file mode 100755 index 000000000000..19aeaf05141f --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: MsgPack format is not available in the fasttest environment + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One async insert batch reuses one MsgPack input format for all its entries. Each case queues an +# invalid entry followed by a valid one: the valid entry must be parsed from a clean state. + +url="${CLICKHOUSE_URL}&async_insert=1&wait_for_async_insert=0&async_insert_use_adaptive_busy_timeout=0&async_insert_busy_timeout_min_ms=100000&async_insert_busy_timeout_max_ms=100000" + +function insert_pair() +{ + local table=$1 bad=$2 good=$3 + printf '%b' "$bad" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + printf '%b' "$good" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + ${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH ASYNC INSERT QUEUE ${table}" + ${CLICKHOUSE_CLIENT} -q "SELECT * FROM ${table} ORDER BY ALL" +} + +${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_scalar (x UInt64) ENGINE = MergeTree ORDER BY x; + CREATE TABLE t_exception (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; + CREATE TABLE t_array (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; +" + +# A uint32 with 1 of its 4 bytes; the valid entry is four rows 1, 2, 3, 4. +insert_pair t_scalar '\xce\x00' '\x01\x02\x03\x04' +# A string inside Array(UInt8) is rejected in the middle of the array. +insert_pair t_exception '\x07\x92\x01\xa1x' '\x01\x93\x01\x02\x03' +# An array of 3 elements with only 1 present. +insert_pair t_array '\x07\x93\x01' '\x01\x93\x01\x02\x03' + +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_scalar; DROP TABLE t_exception; DROP TABLE t_array" diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference new file mode 100644 index 000000000000..60ef3fadf28c --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference @@ -0,0 +1,13 @@ +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string +which the MySQL client library would read as a list of hosts +which the MySQL client library would read as a connection plugin URL +which the MySQL client library would read as the end of the host +connection failed +port 0: rejected +dictionary 127.0.0.1 port 0: rejected +dictionary localhost port 0: unix socket +dictionary localhost port 0: rejected +localhost: tcp +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh new file mode 100755 index 000000000000..bc24f80c9622 --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MySQL client library is not built in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The MySQL client library reinterprets some host strings: a connection string (which can set a socket, a plugin +# directory, TLS files), a connection plugin URL, a list of hosts, or a host cut at a NUL. They must be rejected +# before any connection attempt. + +# Prints how the host was rejected, or "connection failed" for an ordinary connection failure. +function check() +{ + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "$1" 2>&1 | tr -d '\000') + if grep -q -F "which the MySQL client library would read as" <<< "$output"; then + grep -o -m1 "which the MySQL client library would read as [a-zA-Z ]*" <<< "$output" + elif grep -q -F "ALL_CONNECTION_TRIES_FAILED" <<< "$output"; then + echo "connection failed" + else + echo "unexpected output: $output" + fi +} + +check "SELECT * FROM mysql('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('host=localhost;socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1,localhost:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('[replication://127.0.0.1]:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1\\0.example.com:1', 'db', 't', 'u', 'p')" + +# A plain host is passed through and fails to connect as usual. +check "SELECT * FROM mysql('127.0.0.1:1', 'db', 't', 'u', 'p')" + +# Port 0 would be replaced by the client library's default port. +$CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('127.0.0.1:0', 'db', 't', 'u', 'p')" 2>&1 \ + | grep -q -F "MySQL port 0" && echo "port 0: rejected" || echo "port 0: connection failed" + +# A dictionary socket is used only for `localhost`; for another host it is ignored and port 0 is rejected. +function check_dictionary() +{ + $CLICKHOUSE_CLIENT --send_logs_level=fatal -q " + CREATE DICTIONARY ${CLICKHOUSE_DATABASE}.d_mysql (x UInt64, y String) PRIMARY KEY x + SOURCE(MYSQL(HOST '$1' PORT 0 SOCKET '$2' USER 'u' PASSWORD 'p' DB 'db' TABLE 't')) + LAYOUT(FLAT()) LIFETIME(0)" + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM ${CLICKHOUSE_DATABASE}.d_mysql" 2>&1) + if grep -q -E "MySQL port 0|MySQL socket" <<< "$output"; then + echo "dictionary $1 port 0: rejected" + elif grep -q -F "through socket" <<< "$output"; then + echo "dictionary $1 port 0: unix socket" + else + echo "unexpected output: $output" + fi + $CLICKHOUSE_CLIENT -q "DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" +} +check_dictionary "127.0.0.1" "/nonexistent/mysqld.sock" +check_dictionary "localhost" "/nonexistent/mysqld.sock" +# The client library would read a socket starting with NUL as no socket and connect over TCP. +check_dictionary "localhost" "\\0" + +# `localhost` uses TCP to the given port, not the client library's default Unix socket. +output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('localhost:1', 'db', 't', 'u', 'p')" 2>&1) +if grep -q -F "Can't connect to server on 'localhost'" <<< "$output"; then + echo "localhost: tcp" +elif grep -q -F "through socket" <<< "$output"; then + echo "localhost: unix socket" +else + echo "unexpected output: $output" +fi + +# The `MySQL` database engine and table engine use the same connection pool. +check "CREATE DATABASE ${CLICKHOUSE_DATABASE}_mysql ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 'u', 'p')" +check "CREATE TABLE ${CLICKHOUSE_DATABASE}.t_mysql (x UInt32) ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p'); SELECT * FROM ${CLICKHOUSE_DATABASE}.t_mysql" + +$CLICKHOUSE_CLIENT -q "DROP DATABASE IF EXISTS ${CLICKHOUSE_DATABASE}_mysql; DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.t_mysql; DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference new file mode 100644 index 000000000000..6ccddfe23c73 --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference @@ -0,0 +1,4 @@ +after_processing_move_access_key_id key_id_05493 +after_processing_move_connection_string [HIDDEN] +after_processing_move_secret_access_key [HIDDEN] +mode unordered diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql new file mode 100644 index 000000000000..63571197469e --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` engine is not built in the fast test. + +-- `system.s3_queue_settings` hides the secrets that `SHOW CREATE TABLE` hides. + +DROP TABLE IF EXISTS t_secrets; + +CREATE TABLE t_secrets (a String) +ENGINE = S3Queue('http://whatever-we-dont-care:9001/root/t_secrets/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', + after_processing_move_access_key_id = 'key_id_05493', + after_processing_move_secret_access_key = 'SEKRIT_05493_1', + after_processing_move_connection_string = 'DefaultEndpointsProtocol=https;AccountName=a;AccountKey=SEKRIT_05493_2;'; + +SELECT name, value +FROM system.s3_queue_settings +WHERE database = currentDatabase() AND table = 't_secrets' + AND name IN ('after_processing_move_access_key_id', 'after_processing_move_secret_access_key', + 'after_processing_move_connection_string', 'mode') +ORDER BY name; + +DROP TABLE t_secrets; diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference new file mode 100644 index 000000000000..573541ac9702 --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference @@ -0,0 +1 @@ +0 diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql new file mode 100644 index 000000000000..1247bc62fb1f --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql @@ -0,0 +1,31 @@ +-- Tags: no-fasttest +-- no-fasttest: needs S3 support in the build. + +-- An SSE-C key that is not the base64 of a 256-bit key is rejected when the S3 client is created, before any request. + +-- Non-ASCII bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'éAAA'); -- { serverError BAD_ARGUMENTS } + +-- Valid base64 of 3 bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'AAAA'); -- { serverError BAD_ARGUMENTS } + +-- An invalid character in a key of the right length. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAx!jM0NTY3ODkwMTIzNDU2Nzg5MDE='); -- { serverError BAD_ARGUMENTS } + +-- A valid key followed by more characters. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=!'); -- { serverError BAD_ARGUMENTS } + +-- A valid key with surrounding whitespace. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = ' MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE= '); -- { serverError BAD_ARGUMENTS } + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name = 't_sse_c'; diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference new file mode 100644 index 000000000000..573a680fbe86 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference @@ -0,0 +1,16 @@ +nanoseconds local push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=1: (INCORRECT_DATA) +statistics local push_down=0 lazy=0: 3 +statistics local push_down=0 lazy=1: 3 +statistics local push_down=1 lazy=0: 3 +statistics local push_down=1 lazy=1: 3 +statistics remote push_down=0 lazy=0: 3 +statistics remote push_down=0 lazy=1: 3 +statistics remote push_down=1 lazy=0: 3 +statistics remote push_down=1 lazy=1: 3 diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh new file mode 100755 index 000000000000..53eae4b38eb0 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The nanoseconds of a timestamp with the 7 removed trailing zeros overflow `Int64`. +orc_check nanoseconds "$DATA/malformed_timestamp_nanoseconds.orc" 't Nullable(DateTime64(9))' "SELECT count(), max(t) FROM SOURCE" \ + 'Invalid timestamp in ORC column 1: seconds=[0-9]+, encoded nanoseconds=-?[0-9]+' + +# The minimum nanoseconds in the statistics is 0x80000000: such statistics must not be used by the filter pushdown. +orc_check statistics "$DATA/malformed_timestamp_statistics_nanoseconds.orc" 't DateTime64(9)' \ + "SELECT count() FROM SOURCE WHERE t > toDateTime64('2000-01-01 00:00:00', 9, 'UTC')" diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference new file mode 100644 index 000000000000..17ac0b58ed17 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference @@ -0,0 +1,7 @@ +1e308 ['0','1','2','0','1','2','0','1','2','0'] +-1e308 ['0','1','2','0','1','2','0','1','2','0'] +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +9223372036854775807 +-9223372036854775808 diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh new file mode 100755 index 000000000000..6da24b0909d7 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A dictionary threshold that does not fit in `size_t` when multiplied by the number of values. +for threshold in 1e308 -1e308; do + $CLICKHOUSE_LOCAL -q "SELECT toString(number % 3) AS s FROM numbers(10) FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = $threshold" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT '$threshold', groupArray(s) FROM table" +done + +# The extreme `DateTime64` values that cannot be stored in ORC with their statistics in milliseconds. +for value in 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(-9223372036854775808), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(1)'"'"')'; do + $CLICKHOUSE_LOCAL -q "SELECT $value AS t FORMAT ORC" 2>&1 >/dev/null | grep -oE '\(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE\)' | head -n1 | grep . || echo "$value: no error" +done + +# The extreme values with the nanoseconds can be stored. +for value in 9223372036854775807 -9223372036854775808; do + $CLICKHOUSE_LOCAL -q "SELECT reinterpret(toInt64($value), 'DateTime64(9, \'UTC\')') AS t FORMAT ORC" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT reinterpret(t, 'Int64') FROM table" +done diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference new file mode 100644 index 000000000000..2d165fb8a6c0 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference @@ -0,0 +1,16 @@ +empty local push_down=0 lazy=0: (INCORRECT_DATA) +empty local push_down=0 lazy=1: (INCORRECT_DATA) +empty local push_down=1 lazy=0: (INCORRECT_DATA) +empty local push_down=1 lazy=1: (INCORRECT_DATA) +empty remote push_down=0 lazy=0: (INCORRECT_DATA) +empty remote push_down=0 lazy=1: (INCORRECT_DATA) +empty remote push_down=1 lazy=0: (INCORRECT_DATA) +empty remote push_down=1 lazy=1: (INCORRECT_DATA) +nulls local push_down=0 lazy=0: 5 5 +nulls local push_down=0 lazy=1: 5 5 +nulls local push_down=1 lazy=0: 5 5 +nulls local push_down=1 lazy=1: 5 5 +nulls remote push_down=0 lazy=0: 5 5 +nulls remote push_down=0 lazy=1: 5 5 +nulls remote push_down=1 lazy=0: 5 5 +nulls remote push_down=1 lazy=1: 5 5 diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh new file mode 100755 index 000000000000..437d071ce5a5 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# A dictionary without entries referenced by the non-null values. +orc_check empty "$DATA/malformed_dictionary_empty.orc" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" \ + 'ORC dictionary index 0 at row 0 is out of range \[0, 0\)' + +# A valid empty dictionary of a column with only nulls. +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_nulls.orc" +trap 'rm -f "$FILE"' EXIT +$CLICKHOUSE_LOCAL -q "SELECT CAST(NULL, 'Nullable(String)') AS s FROM numbers(5) INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 1" +orc_check nulls "$FILE" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.reference b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference new file mode 100644 index 000000000000..1e94a8329c54 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference @@ -0,0 +1,32 @@ +compression_block local push_down=0 lazy=0: 1 10000 +compression_block local push_down=0 lazy=1: 1 10000 +compression_block local push_down=1 lazy=0: 1 10000 +compression_block local push_down=1 lazy=1: 1 10000 +compression_block remote push_down=0 lazy=0: 1 10000 +compression_block remote push_down=0 lazy=1: 1 10000 +compression_block remote push_down=1 lazy=0: 1 10000 +compression_block remote push_down=1 lazy=1: 1 10000 +dictionary_size local push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.sh b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh new file mode 100755 index 000000000000..bc5685ba3187 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The memory must be allocated by the size of the data, not by the sizes declared in the file. +LIMIT='max_memory_usage = 100000000' + +# The declared compression block size is 1 GiB, the chunks are small. The schema inference reads the compressed footer. +orc_check compression_block "$DATA/malformed_compression_block_1g.orc" '' "SELECT count(), sum(length(s)) FROM SOURCE" '' "$LIMIT" + +# The declared dictionary size is 2^32 - 1, the stream has a few entries. +orc_check dictionary_size "$DATA/malformed_dictionary_size_max.orc" 's Nullable(String)' "SELECT count(), sum(length(s)) FROM SOURCE" \ + 'Unexpected end of ORC stream column 1 kind 2' "$LIMIT" + +# The sizes stored in the snappy and zstd chunks are 1 GiB, the chunks have a few bytes. +orc_check snappy_chunk_size "$DATA/malformed_snappy_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'snappy-compressed chunk of ORC file decompresses to 1073741824 bytes' "$LIMIT" +orc_check zstd_chunk_size "$DATA/malformed_zstd_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'Malformed zstd-compressed data in ORC file' "$LIMIT" diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference new file mode 100644 index 000000000000..3c50f86ded0e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference @@ -0,0 +1,16 @@ +stripe local push_down=0 lazy=0: (INCORRECT_DATA) +stripe local push_down=0 lazy=1: (INCORRECT_DATA) +stripe local push_down=1 lazy=0: (INCORRECT_DATA) +stripe local push_down=1 lazy=1: (INCORRECT_DATA) +stripe remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe remote push_down=1 lazy=1: (INCORRECT_DATA) +stream local push_down=0 lazy=0: (INCORRECT_DATA) +stream local push_down=0 lazy=1: (INCORRECT_DATA) +stream local push_down=1 lazy=0: (INCORRECT_DATA) +stream local push_down=1 lazy=1: (INCORRECT_DATA) +stream remote push_down=0 lazy=0: (INCORRECT_DATA) +stream remote push_down=0 lazy=1: (INCORRECT_DATA) +stream remote push_down=1 lazy=0: (INCORRECT_DATA) +stream remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh new file mode 100755 index 000000000000..2d3b50f7f31e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The sum of the offset and the lengths of the stripe overflows `UInt64`. +orc_check stripe "$DATA/malformed_stripe_offset_overflow.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stripe information at stripe index 0' + +# The length of a stream of a column that is not read is 2^64 - 1, the offsets of the next streams wrap around. +orc_check stream "$DATA/malformed_stream_offset_overflow.orc" 'b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stream.*11.*18446744073709551615' diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference new file mode 100644 index 000000000000..1fafd3d526a4 --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference @@ -0,0 +1,32 @@ +row_groups local push_down=1 lazy=0: (INCORRECT_DATA) +row_groups local push_down=1 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=1: (INCORRECT_DATA) +row_groups local push_down=0 lazy=0: (INCORRECT_DATA) +row_groups local push_down=0 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=0 lazy=0: (INCORRECT_DATA) +patched_base local push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=1 lazy=0: (INCORRECT_DATA) +patched_base local push_down=1 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek local push_down=0 lazy=0: 1 +row_index_seek local push_down=0 lazy=1: 1 +row_index_seek local push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek local push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek remote push_down=0 lazy=0: 1 +row_index_seek remote push_down=0 lazy=1: 1 +row_index_seek remote push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_control local push_down=0 lazy=0: 1 +row_index_control local push_down=0 lazy=1: 1 +row_index_control local push_down=1 lazy=0: 1 +row_index_control local push_down=1 lazy=1: 1 +row_index_control remote push_down=0 lazy=0: 1 +row_index_control remote push_down=0 lazy=1: 1 +row_index_control remote push_down=1 lazy=0: 1 +row_index_control remote push_down=1 lazy=1: 1 diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh new file mode 100755 index 000000000000..163a644dea9f --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The stripe has 2^64 - 1 rows: rounding up the number of row groups overflows. +ORC_PUSH_DOWN_VALUES=1 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'The row index of ORC column 1 has 2 entries, less than the [0-9]+ row groups of stripe 0' +ORC_PUSH_DOWN_VALUES=0 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Unexpected end of ORC stream column 1 kind 1' + +# A PATCHED_BASE run whose last patch is a continuation (gap 255, patch 0). +orc_check patched_base "$DATA/malformed_patched_base_terminal_continuation.orc" 'x Int64' "SELECT count(), sum(x) FROM SOURCE" \ + 'Corrupt PATCHED_BASE encoded data in ORC stream column 1 kind 1 in stripe 0 \(unterminated gap\)' + +# A row index position beyond the end of the stream, and the same file with the valid position. +orc_check row_index_seek "$DATA/malformed_row_index_seek_past_stream.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Seek position 127 is beyond the end of ORC stream column 1 kind 1 in stripe 0 of size 3' +orc_check row_index_control "$DATA/row_index_seek_control.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference new file mode 100644 index 000000000000..bac3e0b9f016 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference @@ -0,0 +1,16 @@ +footer_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh new file mode 100755 index 000000000000..9c0fb713fb91 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The number of the repeated objects in the metadata is limited by the numbers of the columns and the stripes. +orc_check footer_statistics "$DATA/malformed_footer_too_many_statistics.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many column statistics in ORC footer: 13, the file has 3 columns' +orc_check stripe_statistics "$DATA/malformed_metadata_too_many_stripes.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many stripe statistics in ORC metadata, at most 1 expected' diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference new file mode 100644 index 000000000000..7f41d79fbe44 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference @@ -0,0 +1,21 @@ +t < fromUnixTimestamp64Nano(-500000001, 'UTC') +500 +500 0 499 +500 0 499 +t <= fromUnixTimestamp64Nano(-500000001, 'UTC') +600 +501 0 500 +501 0 500 +t = fromUnixTimestamp64Nano(-950000001, 'UTC') +100 +1 50 50 +1 50 50 +t = fromUnixTimestamp64Nano(-999500000, 'UTC') +1 +1 1 1 +1 1 1 +-2000000000 1 +-1 1 +-999500000 1 +-1500000 1 +1000000000 1 diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh new file mode 100755 index 000000000000..21a4b8bb4428 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Prints the number of rows that are not pruned, and the result with and without the filter pushdown. +function check() +{ + local condition=$1 + echo "$condition" + $CLICKHOUSE_LOCAL -q " + SELECT count() FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE indexHint($condition); + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition; + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition + SETTINGS input_format_orc_filter_push_down = 0" +} + +# The timestamps before the epoch with a negative sub-millisecond part, from -1.000000001 to -0.001000001 seconds, +# in row groups of 100 rows. Their statistics must allow the pruning. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano(toInt64(number) * 1000000 - 1000000001, 'UTC') AS t FROM numbers(1000) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 100" +check "t < fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t <= fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t = fromUnixTimestamp64Nano(-950000001, 'UTC')" + +# A timestamp in the millisecond after -1 second, in its own row group: the pruning must keep it. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano([-2000000000, -999500000, -500000000][number + 1], 'UTC') AS t FROM numbers(3) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 1" +check "t = fromUnixTimestamp64Nano(-999500000, 'UTC')" + +# A file from PyArrow (the C++ writer of ORC) with a bloom filter, which rounds the negative milliseconds toward zero, +# and one row in each row group: the bloom filter must keep the matching rows. +for value in -2000000000 -1 -999500000 -1500000 1000000000; do + $CLICKHOUSE_LOCAL -q " + SELECT $value, count() FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc', 'ORC', 't Nullable(DateTime64(9))') + WHERE t = fromUnixTimestamp64Nano($value)" +done diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.reference b/tests/queries/0_stateless/05515_orc_nullable_floats.reference new file mode 100644 index 000000000000..4aae050a32fc --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.reference @@ -0,0 +1,2 @@ +1 +1086 1410 5000 10000 0 diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.sh b/tests/queries/0_stateless/05515_orc_nullable_floats.sh new file mode 100755 index 000000000000..c7eba0810a43 --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Nullable floats with different patterns of nulls, and special values, at the top level and nested. +QUERY=" + SELECT + number, + multiIf(k = 0, NULL, k = 1, nan, k = 2, inf, k = 3, -inf, k = 4, -0., k = 5, toFloat32(1e-42), toFloat32(number) / 7)::Nullable(Float32) AS f32, + multiIf(k2 = 0, NULL, k2 = 1, nan, k2 = 2, -inf, k2 = 3, 5e-324, k2 = 4, -0., number / 3.)::Nullable(Float64) AS f64, + if(intDiv(number, 1000) % 2 = 0, NULL, number / 2.)::Nullable(Float64) AS runs, + NULL::Nullable(Float32) AS all_null, + (number * 1.5)::Nullable(Float64) AS no_null, + arrayMap(x -> if(x % 3 = 0, NULL, toFloat32(x) / 4), range(number % 5))::Array(Nullable(Float32)) AS arr + FROM (SELECT number, cityHash64(number) % 9 AS k, cityHash64(number, 1) % 7 AS k2 FROM numbers(10000))" +STRUCTURE='number UInt64, f32 Nullable(Float32), f64 Nullable(Float64), runs Nullable(Float64), all_null Nullable(Float32), no_null Nullable(Float64), arr Array(Nullable(Float32))' +DIGEST="sum(cityHash64(number, isNull(f32), reinterpretAsUInt32(ifNull(f32, 0)), isNull(f64), reinterpretAsUInt64(ifNull(f64, 0)), + isNull(runs), ifNull(runs, 0), isNull(all_null), no_null, arrayMap(x -> (isNull(x), reinterpretAsUInt32(ifNull(x, 0))), arr)))" + +$CLICKHOUSE_LOCAL -q "$QUERY INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q " + SELECT (SELECT $DIGEST FROM ($QUERY)) = (SELECT $DIGEST FROM file('$FILE', 'ORC', '$STRUCTURE')); + SELECT countIf(f32 IS NULL), countIf(f64 IS NULL), countIf(runs IS NULL), countIf(all_null IS NULL), countIf(no_null IS NULL) FROM file('$FILE', 'ORC', '$STRUCTURE')" diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference new file mode 100644 index 000000000000..36b34a909261 --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference @@ -0,0 +1,6 @@ +restore is waiting 1 +alter succeeded +restore finished +x +y +0 diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh new file mode 100755 index 000000000000..4083ae7715ff --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# `SYSTEM RESTORE DATABASE REPLICA` waits for the initial DDL queries that the DDL worker has already admitted. +# An `ALTER` of a `ReplicatedMergeTree` table with `alter_sync = 1` waits until the table executes its +# `ALTER_METADATA` entry, which requires an active DDL worker of the database (`canExecuteReplicatedMetadataAlter`). +# The restore must not stop the worker before such a query finishes, otherwise both queries wait for each other. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = ReplicatedMergeTree ORDER BY x" + +# Hold the initial `ALTER` after the DDL worker has admitted it, before it executes. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --alter_sync 1 --distributed_ddl_output_mode=none --query "ALTER TABLE ${DB}.t ADD COLUMN y UInt64" & +alter_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore has to wait for the paused `ALTER`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +# The `ALTER` finishes, including the wait for its `ALTER_METADATA` entry, and then the restore proceeds. +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $alter_pid && echo "alter succeeded" +# The replica is not lost (its digest is not empty), so the restore may refuse with `REPLICA_ALREADY_EXISTS`; +# either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "SELECT name FROM system.columns WHERE database = '${DB}' AND table = 't' ORDER BY name" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference new file mode 100644 index 000000000000..4e3dc3cd1a09 --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference @@ -0,0 +1 @@ +4800 552844800 24 diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh new file mode 100755 index 000000000000..b33d61ad599f --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires the Parquet format (USE_PARQUET build option) + +# Every Parquet writer had its own pool of `max_threads` encoder threads, so many open writers with `max_threads = 32` +# did not fit in a 500-thread global pool: the 24 partitions of one stream. +# https://github.com/ClickHouse/ClickHouse/issues/129864 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 48); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 48); do printf ', number * %d' "$i"; done) +SETTINGS="SET max_threads = 32, + output_format_parquet_parallel_encoding = 1, output_format_parquet_row_group_size = 200, + max_block_size = 1000, min_insert_block_size_rows = 1000, min_insert_block_size_bytes = 0" + +# Small row groups make every writer encode while the INSERT runs, not only when its file is finalized. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}, max_insert_threads = 1; + INSERT INTO FUNCTION file('${TABLE_DIR}/file/{_partition_id}.parquet', 'Parquet', 'p UInt8 ${COLS}') PARTITION BY p + SELECT number % 24 ${EXPRS} FROM numbers(4800); + SELECT count(), sum(c48), uniqExact(_path) FROM file('${TABLE_DIR}/file/*.parquet'); +" -- --max_thread_pool_size=500 --thread_pool_queue_size=500 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference new file mode 100644 index 000000000000..ec1c393fef3a --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference @@ -0,0 +1,3 @@ +1 +1 +still alive diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql new file mode 100644 index 000000000000..36af86696314 --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql @@ -0,0 +1,28 @@ +-- A deserialized `groupArraySample` state may carry an arbitrary `total_values` counter. +-- Merging must not wrap it around to zero, which led to a division by zero. + +-- Valid states merge fine. +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')])); +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')])); + +-- total_values = UINT64_MAX, merged with a state with one value. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('010141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +-- Both states have more values than the sample size, and their counters sum to 2^64. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +SELECT 'still alive'; diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.reference b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference new file mode 100644 index 000000000000..d509bf4d85ea --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference @@ -0,0 +1,21 @@ +Mechanisms that take the credentials from the server, and a client certificate file +refused +refused +refused +refused +refused +refused +refused +refused +Credentials in the connection string +connects +connects +connects +A MongoDB table is checked when it is read +refused +refused +So is a table created with CREATE TABLE ... AS mongodb(...) +x UInt8 +refused +And the table function with a named collection +refused diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.sh b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh new file mode 100755 index 000000000000..e563e94de006 --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB table function and table engine need USE_MONGODB + +# A query that reads with the `mongodb` table function or from a `MongoDB` table is refused with `ACCESS_DENIED` if the +# connection string makes the server authenticate with credentials of the server process. Nothing listens on +# 127.0.0.1:1, so a query that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +NC="nc_05567_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +check() +{ + $CLICKHOUSE_CLIENT -q "$1" 2>&1 | classify +} + +read_uri() +{ + check "SELECT count() FROM mongodb('mongodb://${HOST}/db?${TIMEOUTS}&$1', 'c', 'x UInt8')" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP TABLE IF EXISTS t_engine; + DROP TABLE IF EXISTS t_as_function; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Mechanisms that take the credentials from the server, and a client certificate file' +read_uri 'authMechanism=MONGODB-OIDC' +read_uri 'authmechanism=mongodb-oidc&authMechanismProperties=ENVIRONMENT:test' +read_uri 'authMechanism=MONGODB-AWS' +read_uri 'authMechanism=MONGODB-X509' +check "SELECT count() FROM mongodb('mongodb://user@${HOST}/db?${TIMEOUTS}&authMechanism=GSSAPI', 'c', 'x UInt8')" +read_uri 'tls=true&tlsCertificateKeyFile=/nonexistent.pem' +read_uri 'ssl=true&sslClientCertificateKeyFile=/nonexistent.pem' +check "SELECT count() FROM mongodb('${HOST}', 'db', 'c', '', '', 'x UInt8', '${TIMEOUTS}&authMechanism=MONGODB-OIDC')" + +echo 'Credentials in the connection string' +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=plain', 'c', 'x UInt8')" + + +echo 'A MongoDB table is checked when it is read' +$CLICKHOUSE_CLIENT -q "CREATE TABLE t_engine (x UInt8) ENGINE = MongoDB('${OIDC_URI}', 'c')" +check "SELECT count() FROM t_engine" +$CLICKHOUSE_CLIENT -m -q "DETACH TABLE t_engine; ATTACH TABLE t_engine;" +check "SELECT count() FROM t_engine" + +echo 'So is a table created with CREATE TABLE ... AS mongodb(...)' +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE t_as_function AS mongodb('${OIDC_URI}', 'c', 'x UInt8'); + DETACH TABLE t_as_function; + ATTACH TABLE t_as_function; + DESCRIBE t_as_function SETTINGS describe_compact_output = 1; +" +check "SELECT count() FROM t_as_function" + +echo 'And the table function with a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS uri = '${OIDC_URI}', collection = 'c', structure = 'x UInt8'" +check "SELECT count() FROM mongodb(${NC})" diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference new file mode 100644 index 000000000000..f0b81f6f43ed --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference @@ -0,0 +1,12 @@ +Refused +refused +refused +Credentials in the connection string +connects +The options that a dictionary adds to a named collection +refused +A named collection that changes after the dictionary is created +connects +refused +clickhouse-local is not restricted +connects diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh new file mode 100755 index 000000000000..354ecf0acbb7 --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB dictionary source needs USE_MONGODB + +# A MongoDB dictionary created with a DDL query may never make the server authenticate with credentials of the server +# process: the source is built when the server loads the dictionary, also after the named collection it refers to +# has changed. The dictionaries are loaded by `dictGet`. +# Nothing listens on 127.0.0.1:1, so a dictionary that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +SCRAM_URI="mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256" +NC="nc_05568_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +# Runs the queries $1. +check() +{ + $CLICKHOUSE_CLIENT -m -q "$1" 2>&1 | classify +} + +# Creates the dictionary $1 with the source $2 and prints whether reading it is refused. +check_source() +{ + $CLICKHOUSE_CLIENT -q "CREATE DICTIONARY $1 (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB($2 COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" + check "SELECT dictGet('$1', 'v', tuple('k'))" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP DICTIONARY IF EXISTS d_uri; + DROP DICTIONARY IF EXISTS d_options; + DROP DICTIONARY IF EXISTS d_scram; + DROP DICTIONARY IF EXISTS d_named_options; + DROP DICTIONARY IF EXISTS d_named_altered; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Refused' +check_source d_uri "URI '${OIDC_URI}'" +check_source d_options "HOST '127.0.0.1' PORT 1 DB 'db' USER '' PASSWORD '' OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" + +echo 'Credentials in the connection string' +check_source d_scram "URI '${SCRAM_URI}'" + +echo 'The options that a dictionary adds to a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS host = '127.0.0.1', port = '1', db = 'db', user = '', password = ''" +check_source d_named_options "NAME ${NC} OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +$CLICKHOUSE_CLIENT -q "DROP DICTIONARY d_named_options" + +echo 'A named collection that changes after the dictionary is created' +$CLICKHOUSE_CLIENT -q "CREATE DICTIONARY d_named_altered (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB(NAME ${NC} COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" +check "SELECT dictGet('d_named_altered', 'v', tuple('k'))" +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${NC} SET options = '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +check "SYSTEM RELOAD DICTIONARY d_named_altered; SELECT dictGet('d_named_altered', 'v', tuple('k'))" + +echo 'clickhouse-local is not restricted' +$CLICKHOUSE_LOCAL -m -q " + CREATE DICTIONARY d (_id String, v String) PRIMARY KEY _id + SOURCE(MONGODB(URI '${OIDC_URI}' COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT()); + SELECT dictGet('d', 'v', tuple('k')); +" 2>&1 | classify diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference new file mode 100644 index 000000000000..338bce460b79 --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference @@ -0,0 +1,18 @@ +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `l` from type Array(String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `s` from type Tuple(value String) to type Map(String, String) +Code: 53 while converting column `s` from type Tuple(value String) to type Array(String) +Code: 53 while converting column `lm` from type Array(Map(String, String)) to type Array(Tuple(value String)) +Code: 53 while converting column `sl` from type Tuple(a Array(String)) to type Tuple(a Map(String, String)) +2 {\'key\':\'profile\'} +2 [('key','profile')] +2 {'k':'(\'v\')'} +['(\'v\')'] +2 {'key':'profile'} ['profile'] ('profile') {'k':('v')} [{'k':'v'}] (['x']) +('profile',0) +2 +Code: 53 while converting column `m` from type Map(LowCardinality(String), LowCardinality(Nullable(String))) to type Tuple(value Nullable(String)) +Code: 53 while converting column `lm` from type Array(Map(LowCardinality(String), LowCardinality(Nullable(String)))) to type Array(Tuple(value String)) +{\'key\':\'profile\'} +{'key':'profile'} [{'k':'v'}] diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh new file mode 100755 index 000000000000..f503b6d888fa --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +# An ORC list, map or struct requested as a type of another kind is cast to it, not read as default values. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Prints the error code and the conversion of a query that has to fail. +function error() +{ + $CLICKHOUSE_LOCAL -q "$1" 2>&1 | tr '\n' ' ' | grep -o -E 'Code: [0-9]+|while converting column [^:]* to type [^:]*' | head -n 2 | paste -sd ' ' +} + +FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +$CLICKHOUSE_LOCAL -q "SELECT 2::Int64 AS id, map('key', 'profile') AS m, ['profile'] AS l, + CAST(tuple('profile'), 'Tuple(value String)') AS s, map('k', CAST(tuple('v'), 'Tuple(value String)')) AS ms, + [map('k', 'v')] AS lm, CAST(tuple(['x']), 'Tuple(a Array(String))') AS sl FORMAT ORC" > "$FILE" +F="file('$FILE', ORC" + +# Conversions the cast cannot do. +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))') SETTINGS input_format_orc_allow_missing_columns = 0" +error "SELECT * FROM $F, 'id Int64, l Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, s Map(String, String)')" +error "SELECT * FROM $F, 'id Int64, s Array(String)')" +error "SELECT * FROM $F, 'id Int64, lm Array(Tuple(value String))')" +error "SELECT * FROM $F, 'id Int64, sl Tuple(a Map(String, String))')" + +# Conversions the cast does, also of a map value. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m String')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Array(Tuple(String, String))')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, ms Map(String, String)')" +$CLICKHOUSE_LOCAL -q "SELECT ms.values FROM $F, 'id Int64, ms Map(String, String)')" + +# Matching kinds, a Tuple naming only some of the fields, and the other columns of a mismatched structure. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Map(String, String), l Array(String), s Tuple(value String), + ms Map(String, Tuple(value String)), lm Array(Map(String, String)), sl Tuple(a Array(String))')" +$CLICKHOUSE_LOCAL -q "SELECT s FROM $F, 's Tuple(value String, other Int32)')" +$CLICKHOUSE_LOCAL -q "SELECT id FROM $F, 'id Int64, m Tuple(value Nullable(String))')" + +DICT_FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}_dict.orc" +$CLICKHOUSE_LOCAL --output_format_orc_dictionary_key_size_threshold=1 -q "SELECT map('key', 'profile') AS m, [map('k', 'v')] AS lm FORMAT ORC" > "$DICT_FILE" +D="file('$DICT_FILE', ORC" +S="SETTINGS input_format_orc_dictionary_as_low_cardinality = 1" + +# A dictionary-encoded map key. +error "SELECT * FROM $D, 'm Tuple(value Nullable(String))') $S" +error "SELECT * FROM $D, 'lm Array(Tuple(value String))') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm String') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm Map(String, String), lm Array(Map(String, String))') $S" + +rm -f "$FILE" +rm -f "$DICT_FILE" diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference new file mode 100644 index 000000000000..d0fcfd538e17 --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference @@ -0,0 +1,6 @@ +MEMORY_LIMIT_EXCEEDED +PrettyCompactMonoBlock 241 +MEMORY_LIMIT_EXCEEDED +PrettyCompact 241 +MEMORY_LIMIT_EXCEEDED +JSONColumns 241 diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh new file mode 100755 index 000000000000..551f08b3f82c --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Every stored block is larger than the memory limit, so the format that accumulates the result fails to copy it +# when the next block arrives: the query must fail with an error, not crash. +for format in PrettyCompactMonoBlock PrettyCompact JSONColumns; do + $CLICKHOUSE_LOCAL --query " + CREATE TABLE t (x UInt64) ENGINE = Memory; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + SELECT * FROM t FORMAT $format SETTINGS max_threads = 1, max_memory_usage = '20Mi', + output_format_pretty_squash_consecutive_ms = 1000000, output_format_pretty_squash_max_wait_ms = 1000000; + " 2>&1 >/dev/null | grep -o -m1 'MEMORY_LIMIT_EXCEEDED' | head -n1 + echo "$format ${PIPESTATUS[0]}" +done diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference new file mode 100644 index 000000000000..8e054e883dc4 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference @@ -0,0 +1,9 @@ +1900-05-31 16:00:00 +1900-07-06 03:13:13 +1949-12-31 16:00:00 +1900-06-01 08:00:00 +1900-06-01 00:36:45 +1960-01-15 00:00:00 +0 1900-06-01 08:00:00.000000000 +1 1900-06-01 08:00:00.000000000 +1900-06-01 08:00:00.000000000 diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh new file mode 100755 index 000000000000..61cb9f7a7221 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no ORC format + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Before the first transition of a time zone, the wall clock is kept with the oldest standard offset +# (Asia/Shanghai +08:00 until 1901), not with the local mean time, as in other ORC readers. +# `DateTime64` starts at 1900 on this branch. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q " + SELECT arrayJoin([toDateTime64('1900-06-01 00:00:00', 0, 'UTC'), toDateTime64('1900-07-06 11:13:13', 0, 'UTC'), toDateTime64('1950-01-01 00:00:00', 0, 'UTC')]) AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Asia/Shanghai'" + +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# Europe/Lisbon starts with a no-op transition record in 1884 that keeps the local mean time (-00:36:45). +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Europe/Lisbon'" + +# Europe/London had +01:00 in 1970 and +00:00 in 1960, a lower offset before the epoch must not shift the day. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1960-01-15 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Europe/London'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# The timestamp statistics must agree with the values that are read, or the filter pushdown drops the row. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 9, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +for push_down in 0 1; do + $CLICKHOUSE_LOCAL -q " + SELECT $push_down, ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') + WHERE ts = toDateTime64('1900-06-01 08:00:00', 9, 'UTC') SETTINGS input_format_orc_filter_push_down = $push_down" +done + +# A time zone that `DateLUT` loads without an embedded file. +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'libc:UTC'" + +rm -f "$FILE" diff --git a/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference new file mode 100644 index 000000000000..1f7e29a97d9d --- /dev/null +++ b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference @@ -0,0 +1,153 @@ +-- { echo } + +SET engine_file_truncate_on_insert = 1; +SET allow_experimental_nullable_tuple_type = 1; +INSERT INTO FUNCTION file(currentDatabase() || '_05617.orc', 'ORC') SELECT + number AS id, + if(number = 0, [(1, 'a'), (2, 'b')], [])::Array(Tuple(a Int32, b String)) AS l, + if(number = 0, map('k1', (1, 'a'), 'k2', (2, 'b')), map())::Map(String, Tuple(a Int32, b String)) AS m, + map(CAST(tuple(toInt32(number)), 'Tuple(a Int32)'), 'v') AS mk, + CAST((toInt32(number), [(toInt32(number), 'x')]), 'Tuple(a Int32, l Array(Tuple(x Int32, y String)))') AS t, + [[(toInt32(number), 'x'), (1, 'y')]]::Array(Array(Tuple(a Int32, b String))) AS ll, + map('k', [(toInt32(number), 'x')])::Map(String, Array(Tuple(a Int32, b String))) AS ml, + if(number = 0, [(1, 'a'), NULL, (2, 'b')], [])::Array(Nullable(Tuple(a Int32, b String))) AS ln, + [(toInt32(number), 'c')]::Array(Tuple(A Int32, b String)) AS lc, + CAST((toInt32(number), map('k', (1, 'v'))), 'Tuple(a Int32, m Map(String, Tuple(a Int32, b String)))') AS tm, + [(1, tuple(2)), (3, tuple(4))]::Array(Tuple(x Int32, z Tuple(w Int32))) AS n, + [(1, [(1, 'a'), (2, 'b')])]::Array(Tuple(y Int32, x Array(Tuple(a Int32, b String)))) AS lx, + if(number = 0, [tuple(tuple(1)), tuple(NULL)], [tuple(NULL)])::Array(Tuple(b Nullable(Tuple(a Int32)))) AS nb, + map('k', (if(number = 0, tuple(1), NULL), if(number = 0, NULL, tuple('x'))))::Map(String, Tuple(b Nullable(Tuple(a Int32)), c Nullable(Tuple(x String)))) AS mb, + CAST((toInt32(number), [tuple(if(number = 0, tuple(1), NULL))]), 'Tuple(a Int32, l Array(Tuple(b Nullable(Tuple(a Int32)))))') AS tb, + if(number = 0, tuple(1, 'a'), NULL)::Nullable(Tuple(a Int32, b String)) AS ts, + [CAST(tuple(toDateTime64('3000-01-01 00:00:00', 0, 'UTC')), 'Tuple(a DateTime64(0, \'UTC\'))')] AS ld, + CAST([tuple(11, tuple(5))], 'Array(Tuple(w Int32, x Tuple(v Int32)))') AS an +FROM numbers(2); +-- A list element, a map value and a map key, also nested in a struct, a list or a map, and with NULL elements. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [(NULL),(NULL)] +1 [] +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(q Nullable(String)))') ORDER BY id; +0 {'k1':(NULL),'k2':(NULL)} +1 {} +SELECT id, mk FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mk Map(Tuple(z Nullable(Int32)), String)') ORDER BY id; +0 {(NULL):'v'} +1 {(NULL):'v'} +SELECT id, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(a Int32, l Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 (0,[(NULL)]) +1 (1,[(NULL)]) +SELECT id, ll FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ll Array(Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 [[(NULL),(NULL)]] +1 [[(NULL),(NULL)]] +SELECT id, ml FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ml Map(String, Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 {'k':[(NULL)]} +1 {'k':[(NULL)]} +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Array(Nullable(Tuple(q Nullable(Int32))))') ORDER BY id; +0 [(NULL),NULL,(NULL)] +1 [] +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id SETTINGS input_format_orc_row_batch_size = 1; +0 [(NULL),(NULL)] +1 [] +-- The same through a subcolumn of a struct and a subcolumn of a Nested column. +SELECT id, `t.a`, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.a` Int32, `t.l` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 0 [(NULL)] +1 1 [(NULL)] +SELECT id, `tm.m` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tm.m` Map(String, Tuple(q Nullable(String)))') ORDER BY id; +0 {'k':(NULL)} +1 {'k':(NULL)} +SELECT id, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [(NULL),(NULL)] +1 [(NULL),(NULL)] +SELECT id, `n.x`, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.x` Array(Int32), `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [1,3] [(NULL),(NULL)] +1 [1,3] [(NULL),(NULL)] +-- A struct that contains such a list is read with its fields. +SELECT id, lx FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lx Array(Tuple(x Array(Tuple(q Nullable(Int32)))))') ORDER BY id; +0 [([(NULL),(NULL)])] +1 [([(NULL),(NULL)])] +-- A struct read whole by another column keeps its data. optimize_functions_to_subcolumns = 0 keeps `t.l` itself in the read. +SELECT id, t, length(`t.l`) FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t String, `t.l` Array(Tuple(q String, r String))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 (0,[(0,\'x\')]) 1 +1 (1,[(1,\'x\')]) 1 +-- A Tuple naming some of the fields, and case-insensitive matching. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Nullable(Int32)))') ORDER BY id; +0 [(1,NULL),(2,NULL)] +1 [] +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(a Int32, q Nullable(String)))') ORDER BY id; +0 {'k1':(1,NULL),'k2':(2,NULL)} +1 {} +SELECT id, lc FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lc Array(Tuple(a Int32))') ORDER BY id SETTINGS input_format_orc_case_insensitive_column_matching = 1; +0 [(0)] +1 [(1)] +-- A non-nullable Date32 field gets the same default with and without a field that is in the file, an Enum gets its first value. +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Date32, e Enum8(\'x\' = 1, \'y\' = 2))), m Map(String, Tuple(q Date32))') ORDER BY id; +0 [('1970-01-01','x'),('1970-01-01','x')] {'k1':('1970-01-01'),'k2':('1970-01-01')} +1 [] {} +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Date32)), m Map(String, Tuple(a Int32, q Date32))') ORDER BY id; +0 [(1,'1970-01-01'),(2,'1970-01-01')] {'k1':(1,'1970-01-01'),'k2':(2,'1970-01-01')} +1 [] {} +-- A requested struct field of such a struct keeps its presence, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id; +0 [((0)),(NULL)] +1 [(NULL)] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(a Nullable(Int32), q Int32))))') ORDER BY id; +0 [((1,0)),(NULL)] +1 [(NULL)] +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(q Int32)), b Nullable(Tuple(r String))))') ORDER BY id; +0 {'k':(NULL,(''))} +1 {'k':((0),NULL)} +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(x Nullable(String), q Int32)), b Nullable(Tuple(a Nullable(Int32), r String))))') ORDER BY id; +0 {'k':(NULL,(1,''))} +1 {'k':(('x',0),NULL)} +-- A NULL struct requested as non-Nullable is rejected or read as default, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +0 [((0)),((0))] +1 [((0))] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +0 [((1,0)),((NULL,0))] +1 [((NULL,0))] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +-- Two columns reading the same struct with different types get the defaults of their own type. +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(q Nullable(Int32)))), `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) [(NULL,NULL)] +1 ([(NULL)]) [(NULL,NULL)] +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(e Enum8(\'x\' = 1)))), `t.l` Array(Tuple(r Nullable(String)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([('x')]) [(NULL)] +1 ([('x')]) [(NULL)] +SELECT id, `t.l`, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32))), t Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 [(NULL,NULL)] ([(NULL)]) +1 [(NULL,NULL)] ([(NULL)]) +-- Of two columns reading the same struct, one that requests a nested struct of it keeps that struct's presence. +SELECT id, tb, `tb.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.l` Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) [((0))] +1 ([(NULL)]) [(NULL)] +SELECT id, `tb.l`, tb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tb.l` Array(Tuple(b Nullable(Tuple(q Int32)))), tb Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 [((0))] ([(NULL)]) +1 [(NULL)] ([(NULL)]) +SELECT id, tb, `tb.a` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.a` Int32') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) 0 +1 ([(NULL)]) 1 +-- A top-level struct keeps its presence too, also when missing columns are not allowed. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id; +0 (0) +1 \N +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id SETTINGS input_format_orc_allow_missing_columns = 0; +0 (0) +1 \N +-- A field read only for the size of its struct is not converted. +SELECT id, ld FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ld Array(Tuple(q Int32))') ORDER BY id; +0 [(0)] +1 [(0)] +-- An unnamed Tuple is matched by position and must have as many elements as the struct. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +-- The same for a Nested column that is not flattened. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Nested(q Int32)') ORDER BY id SETTINGS flatten_nested = 0; +0 [(0),(0)] +1 [] +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +0 [(NULL),(NULL),(NULL)] +1 [] +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(a Nullable(Int32), q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +0 [(1,NULL),(NULL,NULL),(2,NULL)] +1 [] diff --git a/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql new file mode 100644 index 000000000000..c0092342d918 --- /dev/null +++ b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql @@ -0,0 +1,99 @@ +-- Tags: no-fasttest +-- no-fasttest: ORC is not available in fasttest builds +-- An ORC list or map whose element, key or value struct has none of the fields of the requested Tuple keeps its +-- elements, and each of them is filled with default values. + +-- { echo } + +SET engine_file_truncate_on_insert = 1; +SET allow_experimental_nullable_tuple_type = 1; + +INSERT INTO FUNCTION file(currentDatabase() || '_05617.orc', 'ORC') SELECT + number AS id, + if(number = 0, [(1, 'a'), (2, 'b')], [])::Array(Tuple(a Int32, b String)) AS l, + if(number = 0, map('k1', (1, 'a'), 'k2', (2, 'b')), map())::Map(String, Tuple(a Int32, b String)) AS m, + map(CAST(tuple(toInt32(number)), 'Tuple(a Int32)'), 'v') AS mk, + CAST((toInt32(number), [(toInt32(number), 'x')]), 'Tuple(a Int32, l Array(Tuple(x Int32, y String)))') AS t, + [[(toInt32(number), 'x'), (1, 'y')]]::Array(Array(Tuple(a Int32, b String))) AS ll, + map('k', [(toInt32(number), 'x')])::Map(String, Array(Tuple(a Int32, b String))) AS ml, + if(number = 0, [(1, 'a'), NULL, (2, 'b')], [])::Array(Nullable(Tuple(a Int32, b String))) AS ln, + [(toInt32(number), 'c')]::Array(Tuple(A Int32, b String)) AS lc, + CAST((toInt32(number), map('k', (1, 'v'))), 'Tuple(a Int32, m Map(String, Tuple(a Int32, b String)))') AS tm, + [(1, tuple(2)), (3, tuple(4))]::Array(Tuple(x Int32, z Tuple(w Int32))) AS n, + [(1, [(1, 'a'), (2, 'b')])]::Array(Tuple(y Int32, x Array(Tuple(a Int32, b String)))) AS lx, + if(number = 0, [tuple(tuple(1)), tuple(NULL)], [tuple(NULL)])::Array(Tuple(b Nullable(Tuple(a Int32)))) AS nb, + map('k', (if(number = 0, tuple(1), NULL), if(number = 0, NULL, tuple('x'))))::Map(String, Tuple(b Nullable(Tuple(a Int32)), c Nullable(Tuple(x String)))) AS mb, + CAST((toInt32(number), [tuple(if(number = 0, tuple(1), NULL))]), 'Tuple(a Int32, l Array(Tuple(b Nullable(Tuple(a Int32)))))') AS tb, + if(number = 0, tuple(1, 'a'), NULL)::Nullable(Tuple(a Int32, b String)) AS ts, + [CAST(tuple(toDateTime64('3000-01-01 00:00:00', 0, 'UTC')), 'Tuple(a DateTime64(0, \'UTC\'))')] AS ld, + CAST([tuple(11, tuple(5))], 'Array(Tuple(w Int32, x Tuple(v Int32)))') AS an +FROM numbers(2); + +-- A list element, a map value and a map key, also nested in a struct, a list or a map, and with NULL elements. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(q Nullable(String)))') ORDER BY id; +SELECT id, mk FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mk Map(Tuple(z Nullable(Int32)), String)') ORDER BY id; +SELECT id, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(a Int32, l Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ll FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ll Array(Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ml FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ml Map(String, Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Array(Nullable(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id SETTINGS input_format_orc_row_batch_size = 1; + +-- The same through a subcolumn of a struct and a subcolumn of a Nested column. +SELECT id, `t.a`, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.a` Int32, `t.l` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, `tm.m` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tm.m` Map(String, Tuple(q Nullable(String)))') ORDER BY id; +SELECT id, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, `n.x`, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.x` Array(Int32), `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; + +-- A struct that contains such a list is read with its fields. +SELECT id, lx FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lx Array(Tuple(x Array(Tuple(q Nullable(Int32)))))') ORDER BY id; + +-- A struct read whole by another column keeps its data. optimize_functions_to_subcolumns = 0 keeps `t.l` itself in the read. +SELECT id, t, length(`t.l`) FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t String, `t.l` Array(Tuple(q String, r String))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- A Tuple naming some of the fields, and case-insensitive matching. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Nullable(Int32)))') ORDER BY id; +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(a Int32, q Nullable(String)))') ORDER BY id; +SELECT id, lc FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lc Array(Tuple(a Int32))') ORDER BY id SETTINGS input_format_orc_case_insensitive_column_matching = 1; + +-- A non-nullable Date32 field gets the same default with and without a field that is in the file, an Enum gets its first value. +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Date32, e Enum8(\'x\' = 1, \'y\' = 2))), m Map(String, Tuple(q Date32))') ORDER BY id; +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Date32)), m Map(String, Tuple(a Int32, q Date32))') ORDER BY id; + +-- A requested struct field of such a struct keeps its presence, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(a Nullable(Int32), q Int32))))') ORDER BY id; +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(q Int32)), b Nullable(Tuple(r String))))') ORDER BY id; +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(x Nullable(String), q Int32)), b Nullable(Tuple(a Nullable(Int32), r String))))') ORDER BY id; + +-- A NULL struct requested as non-Nullable is rejected or read as default, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } + +-- Two columns reading the same struct with different types get the defaults of their own type. +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(q Nullable(Int32)))), `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(e Enum8(\'x\' = 1)))), `t.l` Array(Tuple(r Nullable(String)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, `t.l`, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32))), t Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- Of two columns reading the same struct, one that requests a nested struct of it keeps that struct's presence. +SELECT id, tb, `tb.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.l` Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, `tb.l`, tb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tb.l` Array(Tuple(b Nullable(Tuple(q Int32)))), tb Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, tb, `tb.a` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.a` Int32') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- A top-level struct keeps its presence too, also when missing columns are not allowed. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id; +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id SETTINGS input_format_orc_allow_missing_columns = 0; + +-- A field read only for the size of its struct is not converted. +SELECT id, ld FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ld Array(Tuple(q Int32))') ORDER BY id; + +-- An unnamed Tuple is matched by position and must have as many elements as the struct. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } + +-- The same for a Nested column that is not flattened. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Nested(q Int32)') ORDER BY id SETTINGS flatten_nested = 0; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(a Nullable(Int32), q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; diff --git a/tests/queries/0_stateless/05621_readonly_named_collection_ddl.reference b/tests/queries/0_stateless/05621_readonly_named_collection_ddl.reference new file mode 100644 index 000000000000..f5cee83fbf7a --- /dev/null +++ b/tests/queries/0_stateless/05621_readonly_named_collection_ddl.reference @@ -0,0 +1,13 @@ +--readonly 1 +READONLY +READONLY +READONLY +--readonly 2 +READONLY +READONLY +READONLY +--allow_ddl 0 +QUERY_IS_PROHIBITED +QUERY_IS_PROHIBITED +QUERY_IS_PROHIBITED +nc_existing diff --git a/tests/queries/0_stateless/05621_readonly_named_collection_ddl.sh b/tests/queries/0_stateless/05621_readonly_named_collection_ddl.sh new file mode 100755 index 000000000000..10e845dafb27 --- /dev/null +++ b/tests/queries/0_stateless/05621_readonly_named_collection_ddl.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Named collection DDL is rejected in readonly mode and with allow_ddl = 0, like other DDL. + +nc="nc_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT -q "DROP NAMED COLLECTION IF EXISTS ${nc}_existing" +$CLICKHOUSE_CLIENT -q "DROP NAMED COLLECTION IF EXISTS ${nc}_new" +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${nc}_existing AS key = 'value'" + +for setting in "--readonly 1" "--readonly 2" "--allow_ddl 0"; do + echo "$setting" + $CLICKHOUSE_CLIENT $setting -q "CREATE NAMED COLLECTION ${nc}_new AS key = 'value'" 2>&1 | grep -o -m1 -E 'READONLY|QUERY_IS_PROHIBITED' + $CLICKHOUSE_CLIENT $setting -q "ALTER NAMED COLLECTION ${nc}_existing SET key = 'other'" 2>&1 | grep -o -m1 -E 'READONLY|QUERY_IS_PROHIBITED' + $CLICKHOUSE_CLIENT $setting -q "DROP NAMED COLLECTION ${nc}_existing" 2>&1 | grep -o -m1 -E 'READONLY|QUERY_IS_PROHIBITED' +done + +# Nothing was created or dropped. +$CLICKHOUSE_CLIENT -q "SELECT name FROM system.named_collections WHERE name LIKE '${nc}%' ORDER BY name" | sed "s/${nc}/nc/" + +$CLICKHOUSE_CLIENT -q "DROP NAMED COLLECTION ${nc}_existing" diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc new file mode 100644 index 0000000000000000000000000000000000000000..6c52f4f0f98b40dec581f1b02ec3936d34d62796 GIT binary patch literal 709 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo mQfoMv*fgJAnSmomfKj5Mfklalfk(r{fUW5ZGqZn?vp4|E0T8hO literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc new file mode 100644 index 0000000000000000000000000000000000000000..fc3ffef8f18c17dc95f532108f94846c6cb9b894 GIT binary patch literal 717 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo vQfoMv*fgI#S!njcc{ArNRAk^N5nz;PXkbxdV&Ks*F<@)@!p!U+JFZE-iyIBTGB(h%cBfX4BGjAJ&?Gn8U6&@(d& zz$y=vGO&;Wsxk>+P+(wKo$%nn**QlR@+j>TaZurBkYr%+<23NG2w({jkqGi}XJ9z6 zYbW!qRlXhHI#@oOiG6Td^2pN_EKS$M7W4_Nc>Rj~#nl5W{0t0koK8+IN-kjSYyv`D ze0)qod?H{j6B7>yAC~|R3qu>wgGrAQgcBw_c*b{mZuY+kFmEzQ>GXvtHD{W zWs;4rS`L~_X0e}<#`Zdy^-@fN9e2o_(5Co~&Su7rnHMtH82$lGnRVvG(L)DC4;)ZE zeNa{9)WwY{H(#^4HOd*NetdLvKd-FANsdH4L0}-t>A5j0stGG=rYRQ(FVL``E)@{c z*M0ZIflEH;k2rN4K6K*36_4{*Ji0C)IdSR0m4Neim{y!?@a9?3$G>FuO^5RVT}K_x zpW#^}ug521v|$3%saXw27$-3@JWde%aZ=^z*@HR-4S|as4*E8Gdp0$@cTAnwIkPpi z%P_FZ(6h@hvdhr5%P_RFv)Q$?x7ok>cmtzPw}gS?Pk~t{8%{Qy?rLq;ZaC;Qt=ZdS z%Hrgco38WrFxe(}Jv!Q5FKyK@N$^mZl1z-7O-v7)laHEP&>6R9%Nzphv`rVRkP+WK zv2p3ld7Z5S?X43RuADe;;?|1sEk78U&P>8TXu+-id_MC9Fa-<` z?lW*QFhnuTafo1Gc%1Y&K{#Q;gJ(<^dxYv@a%6g#dW4FAv=5MebWNDr~+4;VnvT^!awPNw&jholK~7@| z!qQ)f-`+hkxUucGmEX^Ib+-3k9pAk34oO3dhvpw=li&Ht=fd(`*2q-Zz@MuUHur+;QX7&$q76$-W;u-w_ literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc b/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc new file mode 100644 index 0000000000000000000000000000000000000000..27d3a7a5694c836382a434b145463145bc7e4969 GIT binary patch literal 174 zcmeYdaz2pEz)<19(7?sU!6?8e!2+b2fixqKW&+a8LQEVCLL5M`|3JVm#q91I!X?hd z!jTfdz{SszqQuF?SRuq%A#s8+fB~q=Sc(fsGDvVJXltY>ad7YmF)~Uq7ArAvup6XU xfwftoYja@mU`*n2&dE&9_Q)?SPUUb18qm-npv1($qakU)*7Sv$*+0lx8~}Ex9uxoo literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc b/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc new file mode 100644 index 0000000000000000000000000000000000000000..00ab37f164451f7d41fdd9918d3a60e6eb3fb9e1 GIT binary patch literal 353 zcmb7!55@c<-_od@Ma)J`I4HxfN+mPlz%p40|nh@xK=W-?pJwH%K)jX%p}<3F&Fh@rNx z?t8Y(IS+(X;JUy~Nt{KsDqAPB`oye0GaG+COmQR4^X~C!`ttU={aZS&{tbFtXANNv_gqUE3}AonBeEZn8f9rlbM|DkzZPz$`J=lJ`D{5 WN=ytq8jF|>*qXjDGy4ZQO8@|~r#gH9 literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc b/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc new file mode 100644 index 0000000000000000000000000000000000000000..43552b05c31d975806e7b28bf0348ac911b93320 GIT binary patch literal 83 zcmeYda_(bbf5@QqpMi^wgHeD{fZBafx-+D4Gk42F|jIl^(saf&@Ul}_i@Q96kobdi?g;4J`i%|p7O zHQHy4J^a)g0`Qj6YX%1aWcQxocSeo^^{~g%Xx3tINijrGbQqKXl}3-r5QS%EZ#Tnm$hsO_t_nvG%Tof%Rfa2K6BY3f#1KM=U?J&`Kze_YKPs*0 zx=Eu0j}P9!do!~|CB`MJ=O9i9z@@C6VX*Am!Mha&!ECV3S+H<8^mY#W1gIGH9|rxw zXpDOxF>EY&jzr&%B;N@{i#~~@xF<_qJ7Nf;voiJcyp((SJL0nbs+X1h!K@W3q*{Nxeoi)D+c$m>ztpwO3DRD- MFyFsQ%@$SX1Y@lyc>n+a literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc b/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc new file mode 100644 index 0000000000000000000000000000000000000000..ab57ba54f6cb5f35ce2f2225cedead3e3c24d9e6 GIT binary patch literal 238 zcmeYdaz4P>@V{v>Ba?moe+amFYzD)Ut4a(EH!q|}F!G&RDZuEwo9hH)g+~tq6u9SsRejxb{KXpyLT!00RfJK%^8GkYtdsQIOT(QsUs?5n^PNVk}W&;@~vk yvI3i7h1U!R1`oz0F6W%gPb;1ObElwvGVV&dR5V73CA xVnx6dhY5Zjj7eP1Iho1X9{HuksT|=zmo_vAC^0ecXlNL)HGN@b_78Fv2LL-3L?-|M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc b/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc new file mode 100644 index 0000000000000000000000000000000000000000..4f30ed6c7f1acfc4f1587ecd851ca828b38d2f80 GIT binary patch literal 38 scmeYda+Y9V(AcW~cL4(fg99T20|&nVt3(43uxKzeePL$y4{{a;0H`qt$^ZZW literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc b/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..ed3597a70455f3319174fea0ea64f41d446cd797 GIT binary patch literal 666 zcmaix&q~8U5XNU_lXYBHS=Webywo6)Qz;&EDiqX}}d=Fp4 ztKzsxN?H%yzWek=6A!rcN(PZ|1U)2|F+f zWWX+C!3O6Z=i#sQ%pmv^#{76&%5v;*uMLjcUdixCsKY(M%hOn5oHKSQO2pknd z7L|gHsv1oio`%E7btpyAVMwAg?1CC}C6^^LhR zwLh!Q)l7zn1(v%$tsAu28&>Xva+&X5G332>ELE}3))P`rPmei1_n?FU6wIoLEbn+y zx|=2Gzb@vjC2M*Is*1l}t*q0qxQr`v&RGZfszKyT&K0WWt$Db%~yI3Rzfh`{f M`sGWh$!rvU0o^4u?*IS* literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_union_type.orc b/tests/queries/0_stateless/data_orc/orc_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..08c73c83fd428e64b0f74df501b573b0d8eb7b8d GIT binary patch literal 398 zcmeYdau#G@;9?VE;b012kOnfjxtJLk7$AIYAYT~5=iy)!V&e!A2$2X0U@%}{cr5fh zDV2dy(T>kel~3;&m*O!l&Sea23@BQdfLfRYSR~j27}yyY{xL8DNk4`VAnCx+0JNq8 z$Z}&;X<=ZnJ$aD#fB^@y0~3eqm*!uaW)*I7+WlY4H&#<#{+Oh#SHY8X=RnpKi2>>P z+5D?QuKz1<{`|h<^6n{bLhf1XSHJtolmc|qrUyw66Sxu@CfUgJIOWJFGARlvIv655 zae|Z_pV|VQ$qd~r(G1KCFMyg7#4OHf96fqaXM&pI;s>h^E>SshQ2EG_6G}%Tw2sbL zd0@f8gaZqX96qRh@VGj1mnEEJ{oaJQ}73 NY)xO7nf-&D#Q~MRda3{b literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/row_index_seek_control.orc b/tests/queries/0_stateless/data_orc/row_index_seek_control.orc new file mode 100644 index 0000000000000000000000000000000000000000..ede347aa81181c970ec5d83161d8595eef07a424 GIT binary patch literal 213 zcmY+7F$=;#426?iIYPMMI7E+5r66?dD4oO#c9E9SA0Uc@C^(4VSp3cY0MA1Nhvb8o z_g>n*7VQ$o4t{h(0M0Nv&0xVpxP3JIYGlb%2P@1(vknFuiM|L#i(WZm2t%pbYzLW0 z!oe?wDK^G5E4xc2?1fj^yr7)fIK&hmIdM`_6*JXeW{C~%rM{dF=jM999eEv|kE6{A OOffC>^QBbV*RwZ`5EX0y literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc new file mode 100644 index 0000000000000000000000000000000000000000..d6e0144685e7e91cbc4e2f76aba78db27c503b4f GIT binary patch literal 294 zcmeYda^_+aV&Py3VBnJHVqpLRA#n~CFF}d-S0A;$tXG(DYv0WG<_0&-0vIZo8Q1fF zHU<%<3}+*pj2X=Co-wUs{tp7J@2o(YK>&?!#l^uMlK_Jhv%7By$R%JG;c^KFv%n-qDJ~$TDPf^tsKKJd$H61S$SB2FqQIcR zV8Ecn!NCb(8L(J^&9cH}mcs-;55^=`BRwGGhyc2?p@Bt-iGfE$(SWV#3p2BSkh3@d Dw(m#M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc new file mode 100644 index 0000000000000000000000000000000000000000..2afd747824ec0515a92db943df384c0a15d9573e GIT binary patch literal 517 zcmah_F-XHu5WUM!;u%X*Gw3%hG-L`zN_4CaLP4z{m7=SIgM;WMjv~5taS^)MxuUCE zXQx6PTq+J-6>$+1LF@hef*^>uyn8P%clTelR(5R9BwT}kal$cy%S#ikkZk6IWVM&3+yxPgX3uK-?@cBI7ut#aQ69Ap@RG z2HVjWORMWDLb5o9G+8=Y{U{Qd6XB0B)D1Zo%tuz3rj&>1G`*BQ+>fo1s*rPY z<~tIo>C52xd@=P*T`HPO=fa~AC5KX$QO)2}nRh1jyG=~AvjcuNo8b}B*Y_dmqTM+s z%Sgh-{5jA?(yFE`wR{4hIO~K=Wjl7=B}Xf}W{@pajjY)=+iq##pbu_Q=h(2_ti3>u z9J)?2=+GRx-X5s=SumAbf+5?n4%qkartR%4)<&I(Tt*DJ7X=wHr|d<1%^YzzE3xM> z-%7E|JP?a`XAz0(J?42JA3%DAus`Z&$y9Xaij(78A=2Oj@9du!#a=!NEc0aI_oNwy zL6aGK>2?l~?dJ7(AxI8I0lE`VGY3E}E@o%dTVTviD!?e2g#g2kAR) empty_values = 2; + map recursive_values = 3; + map big_enum_values = 4; + map supported_values = 5; +} diff --git a/tests/queries/0_stateless/orc_malformed.lib b/tests/queries/0_stateless/orc_malformed.lib new file mode 100644 index 000000000000..64f884cc4498 --- /dev/null +++ b/tests/queries/0_stateless/orc_malformed.lib @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2154 + +# Helpers to read (possibly malformed) ORC files from the tests: locally with `file` in clickhouse-local, and remotely +# with `s3` in the server, with the filter pushdown and the lazy dictionaries both enabled and disabled. + +ORC_S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}" +# The values of `input_format_orc_filter_push_down` to check. +ORC_PUSH_DOWN_VALUES="0 1" + +# Prints the result in one line, or the name of the error code (with the message if it does not match `expected_error`). +function orc_result() +{ + local output=$1 status=$2 expected_error=$3 + if [ "$status" -eq 0 ]; then + echo "$output" | tr '\n' ' ' | sed 's/ $//' + return + fi + local code + code=$(echo "$output" | grep -oE '\([A-Z_]{3,}\)' | tail -n1) + if [ -z "$code" ]; then + echo "unexpected failure with status $status: $(echo "$output" | head -n3)" + elif [ -z "$expected_error" ] || echo "$output" | grep -qE "$expected_error"; then + echo "$code" + else + echo "$code with an unexpected message: $(echo "$output" | head -n1 | cut -c1-300)" + fi +} + +# orc_check
`, so it requires the `WRITE` grant on the `S3` source. A grant limited by a URL filter is not enough, because the move writes keys that are built from `after_processing_move_prefix` and the source keys, not from the URI. `ALTER TABLE ... MODIFY SETTING` also requires `SELECT` on the table. The destination must be allowed by `remote_url_allow_hosts`. + Possible values: - String. diff --git a/docs/en/operations/settings/settings-users.md b/docs/en/operations/settings/settings-users.md index d7d61ff6ee9c..d029b4cca3ad 100644 --- a/docs/en/operations/settings/settings-users.md +++ b/docs/en/operations/settings/settings-users.md @@ -110,6 +110,7 @@ It's not yet supported in SQL-driven Access Control. To authenticate using TOTP, users must provide a primary password along with a one-time password generated by their TOTP application via the `--one-time-password` command line option or concatenated to main password together with a '+' character. For example if the primary password is `some_password` and the generated TOTP code is `345123`, user may specify `--password some_password+345123` or `--password some_password --one-time-password 345123` when connecting to ClickHouse. If no password specified `clickhouse-client` will prompt for it interactively. +When no code is supplied for an account with TOTP, the server replies with the error `REQUIRED_SECOND_FACTOR` whether or not the password is correct, and `clickhouse-client` prompts for the code; the password is verified only together with the code. Each code is accepted at most once, as required by [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238#section-5.2), so a user can successfully authenticate at most once per `period`. Keep this in mind for clients that authenticate on every request or connection (for example, scripts using the HTTP interface): each authentication needs a fresh code. diff --git a/programs/client/Client.cpp b/programs/client/Client.cpp index d37218c596e4..e7d0ad5281c8 100644 --- a/programs/client/Client.cpp +++ b/programs/client/Client.cpp @@ -408,6 +408,16 @@ try if (should_ask_2fa) { + /// The server asks for the second factor before it checks the password, so the first attempt + /// without any password ends here too. Ask for the password alone first: it may already contain + /// the code (`password+code`); otherwise the server asks again and the code is prompted. + if (!asked_password && !config().has("password") && !config().getBool("ask-password", false)) + { + asked_password = true; + config().setBool("ask-password", true); + continue; + } + asked_2fa = true; if (!connection_parameters.password.empty()) config().setString("password", connection_parameters.password); @@ -567,7 +577,8 @@ void Client::connect() catch (Exception & e) { /// This problem can't be fixed with reconnection so it is not attempted - if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD) + if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD + || e.code() == ErrorCodes::REQUIRED_SECOND_FACTOR) throw; if (attempted_address_index == hosts_and_ports.size() - 1) diff --git a/src/Access/AccessBackup.cpp b/src/Access/AccessBackup.cpp index d22edd007e2f..6af476b88b1b 100644 --- a/src/Access/AccessBackup.cpp +++ b/src/Access/AccessBackup.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -176,6 +177,23 @@ namespace } } }; + + AccessRights getRequiredAccessToRestoreGrants(const AccessRights & access) + { + AccessRights required_access; + for (const auto & element : access.getElements()) + { + /// Restoring a grant requires `GRANT OPTION` even if the backed-up entity does not have it. + if (element.is_partial_revoke && element.grant_option) + continue; + + if (element.is_partial_revoke) + required_access.revoke(element); + else + required_access.grantWithGrantOption(element); + } + return required_access; + } } @@ -338,12 +356,14 @@ void AccessRestorerFromBackup::loadFromBackup() } -AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const +AccessRights AccessRestorerFromBackup::getRequiredAccess() const { if (!loaded) throw Exception(ErrorCodes::LOGICAL_ERROR, "Access entities not loaded"); - AccessRightsElements res; + AccessRights res; + /// Like `CREATE ... OR REPLACE`, replacement requires `DROP` even if the entity does not exist. + const bool replace = (creation_mode == RestoreAccessCreationMode::kReplace); for (const auto & [id, entity_info] : entity_infos) { if (!entity_info.restore) @@ -355,57 +375,56 @@ AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const case User::TYPE: { const auto & user = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_USER, user.getName()); + AccessFlags flags = AccessType::CREATE_USER; + if (replace) + flags |= AccessType::DROP_USER; + res.grant(flags, user.getName()); if (!restore_with_current_grants) - { - auto elements = user.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(user.access)); if (!user.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case Role::TYPE: { const auto & role = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROLE, role.getName()); + AccessFlags flags = AccessType::CREATE_ROLE; + if (replace) + flags |= AccessType::DROP_ROLE; + res.grant(flags, role.getName()); if (!restore_with_current_grants) - { - auto elements = role.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(role.access)); if (!role.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case SettingsProfile::TYPE: { - res.emplace_back(AccessType::CREATE_SETTINGS_PROFILE); + AccessFlags flags = AccessType::CREATE_SETTINGS_PROFILE; + if (replace) + flags |= AccessType::DROP_SETTINGS_PROFILE; + res.grant(flags); break; } case RowPolicy::TYPE: { const auto & policy = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROW_POLICY, policy.getDatabase(), policy.getTableName()); + AccessFlags flags = AccessType::CREATE_ROW_POLICY; + if (replace) + flags |= AccessType::DROP_ROW_POLICY; + res.grant(flags, policy.getDatabase(), policy.getTableName()); break; } case Quota::TYPE: { - res.emplace_back(AccessType::CREATE_QUOTA); + AccessFlags flags = AccessType::CREATE_QUOTA; + if (replace) + flags |= AccessType::DROP_QUOTA; + res.grant(flags); break; } diff --git a/src/Access/AccessBackup.h b/src/Access/AccessBackup.h index 8219d1051035..da0f3088a033 100644 --- a/src/Access/AccessBackup.h +++ b/src/Access/AccessBackup.h @@ -11,7 +11,7 @@ class AccessControl; enum class AccessEntityType : uint8_t; struct IAccessEntity; using AccessEntityPtr = std::shared_ptr; -class AccessRightsElements; +class AccessRights; class IAccessStorage; class IBackup; using BackupPtr = std::shared_ptr; @@ -69,9 +69,9 @@ class AccessRestorerFromBackup /// Loads access entities from the backup. void loadFromBackup(); - /// Checks that the current user can do restoring. - /// Function loadFromBackup() must be called before that. - AccessRightsElements getRequiredAccess() const; + /// Returns the access required to restore the loaded entities. + /// `loadFromBackup` must be called first. + AccessRights getRequiredAccess() const; /// Generates random IDs for access entities we're restoring to insert them into an access storage; /// and finds IDs of existing access entities which are used as dependencies. diff --git a/src/Access/AccessControl.cpp b/src/Access/AccessControl.cpp index 03e25e9c513f..92f938920279 100644 --- a/src/Access/AccessControl.cpp +++ b/src/Access/AccessControl.cpp @@ -602,22 +602,25 @@ AuthResult AccessControl::authenticate(const Credentials & credentials, const Po // NOTE: In the case where the user has never been logged in using LDAP, // Then user_id is not generated, and the authentication quota will always be nullptr. auto authentication_quota = getAuthenticationQuota(credentials.getUserName(), address, client_info.getLastForwardedForHost()); - if (authentication_quota) - { - /// Reserve a single try from the quota to check whether we have another authentication try. - /// This is required for correct behavior in this situation: - /// User has 1 login failures quota. - /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. - /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. - /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED - /// and don't let the user authenticate. - /// - /// The authentication failures counter will be reset after successful authentication. - authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); - } try { + if (authentication_quota) + { + /// Reserve a single try from the quota to check whether we have another authentication try. + /// This is required for correct behavior in this situation: + /// User has 1 login failures quota. + /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. + /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. + /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED + /// and don't let the user authenticate. + /// + /// The authentication failures counter will be reset after successful authentication. + /// Inside the try block, so that an exceeded quota is reported like any other authentication failure + /// and doesn't reveal whether the user exists. + authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); + } + const auto auth_result = MultipleAccessStorage::authenticate(credentials, address, *external_authenticators, client_info, allow_no_password, allow_plaintext_password); if (authentication_quota) @@ -859,7 +862,7 @@ std::shared_ptr AccessControl::getEnabledQuota( const String & forwarded_address, const String & custom_quota_key) const { - return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key, true); + return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key); } std::shared_ptr AccessControl::getAuthenticationQuota( @@ -872,18 +875,13 @@ std::shared_ptr AccessControl::getAuthenticationQuota( const auto new_current_roles = user->granted_roles.findGranted(user->default_roles); const auto roles_info = getEnabledRolesInfo(new_current_roles, {}); - // client_key is not received at the moment of authentication during TCP connection - // if key type is set to QuotaKeyType::CLIENT_KEY - // QuotaCache::QuotaInfo::calculateKey will throw exception without throw_if_client_key_empty = false String quota_key; - bool throw_if_client_key_empty = false; return quota_cache->getEnabledQuota(*user_id, user->getName(), roles_info->enabled_roles, std::make_shared(address), forwarded_address, - quota_key, - throw_if_client_key_empty); + quota_key); } return nullptr; } diff --git a/src/Access/Authentication.cpp b/src/Access/Authentication.cpp index 055109dc596b..7745947d0fd2 100644 --- a/src/Access/Authentication.cpp +++ b/src/Access/Authentication.cpp @@ -183,80 +183,60 @@ namespace return {password_with_otp.substr(0, separator_pos), password_with_otp.substr(separator_pos + 1)}; } - Authentication::CredentialsCheckResult checkBasicAuthentication( - const BasicCredentials * basic_credentials, + /// Verifies the primary credential: the password without the one-time password part. + bool checkPrimaryCredential( + std::string_view password, + const BasicCredentials & basic_credentials, const AuthenticationData & authentication_method, const ExternalAuthenticators & external_authenticators, const ClientInfo & client_info, SettingsChanges & settings) { - const auto & provided_password = basic_credentials->getPassword(); - const auto & otp_secret = authentication_method.getOneTimePassword(); - auto [password, one_time_password] = splitOneTimePasswordAndPassword(provided_password, authentication_method); - Authentication::CredentialsCheckResult on_success = Authentication::CredentialsCheckResult::Success; - if (otp_secret) - { - /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after - /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. - if (one_time_password.empty()) - on_success = Authentication::CredentialsCheckResult::NeedSecondFactor; - else if (!checkOneTimePassword(one_time_password, *otp_secret)) - return Authentication::CredentialsCheckResult::Fail; - } - switch (authentication_method.getType()) { case AuthenticationType::NO_PASSWORD: { - return on_success; // N.B. even if the password is not empty! + return true; // N.B. even if the password is not empty! } case AuthenticationType::PLAINTEXT_PASSWORD: { const auto & password_plaintext = authentication_method.getPasswordHashBinary(); - return constantTimeEquals(Util::stringToDigest(password), password_plaintext) ? on_success : Authentication::CredentialsCheckResult::Fail; + return constantTimeEquals(Util::stringToDigest(password), password_plaintext); } case AuthenticationType::SHA256_PASSWORD: { const auto & password_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); String salted_password = String(password).append(salt); - return Util::encodeSHA256(salted_password) == password_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeSHA256(salted_password) == password_sha256; } case AuthenticationType::SCRAM_SHA256_PASSWORD: { const auto & password_scram_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); auto digest = Util::encodeScramSHA256(password, salt); - return digest == password_scram_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return digest == password_scram_sha256; } case AuthenticationType::DOUBLE_SHA1_PASSWORD: { const auto & password_double_sha1 = authentication_method.getPasswordHashBinary(); - return Util::encodeDoubleSHA1(password) == password_double_sha1 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeDoubleSHA1(password) == password_double_sha1; } case AuthenticationType::LDAP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; - return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), *basic_credentials) ? - on_success : Authentication::CredentialsCheckResult::Fail; + return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), basic_credentials); } case AuthenticationType::BCRYPT_PASSWORD: { const auto & password_bcrypt = authentication_method.getPasswordHashBinary(); - return Util::checkPasswordBcrypt(password, password_bcrypt) ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::checkPasswordBcrypt(password, password_bcrypt); } case AuthenticationType::HTTP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; if (authentication_method.getHTTPAuthenticationScheme() == HTTPAuthenticationScheme::BASIC) { return external_authenticators.checkHTTPBasicCredentials( - authentication_method.getHTTPAuthenticationServerName(), *basic_credentials, client_info, settings) ? - on_success : Authentication::CredentialsCheckResult::Fail; + authentication_method.getHTTPAuthenticationServerName(), basic_credentials, client_info, settings); } break; } @@ -264,7 +244,38 @@ namespace break; } - return Authentication::CredentialsCheckResult::Fail; + return false; + } + + Authentication::CredentialsCheckResult checkBasicAuthentication( + const BasicCredentials * basic_credentials, + const AuthenticationData & authentication_method, + const ExternalAuthenticators & external_authenticators, + const ClientInfo & client_info, + SettingsChanges & settings) + { + const auto & otp_secret = authentication_method.getOneTimePassword(); + auto [password, one_time_password] = splitOneTimePasswordAndPassword(basic_credentials->getPassword(), authentication_method); + + const auto auth_type = authentication_method.getType(); + if (otp_secret && (auth_type == AuthenticationType::LDAP || auth_type == AuthenticationType::HTTP)) + /// One-time password supported only with password-based authentication methods. + return Authentication::CredentialsCheckResult::Fail; + + /// Decided before the primary credential is looked at, so that the response (and its timing) is the same + /// for a right and a wrong password: otherwise an attacker could confirm a guessed password without the code. + if (otp_secret && one_time_password.empty()) + return Authentication::CredentialsCheckResult::NeedSecondFactor; + + const bool primary_ok = checkPrimaryCredential(password, *basic_credentials, authentication_method, external_authenticators, client_info, settings); + if (!otp_secret) + return primary_ok ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; + + /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after + /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. + /// Both factors are evaluated unconditionally, so that the timing does not tell which one failed. + const bool otp_ok = checkOneTimePassword(one_time_password, *otp_secret); + return (primary_ok && otp_ok) ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; } #if USE_SSL diff --git a/src/Access/ContextAccess.cpp b/src/Access/ContextAccess.cpp index 98cd4af879ed..aedfc9fa08a5 100644 --- a/src/Access/ContextAccess.cpp +++ b/src/Access/ContextAccess.cpp @@ -586,6 +586,10 @@ std::shared_ptr ContextAccess::getQuota() const } } + /// Outside the branch above on purpose: `QuotaCache` refreshes the quota set in place, so an already + /// memoised object has to be re-checked on every call. + enabled_quota->checkClientKeySupplied(); + return enabled_quota; } diff --git a/src/Access/EnabledQuota.cpp b/src/Access/EnabledQuota.cpp index 92518d5506ea..c5333af77e4d 100644 --- a/src/Access/EnabledQuota.cpp +++ b/src/Access/EnabledQuota.cpp @@ -14,6 +14,7 @@ namespace DB namespace ErrorCodes { extern const int QUOTA_EXCEEDED; + extern const int QUOTA_REQUIRES_CLIENT_KEY; } @@ -307,6 +308,18 @@ void EnabledQuota::checkExceeded(QuotaType quota_type) const } +void EnabledQuota::checkClientKeySupplied() const +{ + if (!requires_client_key) + return; + throw Exception( + ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, + "Quota {} (for user {}) requires a client supplied key.", + intervals.load()->quota_name, + getUserName()); +} + + void EnabledQuota::reset(QuotaType quota_type) const { const auto loaded = intervals.load(); diff --git a/src/Access/EnabledQuota.h b/src/Access/EnabledQuota.h index 2513bed9622c..587c97f108f4 100644 --- a/src/Access/EnabledQuota.h +++ b/src/Access/EnabledQuota.h @@ -52,6 +52,10 @@ class EnabledQuota : public boost::noncopyable void checkExceeded() const; void checkExceeded(QuotaType quota_type) const; + /// Throws if a governing quota is keyed by `client_key` and this context supplied none. Authentication + /// is metered before a client key can exist, so only the query path calls this. + void checkClientKeySupplied() const; + void reset(QuotaType quota_type) const; /// Returns the information about quota consumption. @@ -97,6 +101,9 @@ class EnabledQuota : public boost::noncopyable const Params params; boost::atomic_shared_ptr intervals; /// atomically changed by QuotaUsageManager std::atomic empty = false; /// Use a separate flag to avoid loading intervals, which is way more expensive than an atomic bool + /// The chosen quota is keyed by `client_key` and this context supplied none, so it cannot be metered. + /// Refreshed in place by `QuotaCache` together with `intervals`; see `checkClientKeySupplied`. + std::atomic requires_client_key = false; }; } diff --git a/src/Access/HTTPAuthClient.h b/src/Access/HTTPAuthClient.h index 27e0d5dc507b..2768639cb709 100644 --- a/src/Access/HTTPAuthClient.h +++ b/src/Access/HTTPAuthClient.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -12,6 +13,11 @@ namespace DB { +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + struct HTTPAuthClientParams { Poco::URI uri; @@ -95,8 +101,13 @@ class HTTPBasicAuthClient : private HTTPAuthClient for (const auto & k : headers) { - if (this->getForwardHeaders().contains(k.first)) - request.add(k.first, k.second); + if (!this->getForwardHeaders().contains(k.first)) + continue; + /// Poco writes header values verbatim, so a line break would let the value inject extra headers + /// (e.g. an `Authorization` placed before ours) into the request to the authentication server. + if (k.second.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Forwarded HTTP header \"{}\" contains CR, LF or NUL", k.first); + request.add(k.first, k.second); } Poco::Net::HTTPBasicCredentials basic_credentials{user_name, password}; diff --git a/src/Access/IAccessStorage.cpp b/src/Access/IAccessStorage.cpp index 2beb46691b4b..7c2ed52f88e7 100644 --- a/src/Access/IAccessStorage.cpp +++ b/src/Access/IAccessStorage.cpp @@ -598,6 +598,8 @@ std::optional IAccessStorage::authenticateImpl( "check allow_no_password and allow_plaintext_password settings in the server configuration"); } + /// Reported for a missing code before the password is checked (see `checkBasicAuthentication`), + /// so this error does not confirm the password. if (need_second_factor) throw Exception(ErrorCodes::REQUIRED_SECOND_FACTOR, "Authentication requires second factor"); throw Exception(ErrorCodes::WRONG_PASSWORD, "Invalid credentials"); diff --git a/src/Access/QuotaCache.cpp b/src/Access/QuotaCache.cpp index d5a019639a2f..338b09a34e73 100644 --- a/src/Access/QuotaCache.cpp +++ b/src/Access/QuotaCache.cpp @@ -26,7 +26,6 @@ namespace DB { namespace ErrorCodes { - extern const int QUOTA_REQUIRES_CLIENT_KEY; extern const int LOGICAL_ERROR; } @@ -40,7 +39,7 @@ void QuotaCache::QuotaInfo::setQuota(const QuotaPtr & quota_, const UUID & quota } -String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool throw_if_client_key_empty) const +String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled) const { const auto & params = enabled.params; switch (quota->key_type) @@ -65,14 +64,9 @@ String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool th { if (!params.client_key.empty()) return params.client_key; - - if (throw_if_client_key_empty) - throw Exception( - ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, - "Quota {} (for user {}) requires a client supplied key.", - quota->getName(), - params.user_name); - return ""; // Authentication quota has no client key at time of authentication. + /// An empty key is a legitimate state: at the time of authentication no client key exists yet. + /// The requirement is published as `EnabledQuota::requires_client_key` and enforced on the query path. + return ""; } case QuotaKeyType::CLIENT_KEY_OR_USER_NAME: { @@ -187,8 +181,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( const boost::container::flat_set & enabled_roles, const std::shared_ptr & client_address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty) + const String & client_key) { std::lock_guard lock{mutex}; ensureAllQuotasRead(); @@ -211,7 +204,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( auto res = std::shared_ptr(new EnabledQuota(params)); enabled_quotas.emplace(std::move(params), res); - chooseQuotaToConsumeFor(*res, throw_if_client_key_empty); + chooseQuotaToConsumeFor(*res); return res; } @@ -294,7 +287,7 @@ void QuotaCache::chooseQuotaToConsume() i = enabled_quotas.erase(i); else { - chooseQuotaToConsumeFor(*elem, true); + chooseQuotaToConsumeFor(*elem); ++i; } } @@ -308,16 +301,18 @@ void QuotaCache::chooseQuotaToConsume() LOG_DEBUG(getLogger("QuotaCache"), "Re-chose quotas for {} enabled set(s) over {} quotas in {} ms", enabled_quotas.size(), all_quotas.size(), elapsed_ms); } -void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_client_key_empty) +void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled) { /// `mutex` is already locked. boost::shared_ptr intervals; + bool requires_client_key = false; for (auto & info : all_quotas | boost::adaptors::map_values) { if (info.roles->match(enabled.params.user_id, enabled.params.enabled_roles)) { - String key = info.calculateKey(enabled, throw_if_client_key_empty); + String key = info.calculateKey(enabled); intervals = info.getOrBuildIntervals(key); + requires_client_key = (info.quota->key_type == QuotaKeyType::CLIENT_KEY) && enabled.params.client_key.empty(); break; } } @@ -332,6 +327,7 @@ void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_c enabled.intervals.store(intervals); enabled.empty = false; } + enabled.requires_client_key = requires_client_key; } diff --git a/src/Access/QuotaCache.h b/src/Access/QuotaCache.h index 4c4cd955bac1..29df5ebe50b6 100644 --- a/src/Access/QuotaCache.h +++ b/src/Access/QuotaCache.h @@ -28,8 +28,7 @@ class QuotaCache const boost::container::flat_set & enabled_roles, const std::shared_ptr & address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty); + const String & client_key); std::vector getAllQuotasUsage() const; @@ -42,7 +41,7 @@ class QuotaCache QuotaInfo(const QuotaPtr & quota_, const UUID & quota_id_) { setQuota(quota_, quota_id_); } void setQuota(const QuotaPtr & quota_, const UUID & quota_id_); - String calculateKey(const EnabledQuota & enabled_quota, bool throw_if_client_key_empty) const; + String calculateKey(const EnabledQuota & enabled_quota) const; boost::shared_ptr getOrBuildIntervals(const String & key); boost::shared_ptr rebuildIntervals(const String & key, std::chrono::system_clock::time_point current_time); void rebuildAllIntervals(); @@ -58,7 +57,7 @@ class QuotaCache void quotaRemoved(const UUID & quota_id); void chooseQuotaToConsume(); void chooseQuotaToConsumeIfNeeded(); - void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota, bool throw_if_client_key_empty); + void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota); const AccessControl & access_control; mutable std::mutex mutex; diff --git a/src/Access/SettingsConstraints.cpp b/src/Access/SettingsConstraints.cpp index bb47d78c603f..dcf8d39879f0 100644 --- a/src/Access/SettingsConstraints.cpp +++ b/src/Access/SettingsConstraints.cpp @@ -287,6 +287,18 @@ void SettingsConstraints::clamp(const Settings & current_settings, SettingsChang }); } +void SettingsConstraints::clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const +{ + /// The surviving list is stored on the query node as the settings set explicitly on that node, + /// so a change equal to the current value must stay in the list. + std::erase_if( + changes, + [&](SettingChange & change) -> bool + { + return !checkImpl(current_settings, change, CLAMP_ON_VIOLATION_THROW_ON_INVALID, source, /*ignore_unchanged_settings=*/ true); + }); +} + /// The value a setting holds now. /// /// `Settings` keeps a `merge_tree_`-prefixed name as a custom setting, under the exact name that wrote it. @@ -321,13 +333,13 @@ Field castValueOfSetting(const String & name, const Field & value) } template -bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool throw_on_failure) +bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool ignore_unchanged_settings, bool throw_on_failure) { Field current_value; bool has_current_value = getCurrentValueOfSetting(current_settings, change.name, current_value); /// Setting isn't checked if value has not changed. - if (has_current_value && change.value == current_value) + if (!ignore_unchanged_settings && has_current_value && change.value == current_value) return false; /// Put the value into the type of the setting. This throws when the value does not fit, as @@ -358,7 +370,7 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan /// stores a Bool, the same 1 in a query arrives as a UInt64, and comparing them as they are would /// make a change that keeps the value look like a real one. Field cast_current_value; - if (has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) + if (!ignore_unchanged_settings && has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) return false; return true; @@ -367,14 +379,18 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan bool SettingsConstraints::checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const + SettingSource source, + bool ignore_unchanged_settings) const { std::string_view setting_name = Settings::resolveName(change.name); if (setting_name == "profile") return true; - if (reaction == THROW_ON_VIOLATION) + /// Invalid changes (an unknown or disallowed name, an uncastable value) throw in every mode but `CLAMP_ON_VIOLATION`. + const bool throw_on_invalid_change = reaction != CLAMP_ON_VIOLATION; + + if (throw_on_invalid_change) { try { @@ -396,7 +412,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, return false; Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, ignore_unchanged_settings, /*throw_on_failure=*/ throw_on_invalid_change)) return false; return getChecker(current_settings, setting_name).check(change, new_value, reaction, source); @@ -405,7 +421,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, bool SettingsConstraints::checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const { Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, /*ignore_unchanged_settings=*/ false, reaction == THROW_ON_VIOLATION)) return false; if (isAnyTierRestricted()) @@ -422,9 +438,12 @@ bool SettingsConstraints::Checker::check(SettingChange & change, ReactionOnViolation reaction, SettingSource source) const { + /// Every reaction other than `THROW_ON_VIOLATION` clamps or drops a violating change. + const bool throw_on_violation = reaction == THROW_ON_VIOLATION; + if (!explain.text.empty()) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(explain, code); return false; } @@ -433,7 +452,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto less_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateLess(left, right); try { @@ -447,7 +466,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto equals_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateEquals(left, right); try { @@ -462,7 +481,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (constraint.writability == SettingConstraintWritability::CONST) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} should not be changed", setting_name); return false; } @@ -473,7 +492,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && !max_value.isNull() && less_or_cannot_compare(max_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception( ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "The maximum ({}) value is less than the minimum ({}) value for setting {}", @@ -485,7 +504,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && less_or_cannot_compare(new_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be less than {}", setting_name, applyVisitor(FieldVisitorToString(), min_value)); @@ -495,7 +514,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!max_value.isNull() && less_or_cannot_compare(max_value, new_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be greater than {}", setting_name, applyVisitor(FieldVisitorToString(), max_value)); @@ -513,7 +532,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!getSettingSourceRestrictions(setting_name).isSourceAllowed(source)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::READONLY, "Setting {} is not allowed to be set by {}", setting_name, toString(source)); return false; } diff --git a/src/Access/SettingsConstraints.h b/src/Access/SettingsConstraints.h index dc87368a62e2..2231cda9cfd6 100644 --- a/src/Access/SettingsConstraints.h +++ b/src/Access/SettingsConstraints.h @@ -95,8 +95,13 @@ class SettingsConstraints void check(const MergeTreeSettings & current_settings, const SettingsChanges & changes) const; /// Checks whether `change` violates these and clamps the `change` if so. + /// A change equal to the current value is dropped from `changes`. void clamp(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + /// Same as `clamp`, but an unknown or disallowed setting name and an uncastable value throw, as in `check`, + /// and a change equal to the current value is kept in `changes`. + void clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + friend bool operator ==(const SettingsConstraints & left, const SettingsConstraints & right); friend bool operator !=(const SettingsConstraints & left, const SettingsConstraints & right) { return !(left == right); } @@ -104,8 +109,12 @@ class SettingsConstraints private: enum ReactionOnViolation { + /// Any violation, an unknown name or an uncastable value throws. THROW_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value is dropped. CLAMP_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value throws. + CLAMP_ON_VIOLATION_THROW_ON_INVALID, }; struct Constraint @@ -165,7 +174,8 @@ class SettingsConstraints bool checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const; + SettingSource source, + bool ignore_unchanged_settings = false) const; bool checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const; diff --git a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp index b1bf4f7edb96..7df726a74610 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp @@ -24,6 +24,8 @@ #include +#include + #include constexpr size_t AGGREGATE_FUNCTION_GROUP_ARRAY_MAX_ELEMENT_SIZE = 0xFFFFFF; @@ -90,6 +92,17 @@ struct GroupArraySamplerData size_t total_values = 0; pcg32_fast rng; + /// The counter may come from a deserialized state, so it can be arbitrarily large, + /// and wrapping it around would make `genRandom` divide by zero. + void addTotalValues(UInt64 count) + { + UInt64 new_total_values = 0; + if (common::addOverflow(static_cast(total_values), count, new_total_values)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The number of values in groupArraySample state overflows: {} + {}", total_values, count); + total_values = new_total_values; + } + UInt64 genRandom(size_t lim) { chassert(lim != 0); @@ -160,7 +173,7 @@ class GroupArrayNumericImpl final void insertWithSampler(Data & a, const T & v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v, arena); else @@ -183,7 +196,10 @@ class GroupArrayNumericImpl final const auto & row_value = assert_cast &>(*columns[0]).getData()[row_num]; auto & cur_elems = this->data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -275,8 +291,8 @@ class GroupArrayNumericImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); @@ -525,7 +541,7 @@ class GroupArrayGeneralImpl final void insertWithSampler(Data & a, const Node * v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v->clone(arena), arena); else @@ -547,7 +563,10 @@ class GroupArrayGeneralImpl final { auto & cur_elems = data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -642,8 +661,8 @@ class GroupArrayGeneralImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp index 8c61d13923ca..610937b52f5f 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp @@ -61,8 +61,14 @@ void forEachSecretArgumentNode( continue; } + if (const auto masked = secret_arguments.masked_arguments.find(n); masked != secret_arguments.masked_arguments.end()) + { + on_secret(n, masked->second ? secretValueSlot(arguments[n]) : arguments[n]); + continue; + } + const bool in_span = secret_arguments.start <= n && n < secret_arguments.start + secret_arguments.count; - if (in_span || secret_arguments.masked_arguments.contains(n) || secret_arguments.replaced_arguments.contains(n)) + if (in_span || secret_arguments.replaced_arguments.contains(n)) on_secret(n, secretValueSlot(arguments[n])); } } diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h index 6afdd5d3a952..ecd7322afc29 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h @@ -122,7 +122,8 @@ using FunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeN using TableFunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeNodeImpl; /// Visits the secret value slots selected by a finder result in a resolved argument list, for the -/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members and the arguments +/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members, the individually +/// masked arguments (whole, unless masked as a named `key = value`) and the arguments /// with a partial replacement (for a `key = value` argument, its value; a tree dump cannot represent /// partial masking, so the whole value is masked: fail closed), and the values of the nested secret /// maps (`headers(..)` / `extra_credentials(..)`; a malformed child is visited whole). The callback diff --git a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp index 44c9ee3df51b..b95cc0fd9410 100644 --- a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp +++ b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp @@ -550,6 +550,10 @@ std::tuple getTypedNodesForOptimizati if (!storage->supportsOptimizationToSubcolumns() || storage->isVirtualColumn(column.name, storage_snapshot->metadata)) return {}; + /// Without buckets the key subcolumn `m.key_` reads the whole Map, so `m['key']` is not rewritten to it. + if (function_node->getFunctionName() == "arrayElement" && isMap(column.type) && !storage->hasBucketedMapSerialization()) + return {}; + auto column_in_table = storage_snapshot->tryGetColumn(GetColumnsOptions(GetColumnsOptions::All).withSubcolumns(), column.name); if (!column_in_table || !column_in_table->type->equals(*column.type)) return {}; diff --git a/src/Analyzer/QueryTreeBuilder.cpp b/src/Analyzer/QueryTreeBuilder.cpp index 285edf278e72..16cab878c838 100644 --- a/src/Analyzer/QueryTreeBuilder.cpp +++ b/src/Analyzer/QueryTreeBuilder.cpp @@ -302,22 +302,28 @@ QueryTreeNodePtr QueryTreeBuilder::buildSelectExpression( set_query.changes.removeSetting("offset"); } - /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) used to be applied to - /// the per-node context unchecked, letting a user override `readonly`, `CONST` and `MIN`/`MAX` - /// constraints - e.g. `additional_table_filters`, which the Planner reads from this context. - /// Clamp it instead of throwing, as done for other settings crossing execution contexts - /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are - /// dropped, out-of-bounds values are clamped, so a view whose inner clause violates the - /// reader's constraints keeps working. A top-level clause still throws - /// (`applySettingsFromQuery`). Clamp a copy: the `QueryNode` keeps the clause as written, so - /// the tree's AST and hash are unchanged, and every node executing the subquery clamps it - /// against its own constraints. `SETTINGS name = DEFAULT` stays ignored here - see #115415. + /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) is clamped to the session's + /// settings constraints, as done for other settings crossing execution contexts + /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are dropped, + /// out-of-bounds values are clamped, so a view whose inner clause violates the reader's constraints + /// keeps working. A top-level clause still throws (`applySettingsFromQuery`). An unknown name or an + /// uncastable value throws as for a top-level clause, on every server that executes the query. The + /// node records the effective `changes`: the ones that survive, with their clamped values and the + /// literals as written, so `toAST`, the tree hash, the `Planner` and the shards receiving the + /// subquery see what was applied. `SETTINGS name = DEFAULT` stays ignored here - see #115415. if (!set_query.changes.empty()) { - auto checked_changes = set_query.changes; - updated_context->clampToSettingsConstraints(checked_changes, SettingSource::QUERY); - updated_context->applySettingsChanges(checked_changes); - settings_changes = set_query.changes; + /// One change at a time, so that each is clamped against the context as the preceding changes + /// left it. Clamping the whole clause as a batch checks every change against the context as it + /// was before the clause - so `SETTINGS use_query_cache = 1, use_query_cache = 0` could resolve + /// differently from the last-wins reading the clause has everywhere else. + for (const auto & change : set_query.changes) + { + SettingsChanges single_change{change}; + updated_context->clampToSettingsConstraintsRejectingInvalidChanges(single_change, SettingSource::QUERY); + updated_context->applySettingsChanges(single_change); + settings_changes.insert(settings_changes.end(), single_change.begin(), single_change.end()); + } } } diff --git a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp index e5ec3cc7c4e1..56109118b128 100644 --- a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp +++ b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp @@ -114,7 +114,7 @@ void QueryAnalyzer::evaluateScalarSubqueryIfNeeded(QueryTreeNodePtr & node, Iden scalar_block = scalars_cache.at(node_with_hash); } - else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasScalar(str_hash)) + else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasComputedScalar(str_hash)) { scalar_block = context->getQueryContext()->getScalar(str_hash); scalar_subquery_to_scalar_value_global.emplace(node_with_hash, scalar_block); diff --git a/src/Backups/BackupIO_AzureBlobStorage.cpp b/src/Backups/BackupIO_AzureBlobStorage.cpp index eb2126f1dd9f..cd08f6e339e3 100644 --- a/src/Backups/BackupIO_AzureBlobStorage.cpp +++ b/src/Backups/BackupIO_AzureBlobStorage.cpp @@ -2,6 +2,7 @@ #include #if USE_AZURE_BLOB_STORAGE +#include #include #include #include @@ -29,6 +30,17 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +namespace +{ + /// An Azure disk configured with `connection_string` is described by that whole string. + String maskedDescription(const DataSourceDescription & description) + { + String result = description.description; + maskAzureConnectionStringSecrets(result); + return result; + } +} + BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const AzureBlobStorage::ConnectionParams & connection_params_, const String & blob_path_, @@ -37,7 +49,7 @@ BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const WriteSettings & write_settings_, const ContextPtr & context_) : BackupReaderDefault(read_settings_, write_settings_, getLogger("BackupReaderAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -85,7 +97,7 @@ void BackupReaderAzureBlobStorage::copyFileToDisk(const String & path_in_backup, DiskPtr destination_disk, const String & destination_path, WriteMode write_mode) { auto destination_data_source_description = destination_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, destination_data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, maskedDescription(destination_data_source_description)); if (destination_data_source_description.object_storage_type == ObjectStorageType::Azure && destination_data_source_description.is_encrypted == encrypted_in_backup) { @@ -132,7 +144,7 @@ BackupWriterAzureBlobStorage::BackupWriterAzureBlobStorage( const ContextPtr & context_, bool attempt_to_create_container) : BackupWriterDefault(read_settings_, write_settings_, getLogger("BackupWriterAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -162,7 +174,7 @@ void BackupWriterAzureBlobStorage::copyFileFromDisk( { /// Use the native copy as a more optimal way to copy a file from AzureBlobStorage to AzureBlobStorage if it's possible. auto source_data_source_description = src_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", source_data_source_description.description, data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", maskedDescription(source_data_source_description), data_source_description.description); if (source_data_source_description.object_storage_type == ObjectStorageType::Azure && source_data_source_description.is_encrypted == copy_encrypted) { diff --git a/src/Backups/BackupMetadataFinder.cpp b/src/Backups/BackupMetadataFinder.cpp index 46115481a708..4b3534b9b24b 100644 --- a/src/Backups/BackupMetadataFinder.cpp +++ b/src/Backups/BackupMetadataFinder.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -287,6 +288,16 @@ void BackupMetadataFinder::findTableInBackupImpl( ParserCreateQuery create_parser; ASTPtr create_table_query = parseQuery(create_parser, create_query_str, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + /// `BACKUP` writes the full definition, without `AS` (see `cleanupObjectDefinitionFromTemporaryFlags`). A definition that + /// inherits its engine with `AS` would let the access check of the restore see no engine, so it is rejected. + if (const auto & create = create_table_query->as(); !create.as_table.empty()) + throw Exception( + ErrorCodes::CANNOT_RESTORE_TABLE, + "The definition of {} in the backup uses AS {}, which BACKUP never writes", + tableNameWithTypeToString(table_name_in_backup.database, table_name_in_backup.table, false), + backQuoteIfNeed(create.as_table)); + applyCustomStoragePolicy(create_table_query); renameDatabaseAndTableNameInCreateQuery(create_table_query, renaming_map, context->getGlobalContext()); String create_table_query_str = create_table_query->formatWithSecretsOneLine(); diff --git a/src/Backups/RestorerFromBackup.cpp b/src/Backups/RestorerFromBackup.cpp index b1cfe0451a94..5c47fd9cea18 100644 --- a/src/Backups/RestorerFromBackup.cpp +++ b/src/Backups/RestorerFromBackup.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ namespace Setting extern const SettingsUInt64 backup_restore_keeper_max_retries; extern const SettingsSeconds lock_acquire_timeout; extern const SettingsBool restore_replicated_merge_tree_to_shared_merge_tree; + extern const SettingsBool restore_replace_external_engines_to_null; } namespace ErrorCodes @@ -276,6 +278,7 @@ void RestorerFromBackup::loadSystemAccessTables() void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const { AccessRightsElements required_access; + AccessRights required_access_rights; { std::lock_guard lock{mutex}; @@ -310,7 +313,17 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const continue; } - if (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE) + const ASTCreateQuery & create = table_info.create_table_query->as(); + const bool is_temporary = (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE); + + /// The definition comes from the backup, and the table is created by an internal query that checks + /// nothing, so settings that send the data elsewhere are authorized here, as for `CREATE`. + /// An external engine replaced by `Null` sends nothing, but temporary tables keep their engine. + if (restore_settings.create_table != RestoreTableCreationMode::kMustExist + && (is_temporary || !context->getSettingsRef()[Setting::restore_replace_external_engines_to_null])) + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + + if (is_temporary) { if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) required_access.emplace_back(AccessType::CREATE_TEMPORARY_TABLE); @@ -318,7 +331,6 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const } AccessFlags flags; - const ASTCreateQuery & create = table_info.create_table_query->as(); if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) { @@ -346,15 +358,12 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const required_access.emplace_back(flags, table_name.database, table_name.table); } + required_access_rights = AccessRights{required_access}; + /// Partial revokes in restored grants must not remove the rights required to restore other objects. if (access_restorer) - insertAtEnd(required_access, access_restorer->getRequiredAccess()); + required_access_rights.makeUnion(access_restorer->getRequiredAccess()); } - /// We convert to AccessRights to check if we have the rights contained in our current access. - /// This handles the situation when restoring partial revoked grants: - /// GRANT SELECT ON *.* - /// REVOKE SELECT FROM systems.* - const auto & required_access_rights = AccessRights{required_access}; const auto & current_user_access_rights = context->getAccess()->getAccessRightsWithImplicit(); if (current_user_access_rights->contains(required_access_rights)) return; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 88dcaa1fa6ab..469b3b3ad16f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -359,6 +359,10 @@ if (USE_PARQUET) add_object_library(clickhouse_processors_formats_impl_parquet Processors/Formats/Impl/Parquet) endif() +if (USE_ORC) + add_object_library(clickhouse_processors_formats_impl_orc Processors/Formats/Impl/ORC) +endif() + if (TARGET ch_contrib::nuraft) add_object_library(clickhouse_coordination Coordination) endif() @@ -642,11 +646,6 @@ endif() target_link_libraries (clickhouse_common_io PUBLIC ch_contrib::fast_float) -if (USE_ORC) - target_link_libraries(dbms PUBLIC ${ORC_LIBRARIES}) - target_include_directories(dbms SYSTEM BEFORE PUBLIC ${ORC_INCLUDE_DIR} "${PROJECT_BINARY_DIR}/contrib/orc/c++/include") -endif () - if (TARGET ch_contrib::rocksdb) target_link_libraries(dbms PUBLIC ch_contrib::rocksdb) endif() @@ -773,6 +772,10 @@ if (ENABLE_TESTS) clickhouse_common_config clickhouse_common_zookeeper) + if (TARGET ch_contrib::brotli) + target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::brotli) + endif() + if (TARGET ch_contrib::simdjson) target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::simdjson) endif() diff --git a/src/Client/ClientBase.cpp b/src/Client/ClientBase.cpp index dfa4234f2042..aa2e00344b73 100644 --- a/src/Client/ClientBase.cpp +++ b/src/Client/ClientBase.cpp @@ -3582,13 +3582,13 @@ void ClientBase::runInteractive() #if USE_REPLXX - replxx::Replxx::highlighter_callback_with_pos_t highlight_callback{}; + ReplxxLineReader::Highlighter highlight_callback{}; if (getClientConfiguration().getBool("highlight", true)) { - highlight_callback = [this](const String & query, std::vector & colors, int pos) + highlight_callback = [this](const String & query, std::vector & colors, int pos, bool & last_is_delimiter) { - highlight(query, colors, *client_context, pos); + highlight(query, colors, *client_context, pos, &last_is_delimiter); }; } diff --git a/src/Client/ClientBaseHelpers.cpp b/src/Client/ClientBaseHelpers.cpp index 3955d1d8edf2..28e01896beb4 100644 --- a/src/Client/ClientBaseHelpers.cpp +++ b/src/Client/ClientBaseHelpers.cpp @@ -155,7 +155,7 @@ static size_t countCodePointsWithSeqLength(const String & query, const char * en return code_points; } -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position) +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter) { using namespace replxx; @@ -512,14 +512,16 @@ void highlight(const String & query, std::vector & colors } /// This is a callback for the client/local app to better find query end. Note: this is a kludge, remove it. + if (!last_is_delimiter) + return; if (last_token.type == TokenType::Semicolon || last_token.type == TokenType::VerticalDelimiter || query.ends_with(';') || query.ends_with("\\G")) /// This is for raw data in INSERT queries, which is not necessarily tokenized. { - ReplxxLineReader::setLastIsDelimiter(true); + *last_is_delimiter = true; } else if (last_token.type != TokenType::Whitespace) { - ReplxxLineReader::setLastIsDelimiter(false); + *last_is_delimiter = false; } } @@ -528,7 +530,7 @@ String highlighted(const String & query, const Context & context) const size_t num_code_points = countCodePointsWithSeqLength(query, query.data() + query.size()); std::vector colors(num_code_points, replxx::Replxx::Color::DEFAULT); - highlight(query, colors, context, 0); + highlight(query, colors, context, 0, nullptr); String res; size_t query_size = query.size(); diff --git a/src/Client/ClientBaseHelpers.h b/src/Client/ClientBaseHelpers.h index 4e41e605f3f7..ad02976550df 100644 --- a/src/Client/ClientBaseHelpers.h +++ b/src/Client/ClientBaseHelpers.h @@ -24,7 +24,9 @@ std::string getChineseZodiac(); bool isCloudEndpoint(const std::string & host); #if USE_REPLXX -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position); +/// If `last_is_delimiter` is not null, it is set to whether the query ends with a delimiter (and left +/// intact if the query ends with whitespace). +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter); String highlighted(const String & query, const Context & context); #endif diff --git a/src/Client/ReplxxLineReader.cpp b/src/Client/ReplxxLineReader.cpp index 14842dbfd77e..c909f14beb44 100644 --- a/src/Client/ReplxxLineReader.cpp +++ b/src/Client/ReplxxLineReader.cpp @@ -286,12 +286,6 @@ void convertHistoryFile(const std::string & path, replxx::Replxx & rx) namespace DB { -static bool replxx_last_is_delimiter = false; -void ReplxxLineReader::setLastIsDelimiter(bool flag) -{ - replxx_last_is_delimiter = flag; -} - ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) : LineReader ( @@ -360,7 +354,12 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) rx.set_indent_multiline(false); if (highlighter) - rx.set_highlighter_callback(highlighter); + { + rx.set_highlighter_callback([this](const String & query, std::vector & colors, int cursor_position) + { + highlighter(query, colors, cursor_position, last_is_delimiter); + }); + } /// By default C-p/C-n bound to COMPLETE_NEXT/COMPLETE_PREV, /// bind C-p/C-n to history-previous/history-next like readline. @@ -376,9 +375,9 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) { /// If we allow multiline and there is already something in the input, start a newline. /// NOTE: Lexer is only available if we use highlighter. - if (highlighter && multiline && !replxx_last_is_delimiter) + if (highlighter && multiline && !last_is_delimiter) return rx.invoke(Replxx::ACTION::NEW_LINE, code); - replxx_last_is_delimiter = false; + last_is_delimiter = false; return rx.invoke(Replxx::ACTION::COMMIT_LINE, code); }; /// bind C-j to ENTER action. diff --git a/src/Client/ReplxxLineReader.h b/src/Client/ReplxxLineReader.h index cdaa5cab6be1..0dae383f8d53 100644 --- a/src/Client/ReplxxLineReader.h +++ b/src/Client/ReplxxLineReader.h @@ -12,6 +12,11 @@ namespace DB class ReplxxLineReader : public LineReader { public: + /// The highlighter callback of replxx, which also reports whether the last token of the + /// query is a delimiter: it sets `last_is_delimiter` to true or false, or leaves it intact + /// when this cannot be determined (e.g. the query ends with whitespace). + using Highlighter = std::function & colors, int cursor_position, bool & last_is_delimiter)>; + struct Options { Suggest & suggest; @@ -24,7 +29,7 @@ class ReplxxLineReader : public LineReader Patterns extenders; Patterns delimiters; std::span word_break_characters; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; std::istream & input_stream = std::cin; std::ostream & output_stream = std::cout; int in_fd = STDIN_FILENO; @@ -38,10 +43,6 @@ class ReplxxLineReader : public LineReader void enableBracketedPaste() override; void disableBracketedPaste() override; - /// If highlight is on, we will set a flag to denote whether the last token is a delimiter. - /// This is useful to determine the behavior of key when multiline is enabled. - static void setLastIsDelimiter(bool flag); - /// Set text to be prepopulated in the next readLine call void setInitialText(const String & text) override; private: @@ -51,7 +52,13 @@ class ReplxxLineReader : public LineReader void openEditor(bool format_query); replxx::Replxx rx; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; + + /// If highlight is on, the highlighter reports whether the last token is a delimiter. + /// This is used to determine the behavior of key when multiline is enabled. + /// It is a member rather than a global, because several readers can work concurrently + /// in one process (client sessions embedded into the server). + bool last_is_delimiter = false; const char * word_break_characters; diff --git a/src/Columns/ColumnArray.cpp b/src/Columns/ColumnArray.cpp index d572873dca0b..b1bc0921a153 100644 --- a/src/Columns/ColumnArray.cpp +++ b/src/Columns/ColumnArray.cpp @@ -978,17 +978,17 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi memset(&nested_filt[offsetAt(i)], 0, sizeAt(i)); } - auto res = ColumnArray::create(data->cloneEmpty()); - ssize_t nested_result_size_hint = 0; if (result_size_hint < 0) nested_result_size_hint = result_size_hint; else if (result_size_hint && result_size_hint < 1000000000 && data->size() < 1000000000) /// Avoid overflow. nested_result_size_hint = result_size_hint * data->size() / size; - res->data = data->filter(nested_filt, nested_result_size_hint); + /// See the comment in `indexImpl` about building the nested result first. + ColumnPtr res_data = data->filter(nested_filt, nested_result_size_hint); - Offsets & res_offsets = res->getOffsets(); + auto res_offsets_column = ColumnOffsets::create(); + Offsets & res_offsets = res_offsets_column->getData(); if (result_size_hint) res_offsets.reserve_exact(result_size_hint > 0 ? result_size_hint : size); @@ -1002,7 +1002,7 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi } } - return res; + return ColumnArray::create(res_data, std::move(res_offsets_column)); } ColumnPtr ColumnArray::filterNullable(const Filter & filt, ssize_t result_size_hint) const @@ -1236,10 +1236,8 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit PaddedPODArray & nested_indexes = nested_indexes_column->getData(); nested_indexes.reserve_exact(getOffsets().back()); - auto res = ColumnArray::create(data->cloneEmpty()); - - Offsets & res_offsets = res->getOffsets(); - res_offsets.resize_exact(limit); + auto res_offsets_column = ColumnOffsets::create(limit); + Offsets & res_offsets = res_offsets_column->getData(); size_t current_offset = 0; for (size_t i = 0; i < limit; ++i) @@ -1250,10 +1248,10 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit res_offsets[i] = current_offset; } - if (current_offset != 0) - res->data = data->index(*nested_indexes_column, current_offset); - - return res; + /// Build the nested result first: an empty clone of `data` copies its whole nested structure, which for + /// `Dynamic` is as deep as the data, and every level of this recursion would hold one. + ColumnPtr res_data = current_offset != 0 ? data->index(*nested_indexes_column, current_offset) : data->cloneEmpty(); + return ColumnArray::create(res_data, std::move(res_offsets_column)); } INSTANTIATE_INDEX_IMPL(ColumnArray) diff --git a/src/Columns/ColumnDynamic.cpp b/src/Columns/ColumnDynamic.cpp index 59ed075737df..446f5c38042e 100644 --- a/src/Columns/ColumnDynamic.cpp +++ b/src/Columns/ColumnDynamic.cpp @@ -314,6 +314,8 @@ void ColumnDynamic::get(size_t n, Field & res) const void ColumnDynamic::getValueNameImpl(WriteBufferFromOwnString & name_buf, size_t n, const Options & options) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); /// Check if value is not in shared variant. if (variant_col.globalDiscriminatorAt(n) != getSharedVariantDiscriminator()) @@ -338,6 +340,8 @@ void ColumnDynamic::insertFrom(const IColumn & src_, size_t n) void ColumnDynamic::doInsertFrom(const IColumn & src_, size_t n) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); /// Same variants: copy the Variant column directly. Skip this fast path when the source has values in @@ -417,6 +421,8 @@ void ColumnDynamic::insertRangeFrom(const IColumn & src_, size_t start, size_t l void ColumnDynamic::doInsertRangeFrom(const IColumn & src_, size_t start, size_t length) #endif { + checkStackSize(); + if (start + length > src_.size()) throw Exception(ErrorCodes::PARAMETER_OUT_OF_BOUND, "Parameter out of bound in ColumnDynamic::insertRangeFrom method. " "[start({}) + length({}) > src.size()({})]", start, length, src_.size()); @@ -649,6 +655,8 @@ void ColumnDynamic::insertManyFrom(const IColumn & src_, size_t position, size_t void ColumnDynamic::doInsertManyFrom(const IColumn & src_, size_t position, size_t length) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); auto & variant_col = getVariantColumn(); @@ -862,6 +870,8 @@ void ColumnDynamic::skipSerializedInArena(ReadBuffer & in) const void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); auto discr = variant_col.globalDiscriminatorAt(n); if (discr == ColumnVariant::NULL_DISCRIMINATOR) @@ -892,6 +902,7 @@ void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const void ColumnDynamic::updateHashWithValueRange(size_t begin, size_t end, SipHash & hash) const { + checkStackSize(); variant_column_ptr->updateHashWithValueRange(begin, end, hash); } @@ -901,6 +912,8 @@ int ColumnDynamic::compareAt(size_t n, size_t m, const IColumn & rhs, int nan_di int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_direction_hint) const #endif { + checkStackSize(); + const auto & left_variant = getVariantColumn(); const auto & right_dynamic = assert_cast(rhs); const auto & right_variant = right_dynamic.getVariantColumn(); @@ -1050,6 +1063,7 @@ void ColumnDynamic::updatePermutation(IColumn::PermutationSortDirection directio ColumnPtr ColumnDynamic::compress(bool force_compression) const { + checkStackSize(); ColumnPtr variant_compressed = variant_column_ptr->compress(force_compression); size_t byte_size = variant_compressed->byteSize(); return ColumnCompressed::create(size(), byte_size, @@ -1061,6 +1075,7 @@ ColumnPtr ColumnDynamic::compress(bool force_compression) const ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const { + checkStackSize(); std::unordered_map variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) variants_checkpoints[name] = variant_column_ptr->getVariantByGlobalDiscriminator(discr).getCheckpoint(); @@ -1069,6 +1084,7 @@ ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const { + checkStackSize(); auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) @@ -1086,6 +1102,7 @@ void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const void ColumnDynamic::rollback(const ColumnCheckpoint & checkpoint) { + checkStackSize(); const auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; /// Manually rollback internals of Variant column @@ -1158,6 +1175,7 @@ void ColumnDynamic::getAllTypeNamesInto(UnorderedSetWithMemoryTracking & void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); if (source_columns.empty()) return; @@ -1181,6 +1199,7 @@ void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t f void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); /// Internal variants of source dynamic columns may differ. /// We want to preallocate memory for all variants we will have after squashing. /// It may happen that the total number of variants in source columns will @@ -1288,6 +1307,8 @@ void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const { + checkStackSize(); + if (const auto * rhs_concrete = typeid_cast(&rhs)) return max_dynamic_types == rhs_concrete->max_dynamic_types && global_max_dynamic_types == rhs_concrete->global_max_dynamic_types && variant_info.variant_name == rhs_concrete->variant_info.variant_name @@ -1297,6 +1318,8 @@ bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_columns, std::optional max_dynamic_subcolumns) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "chooseDynamicStructureForMerge should be called only on empty Dynamic column"); @@ -1431,6 +1454,8 @@ void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_column void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "takeExactDynamicStructureFrom should be called only on empty Dynamic column"); @@ -1453,6 +1478,8 @@ void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) void ColumnDynamic::fixDynamicStructure() { + checkStackSize(); + /// Reduce max_dynamic_types to the number of selected variants, so there will be no possibility /// to extend selected variants on inserts into this column. /// -1 because we don't count shared variant in the limit. @@ -1487,6 +1514,8 @@ ColumnDynamic::StatisticsPtr ColumnDynamic::getOrCalculateStatistics() const void ColumnDynamic::takeOrCalculateStatisticsFrom(const Columns & source_columns) { + checkStackSize(); + /// Assumes dynamic structure has already been set by `takeExactDynamicStructureFrom` or `chooseDynamicStructureForMerge`. Statistics new_statistics; /// Collect total sizes for variants that are not in our structure (candidates for shared variant statistics). diff --git a/src/Columns/ColumnDynamic.h b/src/Columns/ColumnDynamic.h index cac25ec194e5..594512677430 100644 --- a/src/Columns/ColumnDynamic.h +++ b/src/Columns/ColumnDynamic.h @@ -7,6 +7,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,10 @@ namespace DB * When the limit on number of dynamic types is exceeded, all values * with new types are inserted into special shared variant with type String * that contains values and their types in binary format. + * + * Values nest into each other through variants like Array(Dynamic) to a depth that comes + * from the data, not from the declared type, so methods that recurse into the Variant + * column call checkStackSize. */ class ColumnDynamic final : public COWHelper, ColumnDynamic> { @@ -116,12 +121,14 @@ class ColumnDynamic final : public COWHelper, Colum MutableColumnPtr cloneEmpty() const override { + checkStackSize(); /// Keep current dynamic structure return Base::create(variant_column->cloneEmpty(), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumnPtr cloneResized(size_t size) const override { + checkStackSize(); return Base::create(variant_column->cloneResized(size), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } @@ -181,6 +188,7 @@ class ColumnDynamic final : public COWHelper, Colum void popBack(size_t n) override { + checkStackSize(); variant_column_ptr->popBack(n); } @@ -204,42 +212,50 @@ class ColumnDynamic final : public COWHelper, Colum void updateHashFast(SipHash & hash) const override { + checkStackSize(); variant_column_ptr->updateHashFast(hash); } ColumnPtr filter(const Filter & filt, ssize_t result_size_hint) const override { + checkStackSize(); return create(variant_column_ptr->filter(filt, result_size_hint), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } void filter(const Filter & filt) override { + checkStackSize(); variant_column_ptr->filter(filt); statistics.reset(); } void expand(const Filter & mask, bool inverted) override { + checkStackSize(); variant_column_ptr->expand(mask, inverted); } ColumnPtr permute(const Permutation & perm, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->permute(perm, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr index(const IColumn & indexes, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->index(indexes, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr replicate(const Offsets & replicate_offsets) const override { + checkStackSize(); return create(variant_column_ptr->replicate(replicate_offsets), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumns scatter(size_t num_columns, const Selector & selector) const override { + checkStackSize(); MutableColumns scattered_variant_columns = variant_column_ptr->scatter(num_columns, selector); MutableColumns scattered_columns; scattered_columns.reserve(num_columns); @@ -257,6 +273,7 @@ class ColumnDynamic final : public COWHelper, Colum bool hasEqualValues() const override { + checkStackSize(); return variant_column_ptr->hasEqualValues(); } @@ -287,31 +304,37 @@ class ColumnDynamic final : public COWHelper, Colum void shrinkToFit() override { + checkStackSize(); variant_column_ptr->shrinkToFit(); } void ensureOwnership() override { + checkStackSize(); variant_column_ptr->ensureOwnership(); } size_t byteSize() const override { + checkStackSize(); return variant_column_ptr->byteSize(); } size_t byteSizeAt(size_t n) const override { + checkStackSize(); return variant_column_ptr->byteSizeAt(n); } size_t allocatedBytes() const override { + checkStackSize(); return variant_column_ptr->allocatedBytes(); } void protect() override { + checkStackSize(); variant_column_ptr->protect(); } @@ -323,11 +346,17 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumn(MutableColumnCallback callback) override { + /// Callers like IColumn::mutate recurse into the subcolumns through this method. + checkStackSize(); callback(variant_column); variant_column_ptr = assert_cast(variant_column.get()); } - void forEachSubcolumn(ColumnCallback callback) const override { callback(variant_column); } + void forEachSubcolumn(ColumnCallback callback) const override + { + checkStackSize(); + callback(variant_column); + } /// Dynamic columns manage their own variant_info type metadata. /// The default convertToFullIfNeeded recurses into subcolumns and strips LowCardinality @@ -337,6 +366,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumnRecursively(RecursiveMutableColumnCallback callback) override { + checkStackSize(); callback(*variant_column); variant_column_ptr = assert_cast(variant_column.get()); variant_column->forEachMutableSubcolumnRecursively(callback); @@ -344,6 +374,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachSubcolumnRecursively(RecursiveColumnCallback callback) const override { + checkStackSize(); callback(*variant_column); variant_column->forEachSubcolumnRecursively(callback); } @@ -374,11 +405,13 @@ class ColumnDynamic final : public COWHelper, Colum void finalize() override { + checkStackSize(); variant_column_ptr->finalize(); } bool isFinalized() const override { + checkStackSize(); return variant_column_ptr->isFinalized(); } diff --git a/src/Columns/ColumnLowCardinality.cpp b/src/Columns/ColumnLowCardinality.cpp index 9a76fde596b9..a6540dbf60c3 100644 --- a/src/Columns/ColumnLowCardinality.cpp +++ b/src/Columns/ColumnLowCardinality.cpp @@ -234,7 +234,7 @@ void ColumnLowCardinality::insertRangeFromFullColumn(const IColumn & src, size_t idx.insertIndexesRange(*inserted_indexes, 0, length); } -static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) +void ColumnLowCardinality::checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) { auto check_for_type = [&](auto type) { @@ -248,14 +248,14 @@ static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) size_t num_rows = data.size(); if (num_rows == 0) return true; - UInt64 max_position = 0; + ColumnType max_position = 0; for (size_t i = 0; i < num_rows; ++i) - max_position = std::max(max_position, data[i]); + max_position = std::max(max_position, data[i]); - if (max_position >= limit) + if (static_cast(max_position) >= limit) throw Exception(ErrorCodes::INCORRECT_DATA, "Index for LowCardinality is out of range. Dictionary size is {}, " - "but found index with value {}", limit, max_position); + "but found index with value {}", limit, static_cast(max_position)); return true; }; diff --git a/src/Columns/ColumnLowCardinality.h b/src/Columns/ColumnLowCardinality.h index 8538b4cededf..d03921bef1fe 100644 --- a/src/Columns/ColumnLowCardinality.h +++ b/src/Columns/ColumnLowCardinality.h @@ -94,6 +94,7 @@ class ColumnLowCardinality final : public COWHelper +#include #include #include #include @@ -16,6 +17,12 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace FailPoints +{ + extern const char reverse_index_build_index_throw[]; } template @@ -432,17 +439,25 @@ void ReverseIndex::buildIndex() if (!column) throw Exception(ErrorCodes::LOGICAL_ERROR, "ReverseIndex can't build index because index column wasn't set."); + /// Build everything into local variables and publish them only at the end, so that an exception + /// thrown midway (for example, `MEMORY_LIMIT_EXCEEDED` from an allocation in `calcHashes`) does not + /// leave a half-built index behind: a non-null `index` with a null `saved_hash` would make the next + /// `insert` dereference a null pointer. auto size = column->size(); - index = std::make_unique(size); + auto new_index = std::make_unique(size); + fiu_do_on(FailPoints::reverse_index_build_index_throw, + throw Exception(ErrorCodes::MEMORY_LIMIT_EXCEEDED, "Injected failure while building ReverseIndex");); + + ColumnUInt64::MutablePtr new_saved_hash; if constexpr (use_saved_hash) - saved_hash = calcHashes(); + new_saved_hash = calcHashes(); - auto & state = index->getState(); + auto & state = new_index->getState(); state.index_column = column; state.base_index = base_index; if constexpr (use_saved_hash) - state.saved_hash_column = &saved_hash->getData(); + state.saved_hash_column = &new_saved_hash->getData(); using IteratorType = typename IndexMapType::iterator; IteratorType iterator; @@ -452,15 +467,18 @@ void ReverseIndex::buildIndex() { UInt64 hash; if constexpr (use_saved_hash) - hash = saved_hash->getElement(row); + hash = new_saved_hash->getElement(row); else hash = getHash(column->getDataAt(row)); - index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); + new_index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); if (!inserted) throw Exception(ErrorCodes::LOGICAL_ERROR, "Duplicating keys found in ReverseIndex."); } + + index = std::move(new_index); + saved_hash = std::move(new_saved_hash); } template @@ -484,37 +502,58 @@ UInt64 ReverseIndex::insert(std::string_view data) if (!index) buildIndex(); - using IteratorType = typename IndexMapType::iterator; - IteratorType iterator; - bool inserted; - - auto hash = getHash(data); - UInt64 num_rows = size(); - - if constexpr (use_saved_hash) + try { - auto & column_data = saved_hash->getData(); - if (column_data.size() <= num_rows) - column_data.resize(num_rows + 1); - column_data[num_rows] = hash; - } - else - column->insertData(data.data(), data.size()); + using IteratorType = typename IndexMapType::iterator; + IteratorType iterator; + bool inserted = false; - index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + auto hash = getHash(data); + UInt64 num_rows = size(); - if constexpr (use_saved_hash) - { - if (inserted) + if constexpr (use_saved_hash) + { + auto & column_data = saved_hash->getData(); + if (column_data.size() <= num_rows) + column_data.resize(num_rows + 1); + column_data[num_rows] = hash; + } + else column->insertData(data.data(), data.size()); + + index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + + if constexpr (use_saved_hash) + { + if (inserted) + column->insertData(data.data(), data.size()); + } + else + { + if (!inserted) + column->popBack(1); + } + + return iterator->getValue(); } - else + catch (...) { - if (!inserted) - column->popBack(1); - } + /// The hash table may now disagree with the column: for example, the key was already added to the + /// hash table, but `insertData` failed, so the key refers to a row that does not exist. Drop the index, + /// it is rebuilt from the column on the next use. + index = nullptr; + saved_hash = nullptr; - return iterator->getValue(); + if constexpr (std::is_same_v) + { + /// `ColumnString::insertData` appends to `chars` before it grows `offsets`. If the latter failed, the bytes + /// of the row that was never added are still there and would become a prefix of the next inserted value. + const auto & offsets = column->getOffsets(); + column->getChars().resize_assume_reserved(offsets.empty() ? 0 : offsets.back()); + } + + throw; + } } template diff --git a/src/Columns/tests/gtest_reverse_index_exception_safety.cpp b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp new file mode 100644 index 000000000000..f0826e7359d1 --- /dev/null +++ b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace DB::FailPoints +{ + extern const char reverse_index_build_index_throw[]; +} + +using namespace DB; + +/// Mimics what happens during an asynchronous insert flush under memory pressure: the first insert into a +/// `LowCardinality` dictionary throws `MEMORY_LIMIT_EXCEEDED` while the reverse index is being built, the error +/// is handled by the caller, and the same dictionary is reused for the next entry. The index must either be +/// fully built or absent, never a non-null hash table paired with a null saved-hash array. +TEST(ReverseIndex, ExceptionWhileBuildingIndexLeavesNoHalfBuiltIndex) +{ + auto column = ColumnUnique::create(DataTypeString()); + + FailPointInjection::enableFailPoint(FailPoints::reverse_index_build_index_throw); + try + { + column->uniqueInsertData("a", 1); + FAIL() << "Expected an exception from the failpoint"; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::MEMORY_LIMIT_EXCEEDED); + } + FailPointInjection::disableFailPoint(FailPoints::reverse_index_build_index_throw); + + /// Index 0 is the default value (empty string). + EXPECT_EQ(column->size(), 1u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("b", 1), 2u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("", 0), 0u); + EXPECT_EQ(column->size(), 3u); + EXPECT_EQ(column->getDataAt(1), "a"); + EXPECT_EQ(column->getDataAt(2), "b"); +} + +/// The same reuse after a failure inside `insert` itself: the key is already in the hash table and the string bytes are +/// already appended to `chars` when growing `offsets` fails. The dictionary must come back to the state before the +/// insert, so that the next inserted value does not get the failed one as a prefix and lookups stay correct. +TEST(ReverseIndex, ExceptionWhileInsertingDataKeepsDictionaryConsistent) +{ + MainThreadStatus::getInstance(); + auto & thread_tracker = CurrentThread::get().memory_tracker; + + auto column = ColumnUnique::create(DataTypeString()); + ASSERT_EQ(column->uniqueInsertData("a", 1), 1u); + + /// Leave `offsets` without spare capacity and `chars` with plenty, so that growing `offsets` is the only + /// allocation of the next insert. + auto & nested = assert_cast(column->getNestedColumn()->assumeMutableRef()); + nested.getOffsets().shrink_to_fit(); + nested.getChars().reserve(nested.getChars().size() + 1024); + + const Int64 saved_untracked_limit = CurrentThread::get().untracked_memory_limit; + const Int64 saved_thread_hard_limit = thread_tracker.getHardLimit(); + const Int64 saved_total_hard_limit = total_memory_tracker.getHardLimit(); + + auto lift_limits = [&] + { + total_memory_tracker.setHardLimit(saved_total_hard_limit); + thread_tracker.setHardLimit(saved_thread_hard_limit); + CurrentThread::get().untracked_memory_limit = saved_untracked_limit; + }; + SCOPE_EXIT_SAFE(lift_limits()); + + /// Make even a tiny allocation reach the trackers and fail: no per-thread untracked buffer, limits of one byte. + CurrentThread::get().untracked_memory_limit = 0; + CurrentThread::flushUntrackedMemory(); + total_memory_tracker.resetCounters(); + thread_tracker.resetCounters(); + total_memory_tracker.setHardLimit(1); + thread_tracker.setHardLimit(1); + + bool thrown = false; + int code = 0; + try + { + column->uniqueInsertData("bb", 2); + } + catch (const Exception & e) + { + thrown = true; + code = e.code(); + } + + /// Lift the limits before anything else, the assertions allocate. + lift_limits(); + + ASSERT_TRUE(thrown) << "the insert was expected to fail under the memory limit"; + EXPECT_EQ(code, ErrorCodes::MEMORY_LIMIT_EXCEEDED); + + EXPECT_EQ(column->size(), 2u); + EXPECT_EQ(nested.getChars().size(), nested.getOffsets().back()); + + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->getDataAt(2), "c"); + EXPECT_EQ(column->uniqueInsertData("bb", 2), 3u); + EXPECT_EQ(column->getDataAt(3), "bb"); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->size(), 4u); +} diff --git a/src/Common/CurrentMetrics.cpp b/src/Common/CurrentMetrics.cpp index 84d3b3c5bd0e..c88478725f6e 100644 --- a/src/Common/CurrentMetrics.cpp +++ b/src/Common/CurrentMetrics.cpp @@ -323,6 +323,8 @@ M(AsyncInsertCacheSize, "Number of async insert hash id in cache") \ M(IcebergMetadataFilesCacheBytes, "Size of the Iceberg metadata cache in bytes") \ M(IcebergMetadataFilesCacheFiles, "Number of cached files in the Iceberg metadata cache") \ + M(GlueCatalogSchemaCacheBytes, "Size of the cache of current Iceberg schema field types in Glue catalogs in bytes") \ + M(GlueCatalogSchemaCacheEntries, "Number of entries in the cache of current Iceberg schema field types in Glue catalogs") \ M(ParquetMetadataCacheBytes, "Size of the Parquet metadata cache in bytes") \ M(ParquetMetadataCacheFiles, "Number of cached files in the Parquet metadata cache") \ M(AvroSchemaCacheBytes, "Size of the Avro schema cache in bytes") \ diff --git a/src/Common/DateLUTImpl.h b/src/Common/DateLUTImpl.h index 4ac32f91a97e..690a6496ab53 100644 --- a/src/Common/DateLUTImpl.h +++ b/src/Common/DateLUTImpl.h @@ -561,21 +561,15 @@ class DateLUTImpl { const LUTIndex index = findIndex(t); - /// Calculate daylight saving offset first. - /// Because the "amount_of_offset_change" in LUT entry only exists in the change day, it's costly to scan it from the very begin. - /// but we can figure out all the accumulated offsets from 1970-01-01 to that day just by get the whole difference between lut[].date, - /// and then, we can directly subtract multiple 86400s to get the real DST offsets for the leap seconds is not considered now. - Time res = (lut[index].date - lut[daynum_offset_epoch].date) % 86400; - - /// As so far to know, the maximal DST offset couldn't be more than 2 hours, so after the modulo operation the remainder - /// will sits between [-offset --> 0 --> offset] which respectively corresponds to moving clock forward or backward. - res = res > 43200 ? (86400 - res) : (0 - res); + /// The offset at the start of the day: local midnight is `day_number * 86400` seconds of local + /// time from the epoch, while `date` is the UTC instant of that same midnight. + Time res = (static_cast(index.toUnderType()) - daynum_offset_epoch) * 86400 - lut[index].date; /// Check if has a offset change during this day. Add the change when cross the line if (lut[index].amount_of_offset_change() != 0 && t >= lut[index].date + lut[index].time_at_offset_change()) res += lut[index].amount_of_offset_change(); - return res + offset_at_start_of_epoch; + return res; } diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 875173c92b8b..7dfb2f297886 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -34,6 +34,7 @@ static struct InitFiu #define APPLY_FOR_FAILPOINTS(ONCE, REGULAR, PAUSEABLE_ONCE, PAUSEABLE) \ ONCE(replicated_merge_tree_commit_zk_fail_after_op) \ ONCE(replicated_queue_fail_next_entry) \ + ONCE(reverse_index_build_index_throw) \ REGULAR(replicated_queue_unfail_entries) \ ONCE(replicated_merge_tree_insert_quorum_fail_0) \ REGULAR(replicated_merge_tree_commit_zk_fail_when_recovering_from_hw_fault) \ @@ -96,6 +97,7 @@ static struct InitFiu PAUSEABLE_ONCE(finish_clean_quorum_failed_parts) \ PAUSEABLE_ONCE(smt_wait_next_mutation) \ PAUSEABLE_ONCE(delta_lake_metadata_iterate_pause) \ + PAUSEABLE_ONCE(rmt_restore_replica_pause_before_metadata_version_raise) \ PAUSEABLE(dummy_pausable_failpoint) \ ONCE(execute_query_calling_empty_set_result_func_on_exception) \ ONCE(terminate_with_exception) \ @@ -129,6 +131,7 @@ static struct InitFiu REGULAR(database_replicated_delay_recovery) \ REGULAR(database_replicated_delay_entry_execution) \ PAUSEABLE(database_replicated_stop_entry_execution) \ + PAUSEABLE_ONCE(database_replicated_pause_before_initial_query_execution) \ REGULAR(remove_merge_tree_part_delay) \ REGULAR(plain_object_storage_copy_temp_source_file_fail_on_file_move) \ REGULAR(plain_object_storage_copy_temp_target_file_fail_on_file_move) \ diff --git a/src/Common/RemoteHostFilter.cpp b/src/Common/RemoteHostFilter.cpp index 6f953f48d48b..5b5da5ec7c6b 100644 --- a/src/Common/RemoteHostFilter.cpp +++ b/src/Common/RemoteHostFilter.cpp @@ -110,6 +110,10 @@ bool RemoteHostFilter::checkForDirectEntry(const std::string & str) const /// Allow everything by default. return true; + /// Connectors take the host as a C string and stop at the first NUL, so the checked string must not contain one. + if (str.contains('\0')) + return false; + std::lock_guard guard(hosts_mutex); if (primary_hosts.contains(str)) diff --git a/src/Common/Scheduler/CPUSlotsAllocation.cpp b/src/Common/Scheduler/CPUSlotsAllocation.cpp index a11e4a6feb9a..30d9d735e60d 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.cpp +++ b/src/Common/Scheduler/CPUSlotsAllocation.cpp @@ -7,6 +7,7 @@ #include #include #include +#include namespace ProfileEvents { @@ -72,6 +73,10 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker for (CPUSlotRequest & request : requests) request.allocation = this; + wait_thread_group = CurrentThread::getGroup(); + if (wait_thread_group) + wait_counters = &wait_thread_group->performance_counters; + std::unique_lock lock{schedule_mutex}; while (allocated < total_slots) { @@ -79,7 +84,7 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker { queue->enqueueRequest(current_request); scheduled_slot_increment.emplace(CurrentMetrics::ConcurrencyControlScheduled); - wait_timer.emplace(CurrentThread::getProfileEvents().timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); + wait_timer.emplace(wait_counters->timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); break; } else // noncompeting slot - provide for free diff --git a/src/Common/Scheduler/CPUSlotsAllocation.h b/src/Common/Scheduler/CPUSlotsAllocation.h index d8963f14b8cf..caaf37139b25 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.h +++ b/src/Common/Scheduler/CPUSlotsAllocation.h @@ -17,6 +17,7 @@ namespace DB { class CPUSlotsAllocation; +class ThreadGroup; // Represents a resource request for a cpu slot for a single thread class CPUSlotRequest final : public ResourceRequest @@ -113,6 +114,9 @@ class CPUSlotsAllocation final : public ISlotAllocation std::vector requests; // Requests per every slot CPUSlotRequest * current_request; std::optional scheduled_slot_increment; + /// `wait_timer` may end on another thread after the creating one has exited, so it counts into the query's group, kept alive here. + std::shared_ptr wait_thread_group; + ProfileEvents::Counters * wait_counters = &ProfileEvents::global_counters; std::optional wait_timer; }; diff --git a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp index 0c6ba16e64d4..cdc0b8f1ad07 100644 --- a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp +++ b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -49,6 +51,7 @@ namespace ProfileEvents { extern const Event ConcurrencyControlUpscales; extern const Event ConcurrencyControlDownscales; + extern const Event ConcurrencyControlWaitMicroseconds; } namespace CurrentMetrics @@ -1068,6 +1071,41 @@ TEST(SchedulerWorkloadResourceManager, CPUSchedulingRoundRobin) t.wait(); } +/// The wait for a CPU slot is accounted to the query even when the allocation outlives the thread that created it +/// (here: destroyed on another thread while its request is still queued, like a `KILL QUERY` of a waiting query). +TEST(SchedulerWorkloadResourceManager, CPUSlotsWaitTimerOutlivesCreatingThread) +{ + ResourceTest t; + t.query("CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD)"); + t.query("CREATE WORKLOAD all SETTINGS max_concurrent_threads = 1"); + ClassifierPtr c = t.manager->acquire("all"); + ResourceLink link = c->get("cpu"); + + /// Takes the only slot, so the next allocation keeps its request queued. + auto blocker = std::make_shared(1, 0, link, link); + auto blocker_slot = blocker->acquire(); + + std::weak_ptr weak_group; + SlotAllocationPtr allocation; + std::thread([&] + { + DB::ThreadStatus thread_status; + auto group = std::make_shared(Context::getGlobalContextInstance(), 0); + weak_group = group; + CurrentThread::attachToGroupIfDetached(group); + allocation = std::make_shared(1, 0, link, link); + CurrentThread::detachFromGroupIfNotDetached(); + }).join(); + + ASSERT_TRUE(allocation->isRequesting()); + /// The creating thread is gone, so only the allocation can still own the group. + ThreadGroupPtr group = weak_group.lock(); + ASSERT_NE(group, nullptr); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + allocation.reset(); + EXPECT_GE(group->performance_counters[ProfileEvents::ConcurrencyControlWaitMicroseconds], 10'000); +} + TEST(SchedulerWorkloadResourceManager, CPUSchedulingFairness) { ResourceTest t; diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 15b5d71e193c..3054e98b8259 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -116,7 +116,10 @@ ThreadStatus::ThreadStatus() last_rusage = std::make_unique(); memory_tracker.setDescription("Thread"); - log = getLogger("ThreadStatus"); + /// A `ThreadStatus` is created for every job of a thread pool, and `getLogger` locks the global mutex of the + /// registry of loggers, so all threads of the pools would contend on it. + static const LoggerPtr thread_status_log = getLogger("ThreadStatus"); + log = thread_status_log; current_thread = this; diff --git a/src/Common/ZooKeeper/ZooKeeperConstants.h b/src/Common/ZooKeeper/ZooKeeperConstants.h index d5c5cc119fb5..7e61d02e91c1 100644 --- a/src/Common/ZooKeeper/ZooKeeperConstants.h +++ b/src/Common/ZooKeeper/ZooKeeperConstants.h @@ -92,6 +92,8 @@ static constexpr int32_t PASSWORD_LENGTH = 16; static constexpr int32_t MAX_STRING_OR_ARRAY_SIZE = 1 << 28; /// 256 MiB /// Upper bound on elements reserved up front when reading an array; the declared size is attacker-controlled static constexpr int32_t MAX_ARRAY_PREALLOCATION = 4096; +/// Bytes read per step when reading a string; the declared size is attacker-controlled, so memory grows with the bytes received +static constexpr int32_t MAX_STRING_PREALLOCATION = 1 << 16; /// 64 KiB static constexpr int32_t DEFAULT_SESSION_TIMEOUT_MS = 30000; static constexpr int32_t DEFAULT_MIN_SESSION_TIMEOUT_MS = 10000; static constexpr int32_t DEFAULT_MAX_SESSION_TIMEOUT_MS = 100000; diff --git a/src/Common/ZooKeeper/ZooKeeperIO.cpp b/src/Common/ZooKeeper/ZooKeeperIO.cpp index 88de2b4dc01d..c872bdac795e 100644 --- a/src/Common/ZooKeeper/ZooKeeperIO.cpp +++ b/src/Common/ZooKeeper/ZooKeeperIO.cpp @@ -93,11 +93,24 @@ void read(std::string & s, ReadBuffer & in) if (size > MAX_STRING_OR_ARRAY_SIZE) throw Exception(Error::ZMARSHALLINGERROR,"Too large string size while reading from ZooKeeper {}", size); - s.resize(size); - size_t read_bytes = in.read(s.data(), size); - if (read_bytes != static_cast(size)) - throw Exception( - Error::ZMARSHALLINGERROR, "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", size, read_bytes); + /// Memory must track bytes actually read, not the declared size: + /// do not pre-allocate for an attacker-controlled length. + s.clear(); + size_t remaining = static_cast(size); + while (remaining > 0) + { + const size_t chunk = std::min(remaining, MAX_STRING_PREALLOCATION); + const size_t old_size = s.size(); + s.resize(old_size + chunk); + const size_t read_bytes = in.read(s.data() + old_size, chunk); + if (read_bytes != chunk) + throw Exception( + Error::ZMARSHALLINGERROR, + "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", + size, + old_size + read_bytes); + remaining -= chunk; + } } void read(ACL & acl, ReadBuffer & in) diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index d368e482aa8c..a4f762ec2d57 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -2,14 +2,69 @@ #include +#include #include #include #include +#include namespace DB { +/** Hides the secrets of an Azure connection string as the Azure SDK reads it (`Azure::Storage::_internal::ParseConnectionString`, + * `contrib/azure/sdk/storage/azure-storage-common/src/storage_credential.cpp`): a key runs to '=' and its value to ';', keys + * match exactly, and the last copy of a repeated key wins. Splitting at every ';' first can only hide more than the SDK reads. + * - secret keys: `AccountName=a;AccountKey=K;SharedAccessSignature=S` -> `AccountName=a;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]` + * - repeated keys: `AccountKey=K1;AccountKey=K2` -> `AccountKey=[HIDDEN];AccountKey=[HIDDEN]` + * - an endpoint is a url, so a query in it is a SAS: `BlobEndpoint=https://h/?sig=S` or `BlobEndpoint=https://u@h/` -> `BlobEndpoint=[HIDDEN]` + * - the whole string is hidden when a '?', '#' or '@' is still shown, or when it has one and holds a url outside the pair + * values (':' or '/' in a key or in a part without '='; no key has them): `https://h/?sig=S` or `https://u:p=s@h/` -> `[HIDDEN]` + * Returns whether anything was hidden. + */ +inline bool maskAzureConnectionStringSecrets(std::string & str) +{ + static constexpr std::array secret_keys = {"AccountKey", "SharedAccessSignature"}; + auto is_secret_key = [](std::string_view key) { return std::ranges::find(secret_keys, key) != secret_keys.end(); }; + + const bool has_url_delimiters = str.find_first_of("?#@") != std::string::npos; + bool url_outside_values = false; + std::string result; + size_t copied = 0; + bool masked = false; + for (size_t part_begin = 0; part_begin <= str.length();) + { + const size_t part_end = std::min(str.find(';', part_begin), str.length()); + const std::string_view part = std::string_view(str).substr(part_begin, part_end - part_begin); + const size_t equals = part.find('='); + if (part.substr(0, equals).find_first_of(":/") != std::string_view::npos) + url_outside_values = true; + if (equals != std::string_view::npos + && (is_secret_key(part.substr(0, equals)) || part.substr(equals + 1).find_first_of("?@") != std::string_view::npos)) + { + const size_t value_begin = part_begin + equals + 1; + result.append(str, copied, value_begin - copied); + result.append("[HIDDEN]"); + copied = part_end; + masked = true; + } + part_begin = part_end + 1; + } + + if (masked) + { + result.append(str, copied, std::string::npos); + str = std::move(result); + } + + if (str.find_first_of("?#@") != std::string::npos || (url_outside_values && has_url_delimiters)) + { + str = "[HIDDEN]"; + return true; + } + return masked; +} + inline bool maskURIPassword(std::string * uri) { return RE2::Replace(uri, R"(([^:]+://[^:]*):([^@]*)@(.*))", "\\1:[HIDDEN]@\\3"); diff --git a/src/Common/mysqlxx/Connection.cpp b/src/Common/mysqlxx/Connection.cpp index f9f2d3e5d1aa..8614bed72705 100644 --- a/src/Common/mysqlxx/Connection.cpp +++ b/src/Common/mysqlxx/Connection.cpp @@ -114,6 +114,14 @@ void Connection::connect(const char* db, if (mysql_ssl_set(driver.get(), ifNotEmpty(ssl_key), ifNotEmpty(ssl_cert), ifNotEmpty(ssl_ca), nullptr, nullptr)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// Without an explicit socket, use TCP to the given port: otherwise `localhost` goes to the library's default socket. + if (!ifNotEmpty(socket)) + { + unsigned protocol = MYSQL_PROTOCOL_TCP; + if (mysql_options(driver.get(), MYSQL_OPT_PROTOCOL, &protocol)) + throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + } + if (!mysql_real_connect(driver.get(), server, user, password, db, port, ifNotEmpty(socket), driver->client_flag)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); diff --git a/src/Common/mysqlxx/Pool.cpp b/src/Common/mysqlxx/Pool.cpp index 7173adf3326c..58d54882fa6c 100644 --- a/src/Common/mysqlxx/Pool.cpp +++ b/src/Common/mysqlxx/Pool.cpp @@ -9,11 +9,61 @@ #include #include #include +#include #include #include #include +namespace DB::ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + +namespace +{ + +/// `mysql_real_connect` reinterprets these hosts and port 0; reject them so it dials exactly what `remote_url_allow_hosts` checked. +void checkConnectionTarget(const std::string & server, unsigned port, const std::string & socket) +{ + std::string_view meaning; + if (server.contains('\0')) + meaning = "the end of the host"; + else if (server.find_first_of(";=") != std::string::npos) + meaning = "a connection string"; + else if (server.contains("://")) + meaning = "a connection plugin URL"; + else if (server.contains(',')) + meaning = "a list of hosts"; + + if (!meaning.empty()) + { + std::string printable; + for (const char c : server) + printable += c == '\0' ? std::string_view("\\0") : std::string_view(&c, 1); + + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL host '{}' contains syntax which the MySQL client library would read as {}. " + "Specify a plain host and port, and use the `socket` and `ssl_*` settings instead", + printable, meaning); + } + + if (socket.contains('\0')) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, "MySQL socket for host '{}' contains a NUL byte, where the MySQL client library would end it", server); + + /// The client library uses the socket only for an empty host or `localhost`, otherwise it connects over TCP. + const bool uses_socket = !socket.empty() && (server.empty() || server == "localhost"); + if (port == 0 && !uses_socket) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL port 0 for host '{}' would be replaced by the default port of the MySQL client library. Specify the port explicitly", + server); +} + +} + namespace mysqlxx { @@ -367,6 +417,9 @@ void Pool::initialize() Pool::Connection * Pool::allocConnection(bool dont_throw_if_failed_first_time) { + /// All connections of the pool are created here. + checkConnectionTarget(server, port, socket); + auto conn_ptr = std::make_unique(); try diff --git a/src/Common/tests/gtest_distrusted_certificates.cpp b/src/Common/tests/gtest_distrusted_certificates.cpp new file mode 100644 index 000000000000..5931feea9f6b --- /dev/null +++ b/src/Common/tests/gtest_distrusted_certificates.cpp @@ -0,0 +1,137 @@ +#include "config.h" + +#if USE_SSL + +#include + +#include +#include + +#include +#include +#include + +#include +#include + + +namespace +{ + +/// `emSign ECC Root CA - G3`, distrusted. +constexpr std::string_view emsign_ecc_root_g3 = R"( +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +)"; + +/// `EM DV TLS CA - G3B` cross-signed by `AAA Certificate Services`, distrusted by the key of the certificate issued by `emSign Root TLS CA - G3`. +constexpr std::string_view em_dv_tls_ca_g3b_cross_signed = R"( +-----BEGIN CERTIFICATE----- +MIIDzjCCAragAwIBAgIRAKAk/fS6Zlx4XOSgIEg4WLcwDQYJKoZIhvcNAQELBQAw +ezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV +BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0yNTA1MTQwMDAwMDBaFw0y +ODEyMzEyMzU5NTlaMD8xCzAJBgNVBAYTAk5MMRMwEQYDVQQKDAplTXVkaHJhIEJW +MRswGQYDVQQDDBJFTSBEViBUTFMgQ0EgLSBHM0IwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAATnntnASpdzxHNeUREdqFrCvV5kqzdLgOEsvCA47B5PDjuBL8mFnh5nr7BO +L4vJf3SFumWqkR7opORbYtXMA9Vr5nizw4y03JN8okYOI4RTyJKTXSnUT5HhVga2 +PM7atGijggE1MIIBMTAfBgNVHSMEGDAWgBSgEQojPpbxB+zirynvgqV/0DCktDAd +BgNVHQ4EFgQU4h4v5xwZOQ5VS2LBICRXNSSKJRQwDgYDVR0PAQH/BAQDAgEGMBIG +A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC +MDEGA1UdIAQqMCgwCAYGZ4EMAQIBMA0GCysGAQQBg44hAQABMA0GCysGAQQBg44h +AQJkMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0FB +QUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEF +BQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBCwUAA4IB +AQBzQ1IoqpdotM6gFrR4Q3YrKifOLeaj5XXunldpVE/vZn2TxC2y0s8oYiLR5ICE +wqVXSB7N6BM1Mp+Nif7Jbhb2IswAfSR4Iik8+B0iRmi7lYoNlycCgHjmsjOmZaxM +QkPmjXAJbG5f4V41OsvJZmS7lI3r0IuvEDVX3GAZ13on6IImSs9ybNpHQ7NCqkMQ +7wH4uAO1dtpFycgJSdHaCOhHjrox2BTYGLdpUrYwY3EOAjlZ8UGgsxs7mG+xquMl +bN1LFURwfnkVMP3T/DBIZ/ys2+lNFyxK3FlArrV4/000uTnVB1lO8oGORYdXoT5V +GUyRCEIDhF5TBUuKF4E3kf1h +-----END CERTIFICATE-----)"; + +/// `emSign Root CA - G1`, not affected. +constexpr std::string_view emsign_root_g1 = R"( +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +)"; + +using X509Ptr = std::unique_ptr; + +X509Ptr parseCertificate(std::string_view pem) +{ + std::unique_ptr bio(BIO_new_mem_buf(pem.data(), static_cast(pem.size())), BIO_free); + X509Ptr certificate(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr), X509_free); + EXPECT_NE(certificate, nullptr); + return certificate; +} + +/// Verifies a trusted self-signed certificate the same way a TLS connection of a Poco context does it. +int verifyTrustedRoot(std::string_view pem) +{ + Poco::Net::Context context(Poco::Net::Context::CLIENT_USE, Poco::Net::Context::Params{}); + X509Ptr certificate = parseCertificate(pem); + X509_STORE * store = SSL_CTX_get_cert_store(context.sslContext()); + EXPECT_EQ(X509_STORE_add_cert(store, certificate.get()), 1); + + std::unique_ptr store_ctx(X509_STORE_CTX_new(), X509_STORE_CTX_free); + EXPECT_EQ(X509_STORE_CTX_init(store_ctx.get(), store, certificate.get(), nullptr), 1); + X509_STORE_CTX_set_verify_cb(store_ctx.get(), SSL_CTX_get_verify_callback(context.sslContext())); + + if (X509_verify_cert(store_ctx.get()) == 1) + return X509_V_OK; + return X509_STORE_CTX_get_error(store_ctx.get()); +} + +} + + +TEST(DistrustedCertificates, Check) +{ + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_ecc_root_g3).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(em_dv_tls_ca_g3b_cross_signed).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_root_g1).get()), X509_V_OK); +} + +TEST(DistrustedCertificates, RejectedEvenIfTrusted) +{ + EXPECT_EQ(verifyTrustedRoot(emsign_ecc_root_g3), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(verifyTrustedRoot(emsign_root_g1), X509_V_OK); +} + +#endif diff --git a/src/Common/tests/gtest_file_channel_rotation_failure.cpp b/src/Common/tests/gtest_file_channel_rotation_failure.cpp new file mode 100644 index 000000000000..d4ca3bee239b --- /dev/null +++ b/src/Common/tests/gtest_file_channel_rotation_failure.cpp @@ -0,0 +1,133 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Log rotation must not leave `FileChannel` with a deleted `LogFile` when the process has no free file descriptors. + +namespace +{ + +/// glibc defines `RLIMIT_NOFILE` as a self-referential macro, which trips -Wdisabled-macro-expansion inside gtest macros. +const auto nofile_resource = RLIMIT_NOFILE; + +struct DescriptorTableGuard +{ + struct rlimit original_limit{}; + std::vector descriptors; + + void release() + { + for (int fd : descriptors) + ::close(fd); + descriptors.clear(); + EXPECT_EQ(0, setrlimit(nofile_resource, &original_limit)); + } + + ~DescriptorTableGuard() { release(); } +}; + +int setSoftLimit(rlim_t value, const struct rlimit & original_limit) +{ + struct rlimit limit = original_limit; + limit.rlim_cur = value; + return setrlimit(nofile_resource, &limit); +} + +int fillDescriptorTable(DescriptorTableGuard & guard) +{ + while (true) + { + int fd = ::open("/dev/null", O_RDONLY | O_CLOEXEC); + if (fd < 0) + return errno; + guard.descriptors.push_back(fd); + } +} + +Poco::Message makeMessage(const std::string & text) +{ + return Poco::Message("gtest_file_channel_rotation_failure", text, Poco::Message::PRIO_INFORMATION); +} + +void expectNoFreeDescriptors(Poco::FileChannel & channel, const std::string & text) +{ + try + { + channel.log(makeMessage(text)); + ADD_FAILURE() << "Expected EMFILE while logging: " << text; + } + catch (const Poco::FileException & e) + { + EXPECT_EQ(EMFILE, e.code()) << e.displayText(); + } +} + +std::string readFile(const std::string & path) +{ + std::ifstream in(path); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +} + +TEST(FileChannelRotation, NoFreeDescriptorsDuringRotation) +{ + const auto dir = std::filesystem::temp_directory_path() / ("gtest_file_channel_rotation_" + std::to_string(::getpid())); + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + struct DirectoryGuard + { + std::filesystem::path path; + ~DirectoryGuard() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + } directory_guard{dir}; + const std::string path = (dir / "server.log").string(); + + Poco::AutoPtr channel = new Poco::FileChannel(path); + channel->setProperty(Poco::FileChannel::PROP_ROTATION, "1K"); + channel->setProperty(Poco::FileChannel::PROP_ARCHIVE, "number"); + channel->setProperty(Poco::FileChannel::PROP_COMPRESS, "false"); + + DescriptorTableGuard guard; + ASSERT_EQ(0, getrlimit(nofile_resource, &guard.original_limit)); + const rlim_t limit = std::min({guard.original_limit.rlim_cur, guard.original_limit.rlim_max - 1, 1024}); + + /// The log file gets descriptor `limit`, so closing it in `archive` frees no descriptor below the limit. + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + ASSERT_EQ(EMFILE, fillDescriptorTable(guard)); + ASSERT_EQ(0, setSoftLimit(limit + 1, guard.original_limit)); + ASSERT_NO_THROW(channel->open()); + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + + ASSERT_NO_THROW(channel->log(makeMessage(std::string(2048, 'x')))); + + expectNoFreeDescriptors(*channel, "rotation without free descriptors"); + EXPECT_TRUE(std::filesystem::exists(path + ".0")); + EXPECT_EQ(0u, channel->size()); + expectNoFreeDescriptors(*channel, "still no free descriptors"); + + guard.release(); + + const std::string marker = "logged after descriptors were released"; + ASSERT_NO_THROW(channel->log(makeMessage(marker))); + channel->close(); + EXPECT_NE(std::string::npos, readFile(path).find(marker)); +} diff --git a/src/Coordination/Changelog.cpp b/src/Coordination/Changelog.cpp index 26f8cff05cae..dd4d3a9e8cff 100644 --- a/src/Coordination/Changelog.cpp +++ b/src/Coordination/Changelog.cpp @@ -2568,6 +2568,8 @@ void Changelog::applyEntriesFromBuffer(uint64_t index, nuraft::buffer & buffer) { uint64_t cur_index = index + i; int buf_size = buffer.get_int(); + if (buf_size < 0 || static_cast(buf_size) > buffer.size() - buffer.pos()) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Log entry {} in a log pack has invalid size {}", cur_index, buf_size); nuraft::ptr buf_local = nuraft::buffer::alloc(buf_size); buffer.get(buf_local); diff --git a/src/Coordination/tests/gtest_coordination.cpp b/src/Coordination/tests/gtest_coordination.cpp index 291bc4236055..6f0a8d868f51 100644 --- a/src/Coordination/tests/gtest_coordination.cpp +++ b/src/Coordination/tests/gtest_coordination.cpp @@ -172,6 +172,69 @@ TYPED_TEST(CoordinationTest, CreateRequestDoesNotPreallocateOversizedACLs) } } +TEST(CoordinationSerialization, StringReadDoesNotPreallocateDeclaredSize) +{ + /// Invariant: memory must track bytes actually read, not the declared string length. + const size_t chunk = Coordination::MAX_STRING_PREALLOCATION; + + auto expect_marshalling_error = [](DB::ReadBuffer & rbuf, std::string & s) + { + try + { + Coordination::read(s, rbuf); + FAIL() << "Expected ZMARSHALLINGERROR"; + } + catch (const Coordination::Exception & e) + { + EXPECT_EQ(e.code, Coordination::Error::ZMARSHALLINGERROR); + } + }; + + { + /// The largest allowed length is declared, but no payload bytes follow. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 2 * chunk); + } + + { + /// The input ends after one complete chunk. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + const std::string first_chunk(chunk, 'x'); + wbuf.write(first_chunk.data(), first_chunk.size()); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 4 * chunk); + } + + { + /// A string that needs more than one chunk is read completely, and the next field is aligned. + std::string expected(chunk + 1, '\0'); + for (size_t i = 0; i < expected.size(); ++i) + expected[i] = static_cast(i % 251); + + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(expected, wbuf); + Coordination::write(static_cast(42), wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + int32_t next = 0; + Coordination::read(s, rbuf); + Coordination::read(next, rbuf); + EXPECT_EQ(s, expected); + EXPECT_EQ(next, 42); + EXPECT_TRUE(rbuf.eof()); + } +} + template struct SimpliestRaftServer { diff --git a/src/Coordination/tests/gtest_coordination_changelog.cpp b/src/Coordination/tests/gtest_coordination_changelog.cpp index c0a33caadbdd..fa3ec468e04e 100644 --- a/src/Coordination/tests/gtest_coordination_changelog.cpp +++ b/src/Coordination/tests/gtest_coordination_changelog.cpp @@ -479,6 +479,45 @@ TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsEmpty) changelog_reader.init(5, 0); } +TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsInvalidSize) +{ + ChangelogDirTest test("./logs"); + this->setLogDirectory("./logs"); + + DB::KeeperLogStore changelog( + DB::LogFileSettings{.force_sync = true, .compress_logs = this->enable_compression, .rotate_interval = 100}, + DB::FlushSettings(), + this->keeper_context); + changelog.init(0, 0); + auto entry = getLogEntry("hello_world", 10); + changelog.append(entry); + changelog.end_of_append_batch(0, 0); + waitDurableLogs(changelog); + + /// A pack of one entry holds the entry count, the entry size and the entry itself. A peer controls the size, + /// so only the size is rewritten here. + auto entries = changelog.pack(1, 1); + const auto entry_size = static_cast(entries->size() - 2 * sizeof(int32_t)); + auto apply_with_size = [&](int32_t size) + { + entries->pos(sizeof(int32_t)); + entries->put(size); + changelog.apply_pack(2, *entries); + }; + + /// On master a size past the entry over-reads the pack in `nuraft::buffer::get` and a negative size + /// wraps the allocation size in `nuraft::buffer::alloc`. + EXPECT_THROW(apply_with_size(entry_size + 1), DB::Exception); + EXPECT_THROW(apply_with_size(-1), DB::Exception); + EXPECT_EQ(changelog.next_slot(), 2); + + apply_with_size(entry_size); + changelog.apply_pack(3, *changelog.pack(1, 0)); + changelog.end_of_append_batch(0, 0); + EXPECT_EQ(changelog.next_slot(), 3); + EXPECT_EQ(changelog.entry_at(2)->get_term(), 10); +} + TYPED_TEST(CoordinationChangelogTest, ChangelogTestWriteAtPreviousFile) { diff --git a/src/Core/Field.cpp b/src/Core/Field.cpp index 8afadfc8ac9e..ca0f375ed111 100644 --- a/src/Core/Field.cpp +++ b/src/Core/Field.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -369,6 +370,9 @@ bool Field::operator== (const Field & rhs) const Field getBinaryValue(UInt8 type, ReadBuffer & buf) { + /// Containers are read recursively, and the nesting depth comes from the data. + checkStackSize(); + switch (static_cast(type)) { case Field::Types::Null: diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 0042be8fe8a1..31643b8133cd 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -1408,6 +1408,13 @@ Compression method for Arrow output format. Supported codecs: lz4_frame, zstd, n )", 0) \ DECLARE(Bool, output_format_arrow_date_as_uint16, false, R"( Write Date values as plain 16-bit numbers (read back as UInt16), instead of converting to a 32-bit Arrow DATE32 type (read back as Date32). +)", 0) \ + DECLARE(UInt64, output_format_arrow_max_record_batch_size_bytes, 2147483646, R"( +Upper bound on the `Utf8`, `Binary` and `List` buffers of a single record batch in the `Arrow` and `ArrowStream` output formats. A block whose strings, binary values or list elements exceed this is written as several record batches. + +This is a limit that splits large blocks. The default is the largest value Arrow can address, because it offsets those buffers with 32-bit integers; a larger value has no effect. + +Only the buffers named above are bounded: a column of a fixed-width type has no offsets to overflow and stays in one batch. A single row never splits either, so a row above the limit still produces a batch that exceeds it. )", 0) \ \ DECLARE(Bool, output_format_orc_string_as_string, true, R"( diff --git a/src/Core/PostgreSQLProtocol.h b/src/Core/PostgreSQLProtocol.h index 20349d50560c..74accb0cef73 100644 --- a/src/Core/PostgreSQLProtocol.h +++ b/src/Core/PostgreSQLProtocol.h @@ -55,6 +55,14 @@ namespace PostgreSQLProtocol namespace Messaging { +/** Upper bound for the declared length of a message that is parsed before the client is authenticated. + * The payload of such a message is bounded by its declared length, but that length is chosen by an + * unauthenticated client, so the length itself must be bounded as well. Otherwise a client declares + * the Int32 maximum and makes the server buffer up to 2 GiB of payload before it gives up. + * PostgreSQL uses the same limit for its startup packet. + */ +constexpr Int32 max_unauthenticated_message_size = 10000; + enum class FrontMessageType : Int32 { // first message types @@ -307,14 +315,26 @@ class FrontMessage : public IMessage virtual void deserialize(ReadBuffer & in) = 0; protected: + /** Parses the payload of a message inside a buffer that ends at the declared length. + * `max_size` bounds the declared length itself. Pass it for every message that is parsed before the + * client is authenticated, because that client chooses the length. A frame rejected by `max_size` is + * left unread in the stream, so only a caller whose error closes the connection may pass a limit. + */ template - static void deserializePayload(ReadBuffer & in, std::string_view message_name, F && deserialize_payload) + static void deserializePayload( + ReadBuffer & in, + std::string_view message_name, + F && deserialize_payload, + Int32 max_size = std::numeric_limits::max()) { Int32 size = 0; readBinaryBigEndian(size, in); if (size < 4) throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT, "Wrong message length {} in {}, it must be at least 4", size, message_name); + if (size > max_size) + throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT, + "Wrong message length {} in {}, it must not exceed {}", size, message_name, max_size); const size_t payload_size = static_cast(size - 4); LimitReadBuffer payload_in(in, {.read_no_less = payload_size, .read_no_more = payload_size}); @@ -598,7 +618,7 @@ class SASLInitialResponse : public Messaging::FrontMessage "Wrong SASL mechanism length {} in SASLInitialResponse, it must not be less than -1", size_sasl_mechanism); if (size_sasl_mechanism > 0) readStringOfDeclaredSize(sasl_mechanism, size_sasl_mechanism, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override @@ -646,7 +666,7 @@ class SASLResponse : public Messaging::FrontMessage deserializePayload(in, "SASLResponse message", [this](ReadBuffer & payload_in) { readStringUntilEOF(sasl_mechanism, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override @@ -687,7 +707,7 @@ class PasswordMessage : FrontMessage deserializePayload(in, "PasswordMessage", [this](ReadBuffer & payload_in) { readNullTerminated(password, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index ac119469ccd0..6cbd2e052809 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -1270,6 +1270,10 @@ Possible values: - `2` — `SELECT` and `INSERT` will be executed on each shard from/to the underlying table of the distributed engine. Setting `enable_parallel_replicas = 1` is needed when using this setting. + +:::note +The rewritten query, including every expression of the `SELECT` (subqueries, UDFs, and so on), is executed on the shards under the credentials of the cluster configuration — the same trust model as other shard-side processing, such as the subqueries of a non-`GLOBAL` `IN`. Configure an interserver secret (the `secret` element of the cluster configuration) if shard-side reads must be authorized as the calling user. +::: )", 0) \ DECLARE(UInt64, distributed_group_by_no_merge, 0, R"( Do not merge aggregation states from different servers for distributed query processing, you can use this in case it is for certain that there are different keys on different shards diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 62e4d873e09d..caf53da95654 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -41,6 +41,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() /// Note: please check if the key already exists to prevent duplicate entries. addSettingsChanges(settings_changes_history, "26.3", { + {"output_format_arrow_max_record_batch_size_bytes", 2147483646, 2147483646, "New setting bounding the size of one record batch in `Arrow` and `ArrowStream` output. The default is Arrow's own addressing limit, so it does not change behavior."}, {"variant_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Variant implementation"}, {"dynamic_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Dynamic implementation"}, {"defer_partition_pruning_after_final", false, true, "Gates the FINAL planner's unconditional skipping of partition pruning when the partition-key column is not in the sorting key. The behavior change itself shipped silently in 26.3 via https://github.com/ClickHouse/ClickHouse/pull/98242; this entry retroactively documents it so `compatibility = '26.2'` restores the pre-regression behavior (0 = prune before FINAL, fast; 1 = defer pruning, correctness-safe)."}, diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp index 4b0be9872423..1b1665c4abff 100644 --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp @@ -607,6 +607,13 @@ void SerializationLowCardinality::deserializeBinaryBulkWithMultipleStreams( bool has_additional_keys = low_cardinality_state->index_type.has_additional_keys; bool column_is_empty = low_cardinality_column.empty(); + /// Indexes come from the stream. + if (low_cardinality_state->index_type.need_global_dictionary) + { + const size_t num_additional_keys = additional_keys ? additional_keys->size() : 0; + ColumnLowCardinality::checkIndexesAreLimited(*indexes_column, global_dictionary->size() + num_additional_keys); + } + if (!low_cardinality_state->index_type.need_global_dictionary) { if (additional_keys == nullptr) diff --git a/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp new file mode 100644 index 000000000000..4ea6070e820a --- /dev/null +++ b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp @@ -0,0 +1,179 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int INCORRECT_DATA; +} + +using namespace DB; + +namespace +{ + +/// The MergeTree layout: the dictionary in one stream, the indexes and the additional keys in another. +template +auto makeGetter(Buffer & keys, Buffer & indexes) +{ + return [&keys, &indexes](const ISerialization::SubstreamPath & path) -> BufferPtr + { + if (!path.empty() && path.back().type == ISerialization::Substream::DictionaryKeys) + return &keys; + return &indexes; + }; +} + +struct Streams +{ + std::string keys; + std::string indexes; +}; + +Streams serialize(const DataTypePtr & type, const IColumn & column, size_t max_dictionary_size) +{ + WriteBufferFromOwnString keys; + WriteBufferFromOwnString indexes; + auto serialization = type->getDefaultSerialization(); + ISerialization::SerializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.low_cardinality_max_dictionary_size = max_dictionary_size; + settings.low_cardinality_use_single_dictionary_for_part = false; + ISerialization::SerializeBinaryBulkStatePtr state; + serialization->serializeBinaryBulkStatePrefix(column, settings, state); + serialization->serializeBinaryBulkWithMultipleStreams(column, 0, column.size(), settings, state); + serialization->serializeBinaryBulkStateSuffix(settings, state); + keys.finalize(); + indexes.finalize(); + return {keys.str(), indexes.str()}; +} + +ColumnPtr deserialize(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + ReadBufferFromString keys(streams.keys); + ReadBufferFromString indexes(streams.indexes); + auto serialization = type->getDefaultSerialization(); + ISerialization::DeserializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.native_format = false; + ISerialization::DeserializeBinaryBulkStatePtr state; + serialization->deserializeBinaryBulkStatePrefix(settings, state, nullptr); + ColumnPtr column = type->createColumn(); + serialization->deserializeBinaryBulkWithMultipleStreams(column, 0, rows, settings, state, nullptr); + return column; +} + +void expectIncorrectData(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + try + { + deserialize(type, streams, rows); + FAIL() << "accepted an index past the keys"; + } + catch (const Exception & e) + { + ASSERT_EQ(e.code(), ErrorCodes::INCORRECT_DATA) << e.message(); + } +} + +/// Calls `check` for `LowCardinality(String)` and `LowCardinality(Nullable(UInt64))`, each serialized with a dictionary +/// of 2 keys (so most values become additional keys) and with one large enough for all values (no additional keys). +template +void forEachCase(Check && check) +{ + for (bool nullable : {false, true}) + { + DataTypePtr inner = nullable ? makeNullable(std::make_shared()) : std::make_shared(); + auto type = std::make_shared(inner); + auto column = type->createColumn(); + for (size_t i = 0; i < 20; ++i) + { + if (nullable) + column->insert(i % 6 == 0 ? Field() : Field(UInt64(i % 6))); + else + column->insert(String(1, static_cast('a' + i % 5))); + } + + for (size_t max_dictionary_size : {2, 8192}) + { + SCOPED_TRACE(type->getName() + " with max dictionary size " + std::to_string(max_dictionary_size)); + auto streams = serialize(type, *column, max_dictionary_size); + + constexpr UInt64 need_global_dictionary_bit = 1ULL << 8; + constexpr UInt64 has_additional_keys_bit = 1ULL << 9; + const UInt64 index_type = unalignedLoadLittleEndian(streams.indexes.data()); + const bool has_additional_keys = (index_type & has_additional_keys_bit) != 0; + ASSERT_NE(index_type & need_global_dictionary_bit, 0u); + ASSERT_EQ(has_additional_keys, max_dictionary_size == 2); + ASSERT_LE(index_type & 0xff, 3u); + + /// The keys stream starts with the version, then the number of keys; the indexes stream starts with the index type, + /// then the number of additional keys if there are any. + const UInt64 num_keys = unalignedLoadLittleEndian(streams.keys.data() + 8) + + (has_additional_keys ? unalignedLoadLittleEndian(streams.indexes.data() + 8) : 0); + const size_t index_width = 1ULL << (index_type & 0xff); + + check(type, *column, std::move(streams), num_keys, index_width); + } + } +} + +} + +TEST(SerializationLowCardinality, ValidStreamsRoundTrip) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64, size_t) + { + auto result = deserialize(type, streams, column.size()); + ASSERT_EQ(result->size(), column.size()); + for (size_t i = 0; i < column.size(); ++i) + ASSERT_EQ((*result)[i], column[i]) << "row " << i; + }); +} + +/// The indexes come from the data, so they have to be checked against the keys of the dictionary and the additional keys. +TEST(SerializationLowCardinality, IndexPastTheKeysIsRejected) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64 num_keys, size_t index_width) + { + const size_t rows = column.size(); + const size_t indexes_begin = streams.indexes.size() - rows * index_width; + + /// The same indexes as `UInt64` (index type 3, the low byte of the index type) read back the same values... + Streams wide{streams.keys, streams.indexes.substr(0, indexes_begin)}; + wide.indexes[0] = 3; + for (size_t row = 0; row < rows; ++row) + { + UInt64 index = 0; + for (size_t i = 0; i < index_width; ++i) + index |= UInt64(static_cast(streams.indexes[indexes_begin + row * index_width + i])) << (8 * i); + for (size_t i = 0; i < 8; ++i) + wide.indexes.push_back(static_cast(index >> (8 * i))); + } + auto result = deserialize(type, wide, rows); + ASSERT_EQ(result->size(), rows); + for (size_t row = 0; row < rows; ++row) + ASSERT_EQ((*result)[row], column[row]) << "row " << row; + + /// ...and the largest possible last index is rejected before `mapIndexWithAdditionalKeys` sizes its overflow map by it. + std::fill(wide.indexes.end() - 8, wide.indexes.end(), '\xff'); + expectIncorrectData(type, wide, rows); + + /// The last index of the original stream becomes the first value past the keys. + ASSERT_LE(num_keys, std::numeric_limits::max() >> (64 - 8 * index_width)); + for (size_t i = 0; i < index_width; ++i) + streams.indexes[streams.indexes.size() - index_width + i] = static_cast(num_keys >> (8 * i)); + expectIncorrectData(type, streams, rows); + }); +} diff --git a/src/Databases/DataLake/GlueCatalog.cpp b/src/Databases/DataLake/GlueCatalog.cpp index df08b71baf8a..3ab1c7067a12 100644 --- a/src/Databases/DataLake/GlueCatalog.cpp +++ b/src/Databases/DataLake/GlueCatalog.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -77,8 +78,8 @@ namespace DB::ServerSetting namespace CurrentMetrics { - extern const Metric MarkCacheBytes; - extern const Metric MarkCacheFiles; + extern const Metric GlueCatalogSchemaCacheBytes; + extern const Metric GlueCatalogSchemaCacheEntries; } namespace DataLake @@ -95,7 +96,7 @@ GlueCatalog::GlueCatalog( , region(settings_.region) , settings(settings_) , table_engine_definition(table_engine_definition_) - , metadata_objects(CurrentMetrics::MarkCacheBytes, CurrentMetrics::MarkCacheFiles, 1024) + , current_schema_field_types(CurrentMetrics::GlueCatalogSchemaCacheBytes, CurrentMetrics::GlueCatalogSchemaCacheEntries, 16_MiB) { DB::S3::CredentialsConfiguration creds_config; creds_config.use_environment_credentials = true; @@ -466,7 +467,7 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet const String & metadata_uri = table_specific_properties->iceberg_metadata_file_location; - if (!metadata_objects.get(metadata_uri)) + auto [field_types, _] = current_schema_field_types.getOrSet(metadata_uri, [&] { auto [object_storage, bucket_name, metadata_path] = createObjectStorageForEarlyTableAccess(metadata_uri, table_metadata); const auto & read_settings = getContext()->getReadSettings(); @@ -479,28 +480,42 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(metadata_file_content); auto metadata_object = result.extract(); - metadata_objects.set(metadata_uri, std::make_shared(metadata_object)); - } + return std::make_shared(getCurrentSchemaFieldTypes(metadata_object)); + }); + + auto it = field_types->find(column_name); + return it != field_types->end() && it->second == DB::Iceberg::f_timestamptz; +} - auto metadata_object = *metadata_objects.get(metadata_uri); +GlueCatalog::FieldTypes GlueCatalog::getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object) +{ + FieldTypes result; auto current_schema_id = metadata_object->getValue("current-schema-id"); auto schemas = metadata_object->getArray(DB::Iceberg::f_schemas); for (size_t i = 0; i < schemas->size(); ++i) { auto schema = schemas->getObject(static_cast(i)); - if (schema->getValue("schema-id") == current_schema_id) + if (schema->getValue("schema-id") != current_schema_id) + continue; + + auto fields = schema->getArray(DB::Iceberg::f_fields); + for (size_t j = 0; j < fields->size(); ++j) { - auto fields = schema->getArray(DB::Iceberg::f_fields); - for (size_t j = 0; j < fields->size(); ++j) - { - auto field = fields->getObject(static_cast(j)); - if (field->getValue(DB::Iceberg::f_name) == column_name) - return field->getValue(DB::Iceberg::f_type) == DB::Iceberg::f_timestamptz; - } + auto field = fields->getObject(static_cast(j)); + auto type = field->get(DB::Iceberg::f_type); + if (type.isString()) + result.emplace(field->getValue(DB::Iceberg::f_name), type.extract()); } } + return result; +} - return false; +size_t GlueCatalog::FieldTypesWeightFunction::operator()(const FieldTypes & field_types) const +{ + size_t result = 0; + for (const auto & [name, type] : field_types) + result += sizeof(FieldTypes::value_type) + name.size() + type.size(); + return result; } GlueCatalog::ObjectStorageWithPath GlueCatalog::createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const diff --git a/src/Databases/DataLake/GlueCatalog.h b/src/Databases/DataLake/GlueCatalog.h index c65c69a2a75a..e0485de5e0e0 100644 --- a/src/Databases/DataLake/GlueCatalog.h +++ b/src/Databases/DataLake/GlueCatalog.h @@ -83,9 +83,18 @@ class GlueCatalog final : public ICatalog, private DB::WithContext const String & column_name, const String & glue_column_type); + using FieldTypes = std::unordered_map; + + static FieldTypes getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object); + private: void createNamespaceIfNotExists(const String & namespace_name) const; + struct FieldTypesWeightFunction + { + size_t operator()(const FieldTypes & field_types) const; + }; + std::unique_ptr glue_client; const LoggerPtr log; std::shared_ptr credentials_provider; @@ -112,7 +121,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext ObjectStorageWithPath createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const; - mutable DB::CacheBase metadata_objects; + mutable DB::CacheBase, FieldTypesWeightFunction> current_schema_field_types; }; } diff --git a/src/Databases/DataLake/HiveCatalog.cpp b/src/Databases/DataLake/HiveCatalog.cpp index b86f70dfc4b5..918ed836737e 100644 --- a/src/Databases/DataLake/HiveCatalog.cpp +++ b/src/Databases/DataLake/HiveCatalog.cpp @@ -10,8 +10,10 @@ #include #include #include +#include #include #include +#include #include namespace DB::ErrorCodes @@ -64,11 +66,23 @@ std::pair parseHostPort(const String & url) } } +std::shared_ptr createSocket(const String & base_url, const DB::ContextPtr & context) +{ + auto [host, port] = parseHostPort(base_url); + + /// Also rejects control characters such as NUL, which `getaddrinfo` would truncate the host at. + context->getRemoteHostFilter().checkAndGetCanonicalHostAndPort( + host + ":" + std::to_string(port), static_cast(port), "Hive metastore address"); + + return std::make_shared(host, port); +} + } -HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr) +HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr context_) : ICatalog(warehouse_) - , socket(new apache::thrift::transport::TSocket(parseHostPort(base_url_).first, parseHostPort(base_url_).second)) + , DB::WithContext(context_) + , socket(createSocket(base_url_, context_)) , transport(new apache::thrift::transport::TBufferedTransport(socket)) , protocol(new apache::thrift::protocol::TBinaryProtocol(transport)) , client(protocol) diff --git a/src/Databases/DatabaseReplicated.cpp b/src/Databases/DatabaseReplicated.cpp index 94d0aa46efd8..8428ea1c4c20 100644 --- a/src/Databases/DatabaseReplicated.cpp +++ b/src/Databases/DatabaseReplicated.cpp @@ -63,6 +63,7 @@ #include #include #include +#include #include #include @@ -798,14 +799,14 @@ void DatabaseReplicated::createEmptyLogEntry(const ZooKeeperPtr & current_zookee bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, SyncReplicaMode mode) { chassert(mode == SyncReplicaMode::DEFAULT || mode == SyncReplicaMode::STRICT); - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - return false; - } + /// The worker can be stopped and replaced concurrently (`SYSTEM RESTORE DATABASE REPLICA`, `DROP DATABASE`): + /// the reference keeps it alive, and a stopped worker returns from the wait. + auto worker = tryGetDDLWorker(); + if (!worker) + return false; if (mode == SyncReplicaMode::DEFAULT) - return ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms); + return worker->waitForReplicaToProcessAllEntries(timeout_ms); Stopwatch elapsed; while (true) @@ -814,15 +815,19 @@ bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, Sy if (elapsed_ms > timeout_ms) return false; - if (ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) + if (worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) return true; - UInt32 our_log_ptr = ddl_worker->getLogPointer(); + UInt32 our_log_ptr = worker->getLogPointer(); UInt32 max_log_ptr = parse(getZooKeeper()->get(fs::path(zookeeper_path) / "max_log_ptr")); bool became_synced = our_log_ptr + db_settings[DatabaseReplicatedSetting::max_replication_lag_to_enqueue] >= max_log_ptr; if (became_synced) return true; + /// The worker was stopped (e.g. by `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE`), it will not make progress. + if (worker->isStopped()) + return false; + /// max_log_ptr might be increased while we were waiting - retry until replication lag is below the threshold } } @@ -995,11 +1000,36 @@ void DatabaseReplicated::initDDLWorkerUnlocked() chassert(!is_probably_dropped.load()); chassert(!ddl_worker_initialized.load()); - ddl_worker = std::make_unique(this, getContext()); + replaceDDLWorkerUnlocked(std::make_shared(this, getContext())); ddl_worker->startup(); ddl_worker_initialized = true; } +std::shared_ptr DatabaseReplicated::tryGetDDLWorker() const +{ + std::lock_guard lock{ddl_worker_mutex}; + if (!ddl_worker || is_probably_dropped) + return nullptr; + return ddl_worker; +} + +std::shared_ptr DatabaseReplicated::replaceDDLWorkerUnlocked(std::shared_ptr new_worker) +{ + std::lock_guard lock{ddl_worker_ptr_mutex}; + std::swap(ddl_worker, new_worker); + return new_worker; +} + +bool DatabaseReplicated::isDDLWorkerCurrentlyActive() const +{ + std::shared_ptr worker; + { + std::lock_guard lock{ddl_worker_ptr_mutex}; + worker = ddl_worker; + } + return worker && worker->isCurrentlyActive(); +} + void DatabaseReplicated::restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper) { auto local_context = getContext(); @@ -1058,7 +1088,7 @@ void DatabaseReplicated::reinitializeDDLWorker() ddl_worker->shutdown(); { ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } } @@ -1279,7 +1309,7 @@ bool DatabaseReplicated::checkDigestValid(const ContextPtr & local_context) cons LOG_TEST(log, "Current in-memory metadata digest: {}", tables_metadata_digest); /// Database is probably being dropped - if (!local_context->getZooKeeperMetadataTransaction() && (!ddl_worker || !ddl_worker->isCurrentlyActive())) + if (!local_context->getZooKeeperMetadataTransaction() && !isDDLWorkerCurrentlyActive()) return true; /// SYSTEM RESTART REPLICA temporarily removes a table from the in-memory tables map @@ -1385,13 +1415,12 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex if (is_readonly) throw Exception(ErrorCodes::NO_ZOOKEEPER, "Database is in readonly mode, because it cannot connect to ZooKeeper"); - String host_fqdn_id; - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); - host_fqdn_id = ddl_worker->getCommonHostID(); - } + /// Hold our own reference: `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE` can stop and replace the worker + /// while this query waits in `tryEnqueueAndExecuteEntry`. A stopped worker makes it throw instead of executing. + auto worker = tryGetDDLWorker(); + if (!worker) + throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); + String host_fqdn_id = worker->getCommonHostID(); if (!flags.internal && query_context->isDDLOrOnClusterInternal()) throw Exception(ErrorCodes::INCORRECT_QUERY, "It's not initial query. ON CLUSTER is not allowed for Replicated database."); @@ -1406,7 +1435,7 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex entry.tracing_context = OpenTelemetry::CurrentContext(); entry.initial_query_id = query_context->getClientInfo().initial_query_id; entry.is_backup_restore = flags.distributed_backup_restore; - String node_path = ddl_worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); + String node_path = worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); Strings hosts_to_wait; Strings unfiltered_hosts = getZooKeeper()->getChildren(zookeeper_path + "/replicas"); @@ -2078,10 +2107,63 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) auto component_guard = Coordination::setCurrentComponent("DatabaseReplicated::restoreDatabaseMetadataInKeeper"); waitDatabaseStarted(); + /// Concurrent restores of the same database would stop and re-create the DDL worker under each other + /// and race on the replication state that `initDatabaseReplica` rewrites (e.g. `max_log_ptr_at_creation`). + std::lock_guard restore_lock{restore_in_keeper_mutex}; + auto zookeeper = getZooKeeper(); if (!zookeeper) throw Exception(ErrorCodes::NO_ZOOKEEPER, "No ZooKeeper"); + /// Stop this replica's DDL worker before the calls below re-initialize replication state: + /// its recovery reads `max_log_ptr_at_creation` and compares the Keeper metadata with the + /// local table set, which those calls rewrite, and a recovery running against a half-updated + /// view detaches local tables into `_broken_replicated_tables`. + std::shared_ptr old_worker; + { + std::lock_guard lock{ddl_worker_mutex}; + old_worker = ddl_worker; + } + + /// Initial queries admitted by the worker execute and commit on their own threads, and `shutdown` does not wait + /// for them. Wait for them before rewriting the replication state: otherwise a query could commit its metadata + /// while the recovery of the new worker compares the Keeper snapshot with the local tables, and the recovery + /// would move the just created table to `_broken_replicated_tables` (or drop it). + /// Stop admitting new initial queries, but keep the worker running while waiting: an admitted query may depend + /// on it, e.g. an `ALTER` of a `ReplicatedMergeTree` table with `alter_sync` waits for its `ALTER_METADATA` entry, + /// which the table executes only while `canExecuteReplicatedMetadataAlter` is true. + /// Not under `ddl_worker_mutex`, because these queries may need it. + if (old_worker) + { + LOG_TRACE(log, "Waiting for initial queries before restoring database metadata in Keeper."); + old_worker->stopInitialQueries(); + old_worker->waitForForegroundTasks(); + } + + { + std::lock_guard lock{ddl_worker_mutex}; + /// Only `restoreDatabaseInKeeper` (serialized by `restore_in_keeper_mutex`) creates a new worker after startup, + /// so the worker is either still the same or was removed by a concurrent `DROP DATABASE`. + chassert(!ddl_worker || ddl_worker == old_worker); + if (ddl_worker) + { + LOG_TRACE(log, "Stopping DDL worker before restoring database metadata in Keeper."); + ddl_worker->shutdown(); + ddl_worker_initialized = false; + replaceDDLWorkerUnlocked(nullptr); + } + } + old_worker.reset(); + + /// If the restore fails, reinitialize the DDL worker so the database remains functional. + /// SAFE: the body runs while an exception propagates and can itself throw (thread + /// creation), which must not replace the restore's own error. + bool need_reinitialize_ddl_worker = true; + SCOPE_EXIT_SAFE({ + if (need_reinitialize_ddl_worker) + reinitializeDDLWorker(); + }); + try { restoreDatabaseNodesInKeeper(zookeeper); @@ -2099,6 +2181,8 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) /// Force the database to recover to update the restored metadata auto current_zookeeper = getZooKeeper(); current_zookeeper->set(replica_path + "/digest", DatabaseReplicatedDDLWorker::FORCE_AUTO_RECOVERY_DIGEST); + + need_reinitialize_ddl_worker = false; reinitializeDDLWorker(); } @@ -2173,7 +2257,7 @@ void DatabaseReplicated::shutdown() { std::lock_guard lock{ddl_worker_mutex}; ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } DatabaseAtomic::shutdown(); } @@ -2184,7 +2268,7 @@ void DatabaseReplicated::dropTable(ContextPtr local_context, const String & tabl waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); + assert(txn || !isDDLWorkerCurrentlyActive() || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); @@ -2293,7 +2377,7 @@ void DatabaseReplicated::commitCreateTable(const ASTCreateQuery & query, const S ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); String statement = getObjectDefinitionFromCreateQuery(query.clone()); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) @@ -2321,7 +2405,7 @@ void DatabaseReplicated::commitAlterTable(const StorageID & table_id, const String & statement, ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_id.table_name); @@ -2361,7 +2445,7 @@ void DatabaseReplicated::detachTablePermanently(ContextPtr local_context, const throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Support for DETACH TABLE PERMANENTLY is disabled"); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { /// We have to remove metadata from zookeeper, because we do not distinguish permanently detached tables @@ -2386,7 +2470,7 @@ void DatabaseReplicated::removeDetachedPermanentlyFlag(ContextPtr local_context, waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery() && attach) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); diff --git a/src/Databases/DatabaseReplicated.h b/src/Databases/DatabaseReplicated.h index aa1f030cb971..d0c6e9377560 100644 --- a/src/Databases/DatabaseReplicated.h +++ b/src/Databases/DatabaseReplicated.h @@ -230,6 +230,15 @@ class DatabaseReplicated : public DatabaseAtomic void stopLoading() override; void initDDLWorkerUnlocked() TSA_REQUIRES(ddl_worker_mutex); + /// Returns a reference to the DDL worker taken under `ddl_worker_mutex`, or nullptr if the database + /// is not initialized yet or is being dropped. + std::shared_ptr tryGetDDLWorker() const; + /// Assigns `ddl_worker` and returns the previous worker. Requires both mutexes, see `ddl_worker_ptr_mutex`. + std::shared_ptr replaceDDLWorkerUnlocked(std::shared_ptr new_worker) + TSA_REQUIRES(ddl_worker_mutex); + /// Whether the current DDL worker exists and is active. Does not take `ddl_worker_mutex`, + /// so it is safe to call from the callbacks of DDL queries executed by the worker. + bool isDDLWorkerCurrentlyActive() const; void restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper); void reinitializeDDLWorker(); @@ -257,9 +266,20 @@ class DatabaseReplicated : public DatabaseAtomic std::atomic_bool is_probably_dropped = false; std::atomic_bool is_recovering = false; std::atomic_bool ddl_worker_initialized = false; - std::unique_ptr ddl_worker; + /// Shared, so that a query thread that uses the worker outside of `ddl_worker_mutex` (e.g. waiting in + /// `tryEnqueueAndExecuteEntry`) keeps it alive while `shutdown`, `restoreDatabaseInKeeper` or + /// `reinitializeDDLWorker` concurrently stop and replace it. Such a thread must take its own reference + /// under the mutex with `tryGetDDLWorker` and never dereference this member without the lock. + std::shared_ptr ddl_worker; mutable std::mutex ddl_worker_mutex; + /// Protects only the `ddl_worker` pointer itself: it is assigned under both mutexes and can be read under either. + /// Unlike `ddl_worker_mutex`, it is never held while the worker is shut down (and its threads are joined), + /// so the callbacks of DDL queries (`commitCreateTable`, `dropTable`, ...) can take it with `isDDLWorkerCurrentlyActive` + /// even when they are executed by the worker's threads or concurrently with `SYSTEM RESTORE DATABASE REPLICA`. + mutable std::mutex ddl_worker_ptr_mutex; UInt32 max_log_ptr_at_creation = 0; + /// Serializes `restoreDatabaseInKeeper`. Taken before `ddl_worker_mutex`. + std::mutex restore_in_keeper_mutex; /// Usually operation with metadata are single-threaded because of the way replication works, /// but StorageReplicatedMergeTree may call alterTable outside from DatabaseReplicatedDDLWorker causing race conditions. diff --git a/src/Databases/DatabaseReplicatedWorker.cpp b/src/Databases/DatabaseReplicatedWorker.cpp index 9112adf427d9..b3e7c1edd804 100644 --- a/src/Databases/DatabaseReplicatedWorker.cpp +++ b/src/Databases/DatabaseReplicatedWorker.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -49,6 +50,7 @@ namespace FailPoints extern const char database_replicated_delay_recovery[]; extern const char database_replicated_delay_entry_execution[]; extern const char database_replicated_stop_entry_execution[]; + extern const char database_replicated_pause_before_initial_query_execution[]; } @@ -160,9 +162,35 @@ void DatabaseReplicatedDDLWorker::shutdown() active_node_holder.reset(); active_node_holder_zookeeper.reset(); + /// Waiters in `tryEnqueueAndExecuteEntry` and `waitForReplicaToProcessAllEntries` (which may outlive the + /// shutdown, holding a reference to this worker) check `stop_flag` under `mutex`. Taking it before notifying + /// guarantees that each of them either sees the flag or receives the notification. + { + std::lock_guard lock{mutex}; + for (const auto & event : log_ptr_waiters) + event->set(); + } + wait_current_task_change.notify_all(); +} + +void DatabaseReplicatedDDLWorker::stopInitialQueries() +{ + { + std::lock_guard lock{mutex}; + initial_queries_stopped = true; + } wait_current_task_change.notify_all(); } +void DatabaseReplicatedDDLWorker::waitForForegroundTasks() +{ + std::unique_lock lock{mutex}; + chassert(stop_flag || initial_queries_stopped); + if (foreground_tasks) + LOG_TRACE(log, "Waiting for {} admitted initial queries", foreground_tasks); + foreground_tasks_finished.wait(lock, [&] { return foreground_tasks == 0; }); +} + void DatabaseReplicatedDDLWorker::initializeReplication() { /// Check if we need to recover replica. @@ -357,19 +385,31 @@ bool DatabaseReplicatedDDLWorker::waitForReplicaToProcessAllEntries(UInt64 timeo return zookeeper->expired() || current_task >= max_log || stop_flag; }); - if (!processed) + if (!processed || stop_flag) return false; } - /// Lets now wait for max_log_ptr to be processed - Coordination::Stat stat; + /// Lets now wait for max_log_ptr to be processed. + /// The event is set either by the watch or by `shutdown`, so a stopped worker does not wait for the whole timeout. auto event_ptr = std::make_shared(); + { + std::lock_guard lock{mutex}; + if (stop_flag) + return false; + log_ptr_waiters.insert(event_ptr); + } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + log_ptr_waiters.erase(event_ptr); + }); + + Coordination::Stat stat; auto new_log = zookeeper->get(our_log_ptr_path, &stat, event_ptr); if (new_log == toString(max_log_ptr)) return true; - return event_ptr->tryWait(timeout_ms); + return event_ptr->tryWait(timeout_ms) && !stop_flag; } @@ -473,9 +513,9 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr { assert(zookeeper->expired() || current_task <= entry_name); - if (zookeeper->expired() || stop_flag) + if (zookeeper->expired() || stop_flag || initial_queries_stopped) { - LOG_TRACE(log, "Not enqueueing query: {}", stop_flag ? "replication stopped" : "ZooKeeper session expired"); + LOG_TRACE(log, "Not enqueueing query: {}", zookeeper->expired() ? "ZooKeeper session expired" : "replication stopped"); throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "ZooKeeper session expired or replication stopped, try again"); } @@ -491,8 +531,21 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr if (!processed) throw Exception(ErrorCodes::UNFINISHED, "Timeout: Cannot enqueue query on this replica, " "most likely because replica is busy with previous queue entries"); + + /// The predicate above has checked `stop_flag` and `initial_queries_stopped` under `mutex`, + /// so `waitForForegroundTasks` will wait for this query. + ++foreground_tasks; } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + --foreground_tasks; + if (foreground_tasks == 0) + foreground_tasks_finished.notify_all(); + }); + + FailPointInjection::pauseFailPoint(FailPoints::database_replicated_pause_before_initial_query_execution); + if (entry.parent_table_uuid.has_value() && !checkParentTableExists(entry.parent_table_uuid.value())) throw Exception(ErrorCodes::TABLE_IS_DROPPED, "Parent table doesn't exist"); diff --git a/src/Databases/DatabaseReplicatedWorker.h b/src/Databases/DatabaseReplicatedWorker.h index 5583f112662f..1f03d0722955 100644 --- a/src/Databases/DatabaseReplicatedWorker.h +++ b/src/Databases/DatabaseReplicatedWorker.h @@ -2,6 +2,9 @@ #include #include #include +#include + +#include namespace DB { @@ -31,8 +34,21 @@ class DatabaseReplicatedDDLWorker : public DDLWorker void shutdown() override; + /// Returns false on timeout or if the worker is stopped before or during the wait. bool waitForReplicaToProcessAllEntries(UInt64 timeout_ms); + /// The worker was shut down. A stopped worker is never restarted, the database replaces it with a new one. + bool isStopped() const { return stop_flag; } + + /// Makes `tryEnqueueAndExecuteEntry` reject new initial queries (as if the worker was stopped), + /// while the worker itself keeps running. Irreversible: the database replaces such a worker afterwards. + void stopInitialQueries(); + + /// Waits until the initial queries that `tryEnqueueAndExecuteEntry` admitted for execution finish. + /// They execute and commit on the submitting threads, so `shutdown` (which joins only the worker's + /// own threads) does not wait for them. Requires `stopInitialQueries` or `shutdown` to be called before. + void waitForForegroundTasks(); + static String enqueueQueryImpl(const ZooKeeperPtr & zookeeper, DDLLogEntry & entry, DatabaseReplicated * const database, bool committed = false, Coordination::Requests additional_checks = {}); /// NOLINT @@ -68,6 +84,15 @@ class DatabaseReplicatedDDLWorker : public DDLWorker std::condition_variable wait_current_task_change; String current_task; + /// The number of initial queries being executed by `tryEnqueueAndExecuteEntry` on the submitting threads. + /// Protected by `mutex`, see `waitForForegroundTasks`. + size_t foreground_tasks = 0; + std::condition_variable foreground_tasks_finished; + /// Set by `stopInitialQueries`. Protected by `mutex`. + bool initial_queries_stopped = false; + /// Events of `waitForReplicaToProcessAllEntries` waiting for our `log_ptr` in Keeper to change. + /// `shutdown` sets them, so that the waiters return without waiting for the timeout. + std::unordered_set> log_ptr_waiters; std::atomic logs_to_keep = std::numeric_limits::max(); std::atomic_bool unsynced_after_recovery = false; diff --git a/src/Databases/MySQL/DatabaseMySQL.cpp b/src/Databases/MySQL/DatabaseMySQL.cpp index 1c85c1ef38d7..ce3ca3203f83 100644 --- a/src/Databases/MySQL/DatabaseMySQL.cpp +++ b/src/Databases/MySQL/DatabaseMySQL.cpp @@ -38,6 +38,7 @@ # include # include # include +# include # include #if CLICKHOUSE_CLOUD @@ -643,6 +644,14 @@ void registerDatabaseMySQL(DatabaseFactory & factory) configuration.username = safeGetLiteralValue(arguments[2], engine_name); configuration.password = safeGetLiteralValue(arguments[3], engine_name); } + + /// Skip only the server's own metadata replay. + if (!(args.is_metadata_replay && args.mode >= LoadingStrictnessLevel::ATTACH)) + { + for (const auto & address : configuration.addresses) + args.context->getRemoteHostFilter().checkHostAndPort(address.first, toString(address.second)); + } + mysql_settings->loadFromQueryContext(args.context, *engine_define); if (engine_define->settings) mysql_settings->loadFromQuery(*engine_define); diff --git a/src/Dictionaries/MongoDBDictionarySource.cpp b/src/Dictionaries/MongoDBDictionarySource.cpp index 437dc9639d5b..21fc0088c6ba 100644 --- a/src/Dictionaries/MongoDBDictionarySource.cpp +++ b/src/Dictionaries/MongoDBDictionarySource.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -45,7 +46,7 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) Block & sample_block, ContextPtr context, const std::string & /* default_database */, - bool /* created_from_ddl */) + bool created_from_ddl) { const auto config_prefix = root_config_prefix + ".mongodb"; auto configuration = std::make_shared(); @@ -102,6 +103,10 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) configuration->checkHosts(context); configuration->checkCollection(); + /// A DDL dictionary is loaded by the server with the global context, so no session setting can permit server credentials here. + if (created_from_ddl && context->getApplicationType() != Context::ApplicationType::LOCAL) + configuration->checkServerCredentialsForDictionary(); + return std::make_unique(dict_struct, std::move(configuration), std::make_shared(sample_block)); }; #else diff --git a/src/Dictionaries/SSDCacheDictionaryStorage.h b/src/Dictionaries/SSDCacheDictionaryStorage.h index e6a732ef34a1..afbf9c3170e2 100644 --- a/src/Dictionaries/SSDCacheDictionaryStorage.h +++ b/src/Dictionaries/SSDCacheDictionaryStorage.h @@ -1370,9 +1370,10 @@ class SSDCacheDictionaryStorage final : public ICacheDictionaryStorage if (memory_buffer_partitions.size() < configuration.max_partitions_count) { /// Try tro create next partition without reusing old partitions - ++current_partition_index; file_buffer.allocateSizeForNextPartition(); memory_buffer_partitions.emplace_back(configuration.block_size, configuration.write_buffer_blocks_size); + /// Advance only after both calls succeed, so the index stays valid if one of them throws. + ++current_partition_index; } else { diff --git a/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp b/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp index 7d5849f91375..8c8226001be9 100644 --- a/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp +++ b/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp @@ -256,7 +256,7 @@ void parseMatchList(UInt64 parent_id, UInt64 & id, const YAML::Node & node, Resu { if (!node.IsSequence()) { - throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Configuration {} must be a yaml list of match rules", node.as()); + throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Configuration must be a yaml list of match rules"); } for (const auto & child_node : node) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp index 41e7a8ced5cf..cc7273537fa2 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp @@ -88,6 +88,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int AZURE_BLOB_STORAGE_ERROR; extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; } @@ -227,6 +228,28 @@ String ConnectionParams::getConnectionURL() const return endpoint.storage_account_url; } +String ConnectionParams::getConnectionURLWithoutQuery() const +{ + if (std::holds_alternative(auth_method)) + { + try + { + /// `ParseConnectionString` appends the SAS of the connection string to `BlobServiceUrl` as its query. + auto url = Azure::Storage::_internal::ParseConnectionString(endpoint.storage_account_url).BlobServiceUrl; + const auto query = url.GetQueryParameters(); + for (const auto & [key, value] : query) + url.RemoveQueryParameter(key); + return url.GetAbsoluteUrl(); + } + catch (const std::logic_error & e) + { + translateAzureSdkParseError(e); + } + } + + return endpoint.storage_account_url.substr(0, endpoint.storage_account_url.find_first_of("?#")); +} + std::unique_ptr ConnectionParams::createForService() const { try @@ -359,6 +382,13 @@ std::unique_ptr getContainerClient(const ConnectionParams & par } } +String getETag(const Azure::ETag & etag, const String & blob_path) +{ + if (!etag.HasValue()) + throw Exception(ErrorCodes::AZURE_BLOB_STORAGE_ERROR, "Azure Blob Storage endpoint did not return an ETag for blob {}", blob_path); + return etag.ToString(); +} + AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { if (config.has(config_prefix + ".account_key") && config.has(config_prefix + ".account_name")) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h index b282df96fae8..7387f59df565 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h @@ -146,6 +146,8 @@ struct ConnectionParams String getContainer() const { return endpoint.container_name; } String getConnectionURL() const; + /// Without the query, which can be a SAS, for where the url only names the endpoint (logs, errors, cache keys). + String getConnectionURLWithoutQuery() const; std::unique_ptr createForService() const; std::unique_ptr createForContainer() const; @@ -163,6 +165,10 @@ BlobClientOptions getClientOptions( AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); +/// `ETag` is an optional response header, and `Azure::ETag::ToString` aborts the process when the tag is absent +/// (also in release builds). Use this function instead: it throws an exception when the endpoint did not send the tag. +String getETag(const Azure::ETag & etag, const String & blob_path); + #endif Endpoint processEndpoint(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp index 80d0714c83ab..d59df48d18a7 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp @@ -100,7 +100,7 @@ class AzureIteratorAsync final : public IObjectStorageIteratorAsync .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); @@ -209,7 +209,7 @@ void AzureObjectStorage::listObjects(const std::string & path, RelativePathsWith .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); diff --git a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp index 241e8c8f7550..ec6a692f6fe6 100644 --- a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp +++ b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp @@ -81,6 +81,7 @@ AsynchronousBoundedReadBuffer::AsynchronousBoundedReadBuffer( { use_page_cache = true; buffer_size = read_settings.page_cache_block_size; + padded = false; } LOG_TEST(log, "Using buffer size {} while reading {}", buffer_size, file_name); diff --git a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp index 672d1bfbf8fb..f206567eea2a 100644 --- a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp +++ b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp @@ -431,7 +431,7 @@ void ReadBufferFromAzureBlobStorage::setMetadataFromResponse(const Azure::Storag { ObjectMetadata new_metadata; new_metadata.size_bytes = blob_size; - new_metadata.etag = details.ETag.ToString(); + new_metadata.etag = AzureBlobStorage::getETag(details.ETag, path); new_metadata.last_modified = static_cast(details.LastModified).time_since_epoch().count(); if (!details.Metadata.empty()) { diff --git a/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp new file mode 100644 index 000000000000..161256caba5b --- /dev/null +++ b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp @@ -0,0 +1,106 @@ +#include "config.h" + +#if USE_AZURE_BLOB_STORAGE + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int AZURE_BLOB_STORAGE_ERROR; +} + +namespace +{ + +class OwningBodyStream : public Azure::Core::IO::BodyStream +{ +public: + explicit OwningBodyStream(std::vector data_) : data(std::move(data_)) { } + + int64_t Length() const override { return static_cast(data.size()); } + + void Rewind() override { position = 0; } + +private: + size_t OnRead(uint8_t * buffer, size_t count, const Azure::Core::Context &) override + { + const size_t to_read = std::min(count, data.size() - position); + if (to_read != 0) + memcpy(buffer, data.data() + position, to_read); + position += to_read; + return to_read; + } + + std::vector data; + size_t position = 0; +}; + +/// A fake Azure endpoint that serves a 10-byte blob in a response without the optional `ETag` header. +class EndpointWithoutETag : public Azure::Core::Http::HttpTransport +{ +public: + std::unique_ptr Send(Azure::Core::Http::Request &, const Azure::Core::Context &) override + { + constexpr size_t blob_size = 10; + auto response = std::make_unique( + 1, 1, Azure::Core::Http::HttpStatusCode::PartialContent, "Partial Content"); + response->SetHeader("Content-Length", std::to_string(blob_size)); + response->SetHeader("Content-Range", "bytes 0-" + std::to_string(blob_size - 1) + "/" + std::to_string(blob_size)); + response->SetHeader("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT"); + response->SetHeader("x-ms-blob-type", "BlockBlob"); + response->SetBodyStream(std::make_unique(std::vector(blob_size, 'a'))); + return response; + } +}; + +} + +/// `Azure::ETag::ToString` aborts the process on an absent tag, also in release builds. +/// A download response without `ETag` must fail the read with an exception instead. +TEST(AzureReadBuffer, MissingETagIsAnException) +{ + Azure::Storage::Blobs::BlobClientOptions client_options; + client_options.Retry.MaxRetries = 0; + client_options.Transport.Transport = std::make_shared(); + + auto container_client = std::make_shared( + Azure::Storage::Blobs::BlobContainerClient("http://azure.invalid/container", client_options), /* blob_prefix */ ""); + + DB::ReadBufferFromAzureBlobStorage buffer( + container_client, + "blob", + DB::ReadSettings{}, + /* max_single_read_retries */ 1, + /* max_single_download_retries */ 1); + + std::optional error_code; + try + { + std::string data; + DB::readStringUntilEOF(data, buffer); + } + catch (const DB::Exception & e) + { + error_code = e.code(); + } + ASSERT_EQ(error_code, std::optional(DB::ErrorCodes::AZURE_BLOB_STORAGE_ERROR)); +} + +#endif diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index 807bf03ce4f7..d82cf35bef76 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -313,6 +313,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se format_settings.arrow.output_fixed_string_as_fixed_byte_array = settings[Setting::output_format_arrow_fixed_string_as_fixed_byte_array]; format_settings.arrow.output_compression_method = settings[Setting::output_format_arrow_compression_method]; format_settings.arrow.output_date_as_uint16 = settings[Setting::output_format_arrow_date_as_uint16]; + format_settings.arrow.output_max_record_batch_bytes = settings[Setting::output_format_arrow_max_record_batch_size_bytes]; format_settings.orc.allow_missing_columns = settings[Setting::input_format_orc_allow_missing_columns]; format_settings.orc.row_batch_size = settings[Setting::input_format_orc_row_batch_size]; format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference = settings[Setting::input_format_orc_skip_columns_with_unsupported_types_in_schema_inference]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 8cc2792c21f8..7ad2d29e34f3 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -5,9 +5,15 @@ #include #include +#include + namespace DB { +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, and the Apache Arrow +/// builders additionally reject the last representable value. +constexpr UInt64 MAX_ARROW_BUFFER_SIZE = std::numeric_limits::max() - 1; + /** * Various tweaks for input/output formats. Text serialization/deserialization * of data types also depend on some of these settings. It is different from @@ -166,6 +172,8 @@ struct FormatSettings bool output_fixed_string_as_fixed_byte_array = true; ArrowCompression output_compression_method = ArrowCompression::NONE; bool output_date_as_uint16 = false; + /// Upper bound on one record batch. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; } arrow{}; struct diff --git a/src/Formats/ProtobufSerializer.cpp b/src/Formats/ProtobufSerializer.cpp index 420d951ed7c0..49089ea851d0 100644 --- a/src/Formats/ProtobufSerializer.cpp +++ b/src/Formats/ProtobufSerializer.cpp @@ -4122,6 +4122,9 @@ namespace if (!name_and_type) return std::nullopt; const auto * tuple_type = assert_cast(name_and_type->type.get()); + /// The key or the value of the map entry was skipped as unsupported, so the map is skipped as a whole. + if (tuple_type->getElements().size() != 2) + return std::nullopt; return NameAndTypePair{name_and_type->name, std::make_shared(tuple_type->getElements())}; } diff --git a/src/Functions/HasSubsequenceImpl.h b/src/Functions/HasSubsequenceImpl.h index 30a522ea50a6..17f370e68344 100644 --- a/src/Functions/HasSubsequenceImpl.h +++ b/src/Functions/HasSubsequenceImpl.h @@ -127,6 +127,8 @@ class HasSubsequenceImpl : public IFunction if (!needle_size) return 1; + if (!haystack_size) + return 0; auto haystack_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(haystack_pos), haystack_end - haystack_pos); auto needle_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(needle_pos), needle_end - needle_pos); diff --git a/src/Functions/URL/protocol.h b/src/Functions/URL/protocol.h index 5e90f538ff1e..5542458a75d9 100644 --- a/src/Functions/URL/protocol.h +++ b/src/Functions/URL/protocol.h @@ -10,6 +10,9 @@ namespace DB /// Extracts scheme from given url. inline std::string_view getURLScheme(const char * data, size_t size) { + if (size == 0) + return {}; + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) const char * pos = data; const char * end = data + size; diff --git a/src/IO/CachedInMemoryReadBufferFromFile.cpp b/src/IO/CachedInMemoryReadBufferFromFile.cpp index c3241d65aede..c2489460cad5 100644 --- a/src/IO/CachedInMemoryReadBufferFromFile.cpp +++ b/src/IO/CachedInMemoryReadBufferFromFile.cpp @@ -26,6 +26,8 @@ CachedInMemoryReadBufferFromFile::CachedInMemoryReadBufferFromFile( , inner_read_until_position(read_until_position) { cache_key.offset = 0; + /// The working buffer is a page cache cell, an exact-size allocation: nothing past its end is readable. + padded = false; } String CachedInMemoryReadBufferFromFile::getFileName() const diff --git a/src/IO/ReadWriteBufferFromHTTP.cpp b/src/IO/ReadWriteBufferFromHTTP.cpp index 02834987d538..29d108ac9ca2 100644 --- a/src/IO/ReadWriteBufferFromHTTP.cpp +++ b/src/IO/ReadWriteBufferFromHTTP.cpp @@ -28,7 +28,8 @@ bool isRetriableError(const Poco::Net::HTTPResponse::HTTPStatus http_status) noe Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND, Poco::Net::HTTPResponse::HTTPStatus::HTTP_FORBIDDEN, Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_IMPLEMENTED, - Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED}; + Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED, + Poco::Net::HTTPResponse::HTTPStatus::HTTP_CONFLICT}; return std::all_of( non_retriable_errors.begin(), non_retriable_errors.end(), [&](const auto status) { return http_status != status; }); diff --git a/src/IO/S3/Client.cpp b/src/IO/S3/Client.cpp index 33dd73a0f579..8e09316d4de7 100644 --- a/src/IO/S3/Client.cpp +++ b/src/IO/S3/Client.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -78,6 +79,7 @@ namespace Setting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; extern const int TOO_MANY_REDIRECTS; } @@ -1196,6 +1198,21 @@ std::unique_ptr ClientFactory::create( // NOLINT if (!server_side_encryption_customer_key_base64.empty()) { + /// `base64Decode` throws on characters outside the alphabet but skips whitespace and ignores padding bits, + /// so the round trip below accepts only the canonical base64 of an AES-256 key, the only key SSE-C takes. + String customer_key; + try + { + customer_key = base64Decode(server_side_encryption_customer_key_base64); + } + catch (const Poco::DataFormatException &) + { + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + } + + if (customer_key.size() != AES256_KEY_BYTES || base64Encode(customer_key) != server_side_encryption_customer_key_base64) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + /// See Client::GeneratePresignedUrlWithSSEC(). headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, @@ -1204,10 +1221,8 @@ std::unique_ptr ClientFactory::create( // NOLINT headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, server_side_encryption_customer_key_base64}); - Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode(server_side_encryption_customer_key_base64); - String str_buffer(reinterpret_cast(buffer.GetUnderlyingData()), buffer.GetLength()); headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, - Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(str_buffer))}); + Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(customer_key))}); } // These will be added after request signing diff --git a/src/IO/S3/Client.h b/src/IO/S3/Client.h index 61ee4ead3dc0..ac7fd172617b 100644 --- a/src/IO/S3/Client.h +++ b/src/IO/S3/Client.h @@ -333,6 +333,8 @@ class Client : private Aws::S3::S3Client class ClientFactory { public: + static constexpr size_t AES256_KEY_BYTES = 32; + ~ClientFactory(); static ClientFactory & instance(); diff --git a/src/IO/SharedThreadPools.cpp b/src/IO/SharedThreadPools.cpp index c299fc8175e5..29e65bf483a8 100644 --- a/src/IO/SharedThreadPools.cpp +++ b/src/IO/SharedThreadPools.cpp @@ -43,6 +43,9 @@ namespace CurrentMetrics extern const Metric MergeTreeSnapshotCommitThreads; extern const Metric MergeTreeSnapshotCommitThreadsActive; extern const Metric MergeTreeSnapshotCommitThreadsScheduled; + extern const Metric ParquetEncoderThreads; + extern const Metric ParquetEncoderThreadsActive; + extern const Metric ParquetEncoderThreadsScheduled; } namespace DB @@ -236,4 +239,10 @@ StaticThreadPool & getFormatParsingThreadPool() return instance; } +StaticThreadPool & getParquetEncoderThreadPool() +{ + static StaticThreadPool instance("ParquetEncoderThreadPool", CurrentMetrics::ParquetEncoderThreads, CurrentMetrics::ParquetEncoderThreadsActive, CurrentMetrics::ParquetEncoderThreadsScheduled); + return instance; +} + } diff --git a/src/IO/SharedThreadPools.h b/src/IO/SharedThreadPools.h index 505688083347..2e8d17d2529c 100644 --- a/src/IO/SharedThreadPools.h +++ b/src/IO/SharedThreadPools.h @@ -91,4 +91,6 @@ StaticThreadPool & getMergeTreePrefixesDeserializationThreadPool(); StaticThreadPool & getFormatParsingThreadPool(); +StaticThreadPool & getParquetEncoderThreadPool(); + } diff --git a/src/IO/tests/gtest_brotli_decoder.cpp b/src/IO/tests/gtest_brotli_decoder.cpp new file mode 100644 index 000000000000..d7b8ade6a3f3 --- /dev/null +++ b/src/IO/tests/gtest_brotli_decoder.cpp @@ -0,0 +1,58 @@ +#include "config.h" + +#if USE_BROTLI + +#include +#include + +#include +#include +#include +#include +#include + +TEST(BrotliDecoder, RejectInvalidBlockSwitch) +{ + // A block switch is invalid when the stream declares only one block type. + // From https://github.com/nodejs/node/blob/main/test/parallel/test-zlib-invalid-input.js. + constexpr std::array input = { + 0x20, 0x00, 0x10, 0x41, 0x41, 0x41, 0xfc, 0xff, 0xff, 0x07, 0x00, + 0x22, 0x28, 0xf0, 0x0b, 0x60, 0xf7, 0xf4, 0x1f, 0x00, 0x00, 0x00}; + + for (size_t chunk_size : {input.size(), size_t{1}}) + { + std::unique_ptr state( + BrotliDecoderCreateInstance(nullptr, nullptr, nullptr), &BrotliDecoderDestroyInstance); + ASSERT_NE(state.get(), nullptr); + + std::array output{}; + size_t total_output = 0; + BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + + for (size_t offset = 0; offset < input.size() && result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;) + { + size_t available_input = std::min(chunk_size, input.size() - offset); + const size_t provided_input = available_input; + const uint8_t * next_input = input.data() + offset; + do + { + uint8_t * next_output = output.data(); + size_t available_output = output.size(); + result = BrotliDecoderDecompressStream( + state.get(), &available_input, &next_input, &available_output, &next_output, nullptr); + total_output += output.size() - available_output; + ASSERT_LT(total_output, 64 * 1024 * 1024); + } + while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT); + offset += provided_input - available_input; + if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) + ASSERT_GT(provided_input - available_input, 0); + } + + EXPECT_EQ(result, BROTLI_DECODER_RESULT_ERROR); + // -17 is the `BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH` code added by the fix. + EXPECT_EQ(BrotliDecoderGetErrorCode(state.get()), static_cast(-17)); + } +} + +#endif diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index 8aa24023956f..b5599a2b6ee6 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -124,12 +124,18 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_) : query(query_->clone()) , query_str_with_secrets(query->formatWithSecretsOneLine()) , user_id(user_id_) , current_roles(current_roles_) + , current_user(current_user_) + , initial_user(initial_user_) + , authenticated_user(authenticated_user_) , settings(std::make_unique(settings_)) , data_kind(data_kind_) { @@ -147,6 +153,13 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( } } + /// Length-prefix each field: update(String) streams only bytes and the queue is keyed + /// by hash alone, so otherwise "a"/"a"/"aaa" and "aa"/"aa"/"a" would collide. + for (const String & identity_field : {current_user, initial_user, authenticated_user}) + { + siphash.update(identity_field.size()); + siphash.update(identity_field); + } setting_changes = settings->changes(); for (auto it = setting_changes.begin(); it != setting_changes.end();) @@ -172,6 +185,9 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -187,6 +203,9 @@ AsynchronousInsertQueue::InsertQuery::operator=(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -533,7 +552,16 @@ AsynchronousInsertQueue::PushResult AsynchronousInsertQueue::pushDataChunk(ASTPt if (insert_query.format == "Values") entry->query_parameters = query_context->getQueryParameters(); - InsertQuery key{query, query_context->getUserID(), query_context->getCurrentRoles(), settings, data_kind}; + const auto & client_info = query_context->getClientInfo(); + InsertQuery key{ + query, + query_context->getUserID(), + query_context->getCurrentRoles(), + client_info.current_user, + client_info.initial_user, + client_info.authenticated_user, + settings, + data_kind}; InsertDataPtr data_to_process; std::future progress_future; @@ -980,6 +1008,14 @@ try insert_context->setCurrentRoles(key.current_roles); } + /// Context::setUser only restores the access-control identity, not the ClientInfo user + /// names. Restore them from the originating query so currentUser()/user()/ + /// authenticatedUser() and the materialized views triggered by the flush observe the + /// inserting user instead of an empty string. + insert_context->setCurrentUserName(key.current_user); + insert_context->setInitialUserName(key.initial_user); + insert_context->setAuthenticatedUserName(key.authenticated_user); + insert_context->setSettings(*key.settings); /// Set initial_query_id, because it's used in InterpreterInsertQuery for table lock. diff --git a/src/Interpreters/AsynchronousInsertQueue.h b/src/Interpreters/AsynchronousInsertQueue.h index 81a6fb36ab6f..f9eed199e90a 100644 --- a/src/Interpreters/AsynchronousInsertQueue.h +++ b/src/Interpreters/AsynchronousInsertQueue.h @@ -85,6 +85,14 @@ class AsynchronousInsertQueue : public WithContext String query_str_with_secrets; std::optional user_id; std::vector current_roles; + /// Client identity of the originating INSERT query (ClientInfo user names). + /// Restored on the flush context so currentUser()/user()/authenticatedUser() and + /// the materialized views triggered by the flush observe the inserting user instead + /// of an empty string. Part of the batching key so inserts from different identities + /// (e.g. impersonation, forwarded distributed queries) are never coalesced. + String current_user; + String initial_user; + String authenticated_user; std::unique_ptr settings; AsynchronousInsertQueueDataKind data_kind; @@ -94,6 +102,9 @@ class AsynchronousInsertQueue : public WithContext const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_); @@ -103,7 +114,7 @@ class AsynchronousInsertQueue : public WithContext StorageID getStorageID() const; private: - auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, setting_changes); } + auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, current_user, initial_user, authenticated_user, setting_changes); } std::vector setting_changes; }; diff --git a/src/Interpreters/Cache/EvictionCandidates.cpp b/src/Interpreters/Cache/EvictionCandidates.cpp index 35500747622d..3a639da3bb33 100644 --- a/src/Interpreters/Cache/EvictionCandidates.cpp +++ b/src/Interpreters/Cache/EvictionCandidates.cpp @@ -323,7 +323,8 @@ void EvictionCandidates::evict() } catch (...) { - failed_candidates.total_cache_size += candidate->file_segment->getDownloadedSize(); + /// Sum up reserved size, which is the queue entry size. + failed_candidates.total_cache_size += candidate->size(); failed_candidates.total_cache_elements += 1; failed_key_candidates.candidates.push_back(candidate); diff --git a/src/Interpreters/Cache/FileCache.cpp b/src/Interpreters/Cache/FileCache.cpp index a2dacdb03547..864a831cf935 100644 --- a/src/Interpreters/Cache/FileCache.cpp +++ b/src/Interpreters/Cache/FileCache.cpp @@ -2512,23 +2512,25 @@ bool FileCache::doDynamicResizeImpl( for (const auto & candidate : key_candidates) { const auto & file_segment = candidate->file_segment; + /// Restore the original queue entry size. For partial segments it is reserved size. + const auto restored_size = candidate->size(); LOG_DEBUG( - log, "Adding back file segment after failed eviction: {}:{}, size: {}", - file_segment->key(), file_segment->offset(), file_segment->getDownloadedSize()); + log, "Adding back file segment after failed eviction: {}:{}, restored size: {}, downloaded size: {}", + file_segment->key(), file_segment->offset(), restored_size, file_segment->getDownloadedSize()); auto original_queue_type = eviction_candidates.getOriginalQueueType(candidate.get()); auto main_priority_iterator = main_priority->addForRestore( key_metadata, file_segment->offset(), - file_segment->getDownloadedSize(), + restored_size, original_queue_type, cache_write_lock, &state_lock); candidate->setRemovedFlag(*locked_key, /* value */false); - file_segment->setQueueIterator(main_priority_iterator); + file_segment->restoreQueueIteratorAfterDelayedRemoval(main_priority_iterator); } } diff --git a/src/Interpreters/Cache/FileSegment.cpp b/src/Interpreters/Cache/FileSegment.cpp index 22befb6f0ef4..5a8a8cb8e25d 100644 --- a/src/Interpreters/Cache/FileSegment.cpp +++ b/src/Interpreters/Cache/FileSegment.cpp @@ -177,6 +177,7 @@ void FileSegment::setQueueIterator(Priority::IteratorPtr iterator) auto lk = lock(); if (queue_iterator) throw Exception(ErrorCodes::LOGICAL_ERROR, "Queue iterator cannot be set twice"); + chassert(!on_delayed_removal); queue_iterator = iterator; } @@ -187,6 +188,17 @@ void FileSegment::markDelayedRemovalAndResetQueueIterator() queue_iterator = {}; } +void FileSegment::restoreQueueIteratorAfterDelayedRemoval( + Priority::IteratorPtr iterator) +{ + auto lk = lock(); + chassert(iterator); + chassert(on_delayed_removal); + chassert(!queue_iterator); + queue_iterator = std::move(iterator); + on_delayed_removal = false; +} + size_t FileSegment::getCurrentWriteOffset() const { return range().left + downloaded_size; @@ -1034,6 +1046,10 @@ bool FileSegment::assertCorrectnessUnlocked(const FileSegmentGuard::Lock & lock) } } + /// A restored queue iterator must clear the delayed-removal state. + if (queue_iterator) + chassert(!on_delayed_removal); + switch (download_state.load()) { case State::EMPTY: @@ -1088,7 +1104,7 @@ bool FileSegment::assertCorrectnessUnlocked(const FileSegmentGuard::Lock & lock) chassert(file_size <= range().size()); chassert(downloaded_size <= range().size()); - chassert(queue_iterator); + chassert(queue_iterator || on_delayed_removal); check_iterator(queue_iterator); break; } diff --git a/src/Interpreters/Cache/FileSegment.h b/src/Interpreters/Cache/FileSegment.h index 7321cbeb1464..86e2048516c8 100644 --- a/src/Interpreters/Cache/FileSegment.h +++ b/src/Interpreters/Cache/FileSegment.h @@ -181,6 +181,10 @@ friend class FileCache; /// Because of reserved_size in tryReserve(). void markDelayedRemovalAndResetQueueIterator(); + /// Restore a queue iterator after dynamic-resize eviction failed. + /// The segment must have been marked by `markDelayedRemovalAndResetQueueIterator`. + void restoreQueueIteratorAfterDelayedRemoval(Priority::IteratorPtr iterator); + KeyMetadataPtr tryGetKeyMetadata() const; KeyMetadataPtr getKeyMetadata() const; @@ -297,6 +301,7 @@ friend class FileCache; /// Because of reserved_size in tryReserve(). std::atomic hits_count = 0; /// cache hits. std::atomic ref_count = 0; /// Used for getting snapshot state + /// Guarded by `segment_guard`. Set while dynamic-resize eviction is pending. bool on_delayed_removal = false; CurrentMetrics::Increment metric_increment{CurrentMetrics::CacheFileSegments}; diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index aa63ec626fc7..c3f710e251d1 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1192,6 +1192,15 @@ void ContextSharedMutex::lockSharedImpl() ProfileEvents::increment(ProfileEvents::ContextLockWaitMicroseconds, watch.elapsedMicroseconds()); } +/// An entry of `ContextData::scalars`. `from_client` is true when the block arrived from the client +/// over the wire (`Context::addClientScalar`) rather than being computed by the server, so that +/// `Context::hasComputedScalar` can keep such a block out of the analyzer's scalar-subquery cache. +struct ScalarEntry +{ + Block block; + bool from_client = false; +}; + ContextData::ContextData() { settings = std::make_unique(); @@ -2383,7 +2392,10 @@ std::pair Context::setConcurrentThreadsSoftLimit(UInt64 num, UIn Scalars Context::getScalars() const { std::lock_guard lock(mutex); - return scalars; + Scalars res; + for (const auto & [name, entry] : scalars) + res.emplace(name, entry.block); + return res; } @@ -2398,7 +2410,7 @@ Block Context::getScalar(const String & name) const // often, so 'bad arguments' for now. throw Exception(ErrorCodes::BAD_ARGUMENTS, "Scalar {} doesn't exist (internal bug)", backQuoteIfNeed(name)); } - return it->second; + return it->second.block; } std::optional Context::tryGetSpecialScalar(const String & name) const @@ -2528,7 +2540,18 @@ void Context::addScalar(const String & name, const Block & block) throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); std::lock_guard lock(mutex); - scalars[name] = block; + /// A server-computed value overrides any client-supplied one of the same name and is trusted. + scalars[name] = ScalarEntry{block, /*from_client=*/ false}; +} + + +void Context::addClientScalar(const String & name, const Block & block) +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + scalars[name] = ScalarEntry{block, /*from_client=*/ true}; } @@ -2551,6 +2574,16 @@ bool Context::hasScalar(const String & name) const return scalars.contains(name); } +bool Context::hasComputedScalar(const String & name) const +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + auto it = scalars.find(name); + return it != scalars.end() && !it->second.from_client; +} + void Context::addQueryAccessInfo( const StorageID & table_id, const Names & column_names) @@ -3201,6 +3234,13 @@ void Context::clampToSettingsConstraintsWithLock(SettingsChanges & changes, Sett doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); } +void Context::clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source) +{ + getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.clampRejectingInvalidChanges(*settings, changes, source); + if (getApplicationType() == ApplicationType::LOCAL || getApplicationType() == ApplicationType::SERVER) + doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); +} + void Context::checkMergeTreeSettingsConstraintsWithLock(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.check(merge_tree_settings, changes); @@ -3284,6 +3324,21 @@ void Context::clampToSettingsConstraints(SettingsChanges & changes, SettingSourc clampToSettingsConstraintsWithLock(changes, source); } +void Context::clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source) +{ + if (std::ranges::any_of(changes, isProfileChange)) + { + changes = enforceConstraintsAlongProfileChanges(shared_from_this(), changes, [source](Context & context, SettingsChanges & segment) + { + context.clampToSettingsConstraintsRejectingInvalidChanges(segment, source); + }); + return; + } + + SharedLockGuard lock(mutex); + clampToSettingsConstraintsRejectingInvalidChangesWithLock(changes, source); +} + void Context::checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { SharedLockGuard lock(mutex); @@ -6999,6 +7054,12 @@ void Context::setInitialUserName(const String & initial_user_name) need_recalculate_access = true; } +void Context::setAuthenticatedUserName(const String & authenticated_user_name) +{ + client_info.authenticated_user = authenticated_user_name; + need_recalculate_access = true; +} + void Context::setInitialAddress(const Poco::Net::SocketAddress & initial_address) { client_info.initial_address = std::make_shared(initial_address); diff --git a/src/Interpreters/Context.h b/src/Interpreters/Context.h index e2fcb1224695..d732882f83e9 100644 --- a/src/Interpreters/Context.h +++ b/src/Interpreters/Context.h @@ -164,6 +164,10 @@ class DDLWorker; class ITableFunction; using TableFunctionPtr = std::shared_ptr; class Block; +/// An entry of the query scalar map: the scalar block plus whether it came from the client. +/// Defined in Context.cpp, where `Block` is complete; here `std::map` only needs the forward +/// declaration, the same way `Scalars` is a `std::map` over the forward-declared `Block`. +struct ScalarEntry; class ActionLocksManager; using ActionLocksManagerPtr = std::shared_ptr; class ShellCommand; @@ -395,8 +399,13 @@ class ContextData String insert_format; /// Format, used in insert query. TemporaryTablesMapping external_tables_mapping; - /// Query scalars - Scalars scalars; + /// Query scalars. Each entry carries whether it was supplied by the client over the wire (the + /// `Scalar` packet, i.e. the `clickhouse-client --external ... --scalar` feature or an initiator + /// shipping scalars to a shard) rather than computed by the server itself. The origin travels with + /// the block so that the analyzer's scalar-subquery cache (which keys on the query-tree hash) never + /// mistakes a client-supplied block for an already-computed subquery result; without this a client + /// could forge the result of a scalar subquery used in a row policy and bypass the policy. + std::map scalars; /// Used to store constant values which are different on each instance during distributed plan, such as _shard_num. Scalars special_scalars; @@ -942,6 +951,7 @@ class Context: public ContextData, public std::enable_shared_from_this void setCurrentUserName(const String & current_user_name); void setCurrentAddress(const Poco::Net::SocketAddress & current_address); void setInitialUserName(const String & initial_user_name); + void setAuthenticatedUserName(const String & authenticated_user_name); void setInitialAddress(const Poco::Net::SocketAddress & initial_address); void setInitialQueryId(const String & initial_query_id); void setInitialQueryStartTime(std::chrono::time_point initial_query_start_time); @@ -981,6 +991,16 @@ class Context: public ContextData, public std::enable_shared_from_this void addScalar(const String & name, const Block & block); bool hasScalar(const String & name) const; + /// Add a scalar received from the client over the wire (the `Scalar` packet). Unlike `addScalar`, + /// the entry is marked as client-supplied so that `hasComputedScalar` will not report it as a + /// server-computed subquery result. Explicit readers (`__getScalar`, `_shard_num`, forwarding to + /// shards) still see it through `getScalar` / `hasScalar` / `getScalars`. + void addClientScalar(const String & name, const Block & block); + /// Like `hasScalar`, but returns true only for scalars the server computed itself, never for + /// client-supplied ones. The analyzer's scalar-subquery cache must use this so that a forged + /// client scalar cannot stand in for the result of a (e.g. row-policy) scalar subquery. + bool hasComputedScalar(const String & name) const; + std::optional tryGetSpecialScalar(const String & name) const; void addSpecialScalar(const String & name, const Block & block); @@ -1117,6 +1137,7 @@ class Context: public ContextData, public std::enable_shared_from_this /// For the resets of a statement that also changes `profile`: `changes_applied_first` decides their constraints. void checkSettingsConstraintsForSettingsReset(const std::vector & names, const SettingsChanges & changes_applied_first, SettingSource source); void clampToSettingsConstraints(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source); void checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const; /// Reset settings to default value @@ -1810,6 +1831,7 @@ class Context: public ContextData, public std::enable_shared_from_this void checkSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source); void checkSettingsConstraintsWithLock(const AlterSettingsProfileElements & profile_elements, SettingSource source) const; void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source) const; diff --git a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp index dc247f5119e3..bd217badfadf 100644 --- a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp +++ b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp @@ -156,7 +156,7 @@ void ExecuteScalarSubqueriesMatcher::visit(const ASTSubquery & subquery, ASTPtr } else { - if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasScalar(scalar_query_hash_str)) + if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasComputedScalar(scalar_query_hash_str)) { if (!data.getContext()->getViewSource()) { diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index 2ad408df7443..9976d55c6111 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -24,12 +25,17 @@ #include #include #include +#include #include #include +#include #include #include +#include #include +#include #include +#include #include #include #include @@ -62,6 +68,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int LOGICAL_ERROR; extern const int INCORRECT_QUERY; extern const int NOT_IMPLEMENTED; @@ -73,6 +80,83 @@ namespace ErrorCodes extern const int SUPPORT_IS_DISABLED; } +namespace +{ + +/// A setting that sends the table's data elsewhere copies the data as it is stored, so nothing can filter the rows +/// that a row policy hides. It reads only the query and the access entities, +/// not the table, so it runs on the initiator. The database is resolved only for such a setting, so that other queries +/// do not need a current database. +void checkNoRowPolicyForExport(const ASTAlterQuery & alter, const ContextPtr & context) +{ + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::MODIFY_SETTING || !command.settings_changes) + continue; + + const auto & changes = command.settings_changes->as().changes; + if (StorageFactory::instance().getExportAccessOfAnyEngine(changes).empty()) + continue; + + const String database = context->resolveDatabase(alter.getDatabase()); + auto row_policy_filter = context->getRowPolicyFilter(database, alter.getTable(), RowPolicyFilterType::SELECT_FILTER); + if (row_policy_filter && !row_policy_filter->isAlwaysTrue()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "Cannot change the settings of table {}.{} that send its data elsewhere because a row policy applies to it. " + "The data is copied as it is stored, so its rows cannot be filtered", + backQuoteIfNeed(database), backQuoteIfNeed(alter.getTable())); + } +} + +/// A `Replicated`-database host applies the statement without the submitting user. `ON CLUSTER` does +/// not reach this: it is refused unless its hosts run as the initiating user. +void checkAddedIndexPermissions(const ASTAlterQuery & alter, const StoragePtr & table, const ContextPtr & context) +{ + if (!table) + return; + + bool adds_transform = false; + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + + if (const auto * declaration = command.index_decl->as()) + if (hasTextIndexPreOrPostProcessor(*declaration)) + adds_transform = true; + } + + /// Against the schema the whole statement produces: a command of the same statement can change what + /// an alias in a transform expands to. Transforms only, so other statements get no extra analysis. + if (!adds_transform) + return; + + AlterCommands commands; + for (const auto & child : alter.command_list->children) + { + const auto * command_ast = child->as(); + if (command_ast->type == ASTAlterCommand::EXECUTE_COMMAND) + continue; + if (auto command = AlterCommand::parse(command_ast)) + commands.emplace_back(std::move(*command)); + } + + /// The same sequence as `executeToTable`: `apply` relies on the checks before it, and it authorizes + /// the added indices as the user. + StorageInMemoryMetadata metadata = table->getInMemoryMetadata(); + commands.validate(table, context); + commands.prepare(metadata); + table->checkAlterIsPossible(commands, context); + /// As the storages do before `apply`: an explicit `ADD STATISTICS` replaces an implicit one. + removeImplicitStatistics(metadata.columns); + commands.apply(metadata, context); +} + +} + InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, ContextMutablePtr context_) : WithMutableContext(context_), query_ptr(query_ptr_) { } @@ -130,15 +214,37 @@ BlockIO InterpreterAlterQuery::executeToTable(const ASTAlterQuery & alter) DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_alter = captured_query_ptr->as(); + for (const auto & child : captured_alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + if (const auto * declaration = command.index_decl->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + } + }; + /// The hosts run the entry without the user, so the row policy is checked here before the entry is enqueued. + checkNoRowPolicyForExport(alter, getContext()); return executeDDLQueryOnCluster(query_ptr, getContext(), params); } getContext()->checkAccess(getRequiredAccess()); + checkNoRowPolicyForExport(alter, getContext()); if (!table_id) throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(alter.getDatabase())); DatabasePtr database = DatabaseCatalog::instance().getDatabase(table_id.database_name); + + checkAddedIndexPermissions(alter, table, getContext()); + if (database->shouldReplicateQuery(getContext(), query_ptr)) { auto guard = DatabaseCatalog::instance().getDDLGuard(table_id.database_name, table_id.table_name, database.get()); @@ -624,6 +730,20 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand(const AS case ASTAlterCommand::MODIFY_SETTING: { required_access.emplace_back(AccessType::ALTER_SETTINGS, database, table); + + /// A setting that sends the table's data elsewhere, e.g. the move destination of a queue, is the same data flow as + /// `INSERT INTO FUNCTION s3(...) SELECT * FROM
`. The creator of the table supplied its source and credentials, + /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator + /// of `ON CLUSTER` can check them without the table. + if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) + { + auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + if (!export_access.empty()) + { + required_access.append_range(std::move(export_access)); + required_access.emplace_back(AccessType::SELECT, database, table); + } + } break; } case ASTAlterCommand::ATTACH_PARTITION: diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index 715a96ebc0b7..d0a1ce770c76 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -34,10 +34,12 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -146,6 +148,7 @@ namespace Setting namespace ServerSetting { + extern const ServerSettingsBool distributed_ddl_use_initial_user_and_roles; extern const ServerSettingsBool ignore_empty_sql_security_in_create_view_query; extern const ServerSettingsUInt64 max_database_num_to_throw; extern const ServerSettingsUInt64 max_dictionary_num_to_throw; @@ -988,6 +991,14 @@ InterpreterCreateQuery::TableProperties InterpreterCreateQuery::getTableProperti if (!create.columns_list) create.set(create.columns_list, make_intrusive()); + /// Authorize the text index transforms of every definition the user supplies now. A replay of stored + /// metadata is not checked, so such a table still attaches. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + { + for (const auto & index : properties.indices) + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + ASTPtr new_columns = formatColumns(properties.columns); ASTPtr new_indices = formatIndices(properties.indices); ASTPtr new_constraints = formatConstraints(properties.constraints); @@ -1714,6 +1725,11 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) /// Set and retrieve list of columns, indices and constraints. Set table engine if needed. Rewrite query in canonical way. TableProperties properties = getTablePropertiesAndNormalizeCreateQuery(create, mode); + /// Only here is an engine inherited through `AS` known, and nothing is enqueued or created yet. + /// A replay of a stored definition was checked when it was created. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + checkExportAccess(create); + DatabasePtr database; bool need_add_to_database = !create.isTemporary(); // In case of an ON CLUSTER query, the database may not be present on the initiator node @@ -2500,6 +2516,20 @@ BlockIO InterpreterCreateQuery::executeQueryOnCluster(ASTCreateQuery & create) prepareOnClusterQuery(create, getContext(), create.cluster); DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_create = captured_query_ptr->as(); + if (!captured_create.columns_list || !captured_create.columns_list->indices) + return; + + for (const auto & index : captured_create.columns_list->indices->children) + if (const auto * declaration = index->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + }; return executeDDLQueryOnCluster(query_ptr, getContext(), params); } @@ -2539,6 +2569,46 @@ BlockIO InterpreterCreateQuery::execute() if (inherited.storage && inherited.storage->engine) getContext()->checkAccess(AccessType::TABLE_ENGINE, inherited.storage->engine->name); + + /// setEngine copies only the outer engine of a `TimeSeries` source, and the worker copies + /// its inner engines while normalizing, so add the ones this query does not give itself + if (inherited.is_time_series_table) + { + auto as_create_ptr = DatabaseCatalog::instance().getDatabase(inherited.as_database)->getCreateTableQuery(inherited.as_table, getContext()); + const auto & as_create = as_create_ptr->as(); + if (as_create.targets) + for (const auto & target : as_create.targets->targets) + if (target.inner_engine && !inherited.getTargetInnerEngine(target.kind)) + inherited.setTargetInnerEngine(target.kind, target.inner_engine->clone()); + } + + /// the worker inherits the move destination of the source too, and runs with no user + checkExportAccess(inherited); + + /// A worker copies the source's indices with no user, so declare their transforms here. + if (inherited.storage && inherited.storage->engine && endsWith(inherited.storage->engine->name, "MergeTree")) + { + /// Before resolving it: an error below would otherwise disclose a source the user + /// cannot see. + getContext()->checkAccess(AccessType::SHOW_COLUMNS, create.as_database, create.as_table); + StoragePtr as_storage = resolveStorageProxyLoading( + DatabaseCatalog::instance().getTable({create.as_database, create.as_table}, getContext())); + /// The query dispatches `AS src`, so each host materializes its own source, which + /// may define the transform differently from the one authorized here. + const bool workers_use_initiator_user + = getContext()->getServerSettings()[ServerSetting::distributed_ddl_use_initial_user_and_roles] + && on_cluster_version >= DDLLogEntry::INITIATOR_USER_VERSION; + + auto as_storage_metadata = as_storage->getInMemoryMetadataPtr(); + for (const auto & index : as_storage_metadata->getSecondaryIndices()) + { + if (index.isImplicitlyCreated()) + continue; + if (!workers_use_initiator_user) + rejectTextIndexTransformWithoutInitiatorUser(index); + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + } } return executeQueryOnCluster(create); @@ -2623,9 +2693,28 @@ AccessRightsElements InterpreterCreateQuery::getRequiredAccess() const if (create.storage && create.storage->engine) required_access.emplace_back(AccessType::TABLE_ENGINE, create.storage->engine->name); + /// `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the table data and then moves it to the + /// data path of the new table. Reading it needs `READ` on the FILE source like the `file` function does, and + /// taking it away from `user_files` needs `WRITE`, like renaming files after processing does. Without this, + /// `CREATE TABLE` on a table of their own would let a user read or consume any data staged in `user_files`. + if (create.has_attach_from_path) + required_access.emplace_back(AccessType::READ | AccessType::WRITE, toStringSource(AccessTypeObjects::Source::FILE)); + + /// Settings that send the table's data elsewhere, e.g. the move destination of a queue, need the grants of that place. + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + return required_access; } +void InterpreterCreateQuery::checkExportAccess(const ASTCreateQuery & create) const +{ + /// Internal queries (initiated by the server itself) always have access to everything. + if (internal) + return; + + getContext()->checkAccess(StorageFactory::instance().getExportAccess(create)); +} + void InterpreterCreateQuery::extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr &, ContextPtr) const { if (!as_table_saved.empty()) diff --git a/src/Interpreters/InterpreterCreateQuery.h b/src/Interpreters/InterpreterCreateQuery.h index 9692dcdedbb6..674965cc7e00 100644 --- a/src/Interpreters/InterpreterCreateQuery.h +++ b/src/Interpreters/InterpreterCreateQuery.h @@ -112,6 +112,10 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext void setEngine(ASTCreateQuery & create) const; AccessRightsElements getRequiredAccess() const; + /// The part of `getRequiredAccess` for settings that send the table's data elsewhere, checked again once + /// `setEngine` has resolved an engine inherited through `AS`, which `getRequiredAccess` cannot see. + void checkExportAccess(const ASTCreateQuery & create) const; + /// Create IStorage and add it to database. If table already exists and IF NOT EXISTS specified, do nothing and return false. bool doCreateTable(ASTCreateQuery & create, const TableProperties & properties, DDLGuardPtr & ddl_guard, LoadingStrictnessLevel mode); BlockIO doCreateOrReplaceTable(ASTCreateQuery & create, const InterpreterCreateQuery::TableProperties & properties, LoadingStrictnessLevel mode); diff --git a/src/Interpreters/JIT/CHJIT.cpp b/src/Interpreters/JIT/CHJIT.cpp index 67c3068d0e0c..85609a0f5f07 100644 --- a/src/Interpreters/JIT/CHJIT.cpp +++ b/src/Interpreters/JIT/CHJIT.cpp @@ -427,7 +427,12 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function { std::lock_guard lock(jit_lock); - auto module = createModuleForCompilation(); + /// A fresh context per compile: `LLVMContext` never frees the constants it interns, and the optimizer + /// creates new ones for every distinct literal, so a long-lived context grows without bound. + /// Declared before `module`, which must be destroyed first. + auto context = std::make_unique(); + + auto module = createModuleForCompilation(*context); compile_function(*module); auto module_info = compileModule(std::move(module)); @@ -435,7 +440,7 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function return module_info; } -std::unique_ptr CHJIT::createModuleForCompilation() +std::unique_ptr CHJIT::createModuleForCompilation(llvm::LLVMContext & context) { std::unique_ptr module = std::make_unique("jit" + std::to_string(current_module_key), context); module->setDataLayout(layout); diff --git a/src/Interpreters/JIT/CHJIT.h b/src/Interpreters/JIT/CHJIT.h index 89d446fd3b34..04788222136e 100644 --- a/src/Interpreters/JIT/CHJIT.h +++ b/src/Interpreters/JIT/CHJIT.h @@ -89,7 +89,7 @@ class CHJIT private: - std::unique_ptr createModuleForCompilation(); + std::unique_ptr createModuleForCompilation(llvm::LLVMContext & context); CompiledModule compileModule(std::unique_ptr module); @@ -99,7 +99,6 @@ class CHJIT static std::unique_ptr getTargetMachine(); - llvm::LLVMContext context; std::unique_ptr machine; llvm::DataLayout layout; std::unique_ptr compiler; diff --git a/src/Interpreters/executeDDLQueryOnCluster.cpp b/src/Interpreters/executeDDLQueryOnCluster.cpp index 514f390e93ff..b2e6a3880daf 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.cpp +++ b/src/Interpreters/executeDDLQueryOnCluster.cpp @@ -194,6 +194,12 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, ContextPtr context, entry.initiator_user = context->getUserName(); entry.initiator_user_roles = context->getAccessControl().tryReadNames(context->getCurrentRoles()); } + + /// The workers run the query as the initiator's user and roles only if the entry carries them. + const bool workers_use_initiator_user = !entry.initiator_user.empty() && entry.version >= DDLLogEntry::INITIATOR_USER_VERSION; + if (params.additional_access_check) + params.additional_access_check(/* throw_if_unresolved = */ !workers_use_initiator_user); + ddl_worker.updateHostIDs(entry.hosts); String node_path = ddl_worker.enqueueQuery(entry, params.retries_info); diff --git a/src/Interpreters/executeDDLQueryOnCluster.h b/src/Interpreters/executeDDLQueryOnCluster.h index 69e0c38834e6..f98f9bb4aafc 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.h +++ b/src/Interpreters/executeDDLQueryOnCluster.h @@ -7,6 +7,8 @@ #include #include +#include + namespace zkutil { @@ -38,6 +40,12 @@ struct DDLQueryOnClusterParams /// Privileges which the current user should have to execute a query. AccessRightsElements access_to_check; + /// An authorization check which must run after the standard cluster and query checks but before enqueueing. + /// It receives whether the workers run the query without the initiator's user: they run it as that user and + /// roles only when `distributed_ddl_use_initial_user_and_roles` is enabled and `distributed_ddl_entry_format_version` + /// carries the initiator's user. + std::function additional_access_check; + /// Use retries when creating nodes "query-0000000000", "query-0000000001", "query-0000000002" in ZooKeeper. ZooKeeperRetriesInfo retries_info; }; diff --git a/src/Interpreters/tests/gtest_async_insert_key.cpp b/src/Interpreters/tests/gtest_async_insert_key.cpp index 0f4095a05bee..327525b4db5c 100644 --- a/src/Interpreters/tests/gtest_async_insert_key.cpp +++ b/src/Interpreters/tests/gtest_async_insert_key.cpp @@ -37,13 +37,59 @@ TEST(AsyncInsertKey, SettingsChanges) auto kind = AsynchronousInsertQueueDataKind::Parsed; - AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, settings1, kind); - AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, settings2, kind); - AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, settings3, kind); - AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, settings4, kind); + AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, {}, {}, {}, settings1, kind); + AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, {}, {}, {}, settings2, kind); + AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, {}, {}, {}, settings3, kind); + AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, {}, {}, {}, settings4, kind); EXPECT_EQ(key1, key2); EXPECT_NE(key1, key3); EXPECT_NE(key2, key3); EXPECT_NE(key3, key4); } + +TEST(AsyncInsertKey, IdentityHashIsNotAmbiguous) +{ + String query_str = "INSERT INTO test (a, b, c) VALUES (1, 2, 3)"; + ParserInsertQuery parser(query_str.data() + query_str.size(), false); + ASTPtr query = parseQuery(parser, query_str, DBMS_DEFAULT_MAX_QUERY_SIZE, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + Settings settings; + settings.set("async_insert", 1); + + auto kind = AsynchronousInsertQueueDataKind::Parsed; + + auto make_key = [&](const String & current_user, const String & initial_user, const String & authenticated_user) + { + return AsynchronousInsertQueue::InsertQuery( + query, {}, {}, current_user, initial_user, authenticated_user, settings, kind); + }; + + /// The three identity fields are variable-length strings folded into the queue key hash, + /// and the queue is indexed by hash alone. Without a length delimiter "a"/"a"/"aaa" and + /// "aa"/"aa"/"a" stream the same bytes ("aaaaa") and collide, which would route a second + /// user's insert into the first user's pending batch and flush it under the wrong + /// ClientInfo. The keys must differ both by hash and by equality. + auto key_a = make_key("a", "a", "aaa"); + auto key_b = make_key("aa", "aa", "a"); + EXPECT_NE(key_a.hash, key_b.hash); + EXPECT_NE(key_a, key_b); + + /// A field boundary shift across the current/initial split must also be distinguished. + auto key_c = make_key("a", "b", ""); + auto key_d = make_key("a", "", "b"); + EXPECT_NE(key_c.hash, key_d.hash); + EXPECT_NE(key_c, key_d); + + /// Same identity still hashes the same and compares equal (batching preserved). + auto key_e = make_key("alice", "alice", "alice"); + auto key_f = make_key("alice", "alice", "alice"); + EXPECT_EQ(key_e.hash, key_f.hash); + EXPECT_EQ(key_e, key_f); + + /// Distinct identities never coalesce. + auto key_g = make_key("alice", "alice", "alice"); + auto key_h = make_key("bob", "bob", "bob"); + EXPECT_NE(key_g.hash, key_h.hash); + EXPECT_NE(key_g, key_h); +} diff --git a/src/Interpreters/tests/gtest_filecache.cpp b/src/Interpreters/tests/gtest_filecache.cpp index 77be320656d2..8e3f36c7c3f3 100644 --- a/src/Interpreters/tests/gtest_filecache.cpp +++ b/src/Interpreters/tests/gtest_filecache.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -1913,3 +1914,220 @@ TEST_F(FileCacheTest, QueryLimitConcurrentReleaseNoLeak) ASSERT_EQ(found.get(), nullptr); } } + +TEST_F(FileCacheTest, PartiallyDownloadedDynamicResizeAssertion) +{ + /// Regression: dynamic resize temporarily clears the queue iterator before + /// evicting a `PARTIALLY_DOWNLOADED` segment. The invariant must allow that + /// delayed-removal state. + + ServerUUID::setRandomForUnitTests(); + DB::ThreadStatus thread_status; + + Poco::XML::DOMParser dom_parser; + std::string xml(R"CONFIG()CONFIG"); + Poco::AutoPtr document = dom_parser.parseString(xml); + Poco::AutoPtr config = new Poco::Util::XMLConfiguration(document); + getMutableContext().context->setConfig(config); + + auto query_context = DB::Context::createCopy(getContext().context); + query_context->makeQueryContext(); + query_context->setCurrentQueryId("partial_dl_dynamic_resize"); + chassert(&DB::CurrentThread::get() == &thread_status); + auto query_scope_holder = DB::QueryScope::create(query_context); + + DB::FileCacheSettings settings; + settings[FileCacheSetting::path] = cache_base_path; + settings[FileCacheSetting::max_size] = 16; + settings[FileCacheSetting::max_elements] = 4; + settings[FileCacheSetting::max_file_segment_size] = 8; + settings[FileCacheSetting::boundary_alignment] = 8; + settings[FileCacheSetting::load_metadata_asynchronously] = false; + settings[FileCacheSetting::cache_policy] = FileCachePolicy::LRU; + settings[FileCacheSetting::allow_dynamic_cache_resize] = true; + + auto cache = std::make_shared("partial_dl_resize", settings); + cache->initialize(); + + const auto & user = FileCache::getCommonOrigin(); + auto key = DB::FileCacheKey::fromPath("partial_dl_resize_key"); + + /// Segment 1: `PARTIALLY_DOWNLOADED` with reserved size 8 and downloaded size 3. + { + auto holder = cache->getOrSet(key, 0, 8, /*file_size=*/8, {}, 0, user); + ASSERT_EQ(holder->size(), 1u); + auto seg = *holder->begin(); + ASSERT_EQ(seg->state(), State::EMPTY); + + ASSERT_EQ(seg->getOrSetDownloader(), FileSegment::getCallerId()); + ASSERT_EQ(seg->state(), State::DOWNLOADING); + + std::string failure_reason; + ASSERT_TRUE(seg->reserve(/*size_to_reserve=*/8, /*lock_wait_timeout_milliseconds=*/1000, failure_reason)); + + /// `seg->write` expects the key directory to exist, as in `download`. + auto key_str = key.toString(); + auto subdir = fs::path(cache_base_path) / key_str.substr(0, 3) / key_str; + if (!fs::exists(subdir)) + fs::create_directories(subdir); + std::string data(3, 'a'); + seg->write(data.data(), data.size(), seg->getCurrentWriteOffset()); + + FileSegment::complete( + FileSegmentPtr(seg), + /*allow_background_download=*/false, + /*force_shrink_to_downloaded_size=*/false); + + ASSERT_EQ(seg->state(), State::PARTIALLY_DOWNLOADED) + << "Test setup did not produce a PARTIALLY_DOWNLOADED segment; " + "got: " << FileSegment::stateToString(seg->state()); + ASSERT_EQ(seg->getReservedSize(), 8u); + ASSERT_EQ(seg->getDownloadedSize(), 3u); + } + + /// Segment 2: a `DOWNLOADED` segment to make resize evict real entries. + { + auto holder = cache->getOrSet(key, 8, 8, /*file_size=*/16, {}, 0, user); + ASSERT_EQ(holder->size(), 1u); + auto seg = *holder->begin(); + ASSERT_EQ(seg->state(), State::EMPTY); + download(seg, /*complete=*/true); + ASSERT_EQ(seg->state(), State::DOWNLOADED); + } + + /// Sanity: the partial segment is still in `PARTIALLY_DOWNLOADED`. + { + auto infos = cache->getFileSegmentInfos(key, user.user_id); + ASSERT_EQ(infos.size(), 2u); + bool found_partial = false; + for (const auto & info : infos) + { + if (info.range_left == 0 && info.range_right == 7) + { + ASSERT_EQ(info.state, State::PARTIALLY_DOWNLOADED); + ASSERT_EQ(info.downloaded_size, 3u); + found_partial = true; + } + } + ASSERT_TRUE(found_partial); + } + + /// Trigger resize while the partial segment is in delayed-removal state. + DB::FileCacheSettings new_settings = settings; + new_settings[FileCacheSetting::max_size] = 4; + DB::FileCacheSettings actual_settings = settings; + + ASSERT_NO_THROW(cache->applySettingsIfPossible(new_settings, actual_settings)); + + ASSERT_LE(cache->getUsedCacheSize(), 4u); +} + +TEST_F(FileCacheTest, FailedEvictionRestorePreservesInvariants) +{ + /// Regression: failed eviction must restore queue entries with reserved size + /// and clear delayed-removal state on the segment. + + ServerUUID::setRandomForUnitTests(); + DB::ThreadStatus thread_status; + + Poco::XML::DOMParser dom_parser; + std::string xml(R"CONFIG()CONFIG"); + Poco::AutoPtr document = dom_parser.parseString(xml); + Poco::AutoPtr config = new Poco::Util::XMLConfiguration(document); + getMutableContext().context->setConfig(config); + + auto query_context = DB::Context::createCopy(getContext().context); + query_context->makeQueryContext(); + query_context->setCurrentQueryId("failed_eviction_restore"); + chassert(&DB::CurrentThread::get() == &thread_status); + auto query_scope_holder = DB::QueryScope::create(query_context); + + DB::FileCacheSettings settings; + settings[FileCacheSetting::path] = cache_base_path; + settings[FileCacheSetting::max_size] = 16; + settings[FileCacheSetting::max_elements] = 4; + settings[FileCacheSetting::max_file_segment_size] = 8; + settings[FileCacheSetting::boundary_alignment] = 8; + settings[FileCacheSetting::load_metadata_asynchronously] = false; + settings[FileCacheSetting::cache_policy] = FileCachePolicy::LRU; + settings[FileCacheSetting::allow_dynamic_cache_resize] = true; + + auto cache = std::make_shared("failed_eviction_restore", settings); + cache->initialize(); + + const auto & user = FileCache::getCommonOrigin(); + auto key = DB::FileCacheKey::fromPath("failed_eviction_restore_key"); + + /// `PARTIALLY_DOWNLOADED` segment, reserved size 8 and downloaded size 3. + { + auto holder = cache->getOrSet(key, 0, 8, /*file_size=*/8, {}, 0, user); + auto seg = *holder->begin(); + ASSERT_EQ(seg->getOrSetDownloader(), FileSegment::getCallerId()); + std::string failure_reason; + ASSERT_TRUE(seg->reserve(/*size_to_reserve=*/8, /*lock_wait_timeout_milliseconds=*/1000, failure_reason)); + + auto key_str = key.toString(); + auto subdir = fs::path(cache_base_path) / key_str.substr(0, 3) / key_str; + if (!fs::exists(subdir)) + fs::create_directories(subdir); + std::string data(3, 'a'); + seg->write(data.data(), data.size(), seg->getCurrentWriteOffset()); + + FileSegment::complete(FileSegmentPtr(seg), false, false); + ASSERT_EQ(seg->state(), State::PARTIALLY_DOWNLOADED); + ASSERT_EQ(seg->getReservedSize(), 8u); + ASSERT_EQ(seg->getDownloadedSize(), 3u); + } + + /// Second segment to keep the cache full and force eviction during resize. + { + auto holder = cache->getOrSet(key, 8, 8, /*file_size=*/16, {}, 0, user); + auto seg = *holder->begin(); + download(seg, /*complete=*/true); + ASSERT_EQ(seg->state(), State::DOWNLOADED); + } + + /// Both priority entries account for reserved size. + ASSERT_EQ(cache->getUsedCacheSize(), 16u); + ASSERT_EQ(cache->getFileSegmentsNum(), 2u); + + /// Force the failed-eviction restore loop to run. + { + DB::FailPointInjection::enableFailPoint("file_cache_dynamic_resize_fail_to_evict"); + SCOPE_EXIT({ + DB::FailPointInjection::disableFailPoint("file_cache_dynamic_resize_fail_to_evict"); + }); + + /// Trigger resize. The restore path must keep total queue size at 16. + DB::FileCacheSettings new_settings = settings; + new_settings[FileCacheSetting::max_size] = 4; + DB::FileCacheSettings actual_settings = settings; + + ASSERT_NO_THROW(cache->applySettingsIfPossible(new_settings, actual_settings)); + + /// Failed eviction reverts limits to the previous value. + ASSERT_EQ(actual_settings[FileCacheSetting::max_size].value, 16u); + + /// Release-visible check for restored reserved-size accounting. + ASSERT_EQ(cache->getUsedCacheSize(), 16u); + ASSERT_EQ(cache->getFileSegmentsNum(), 2u); + + /// All segments must still be reachable from the priority queue. + { + auto infos = cache->getFileSegmentInfos(key, user.user_id); + ASSERT_EQ(infos.size(), 2u); + for (const auto & info : infos) + ASSERT_NE(info.queue_entry_type, FileCacheQueueEntryType::None); + } + } + + /// A second resize verifies delayed-removal state was cleared. + { + DB::FileCacheSettings second_new_settings = settings; + second_new_settings[FileCacheSetting::max_size] = 4; + DB::FileCacheSettings second_actual = settings; + + ASSERT_NO_THROW(cache->applySettingsIfPossible(second_new_settings, second_actual)); + ASSERT_LE(cache->getUsedCacheSize(), 4u); + } +} diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index 8509d3903c38..e2698652f3fc 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -72,6 +73,16 @@ namespace return AzureConnectionValue::PlainStorageAccountURL; } + /// The keys an Azure named collection accepts (`StorageAzureConfiguration`). An override with any + /// other key, which can name any credential, is rejected only after the statement is logged. + bool isAzureCollectionKey(std::string_view key) + { + static const std::unordered_set keys = {"blob_path", "container", "format", "compression", "structure", + "compression_method", "account_name", "account_key", "connection_string", "storage_account_url", "partition_strategy", + "partition_columns_in_data_file", "client_id", "tenant_id"}; + return keys.contains(key); + } + /// The backup engines whose locator names a destination with no credential in it, each with the /// argument count it accepts. `BackupFactory` registers exactly these plus `S3` and `AzureBlobStorage`. std::optional credentialFreeBackupEngineArity(const String & engine_name) @@ -607,43 +618,147 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageFunctionSecretArguments( /// azureBlobStorageCluster('cluster_name', 'conn_string/storage_account_url', ...) has 'conn_string/storage_account_url' as its second argument. size_t url_arg_idx = is_cluster_function ? 1 : 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + + /// The other values are hidden before a connection string is: hiding that replaces its whole argument. if (!is_cluster_function && isNamedCollectionName(0)) { /// azureBlobStorage(named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(1); + maskUnreadAzureCollectionOverrides(1); + findSecretNamedArgument("account_key", 1); if (maskAzureConnectionString(-1, true, 1)) return; - findSecretNamedArgument("account_key", 1); + maskUnshowableAzureConnectionOverrides(1); return; } if (is_cluster_function && isNamedCollectionName(1)) { /// azureBlobStorageCluster(cluster, named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(2); + maskUnreadAzureCollectionOverrides(2); + findSecretNamedArgument("account_key", 2); if (maskAzureConnectionString(-1, true, 2)) return; - findSecretNamedArgument("account_key", 2); + maskUnshowableAzureConnectionOverrides(2); return; } - if (maskAzureConnectionString(url_arg_idx)) + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + + if (const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx)) + markSecretArgument(*credential_arg_idx); + + if (maskAzureConnectionString(arg(url_arg_idx))) return; - /// We should check other arguments first because we don't need to do any replacement in case of - /// azureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - /// azureBlobStorageCluster(cluster, connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) + if (arg(url_arg_idx) < function->arguments->size()) + maskUnshowableAzureConnectionValue(arg(url_arg_idx), *function->arguments->at(arg(url_arg_idx)), /* argument_is_named= */ false); +} + +void FunctionSecretArgumentsFinder::maskAzureExtraCredentials() +{ + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + if (const auto f = function->arguments->at(i)->getFunction(); f && f->name() == "extra_credentials") + markSecretArgument(i); + } +} + +std::optional FunctionSecretArgumentsFinder::tryGetAzureKey(const AbstractFunction & equals) +{ + String key; + if (equals.arguments && equals.arguments->size() == 2 && tryGetStringFromArgument(*equals.arguments->at(0), &key) + && isAzureCollectionKey(key)) + return key; + return {}; +} + +void FunctionSecretArgumentsFinder::maskUnreadAzureCollectionOverrides(size_t start) +{ + std::vector connection_overrides; + for (size_t i = start, size = function->arguments->size(); i < size; ++i) { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) + const auto f = function->arguments->at(i)->getFunction(); + if (!f || f->name() != "equals") + continue; + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if (!(tryGetStringFromArgument(*f->arguments->at(1), nullptr) || f->arguments->at(1)->tryGetLiteralText(nullptr))) + markSecretArgument(i, /* argument_is_named= */ true); + if (key == "connection_string" || key == "storage_account_url") + connection_overrides.push_back(i); + } + + if (connection_overrides.size() > 1) + for (const size_t i : connection_overrides) + markSecretArgument(i, /* argument_is_named= */ true); +} + +std::vector FunctionSecretArgumentsFinder::azureSlotArguments(size_t start) +{ + std::vector slots; + size_t extra_credentials = 0; + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + const auto argument = function->arguments->at(i); + if (argument->isSettings()) + continue; + const auto f = i < start ? nullptr : argument->getFunction(); + if (f && f->name() == "extra_credentials") { - if (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg)) - return; + ++extra_credentials; + continue; + } + if (f && f->name() == "equals" && f->arguments && f->arguments->size() == 2) + { + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if ((key != "partition_strategy" && key != "partition_columns_in_data_file") || !f->arguments->at(1)->tryGetLiteralText(nullptr)) + markSecretArgument(i, /* argument_is_named= */ true); + continue; } + slots.push_back(i); } - /// We're going to replace 'account_key' with '[HIDDEN]' if account_key is used in the signature - if (url_arg_idx + 4 < count) - markSecretArgument(url_arg_idx + 4); + if (extra_credentials > 1) + { + maskEveryArgument(); + return {}; + } + return slots; +} + +std::optional FunctionSecretArgumentsFinder::azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const +{ + const size_t count = slot_arguments.size(); + if (count == url_arg_idx + 2) + return slot_arguments[url_arg_idx + 1]; + if (count <= url_arg_idx + 4) + return {}; + String fourth_arg; + if (count <= url_arg_idx + 7 && tryGetStringFromArgument(slot_arguments[url_arg_idx + 3], &fourth_arg) + && (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg))) + return {}; + return slot_arguments[url_arg_idx + 4]; +} + +void FunctionSecretArgumentsFinder::maskPositionalsAfterAzureCollection(size_t start) +{ + for (size_t i = start, size = function->arguments->size(); i < size; ++i) + { + const auto f = function->arguments->at(i)->getFunction(); + if (!f || (f->name() != "equals" && f->name() != "extra_credentials")) + markSecretArgument(i); + } } bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named, size_t start) @@ -663,32 +778,38 @@ bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_id return false; } - if (!url_arg.starts_with("http")) + if (!url_arg.starts_with("http") && maskAzureConnectionStringSecrets(url_arg)) { - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - if (RE2::Replace(&url_arg, account_key_pattern, "AccountKey=[HIDDEN]\\1")) - { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; - } + chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments + result.start = url_arg_idx; + result.are_named = argument_is_named; + result.count = 1; + result.replacement = url_arg; + return true; + } - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - if (RE2::Replace(&url_arg, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1")) + return false; +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionValue( + size_t index, const AbstractFunction::Argument & value, bool argument_is_named) +{ + String text; + if (!value.tryGetString(&text, /* allow_identifier= */ false) || classifyAzureConnectionValue(text) == AzureConnectionValue::Unmaskable) + markSecretArgument(index, argument_is_named); +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionOverrides(size_t start) +{ + for (const auto * key : {"connection_string", "storage_account_url"}) + { + for (ssize_t i = findNamedArgument(nullptr, key, start); i >= 0; i = findNamedArgument(nullptr, key, static_cast(i) + 1)) { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; + const auto index = static_cast(i); + /// `findNamedArgument` returns only an `equals` function with two arguments. + maskUnshowableAzureConnectionValue(index, *function->arguments->at(index)->getFunction()->arguments->at(1), /* argument_is_named= */ true); } } - - return false; } bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit) @@ -701,8 +822,10 @@ bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t s { /// A key this rule cannot read hides which credential the override carries; a value that is /// no plain literal or identifier can nest one (`headers('Authorization' = '...')`). + String key; if (argument_function->arguments && argument_function->arguments->size() == 2 - && tryGetStringFromArgument(*argument_function->arguments->at(0), nullptr) + && tryGetStringFromArgument(*argument_function->arguments->at(0), &key) + && isAzureCollectionKey(key) && (tryGetStringFromArgument(*argument_function->arguments->at(1), nullptr) || argument_function->arguments->at(1)->tryGetLiteralText(nullptr))) continue; @@ -1043,6 +1166,12 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format, [account_name, account_key, ...]) size_t url_arg_idx = 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + if (isNamedCollectionName(url_arg_idx)) { /// AzureBlobStorage(named_collection, ..., account_key = 'account_key', ...) @@ -1057,28 +1186,15 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - /// We should check other arguments first because we don't need to do any replacement in case of - /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - bool fourth_argument_is_format = false; - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) - { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) - fourth_argument_is_format = fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg); - } - /// Which argument holds a credential: the two-argument shape takes a shared access signature beside - /// the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. - std::optional credential_arg_idx; - if (count == url_arg_idx + 2) - credential_arg_idx = url_arg_idx + 1; - else if (!fourth_argument_is_format && (url_arg_idx + 4 < count)) - credential_arg_idx = url_arg_idx + 4; + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx); /// The engine reads this argument as a connection string or as a plain account url; a value of /// another shape is read by neither rule below, and a hidden connection string replaces it whole. String connection_value; - const auto shape = tryGetStringFromArgument(url_arg_idx, &connection_value) + const auto shape = tryGetStringFromArgument(arg(url_arg_idx), &connection_value) ? classifyAzureConnectionValue(connection_value) : AzureConnectionValue::Unmaskable; if (shape == AzureConnectionValue::Unmaskable || (shape == AzureConnectionValue::ConnectionString && credential_arg_idx)) @@ -1087,7 +1203,7 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - if (maskAzureConnectionString(url_arg_idx)) + if (maskAzureConnectionString(arg(url_arg_idx))) return; if (credential_arg_idx) diff --git a/src/Parsers/FunctionSecretArgumentsFinder.h b/src/Parsers/FunctionSecretArgumentsFinder.h index b2c0f511ebbd..161a9754aa52 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.h +++ b/src/Parsers/FunctionSecretArgumentsFinder.h @@ -28,6 +28,9 @@ class AbstractFunction /// The exact literal text of any scalar literal (`1`, `true`, `1.5`), with strings quoted. /// Lets a reconstructor keep non-string values like `use_environment_credentials = 1` visible. virtual bool tryGetLiteralText(String * res) const = 0; + /// A `SETTINGS` clause among the arguments (`remote(..., SETTINGS ...)`): not a positional + /// argument, and it hides its own secret values when formatted. + virtual bool isSettings() const { return false; } }; class Arguments { @@ -164,12 +167,37 @@ class FunctionSecretArgumentsFinder void findS3FunctionSecretArguments(bool is_cluster_function); void findAzureBlobStorageFunctionSecretArguments(bool is_cluster_function); + /// Hides every `extra_credentials(...)` whole, its keys included: a key can be written as anything, a credential too. + void maskAzureExtraCredentials(); + /// The key of a `key = value` argument if it is one of the keys an Azure named collection accepts. Any other left + /// operand can be the credential itself (`'sp=r&sig=...' = 'x'`), so its argument is hidden whole. + static std::optional tryGetAzureKey(const AbstractFunction & equals); + /// Hides every override from `start` on that this rule cannot read: one whose key an Azure named collection does not + /// accept or whose value is no plain literal (it can nest a credential), and every connection override when there are + /// several: only one is read, and only one can be partly shown. + void maskUnreadAzureCollectionOverrides(size_t start); + /// The raw indexes of the arguments the Azure parser assigns slots to, the ones before `start` (the cluster name) as + /// written: it strips the `SETTINGS` clause and the first `extra_credentials(...)`, and a `key = value` takes no slot. + /// Also hides the value of a key the explicit form does not read (all of an argument whose key is no Azure key), and + /// every argument when a second `extra_credentials(...)` shifts the slots. + std::vector azureSlotArguments(size_t start); + /// The raw index of the argument holding a credential, if any: the two-argument shape takes a shared access signature + /// beside the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. + std::optional azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const; + /// After the collection name every argument must be an override or `extra_credentials(...)`; a positional one is + /// invalid but logged before validation rejects it, and can be a credential. + void maskPositionalsAfterAzureCollection(size_t start); bool maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named = false, size_t start = 0); /// Whether the arguments an `AzureBlobStorage(named_collection, ...)` destination or table takes /// from `start` can be shown: only an argument written here can carry a credential, and each has /// to be readable enough to tell that it does not. `positional_limit` bounds the plain literals /// read beside the overrides: one filename for a backup locator, none for a table engine. bool azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit); + /// Hides a connection value that no rule here can show: a URL carrying a credential of its own + /// (`user:key@`, a SAS `?sig=...`), or a value that is not a plain string literal. + void maskUnshowableAzureConnectionValue(size_t index, const AbstractFunction::Argument & value, bool argument_is_named); + /// The same, for the `connection_string` and `storage_account_url` overrides of a named collection from `start` on. + void maskUnshowableAzureConnectionOverrides(size_t start); /// Masks the secrets of every URL form (`url`/`urlCluster` table functions, the `URL` table /// engine, and their named-collection variants): the userinfo password of the url positional or a /// named `url = ...` override, and the `headers(...)` values at any position. `url` is at diff --git a/src/Parsers/FunctionSecretArgumentsFinderAST.h b/src/Parsers/FunctionSecretArgumentsFinderAST.h index 754411535c8d..6d0c5c050342 100644 --- a/src/Parsers/FunctionSecretArgumentsFinderAST.h +++ b/src/Parsers/FunctionSecretArgumentsFinderAST.h @@ -5,6 +5,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,7 @@ class FunctionAST : public AbstractFunction return nullptr; } bool isIdentifier() const override { return argument->as(); } + bool isSettings() const override { return argument->as(); } bool tryGetString(String * res, bool allow_identifier) const override { if (const auto * literal = argument->as()) diff --git a/src/Parsers/Lexer.cpp b/src/Parsers/Lexer.cpp index 8806ed24492c..abb35a149bc5 100644 --- a/src/Parsers/Lexer.cpp +++ b/src/Parsers/Lexer.cpp @@ -116,7 +116,7 @@ Token quotedHexOrBinString(const char *& pos, const char * const token_begin, co Token Lexer::nextToken() { Token res = nextTokenImpl(); - if (max_query_size && res.end > begin + max_query_size) + if (begin && max_query_size && res.end > begin + max_query_size) res.type = TokenType::ErrorMaxQuerySizeExceeded; if (res.isSignificant()) prev_significant_token_type = res.type; diff --git a/src/Parsers/tests/gtest_Parser.cpp b/src/Parsers/tests/gtest_Parser.cpp index 22f73a45a039..429e65d8d125 100644 --- a/src/Parsers/tests/gtest_Parser.cpp +++ b/src/Parsers/tests/gtest_Parser.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -38,6 +39,13 @@ std::ostream & operator<<(std::ostream & ostr, const ParserTestCase & test_case) return ostr << "ParserTestCase input: " << input_text; } +TEST(Lexer, NullInputWithMaxQuerySize) +{ + Lexer lexer(nullptr, nullptr, 262144); + Token token = lexer.nextToken(); + EXPECT_EQ(TokenType::EndOfStream, token.type); +} + TEST_P(ParserTest, parseQuery) { const auto & parser = std::get<0>(GetParam()); diff --git a/src/Processors/Chunk.cpp b/src/Processors/Chunk.cpp index 0564131c8768..aef99bd3dee0 100644 --- a/src/Processors/Chunk.cpp +++ b/src/Processors/Chunk.cpp @@ -69,13 +69,11 @@ void Chunk::checkNumRowsIsConsistent() MutableColumns Chunk::mutateColumns() { - size_t num_columns = columns.size(); - MutableColumns mutable_columns(num_columns); - for (size_t i = 0; i < num_columns; ++i) - mutable_columns[i] = IColumn::mutate(std::move(columns[i])); - - columns.clear(); - num_rows = 0; + MutableColumns mutable_columns(columns.size()); + /// Detach first: `IColumn::mutate` consumes the column even when it throws, and a chunk never holds a null column. + Columns detached_columns = detachColumns(); + for (size_t i = 0; i < detached_columns.size(); ++i) + mutable_columns[i] = IColumn::mutate(std::move(detached_columns[i])); return mutable_columns; } diff --git a/src/Processors/Formats/IInputFormat.h b/src/Processors/Formats/IInputFormat.h index 2b1eb5a447e8..a2e2f693ef54 100644 --- a/src/Processors/Formats/IInputFormat.h +++ b/src/Processors/Formats/IInputFormat.h @@ -130,6 +130,8 @@ class IInputFormat : public ISource void needOnlyCount() { need_only_count = true; } + virtual void prefetch() {} + protected: ReadBuffer & getReadBuffer() const { chassert(in); return *in; } diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp new file mode 100644 index 000000000000..8f76772b9ef6 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp @@ -0,0 +1,319 @@ +#include + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace DB +{ + +namespace +{ + +/// The largest `n <= end - begin` for which the non-decreasing `offsets` grow by at most `limit` over +/// rows [begin, begin + n). +size_t maxRowsByOffsets(const IColumn::Offsets & offsets, size_t begin, size_t end, UInt64 limit) +{ + const UInt64 base = offsets[static_cast(begin) - 1]; + const auto * first = offsets.data() + begin; + const auto * it = std::upper_bound(first, offsets.data() + end, base + limit); + return static_cast(it - first); +} + +/// A writer either materializes the column or dictionary-encodes it; measuring it as materialized bounds +/// both, since a batch's dictionary holds at most the distinct values of its rows. `canBeInsideLowCardinality` +/// allows only fixed-width types, `String` and `FixedString`, and of those only the two string types reach +/// a 32-bit-offset buffer. +size_t maxRowsForLowCardinality( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const DataTypePtr values_type = removeNullable(removeLowCardinality(type)); + const auto & low_cardinality = assert_cast(column); + const IColumn & values_column = *low_cardinality.getDictionary().getNestedNotNullableColumn(); + + if (isFixedString(values_type)) + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(values_column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + + if (!isString(values_type)) + return num_rows; + + const auto & values = assert_cast(values_column); + const auto & value_offsets = values.getOffsets(); + + /// Scanning the indexes is only needed when the whole dictionary repeated on every row could overflow: + /// no single value is larger than all of them together. This is O(1), unlike finding the largest value, + /// so it does not add work proportional to the dictionary for every batch of a split chunk. + const UInt64 dictionary_bytes = values.empty() ? 0 : value_offsets.back(); + if (dictionary_bytes == 0 || num_rows <= max_batch_bytes / dictionary_bytes) + return num_rows; + + const auto & indexes = low_cardinality.getIndexes(); + UInt64 total = 0; + for (size_t row = begin; row != end; ++row) + { + const auto index = static_cast(indexes.getUInt(row)); + total += value_offsets[index] - value_offsets[index - 1]; + if (total > max_batch_bytes) + return row - begin; + } + return num_rows; +} + +/// A `Variant` becomes an Arrow dense union, whose own buffers are bounded by the row count; only its +/// children, holding one alternative's rows each, can overflow. +size_t maxRowsForVariant( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const auto & variant_column = assert_cast(column); + const auto & variant_type = assert_cast(*type); + const size_t num_variants = variant_column.getNumVariants(); + const auto & local_discriminators = variant_column.getLocalDiscriminators(); + const auto & variant_offsets = variant_column.getOffsets(); + + /// Within a contiguous row range the offsets of each alternative are contiguous too (see + /// `ColumnVariant::updateHashWithValueRange`), so [begin, end) maps to the range + /// [nested_begin, nested_begin + nested_rows) of every alternative. + std::vector nested_begin(num_variants, 0); + std::vector nested_rows(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows[local_discr] == 0) + nested_begin[local_discr] = variant_offsets[row]; + ++nested_rows[local_discr]; + } + + std::vector nested_rows_that_fit(num_variants); + bool all_fit = true; + for (size_t local_discr = 0; local_discr != num_variants; ++local_discr) + { + const auto global_discr + = variant_column.globalDiscriminatorByLocal(static_cast(local_discr)); + nested_rows_that_fit[local_discr] = maxRowsFittingOneArrowBatch( + variant_column.getVariantByLocalDiscriminator(local_discr), + variant_type.getVariant(global_discr), + nested_begin[local_discr], + nested_begin[local_discr] + nested_rows[local_discr], + fixed_string_as_fixed_byte_array, max_batch_bytes); + all_fit &= nested_rows_that_fit[local_discr] == nested_rows[local_discr]; + } + if (all_fit) + return num_rows; + + /// Some alternative cannot take all of its rows: cut at the row where it runs out. + std::vector nested_rows_taken(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows_taken[local_discr] == nested_rows_that_fit[local_discr]) + return row - begin; + ++nested_rows_taken[local_discr]; + } + return num_rows; +} + +} + +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Arrow cannot address more than this however the caller was configured. + max_batch_bytes = std::min(max_batch_bytes, MAX_ARROW_BUFFER_SIZE); + + if (type->lowCardinality()) + return maxRowsForLowCardinality(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + if (isVariant(type)) + return maxRowsForVariant(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + /// A null row is written as a zero-length slot, so measuring the nested column only overestimates. + if (type->isNullable()) + { + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + removeNullable(type), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + + switch (WhichDataType(type).idx) + { + case TypeIndex::String: + { + return maxRowsByOffsets(assert_cast(column).getOffsets(), begin, end, max_batch_bytes); + } + case TypeIndex::FixedString: + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + case TypeIndex::Array: + { + const auto & array = assert_cast(column); + const auto & offsets = array.getOffsets(); + const size_t nested_begin = offsets[static_cast(begin) - 1]; + const size_t nested_rows = maxRowsFittingOneArrowBatch( + array.getData(), + assert_cast(*type).getNestedType(), + nested_begin, + offsets[end - 1], + fixed_string_as_fixed_byte_array, max_batch_bytes); + return maxRowsByOffsets(offsets, begin, end, std::min(nested_rows, max_batch_bytes)); + } + case TypeIndex::Map: + { + /// Both writers encode a Map exactly as its nested `Array(Tuple(key, value))`. + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + assert_cast(*type).getNestedType(), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + case TypeIndex::Tuple: + { + const auto & tuple = assert_cast(column); + const auto & elements = assert_cast(*type).getElements(); + size_t rows = num_rows; + for (size_t i = 0; i != elements.size(); ++i) + { + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + tuple.getColumn(i), elements[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + } + return rows; + } + /// Fixed-width Arrow types: a single values buffer, no offsets, nothing to exceed. + case TypeIndex::UInt8: + case TypeIndex::UInt16: + case TypeIndex::UInt32: + case TypeIndex::UInt64: + case TypeIndex::UInt128: + case TypeIndex::UInt256: + case TypeIndex::Int8: + case TypeIndex::Int16: + case TypeIndex::Int32: + case TypeIndex::Int64: + case TypeIndex::Int128: + case TypeIndex::Int256: + case TypeIndex::Float32: + case TypeIndex::Float64: + case TypeIndex::Enum8: + case TypeIndex::Enum16: + case TypeIndex::Date: + case TypeIndex::Date32: + case TypeIndex::DateTime: + case TypeIndex::DateTime64: + case TypeIndex::Time: + case TypeIndex::Time64: + case TypeIndex::Decimal32: + case TypeIndex::Decimal64: + case TypeIndex::Decimal128: + case TypeIndex::Decimal256: + case TypeIndex::IPv4: + case TypeIndex::IPv6: + case TypeIndex::UUID: + case TypeIndex::Interval: + { + return num_rows; + } + default: + { + /// A type with no Arrow equivalent is written by serializing each value, so bounding its + /// encoded size would mean serializing twice. The encoder rejects a batch that overflows. + return num_rows; + } + } +} + +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + chassert(columns.size() == types.size()); + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Some limits (`Variant`, `LowCardinality`) take time linear in the rows they are given, so measuring + /// the whole remainder of a chunk for each of its batches would be quadratic. The window grows instead: + /// the limit of a prefix is the limit of the whole range capped at the prefix's length, so the first + /// window that does not fit entirely gives the answer, and the work stays proportional to the rows + /// emitted, plus the initial window. + static constexpr size_t initial_window = 8192; + size_t window = std::min(num_rows, initial_window); + while (true) + { + /// Two columns never share an Arrow buffer, so the smallest per-column limit applies. + size_t rows = window; + for (size_t i = 0; i < columns.size() && rows != 0; ++i) + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + *columns[i], types[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + + if (rows < window || window == num_rows) + return rows; + window = std::min(num_rows, window * 2); + } +} + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.h b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h new file mode 100644 index 000000000000..c532138a8da0 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h @@ -0,0 +1,47 @@ +#pragma once + +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include + +namespace DB +{ + +/// The largest `n` such that rows [begin, begin + n) of `column` stay within `max_batch_bytes`; writers +/// split an oversized chunk accordingly. Returns 0 only when the first row does not fit on its own, which +/// the writer then lets Arrow reject. `ColumnConst` and the sparse/replicated representations are not +/// handled; callers materialize first. +/// +/// `LowCardinality` is measured as materialized, which only over-splits when it is written as an Arrow +/// dictionary. A dictionary larger than one buffer is not covered at all: its bytes do not depend on the +/// row count, because `ColumnLowCardinality::insertRangeFrom` keeps a shared source dictionary whole, so +/// every slice re-emits it. Arrow rejects such a chunk. +/// +/// A type with no Arrow equivalent is not covered either, since only serializing its values reveals their +/// encoded size. Both uncovered shapes are rejected by the writer instead of being split. +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes = MAX_ARROW_BUFFER_SIZE); + +/// The largest `n` such that rows [begin, begin + n) of every column stay within `max_batch_bytes`: the +/// number of rows of the next record batch of a chunk. The work is proportional to the returned number of +/// rows rather than to `end - begin`, so splitting a chunk into many batches stays linear. +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes); + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp index 1a71a4a32447..7c0dfb0044ae 100644 --- a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp @@ -64,6 +64,7 @@ void ArrowBlockOutputFormat::consume(Chunk chunk) .use_signed_indexes_for_dictionary = format_settings.arrow.use_signed_indexes_for_dictionary, .use_64_bit_indexes_for_dictionary = format_settings.arrow.use_64_bit_indexes_for_dictionary, .output_date_as_uint16 = format_settings.arrow.output_date_as_uint16, + .output_max_record_batch_bytes = format_settings.arrow.output_max_record_batch_bytes, }); } diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp index 4699b1b2fdf0..7c2d5b54eed9 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp @@ -1,7 +1,7 @@ #pragma clang diagnostic ignored "-Wreserved-identifier" #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include #include diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.h b/src/Processors/Formats/Impl/ArrowBufferedStreams.h index ecb6ef8cb6fe..510e3ee4c26e 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.h +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.h @@ -3,7 +3,7 @@ #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp index ffac42b86605..a9b508893a8f 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp @@ -1,7 +1,7 @@ #include #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h index e06cce04579d..bf0e3ecf828a 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h @@ -5,7 +5,7 @@ #include "config.h" -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp index 60f89e76aeef..f4e991cc1643 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp @@ -21,9 +21,12 @@ #include #include #include +#include #include #include +#include + #include #include #include @@ -66,6 +69,7 @@ namespace DB extern const int LOGICAL_ERROR; extern const int DECIMAL_OVERFLOW; extern const int ILLEGAL_COLUMN; + extern const int TOO_LARGE_ARRAY_SIZE; } static const std::initializer_list>> internal_type_to_arrow_type = @@ -517,6 +521,18 @@ namespace DB throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot fill arrow array {} with {} data", value_type->name(), column_type->getName()); } + /// Arrow's `Utf8`/`Binary` builders take an int32 length and their `Append` skips the copy when it is + /// negative, so a narrowed size would store an empty value instead of failing. + static void checkStringSizeFitsArrowOffsets(size_t size, const String & column_name, const String & format_name) + { + if (size > MAX_ARROW_BUFFER_SIZE) + throw Exception( + ErrorCodes::TOO_LARGE_ARRAY_SIZE, + "Cannot write a value of {} bytes of column {} to {}: `Utf8`/`Binary` offsets are 32-bit, so a single " + "value cannot be larger than {} bytes", + size, column_name, format_name, MAX_ARROW_BUFFER_SIZE); + } + template static void fillArrowArrayWithStringColumnData( ColumnPtr write_column, @@ -541,6 +557,7 @@ namespace DB else { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); } checkStatus(status, write_column->getName(), format_name); @@ -551,6 +568,7 @@ namespace DB for (size_t string_i = start; string_i < end; ++string_i) { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); checkStatus(status, write_column->getName(), format_name); } @@ -1200,37 +1218,72 @@ namespace DB for (const auto & chunk : chunks) { - /// For arrow::Table creation + /// Normalize once per chunk, so that it is not repeated for each row range below. + Columns columns(columns_num); + DataTypes column_types(columns_num); for (size_t column_i = 0; column_i < columns_num; ++column_i) { - const ColumnWithTypeAndName & header_column = header_columns[column_i]; - auto column = chunk.getColumns()[column_i]; - + auto column = chunk.getColumns()[column_i]->convertToFullColumnIfConst()->convertToFullColumnIfReplicated(); + auto column_type = header_columns[column_i].type; if (!settings.low_cardinality_as_dictionary) column = recursiveRemoveLowCardinality(column); - - std::unique_ptr array_builder; - arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); - checkStatus(status, column->getName(), format_name); - - fillArrowArray( - header_column.name, - column, - header_column.type, - nullptr, - array_builder.get(), - format_name, - 0, - column->size(), - settings, - dictionary_values); - - std::shared_ptr arrow_array; - status = array_builder->Finish(&arrow_array); - checkStatus(status, column->getName(), format_name); - - table_data.at(column_i).emplace_back(std::move(arrow_array)); + columns[column_i] = std::move(column); + column_types[column_i] = std::move(column_type); } + + /// The row limit is measured on types matching the columns: without dictionary output the + /// `LowCardinality` columns were materialized above. + DataTypes measured_types = column_types; + if (!settings.low_cardinality_as_dictionary) + for (auto & type : measured_types) + type = recursiveRemoveLowCardinality(type); + + /// A chunk that exceeds the 32-bit Arrow offsets becomes several arrays of the ChunkedArray. + const size_t num_rows = chunk.getNumRows(); + size_t offset = 0; + do + { + size_t rows = maxRowsFittingOneArrowBatch( + columns, + measured_types, + offset, + num_rows, + settings.output_fixed_string_as_fixed_byte_array, + settings.output_max_record_batch_bytes); + /// A row that does not fit on its own cannot be represented at all; the leaf encoders reject it. + rows = std::min(std::max(rows, 1), num_rows - offset); + + /// For arrow::Table creation + for (size_t column_i = 0; column_i < columns_num; ++column_i) + { + const ColumnWithTypeAndName & header_column = header_columns[column_i]; + ColumnPtr column = columns[column_i]; + + std::unique_ptr array_builder; + arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); + checkStatus(status, column->getName(), format_name); + + fillArrowArray( + header_column.name, + column, + column_types[column_i], + nullptr, + array_builder.get(), + format_name, + offset, + offset + rows, + settings, + dictionary_values); + + std::shared_ptr arrow_array; + status = array_builder->Finish(&arrow_array); + checkStatus(status, column->getName(), format_name); + + table_data.at(column_i).emplace_back(std::move(arrow_array)); + } + + offset += rows; + } while (offset < num_rows); } std::vector> columns; diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h index 2544faf9ed1d..160a78ed1c9f 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h @@ -4,6 +4,7 @@ #if USE_ARROW || USE_PARQUET #include +#include #include #include @@ -33,6 +34,8 @@ class CHColumnToArrowColumn bool use_64_bit_indexes_for_dictionary = false; /// Output Date as UInt16 instead of Arrow DATE32 for backward compatibility. bool output_date_as_uint16 = false; + /// Upper bound on one record batch; a chunk holding more is written as several. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; }; CHColumnToArrowColumn(const Block & header, const std::string & format_name_, const Settings & settings_); diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp index 58e797b4d591..a6e69f02d3a8 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp @@ -59,7 +59,7 @@ MsgPackRowInputFormat::MsgPackRowInputFormat(SharedHeader header_, std::unique_p void MsgPackRowInputFormat::resetParser() { IRowInputFormat::resetParser(); - visitor.reset(); + parser.init(); } void MsgPackRowInputFormat::setReadBuffer(ReadBuffer & in_) @@ -83,7 +83,7 @@ void MsgPackVisitor::set_info(IColumn & column, DataTypePtr type, UInt8 & read) info_stack.push(Info{column, type, false, std::nullopt, &read}); } -void MsgPackVisitor::reset() +void MsgPackVisitor::init() { info_stack = {}; } @@ -667,10 +667,10 @@ DataTypePtr MsgPackSchemaReader::getDataType(const msgpack::object & object, siz msgpack::object_map object_map = object.via.map; if (object_map.size) { - auto key_type = removeNullable(getDataType(object_map.ptr[0].key, depth + 1)); + auto key_type = getDataType(object_map.ptr[0].key, depth + 1); auto value_type = getDataType(object_map.ptr[0].val, depth + 1); if (key_type && value_type) - return std::make_shared(key_type, value_type); + return std::make_shared(removeNullable(key_type), value_type); } return nullptr; } diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h index be9dd30d6e8f..323df67d9707 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h @@ -52,7 +52,8 @@ class MsgPackVisitor : public msgpack::null_visitor /// Update info_stack void set_info(IColumn & column, DataTypePtr type, UInt8 & read); - void reset(); + /// Called by msgpack's parse_helper::init. + void init(); private: /// Stack is needed to process arrays and maps diff --git a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp index 96bb9b23ef3c..a39c4d82ec12 100644 --- a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp @@ -377,8 +377,12 @@ static bool tryToExtractStructureFromCreateQuery(ReadBuffer & in, NamesAndTypesL if (!create_query) return false; + /// `CREATE TABLE ... LIKE` has no column list, and a column list with only indexes or constraints has no columns. + if (!create_query->columns_list) + return false; + const auto * create_defines = create_query->columns_list->as(); - if (!create_defines) + if (!create_defines || !create_defines->columns) return false; structure = getColumnsList(create_defines->columns); @@ -431,9 +435,10 @@ static void readFirstCreateAndInsertQueries(ReadBuffer & in, String & table_name if (type == MySQLQueryType::CREATE) { /// If we have CREATE query, we can extract columns names and types from it. + /// `tryToExtractStructureFromCreateQuery` reads the CREATE query up to and including its `;`, + /// so the next query must not be skipped: it can be the first INSERT query. if (tryToExtractStructureFromCreateQuery(in, structure_from_create)) column_names = structure_from_create.getNames(); - skipQuery(in); insert_query_present = skipToInsertQuery(table_name, in); } diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp index 0e999852c352..b2f26243171e 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp @@ -3,6 +3,7 @@ #if USE_ORC #include +#include #include #include #include @@ -10,8 +11,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include @@ -25,20 +29,26 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include +#include +#include #include #include #include -#include #include #include #include @@ -47,10 +57,11 @@ #include #include -#include #include +#include + namespace DB { namespace ErrorCodes @@ -66,9 +77,12 @@ extern const int TOO_DEEP_RECURSION; ORCInputStream::ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch) - : in(in_), file_size(file_size_), supports_read_at(use_prefetch && in_.supportsReadAt()) + : in(in_) + , file_size(file_size_) + , use_offset_based_read(in_.supportsReadAt()) + , use_async_prefetch(use_prefetch && use_offset_based_read) { - if (supports_read_at) + if (use_async_prefetch) async_runner = threadPoolCallbackRunnerUnsafe(getIOThreadPool().get(), ThreadName::ORC_FILE); } @@ -77,20 +91,23 @@ UInt64 ORCInputStream::getLength() const return file_size; } -UInt64 ORCInputStream::getNaturalReadSize() const -{ - return 128 * 1024; -} - void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) { - if (supports_read_at) + if (use_offset_based_read) { size_t bytes_read = 0; while (bytes_read < length) { size_t bytes_to_read = length - bytes_read; size_t n = in.readBigAt(reinterpret_cast(buf) + bytes_read, bytes_to_read, offset + bytes_read, nullptr); + if (n == 0) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Truncated or corrupted ORC input: readBigAt returned 0 bytes at offset {} ({} bytes remaining of {} requested from base offset {})", + offset + bytes_read, + bytes_to_read, + length, + offset); bytes_read += n; } } @@ -104,7 +121,7 @@ void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_t offset) { - if (supports_read_at) + if (use_async_prefetch) { return async_runner( [this, buf, length, offset] @@ -129,7 +146,7 @@ std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_ } } -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled) { bool has_file_size = isBufferWithFileSize(in); @@ -142,14 +159,15 @@ asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_pref return asORCInputStreamLoadIntoMemory(in, is_cancelled); } -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) { - size_t magic_size = strlen(ORC_MAGIC_BYTES); + static constexpr std::string_view orc_magic_bytes = "ORC"; + size_t magic_size = orc_magic_bytes.size(); std::string file_data(magic_size, '\0'); /// Avoid loading the whole file if it doesn't seem to even be in the correct format. size_t bytes_read = in.read(file_data.data(), magic_size); - if (bytes_read < magic_size || file_data != ORC_MAGIC_BYTES) + if (bytes_read < magic_size || file_data != orc_magic_bytes) throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file"); { @@ -161,53 +179,157 @@ std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in return std::make_unique(std::move(file_data), file_size); } -/// The default ORC memory pool allocates with `std::malloc`, which returns a null pointer when it -/// fails - and the library dereferences it - and which is invisible to the memory tracker. A -/// malformed file can ask for an arbitrarily large buffer, so allocate through `operator new` -/// instead: it is accounted for and it throws instead of returning null. -class ORCMemoryPool : public orc::MemoryPool +/// Defined below, next to the read path that also uses it. The sargs path resolves predicate column +/// names through the same recursive walk, so pruning and reading always agree on the column. +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case); + +struct ORCPredicateColumnTypes { -public: - char * malloc(uint64_t size) override { return new char[size]; } - void free(char * p) override { delete[] p; } + DataTypePtr result_type; + DataTypePtr declared_type; }; -orc::MemoryPool & getORCMemoryPool() +struct ORCSubcolumnInfo { - static ORCMemoryPool pool; - return pool; + ISerialization::SubstreamData data; + ISerialization::SubstreamPath substreams_path; +}; + +/// Finds a subcolumn of `type` together with the substreams path that leads to it. +static std::optional tryGetORCSubcolumnInfo(const IDataType & type, std::string_view subcolumn_name) +{ + std::optional result; + auto data = ISerialization::SubstreamData(type.getDefaultSerialization()).withType(type.getPtr()); + IDataType::forEachSubcolumn( + [&](const ISerialization::SubstreamPath & path, const String & name, const ISerialization::SubstreamData & subcolumn_data) + { + if (!result && name == subcolumn_name) + result = ORCSubcolumnInfo{subcolumn_data, path}; + }, + data); + return result; } -static const orc::Type * getORCTypeByName(const orc::Type & schema, const String & name, bool ignore_case) +/// True when `path` is a named tuple element at every level, so it is a file leaf with its own +/// statistics. Nullable, LowCardinality and Array are transparent; anything else is refused, +/// which is what rejects Map/Variant/JSON/Dynamic and `.null`, `.size0`, `.keys`, `.values`. +static bool isNamedTupleElementPath(const IDataType & type, std::string_view path, bool ignore_case) { - for (UInt64 i = 0; i != schema.getSubtypeCount(); ++i) - if (boost::equals(schema.getFieldName(i), name) || (ignore_case && boost::iequals(schema.getFieldName(i), name))) - return schema.getSubtype(i); - return nullptr; + const IDataType * current = &type; + while (true) + { + if (const auto * nullable = typeid_cast(current)) + current = nullable->getNestedType().get(); + else if (const auto * low_cardinality = typeid_cast(current)) + current = low_cardinality->getDictionaryType().get(); + else if (const auto * array = typeid_cast(current)) + current = array->getNestedType().get(); + else + break; + } + + const auto * tuple = typeid_cast(current); + if (!tuple || !tuple->hasExplicitNames()) + return false; + + if (tuple->tryGetPositionByName(path, ignore_case)) + return true; + + /// An element name may itself contain dots, so every split has to be considered. + for (size_t dot = path.find('.'); dot != std::string_view::npos; dot = path.find('.', dot + 1)) + { + auto head = path.substr(0, dot); + auto tail = path.substr(dot + 1); + if (head.empty() || tail.empty()) + continue; + if (auto position = tuple->tryGetPositionByName(head, ignore_case)) + if (isNamedTupleElementPath(*tuple->getElement(*position), tail, ignore_case)) + return true; + } + return false; +} + +/// Resolves a named tuple element and retains its declared type before ancestor wrappers are applied. +static std::optional findTupleElementKeyTypes( + const Block & header, const String & name, bool ignore_case) +{ + for (auto [column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(name)) + { + const auto * column = header.findByName(String(column_name), ignore_case); + if (!column || !isNamedTupleElementPath(*column->type, subcolumn_name, ignore_case)) + continue; + if (auto subcolumn = tryGetORCSubcolumnInfo(*column->type, subcolumn_name)) + { + const auto & path = subcolumn->substreams_path; + chassert(!path.empty() && path.back().data.type); + /// A dotted field name can also resolve to a virtual subcolumn of another element. + if (path.back().type != ISerialization::Substream::TupleElement) + continue; + return ORCPredicateColumnTypes{subcolumn->data.type, path.back().data.type}; + } + } + return {}; +} + +/// Resolves predicate types from the reader header, which can contain only the parent tuple column. +static std::optional findHeaderTypesByPath( + const Block & header, const String & name, bool ignore_case) +{ + if (const auto * column = header.findByName(name, ignore_case)) + return ORCPredicateColumnTypes{column->type, column->type}; + return findTupleElementKeyTypes(header, name, ignore_case); +} + +/// KeyCondition derives its key names from this block, and the ORC header carries only the parent +/// column, so a tuple element predicate would degrade to `unknown`. Only the local copy grows; +/// the reader header stays as it is, so the read path is unaffected. +static Block buildORCKeyConditionBlock(const Block & header, const ActionsDAG * filter_dag, bool ignore_case) +{ + if (!filter_dag) + return header; + + Block keys = header; + for (const auto & required : filter_dag->getRequiredColumns()) + { + if (keys.has(required.name)) + continue; + if (auto types = findTupleElementKeyTypes(header, required.name, ignore_case)) + keys.insert({types->result_type->createColumn(), types->result_type, required.name}); + } + return keys; } -static bool isDictionaryEncoded(const orc::StripeInformation * stripe_info, const orc::Type * orc_type) +static bool isDictionaryEncoded(const ORC::Proto::StripeFooter * stripe_footer, const ORC::Type * orc_type) { - if (!stripe_info) + if (!stripe_footer) return false; - auto encoding = stripe_info->getColumnEncoding(orc_type->getColumnId()); - return encoding == orc::ColumnEncodingKind_DICTIONARY || encoding == orc::ColumnEncodingKind_DICTIONARY_V2; + UInt64 column_id = orc_type->getColumnId(); + if (column_id >= stripe_footer->columns.size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Failed to read ORC schema: the first stripe has no encoding for column {}, it has {} column encodings", + column_id, + stripe_footer->columns.size()); + + auto encoding = stripe_footer->columns[column_id].kind; + return encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY || encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY_V2; } static DataTypePtr parseORCType( - const orc::Type * orc_type, + const ORC::Type * orc_type, bool skip_columns_with_unsupported_types, bool dictionary_as_low_cardinality, - const orc::StripeInformation * stripe_info, + const ORC::Proto::StripeFooter * stripe_info, bool & skipped, size_t max_depth = DBMS_DEFAULT_MAX_PARSER_DEPTH, size_t depth = 0) { - assert(orc_type != nullptr); + chassert(orc_type != nullptr); - /// ORC LIST/MAP/STRUCT types can be nested arbitrarily deep and the ORC library does not bound - /// the nesting, so reject deep nesting early (before building the type) with an explicit limit. + /// ORC LIST/MAP/STRUCT types can be nested deep (the ORC reader allows up to 2000 levels) + /// so reject deep nesting early (before building the type) with an explicit limit. /// This keeps schema inference cheap and interruptible instead of recursing over (and later /// walking) a pathologically deep type. checkStackSize is a last-resort backstop. /// max_depth == 0 means unlimited (matching the SQL parser), leaving only checkStackSize. @@ -220,34 +342,111 @@ static DataTypePtr parseORCType( checkStackSize(); const int subtype_count = static_cast(orc_type->getSubtypeCount()); + + /// ORC union maps to the ClickHouse Variant type. It is handled before the switch below so the + /// switch stays non-exhaustive (its default handles unsupported types). Variant sorts and + /// de-duplicates its nested types, but ORC keeps a separate physical stream per branch, so two + /// branches with identical types cannot be represented as a Variant; reject them explicitly + /// instead of silently squashing them. A branch that is itself a union is rejected too: it + /// would map to a Variant, which Variant does not allow to nest. + if (orc_type->getKind() == ORC::TypeKind::UNION) + { + /// A union with more branches than Variant can hold (ColumnVariant::MAX_NESTED_COLUMNS) + /// is valid ORC but not representable; reject it through the normal unsupported-type / + /// skip path before any branch is parsed - otherwise the DataTypeVariant constructor + /// throws a generic BAD_ARGUMENTS and the skip setting is never consulted. + if (static_cast(subtype_count) > ColumnVariant::MAX_NESTED_COLUMNS) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported: Variant supports at most {} nested types", + subtype_count, ColumnVariant::MAX_NESTED_COLUMNS); + } + + DataTypes nested_types; + std::unordered_set seen_type_names; + nested_types.reserve(subtype_count); + for (int i = 0; i < subtype_count; ++i) + { + const auto * subtype = orc_type->getSubtype(i); + + /// A union branch that is itself a union would map to a Variant, and Variant does not + /// allow a nested Variant. Reject it through the normal unsupported-type / skip path + /// here, before the outer DataTypeVariant is constructed - otherwise its constructor + /// throws a confusing BAD_ARGUMENTS ("Nested Variant types are not allowed") and the + /// skip setting is never consulted because the inner union has already been parsed. + if (subtype->getKind() == ORC::TypeKind::UNION) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported", + orc_type->toString()); + } + + auto parsed_type = parseORCType( + subtype, skip_columns_with_unsupported_types, dictionary_as_low_cardinality, stripe_info, skipped, max_depth, depth + 1); + if (skipped) + return {}; + + /// Branch identity must not depend on the stripe's physical encoding: a + /// dictionary-encoded branch parses as LowCardinality(...), which would let e.g. + /// uniontype with one dictionary-encoded branch slip past this check + /// (and the read would then fail on any stripe where the encodings agree). + if (!seen_type_names.insert(recursiveRemoveLowCardinality(parsed_type)->getName()).second) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported", + orc_type->toString()); + } + nested_types.push_back(parsed_type); + } + return std::make_shared(nested_types); + } + switch (orc_type->getKind()) { - case orc::TypeKind::BOOLEAN: + case ORC::TypeKind::BOOLEAN: return DataTypeFactory::instance().get("Bool"); - case orc::TypeKind::BYTE: + case ORC::TypeKind::BYTE: return std::make_shared(); - case orc::TypeKind::SHORT: + case ORC::TypeKind::SHORT: return std::make_shared(); - case orc::TypeKind::INT: + case ORC::TypeKind::INT: return std::make_shared(); - case orc::TypeKind::LONG: + case ORC::TypeKind::LONG: return std::make_shared(); - case orc::TypeKind::FLOAT: + case ORC::TypeKind::FLOAT: return std::make_shared(); - case orc::TypeKind::DOUBLE: + case ORC::TypeKind::DOUBLE: return std::make_shared(); - case orc::TypeKind::DATE: + case ORC::TypeKind::DATE: return std::make_shared(); - case orc::TypeKind::TIMESTAMP: + case ORC::TypeKind::TIMESTAMP: return std::make_shared(9); - case orc::TypeKind::TIMESTAMP_INSTANT: + case ORC::TypeKind::TIMESTAMP_INSTANT: return std::make_shared(9, "UTC"); - case orc::TypeKind::CHAR: - case orc::TypeKind::VARCHAR: - case orc::TypeKind::BINARY: - case orc::TypeKind::STRING: { + case ORC::TypeKind::CHAR: + case ORC::TypeKind::VARCHAR: + case ORC::TypeKind::BINARY: + case ORC::TypeKind::STRING: { DataTypePtr type; - if (orc_type->getKind() == orc::TypeKind::CHAR) + if (orc_type->getKind() == ORC::TypeKind::CHAR) type = std::make_shared(orc_type->getMaximumLength()); else type = std::make_shared(); @@ -258,7 +457,7 @@ static DataTypePtr parseORCType( return type; } - case orc::TypeKind::DECIMAL: { + case ORC::TypeKind::DECIMAL: { UInt64 precision = orc_type->getPrecision(); UInt64 scale = orc_type->getScale(); if (precision == 0) @@ -268,7 +467,7 @@ static DataTypePtr parseORCType( } return createDecimal(precision, scale); } - case orc::TypeKind::LIST: { + case ORC::TypeKind::LIST: { if (subtype_count != 1) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc List type {}", orc_type->toString()); @@ -279,7 +478,7 @@ static DataTypePtr parseORCType( return std::make_shared(nested_type); } - case orc::TypeKind::MAP: { + case ORC::TypeKind::MAP: { if (subtype_count != 2) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc Map type {}", orc_type->toString()); @@ -295,7 +494,7 @@ static DataTypePtr parseORCType( return std::make_shared(key_type, value_type); } - case orc::TypeKind::STRUCT: { + case ORC::TypeKind::STRUCT: { DataTypes nested_types; Strings nested_names; nested_types.reserve(subtype_count); @@ -322,7 +521,7 @@ static DataTypePtr parseORCType( throw Exception( ErrorCodes::UNKNOWN_TYPE, - "Unsupported ORC type '{}'." + "Unsupported ORC type '{}'. " "If you want to skip columns with unsupported types, " "you can enable setting input_format_orc_skip_columns_with_unsupported_types_in_schema_inference", orc_type->toString()); @@ -330,30 +529,30 @@ static DataTypePtr parseORCType( } } -static std::optional convertORCTypeToPredicateType(const orc::Type & orc_type) +static std::optional convertORCTypeToPredicateType(const ORC::Type & orc_type) { switch (orc_type.getKind()) { - case orc::BOOLEAN: - return orc::PredicateDataType::BOOLEAN; - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: - return orc::PredicateDataType::LONG; - case orc::FLOAT: - case orc::DOUBLE: - return orc::PredicateDataType::FLOAT; - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: - return orc::PredicateDataType::STRING; - case orc::DATE: - return orc::PredicateDataType::DATE; - case orc::TIMESTAMP: - return orc::PredicateDataType::TIMESTAMP; - case orc::DECIMAL: - return orc::PredicateDataType::DECIMAL; + case ORC::BOOLEAN: + return ORC::PredicateDataType::BOOLEAN; + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: + return ORC::PredicateDataType::LONG; + case ORC::FLOAT: + case ORC::DOUBLE: + return ORC::PredicateDataType::FLOAT; + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: + return ORC::PredicateDataType::STRING; + case ORC::DATE: + return ORC::PredicateDataType::DATE; + case ORC::TIMESTAMP: + return ORC::PredicateDataType::TIMESTAMP; + case ORC::DECIMAL: + return ORC::PredicateDataType::DECIMAL; default: return {}; } @@ -370,23 +569,23 @@ static String getColumnNameFromKeyCondition(const KeyCondition & key_condition, throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't get column from KeyCondition with indice {}", indice); } -static std::optional -convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) +static std::optional +convertFieldToORCLiteral(const ORC::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) { try { /// We always fallback to return null if possible CH type hint not consistent with ORC type switch (orc_type.getKind()) { - case orc::BOOLEAN: { + case ORC::BOOLEAN: { /// May throw exception auto val = field.safeGet(); - return orc::Literal(val != 0); + return ORC::Literal(val != 0); } - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: { + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: { /// May throw exception. /// /// In particular, it'll throw if we request the column as unsigned, like this: @@ -394,30 +593,30 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy /// We have to reject this, otherwise it would miss values > 127 (because /// they're treated as negative by ORC). auto val = field.safeGet(); - return orc::Literal(val); + return ORC::Literal(val); } - case orc::FLOAT: - case orc::DOUBLE: { - Float64 val; + case ORC::FLOAT: + case ORC::DOUBLE: { + Float64 val = 0; if (field.tryGet(val)) - return orc::Literal(val); + return ORC::Literal(val); break; } - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: { + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: { String str; if (field.tryGet(str)) - return orc::Literal(str.data(), str.size()); + return ORC::Literal(str.data(), str.size()); break; } - case orc::DATE: { - Int64 val; + case ORC::DATE: { + Int64 val = 0; if (field.tryGet(val)) - return orc::Literal(orc::PredicateDataType::DATE, val); + return ORC::Literal(ORC::PredicateDataType::DATE, val); break; } - case orc::TIMESTAMP: { + case ORC::TIMESTAMP: { if (type_hint && isDateTime64(type_hint)) { const auto * datetime64_type = typeid_cast(type_hint.get()); @@ -426,15 +625,23 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy } DecimalField ts; - if (field.tryGet(ts)) + if (field.tryGet(ts) && ts.getScale() <= 9) { - Int64 secs = (ts.getValue() / ts.getScaleMultiplier()).convertTo(); - Int32 nanos = (ts.getValue() - (ts.getValue() / ts.getScaleMultiplier()) * ts.getScaleMultiplier()).convertTo(); - return orc::Literal(secs, nanos); + /// The nanoseconds are not negative, as in the reference implementation and in the statistics. + const Int64 value = ts.getValue().value; + const Int64 multiplier = ts.getScaleMultiplier().value; + Int64 secs = value / multiplier; + Int64 rest = value % multiplier; + if (rest < 0) + { + rest += multiplier; + --secs; + } + return ORC::Literal(secs, static_cast(rest * (1'000'000'000 / multiplier))); } break; } - case orc::DECIMAL: { + case ORC::DECIMAL: { auto precision = orc_type.getPrecision(); if (precision == 0) precision = 38; @@ -445,8 +652,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -455,8 +662,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -464,10 +671,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy DecimalField val; if (field.tryGet(val)) { - Int64 high = val.getValue().value.items[1]; - UInt64 low = static_cast(val.getValue().value.items[0]); - return orc::Literal( - orc::Int128(high, low), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + val.getValue().value, static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } break; @@ -538,9 +743,9 @@ static bool evaluateRPNElement(const Field & field, const KeyCondition::RPNEleme static void buildORCSearchArgumentImpl( const KeyCondition & key_condition, const Block & header, - const orc::Type & schema, + const ORC::Type & schema, KeyCondition::RPN & rpn_stack, - orc::SearchArgumentBuilder & builder, + ORC::SearchArgumentBuilder & builder, const FormatSettings & format_settings) { if (rpn_stack.empty()) @@ -572,7 +777,7 @@ static void buildORCSearchArgumentImpl( /// Key filter expressions like "func(col) > 100" are not supported for ORC filter push down if (!curr.monotonic_functions_chain.empty()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -583,16 +788,32 @@ static void buildORCSearchArgumentImpl( { if (!set_index || set_index->getOrderedSet().size() != 1 || set_index->hasMonotonicFunctionsChain()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } String column_name = getColumnNameFromKeyCondition(key_condition, curr.getKeyColumn()); - const auto * orc_type = getORCTypeByName(schema, column_name, format_settings.orc.case_insensitive_column_matching); + const bool ignore_case = format_settings.orc.case_insensitive_column_matching; + + /// The predicate column may be a tuple element (`t.x`), which the ORC header does not + /// carry as a flat entry, so resolve it through the type as well as through the schema. + auto column_types = findHeaderTypesByPath(header, column_name, ignore_case); + if (!column_types) + { + builder.literal(ORC::TruthValue::YES_NO_NULL); + break; + } + + /// The resolver rewrites the type it is given when it descends a LIST (a flattened + /// Nested column), so give it a scratch copy: the guards below must judge the key's + /// own type, which is what KeyCondition's RPN holds. + const auto & column_type = column_types->result_type; + auto resolved_type = column_type; + const auto * orc_type = traverseDownORCTypeByName(column_name, &schema, resolved_type, ignore_case); if (!orc_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -607,30 +828,34 @@ static void buildORCSearchArgumentImpl( /// down filters would result in different outputs. bool skipped = false; auto expect_type = makeNullableRecursively(parseORCType(orc_type, true, false, nullptr, skipped, format_settings.max_parser_depth), format_settings); - const ColumnWithTypeAndName * column = header.findByName(column_name, format_settings.orc.case_insensitive_column_matching); - if (!expect_type || !column) + if (!expect_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - auto nested_type = removeNullable(recursiveRemoveLowCardinality(column->type)); + auto nested_type = removeNullable(recursiveRemoveLowCardinality(column_type)); auto expect_nested_type = removeNullable(expect_type); if (!nested_type->equals(*expect_nested_type)) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - /// If null_as_default is true, the only difference is nullable, and the evaluations of current RPNElement based on default and null field - /// have the same result, we still should push down current filter. - if (format_settings.null_as_default && !column->type->isNullable() && !column->type->isLowCardinalityNullable()) + /// A non-nullable element converts NULL to its default even when a nullable ancestor makes + /// its extracted type nullable. Pruning must agree with the values produced by the reader. + const auto & declared_type = column_types->declared_type; + if (format_settings.null_as_default && !isNullableOrLowCardinalityNullable(declared_type)) { - bool match_if_null = evaluateRPNElement({}, curr); - bool match_if_default = evaluateRPNElement(column->type->getDefault(), curr); + /// Use the column default inserted by `insertNullAsDefaultIfNeeded`. It differs from + /// the type default for `Date32`. + auto default_column = declared_type->createColumn(); + default_column->insertDefault(); + const bool match_if_null = evaluateRPNElement({}, curr); + const bool match_if_default = evaluateRPNElement((*default_column)[0], curr); if (match_if_default != match_if_null) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } @@ -638,13 +863,21 @@ static void buildORCSearchArgumentImpl( auto predicate_type = convertORCTypeToPredicateType(*orc_type); if (!predicate_type.has_value()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } if (need_wrap_not) builder.startNot(); + /// A relaxed atom can be false even when its approximation is true. Preserve that + /// possibility before negation, as `KeyCondition` does with `can_be_false`. + if (curr.relaxed) + { + builder.startAnd(); + builder.literal(ORC::TruthValue::YES_NO); + } + if (contains_is_null) { builder.isNull(orc_type->getColumnId(), *predicate_type); @@ -656,8 +889,8 @@ static void buildORCSearchArgumentImpl( bool has_right_bound = !range.right.isPositiveInfinity(); if (!has_left_bound && !has_right_bound) { - /// Transform whole range orc::TruthValue::YES_NULL - builder.literal(orc::TruthValue::YES_NULL); + /// Transform whole range ORC::TruthValue::YES_NULL + builder.literal(ORC::TruthValue::YES_NULL); } else if (has_left_bound && has_right_bound && range.left_included && range.right_included && range.left == range.right) { @@ -666,15 +899,15 @@ static void buildORCSearchArgumentImpl( if (literal.has_value()) builder.equals(orc_type->getColumnId(), *predicate_type, *literal); else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } else { - std::optional left_literal; + std::optional left_literal; if (has_left_bound) left_literal = convertFieldToORCLiteral(*orc_type, range.left); - std::optional right_literal; + std::optional right_literal; if (has_right_bound) right_literal = convertFieldToORCLiteral(*orc_type, range.right); @@ -694,7 +927,7 @@ static void buildORCSearchArgumentImpl( builder.end(); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_right_bound) @@ -707,7 +940,7 @@ static void buildORCSearchArgumentImpl( builder.lessThan(orc_type->getColumnId(), *predicate_type, *right_literal); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_left_bound && has_right_bound) @@ -721,7 +954,7 @@ static void buildORCSearchArgumentImpl( const auto & set_column = ordered_set[0]; bool fail = false; - std::vector literals; + std::vector literals; literals.reserve(set_column->size()); for (size_t i = 0; i < set_column->size(); ++i) { @@ -735,15 +968,28 @@ static void buildORCSearchArgumentImpl( literals.emplace_back(*literal); } - /// set has zero element - if (literals.empty()) - builder.literal(orc::TruthValue::YES); - else if (fail) - builder.literal(orc::TruthValue::YES_NO_NULL); + if (fail) + builder.literal(ORC::TruthValue::YES_NO_NULL); + else if (literals.empty()) + builder.literal(ORC::TruthValue::NO); else + { + /// A set without NULL has no NULL matches. ORC evaluates `IN` as NULL for a + /// NULL key, so exclude NULL explicitly before applying any outer negation. + /// This preserves `nullIn` and `notNullIn` semantics. For regular nullable + /// `IN`, it can only retain extra rows, which the query filter removes. + builder.startAnd(); + builder.startNot(); + builder.isNull(orc_type->getColumnId(), *predicate_type); + builder.end(); builder.in(orc_type->getColumnId(), *predicate_type, literals); + builder.end(); + } } + if (curr.relaxed) + builder.end(); + if (need_wrap_not) builder.end(); @@ -755,7 +1001,7 @@ static void buildORCSearchArgumentImpl( case KeyCondition::RPNElement::FUNCTION_POINT_IN_POLYGON: case KeyCondition::RPNElement::FUNCTION_UNKNOWN: { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); rpn_stack.pop_back(); break; } @@ -787,34 +1033,45 @@ static void buildORCSearchArgumentImpl( } case KeyCondition::RPNElement::ALWAYS_FALSE: { - builder.literal(orc::TruthValue::NO); + builder.literal(ORC::TruthValue::NO); rpn_stack.pop_back(); break; } case KeyCondition::RPNElement::ALWAYS_TRUE: { - builder.literal(orc::TruthValue::YES); + builder.literal(ORC::TruthValue::YES); rpn_stack.pop_back(); break; } } } -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings) +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings) { auto rpn_stack = key_condition.getRPN(); if (rpn_stack.empty()) return nullptr; - auto builder = orc::SearchArgumentFactory::newBuilder(); + auto builder = std::make_unique(); buildORCSearchArgumentImpl(key_condition, header, schema, rpn_stack, *builder, format_settings); return builder->build(); } +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options) +{ + auto reader = std::make_unique(std::move(stream), options); + if (reader->getType().getKind() != ORC::STRUCT) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC files whose root type is not a struct are not supported, the file has root type {}", + reader->getType().toString()); + return reader; +} + static void getFileReader( ReadBuffer & in, - std::unique_ptr & file_reader, + std::unique_ptr & file_reader, const FormatSettings & format_settings, bool use_prefetch, size_t min_bytes_for_seek, @@ -823,16 +1080,18 @@ static void getFileReader( if (is_stopped) return; - orc::ReaderOptions options; - options.setMemoryPool(getORCMemoryPool()); - options.setCacheOptions(orc::CacheOptions{.holeSizeLimit = min_bytes_for_seek, .rangeSizeLimit = 10 * 1024 * 1024UL}); + /// The ranges with the gaps up to `min_bytes_for_seek` are read with one request. + static constexpr UInt64 default_range_size_limit = 10 * 1024 * 1024UL; + ORC::ReaderOptions options; + options.hole_size_limit = min_bytes_for_seek; + options.range_size_limit = std::max(default_range_size_limit, min_bytes_for_seek); auto input_stream = asORCInputStream(in, format_settings, use_prefetch, is_stopped); - file_reader = orc::createReader(std::move(input_stream), options); + file_reader = createORCReader(std::move(input_stream), options); } -static const orc::Type * -traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type, DataTypePtr & type, bool ignore_case) +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case) { /// Recurses the file-controlled ORC type tree. The matching CH type (and the requested column /// name) bound the depth in practice, but keep a stack backstop here too, since this runs in @@ -842,39 +1101,50 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type if (target.empty()) return orc_type; - auto search_struct_field = [&](const std::string & target_, const orc::Type * type_) -> std::pair + auto search_struct_field = [&](const std::string & target_, const ORC::Type * type_) -> std::pair { - auto target_copy = target_; - if (ignore_case) - boost::to_lower(target_copy); - - for (size_t i = 0; i < type_->getSubtypeCount(); ++i) + auto search_pass = [&](bool fold) -> std::pair { - auto field_name = type_->getFieldName(i); - if (ignore_case) - boost::to_lower(field_name); + auto target_copy = target_; + if (fold) + boost::to_lower(target_copy); - if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + for (size_t i = 0; i < type_->getSubtypeCount(); ++i) { - return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + auto field_name = type_->getFieldName(i); + if (fold) + boost::to_lower(field_name); + + if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + { + return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + } } - } - return {"", nullptr}; + return {"", nullptr}; + }; + + /// A field spelled exactly like the request always wins: a struct may hold several fields + /// whose names differ only by case, and case-folding first binds the request to whichever + /// of them the file lists first. + auto exact_match = search_pass(/*fold=*/false); + if (exact_match.second || !ignore_case) + return exact_match; + return search_pass(/*fold=*/true); }; - if (orc::STRUCT == orc_type->getKind()) + if (ORC::STRUCT == orc_type->getKind()) { const auto [next_target, next_orc_type] = search_struct_field(target, orc_type); return next_orc_type ? traverseDownORCTypeByName(next_target, next_orc_type, type, ignore_case) : nullptr; } - if (orc::LIST == orc_type->getKind()) + if (ORC::LIST == orc_type->getKind()) { /// For cases in which header contains subcolumns flattened from nested columns. /// For example, "a Nested(x String, y Int64)" is flattened to "a.x Array(String), a.y Array(Int64)", and ORC file schema is still "a array>". /// In this case, we should skip possible array type and traverse down to its nested struct type. const auto * array_type = typeid_cast(removeNullable(type).get()); const auto * orc_nested_type = orc_type->getSubtype(0); - if (array_type && orc::STRUCT == orc_nested_type->getKind()) + if (array_type && ORC::STRUCT == orc_nested_type->getKind()) { auto next_type_and_target = search_struct_field(target, orc_nested_type); const auto & next_target = next_type_and_target.first; @@ -890,8 +1160,37 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type return nullptr; } -static void -updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_case, std::unordered_set & include_typeids) +/// Forward declarations: updateIncludeTypeIds needs the union branch-hint machinery (defined +/// below, near readColumnFromORCColumn, which is where it is also used) to prune struct-branch +/// fields the same way the read path does. See computeOrcUnionBranchHints. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive); +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type); +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching); + +/// Binds a name to a field of an ORC struct type. A field spelled exactly like the name always +/// wins over one that only matches case-folded, so a struct holding several fields whose names +/// differ only by case resolves the name to the same field everywhere. +static std::optional findORCStructFieldByName(const ORC::Type * orc_type, const String & name, bool ignore_case) +{ + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (name == orc_type->getFieldName(i)) + return i; + + if (ignore_case) + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (boost::iequals(name, orc_type->getFieldName(i))) + return i; + + return std::nullopt; +} + +/// Also collects the ORC structs that are requested as a `Tuple`. +static void updateIncludeTypeIds( + DataTypePtr type, + const ORC::Type * orc_type, + bool ignore_case, + std::unordered_set & include_typeids, + std::vector & requested_structs) { /// Recurses the file-controlled ORC type tree in lockstep with the (parser-bounded) CH type. /// Keep a stack backstop here too: this runs in prepareFileReader, before the @@ -908,71 +1207,121 @@ updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_c auto non_nullable_type = removeNullable(type); switch (orc_type->getKind()) { - case orc::LIST: { + case ORC::LIST: { const auto * array_type = typeid_cast(non_nullable_type.get()); if (array_type) { - updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids); + updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids, requested_structs); + return; } - return; + break; } - case orc::MAP: { + case ORC::MAP: { const auto * map_type = typeid_cast(non_nullable_type.get()); if (map_type) { - updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids); - updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids); + updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids, requested_structs); + updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids, requested_structs); + return; } - return; + break; } - case orc::STRUCT: { + case ORC::STRUCT: { /// To make sure tuple field pruning work fine, we should include only the fields of ORC struct type which are also contained in CH tuple types, instead of all fields of ORC struct type. /// For example, CH tupe type in header is "x Tuple(a String)", ORC struct type is "x struct", then only type id of field "x.a" should be included. /// For tuple field pruning purpose, we should never include "x.b" for it is not required in format header. const auto * tuple_type = typeid_cast(non_nullable_type.get()); if (tuple_type) { + requested_structs.push_back(orc_type); if (tuple_type->hasExplicitNames()) { - std::unordered_map orc_field_name_to_index; - orc_field_name_to_index.reserve(orc_type->getSubtypeCount()); - for (size_t struct_i = 0; struct_i < orc_type->getSubtypeCount(); ++struct_i) - { - String field_name = orc_type->getFieldName(struct_i); - if (ignore_case) - boost::to_lower(field_name); - - orc_field_name_to_index[field_name] = struct_i; - } - const auto & element_names = tuple_type->getElementNames(); for (size_t tuple_i = 0; tuple_i < element_names.size(); ++tuple_i) { - String element_name = element_names[tuple_i]; - if (ignore_case) - boost::to_lower(element_name); - - if (orc_field_name_to_index.contains(element_name)) - { + if (auto field_i = findORCStructFieldByName(orc_type, element_names[tuple_i], ignore_case)) updateIncludeTypeIds( - tuple_type->getElement(tuple_i), - orc_type->getSubtype(orc_field_name_to_index[element_name]), - ignore_case, - include_typeids); - } + tuple_type->getElement(tuple_i), orc_type->getSubtype(*field_i), ignore_case, include_typeids, requested_structs); } } else { for (size_t i = 0; i < tuple_type->getElements().size() && i < orc_type->getSubtypeCount(); ++i) - updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids); + updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids, requested_structs); } + return; + } + break; + } + case ORC::UNION: { + /// ORC union maps to the ClickHouse Variant type. A branch that gets a forced type hint + /// (the same way readColumnFromORCColumn computes it - see computeOrcUnionBranchHints) + /// is selected by recursing into the hint, so a STRUCT branch keeps the named-tuple + /// field pruning above: a field the hint's tuple does not reference (e.g. an + /// unsupported or corrupt one) is never added to include_typeids. A branch without a + /// forced hint is read in full, matching readColumnFromORCColumn's "no guess is ever + /// made" policy, so its entire subtree is selected. Every branch always contributes at + /// least one id, so ORC's ColumnSelector::selectParents never falls back to its "fully + /// select every branch or none" override for partial branch selection, and the union's + /// own tag stream is selected as the automatic parent of the selected branches. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, non_nullable_type, ignore_case); + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + { + const auto * branch_orc_type = orc_type->getSubtype(i); + if (branch_hints[i]) + updateIncludeTypeIds(branch_hints[i], branch_orc_type, ignore_case, include_typeids, requested_structs); + else + include_typeids.insert(branch_orc_type->getColumnId()); } return; } default: return; } + + /// A requested type of another kind reads the whole node, and the cast to the requested type converts it or throws. + include_typeids.insert(orc_type->getColumnId()); +} + +/// Whether a column of the subtree of `orc_type`, or one of its ancestors (which reads the subtree whole), is included. +static bool isORCTypeRead( + const ORC::Type & root, const ORC::Type & orc_type, const std::unordered_set & include_typeids) +{ + for (UInt64 id = orc_type.getColumnId(); id <= orc_type.getMaximumColumnId(); ++id) + { + if (include_typeids.contains(id)) + return true; + } + + const ORC::Type * node = &root; + while (node && node->getColumnId() < orc_type.getColumnId()) + { + if (include_typeids.contains(node->getColumnId())) + return true; + + const ORC::Type * child = nullptr; + for (UInt64 i = 0; i < node->getSubtypeCount() && !child; ++i) + { + if (node->getSubtype(i)->getMaximumColumnId() >= orc_type.getColumnId()) + child = node->getSubtype(i); + } + node = child; + } + return false; +} + +/// The field of an ORC struct with the fewest columns, or the struct itself if it has no fields. +static const ORC::Type & getNarrowestORCStructField(const ORC::Type & orc_struct) +{ + const ORC::Type * narrowest = &orc_struct; + for (UInt64 i = 0; i < orc_struct.getSubtypeCount(); ++i) + { + const auto * field = orc_struct.getSubtype(i); + if (narrowest == &orc_struct + || field->getMaximumColumnId() - field->getColumnId() < narrowest->getMaximumColumnId() - narrowest->getColumnId()) + narrowest = field; + } + return *narrowest; } NativeORCBlockInputFormat::NativeORCBlockInputFormat( @@ -999,34 +1348,51 @@ void NativeORCBlockInputFormat::prepareFileReader() return; if (format_filter_info) - format_filter_info->initKeyConditionOnce(getPort().getHeader()); - - std::unique_ptr stripe_info; - if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); - - orc_column_to_ch_column = std::make_unique( - getPort().getHeader(), - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.orc.case_insensitive_column_matching, - format_settings.orc.dictionary_as_low_cardinality); + format_filter_info->initKeyConditionOnce(buildORCKeyConditionBlock( + getPort().getHeader(), + format_filter_info->filter_actions_dag.get(), + format_settings.orc.case_insensitive_column_matching)); const bool ignore_case = format_settings.orc.case_insensitive_column_matching; const auto & header = getPort().getHeader(); const auto & file_schema = file_reader->getType(); std::unordered_set include_typeids; + std::vector requested_structs; for (const auto & column : header) { auto adjusted_type = column.type; const auto * orc_type = traverseDownORCTypeByName(column.name, &file_schema, adjusted_type, ignore_case); if (orc_type) - updateIncludeTypeIds(adjusted_type, orc_type, ignore_case, include_typeids); + updateIncludeTypeIds(adjusted_type, orc_type, ignore_case, include_typeids, requested_structs); + } + + /// A requested struct none of whose requested fields is in the file is still read, through its narrowest field, + /// for its presence and the sizes of the lists and maps around it; `matchORCTupleElementsByName` then fills the + /// requested fields with defaults. Inner structs first, as a read inner one makes its parents read. + std::ranges::sort(requested_structs, std::greater{}, &ORC::Type::getColumnId); + std::unordered_set count_only_fields; + for (const auto * orc_struct : requested_structs) + { + if (isORCTypeRead(file_schema, *orc_struct, include_typeids)) + continue; + const auto & narrowest = getNarrowestORCStructField(*orc_struct); + include_typeids.insert(narrowest.getColumnId()); + if (&narrowest != orc_struct) + count_only_fields.insert(narrowest.getColumnId()); } include_indices.assign(include_typeids.begin(), include_typeids.end()); + orc_column_to_ch_column = std::make_unique( + getPort().getHeader(), + format_settings.orc.allow_missing_columns, + format_settings.null_as_default, + format_settings.orc.case_insensitive_column_matching, + format_settings.orc.dictionary_as_low_cardinality, + format_settings.date_time_overflow_behavior, + std::move(count_only_fields)); + if (format_settings.orc.filter_push_down && format_filter_info && format_filter_info->key_condition && !sargs) - sargs = buildORCSearchArgument(*format_filter_info->key_condition, getPort().getHeader(), file_reader->getType(), format_settings); + sargs = buildORCSearchArgument(*format_filter_info->key_condition, header, file_schema, format_settings); selected_stripes = calculateSelectedStripes(static_cast(file_reader->getNumberOfStripes()), skip_stripes); read_iterator = 0; @@ -1048,7 +1414,7 @@ void NativeORCBlockInputFormat::prefetchStripes() int stripe = selected_stripes[prefetch_iterator]; stripes.push_back(stripe); - total_stripe_size += file_reader->getStripe(stripe)->getLength(); + total_stripe_size += ORC::Reader::getStripeLength(file_reader->getStripe(stripe)); ++prefetch_iterator; } @@ -1079,32 +1445,31 @@ std::vector NativeORCBlockInputFormat::calculateSelectedStripes(int num_str bool NativeORCBlockInputFormat::prepareStripeReader() { - assert(file_reader); + chassert(file_reader); if (read_iterator >= selected_stripes.size()) return false; int current_stripe = selected_stripes[read_iterator]; - current_stripe_info = file_reader->getStripe(current_stripe); - if (!current_stripe_info->getNumberOfRows()) + current_stripe_info = &file_reader->getStripe(current_stripe); + if (!current_stripe_info->number_of_rows) throw Exception(ErrorCodes::INCORRECT_DATA, "ORC stripe {} has no rows", current_stripe); - orc::RowReaderOptions row_reader_options; - row_reader_options.setEnableLazyDecoding(format_settings.orc.dictionary_as_low_cardinality); - row_reader_options.includeTypes(include_indices); - row_reader_options.setTimezoneName(format_settings.orc.reader_time_zone_name); - row_reader_options.range(current_stripe_info->getOffset(), current_stripe_info->getLength()); + ORC::RowReaderOptions row_reader_options; + row_reader_options.enable_lazy_decoding = format_settings.orc.dictionary_as_low_cardinality; + row_reader_options.include_types = include_indices; + row_reader_options.timezone_name = format_settings.orc.reader_time_zone_name; + row_reader_options.range_offset = current_stripe_info->offset; + row_reader_options.range_length = ORC::Reader::getStripeLength(*current_stripe_info); if (format_settings.orc.filter_push_down && sargs) - { - row_reader_options.searchArgument(sargs); - } + row_reader_options.search_argument = sargs; stripe_reader = file_reader->createRowReader(row_reader_options); ++read_iterator; if (use_prefetch) { /// Release outdated buffer before boundary to avoid OOM - file_reader->releaseBuffer(current_stripe_info->getOffset()); + file_reader->releaseBuffer(current_stripe_info->offset); /// Prefetch next selected stripe prefetchStripes(); @@ -1127,7 +1492,7 @@ Chunk NativeORCBlockInputFormat::read() int current_stripe = selected_stripes[read_iterator]; ++read_iterator; - return getChunkForCount(file_reader->getStripe(current_stripe)->getNumberOfRows()); + return getChunkForCount(file_reader->getStripe(current_stripe).number_of_rows); } if (!stripe_reader) @@ -1139,14 +1504,12 @@ Chunk NativeORCBlockInputFormat::read() if (is_stopped) return {}; - /// TODO: figure out why reuse batch would cause asan fatals in https://s3.amazonaws.com/clickhouse-test-reports/55330/be39d23af2d7e27f5ec7f168947cf75aeaabf674/stateless_tests__asan__[4_4].html - /// Not sure if it is a false positive case. Notice that reusing batch will speed up reading ORC by 1.15x. + /// The values are decoded directly into the columns of the batch, which are then handed over to the chunk. Stopwatch time; - auto batch = stripe_reader->createRowBatch(format_settings.orc.row_batch_size); + auto batch = stripe_reader->createRowBatch(); while (true) { - bool ok = stripe_reader->next(*batch); - if (ok) + if (stripe_reader->next(*batch, static_cast(format_settings.orc.row_batch_size))) break; /// No more rows to read in current stripe, continue to prepare reading next stripe @@ -1163,7 +1526,7 @@ Chunk NativeORCBlockInputFormat::read() orc_column_to_ch_column->orcTableToCHChunk(res, &schema, batch.get(), num_rows, &block_missing_values); LOG_TEST(getLogger("NativeORCBlockInputFormat"), "Convert {} rows take {} ms", num_rows, time.elapsedMilliseconds()); - approx_bytes_read_for_chunk = num_rows * current_stripe_info->getLength() / current_stripe_info->getNumberOfRows(); + approx_bytes_read_for_chunk = num_rows * ORC::Reader::getStripeLength(*current_stripe_info) / current_stripe_info->number_of_rows; return res; } @@ -1188,33 +1551,41 @@ NativeORCSchemaReader::NativeORCSchemaReader(ReadBuffer & in_, const FormatSetti { } -NamesAndTypesList NativeORCSchemaReader::readSchema() +void NativeORCSchemaReader::initializeIfNeeded() { - std::unique_ptr file_reader; - std::atomic is_stopped = 0; + if (initialized) + return; getFileReader(in, file_reader, format_settings, false, 0, is_stopped); + initialized = true; +} + +NamesAndTypesList NativeORCSchemaReader::readSchema() +{ + initializeIfNeeded(); const auto & schema = file_reader->getType(); Block header; - std::unique_ptr stripe_info; + std::optional first_stripe_footer; if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); + first_stripe_footer = file_reader->readStripeFooter(0); - for (size_t i = 0; i < schema.getSubtypeCount(); ++i) { - const std::string & name = schema.getFieldName(i); - const orc::Type * orc_type = schema.getSubtype(i); + for (size_t i = 0; i < schema.getSubtypeCount(); ++i) + { + const std::string & name = schema.getFieldName(i); + const ORC::Type * orc_type = schema.getSubtype(i); - bool skipped = false; - DataTypePtr type = parseORCType( - orc_type, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.orc.dictionary_as_low_cardinality, - stripe_info.get(), - skipped, - format_settings.max_parser_depth); - if (!skipped) - header.insert(ColumnWithTypeAndName{type, name}); + bool skipped = false; + DataTypePtr type = parseORCType( + orc_type, + format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + format_settings.orc.dictionary_as_low_cardinality, + first_stripe_footer ? &*first_stripe_footer : nullptr, + skipped, + format_settings.max_parser_depth); + if (!skipped) + header.insert(ColumnWithTypeAndName{type, name}); + } } /// ORC doesn't have non-nullable data types. @@ -1223,26 +1594,36 @@ NamesAndTypesList NativeORCSchemaReader::readSchema() return header.getNamesAndTypesList(); } +std::optional NativeORCSchemaReader::readNumberOrRows() +{ + initializeIfNeeded(); + return file_reader->getNumberOfRows(); +} + ORCColumnToCHColumn::ORCColumnToCHColumn( const Block & header_, bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_, - bool dictionary_as_low_cardinality_) + bool dictionary_as_low_cardinality_, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_, + std::unordered_set count_only_fields_) : header(header_) , allow_missing_columns(allow_missing_columns_) , null_as_default(null_as_default_) , case_insensitive_matching(case_insensitive_matching_) , dictionary_as_low_cardinality(dictionary_as_low_cardinality_) + , date_time_overflow_behavior(date_time_overflow_behavior_) + , count_only_fields(std::move(count_only_fields_)) { } void ORCColumnToCHColumn::orcTableToCHChunk( - Chunk & res, const orc::Type * schema, const orc::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, const ORC::Type * schema, const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) { - const auto * struct_batch = dynamic_cast(table); + const auto * struct_batch = dynamic_cast(table); if (!struct_batch) - throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", struct_batch->toString()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", demangle(typeid(*table).name())); if (schema->getSubtypeCount() != struct_batch->fields.size()) throw Exception( @@ -1250,24 +1631,26 @@ void ORCColumnToCHColumn::orcTableToCHChunk( size_t field_num = struct_batch->fields.size(); NameToColumnPtr name_to_column_ptr; + /// The file's own spellings, in file order: the keys above are what a request is matched + /// against, and a case-folded match has to pick among them in a fixed order. + Names orc_field_names; + orc_field_names.reserve(field_num); for (size_t i = 0; i < field_num; ++i) { - auto name = schema->getFieldName(i); + const auto & name = schema->getFieldName(i); const auto * field = struct_batch->fields[i]; if (!field) throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table field {} is null", name); - if (case_insensitive_matching) - boost::to_lower(name); - - name_to_column_ptr[std::move(name)] = {field, schema->getSubtype(i)}; + name_to_column_ptr[name] = {field, schema->getSubtype(i)}; + orc_field_names.push_back(name); } - orcColumnsToCHChunk(res, name_to_column_ptr, num_rows, block_missing_values); + orcColumnsToCHChunk(res, name_to_column_ptr, orc_field_names, num_rows, block_missing_values); } /// Creates a null bytemap from ORC's not-null bytemap -static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_column) +static ColumnPtr readByteMapFromORCColumn(const ORC::ColumnVectorBatch * orc_column) { if (!orc_column->hasNulls) return ColumnUInt8::create(orc_column->numElements, static_cast(0)); @@ -1282,70 +1665,67 @@ static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_col } -static const orc::ColumnVectorBatch * getNestedORCColumn(const orc::ListVectorBatch * orc_column) +/// A branch of an ORC union can be non-null at the union level yet select a null payload; ORC +/// leaves a placeholder (a default value) at such positions. When the branch is later cast to an +/// explicit Variant alternative, a value-checking cast (e.g. Int8 -> Enum8, or the same inside a +/// Tuple field) would reject those placeholders even though the rows are never read (they become +/// the Variant NULL discriminator). Overwrite every null-payload row with a copy of a non-null row +/// before casting; the copied values are discarded downstream. If every row is a null payload there +/// is nothing to read, so a null is returned and the caller uses a default-valued column instead. +static ColumnPtr replaceNullPayloadRowsWithValidRow(const ColumnPtr & column, const NullMap & null_map) +{ + size_t valid_row = column->size(); + for (size_t row = 0; row < column->size(); ++row) + if (!null_map[row]) + { + valid_row = row; + break; + } + + if (valid_row == column->size()) + return nullptr; + + auto result = column->cloneEmpty(); + result->reserve(column->size()); + for (size_t row = 0; row < column->size(); ++row) + result->insertFrom(*column, null_map[row] ? valid_row : row); + return result; +} + + +static const ORC::ColumnVectorBatch * getNestedORCColumn(const ORC::ListVectorBatch * orc_column) { return orc_column->elements.get(); } +/// The reader decodes the lengths directly into the end offsets, as in `ColumnArray`. template static ColumnPtr readOffsetsFromORCListColumn(const BatchType * orc_column) { - auto offsets_column = ColumnUInt64::create(); - ColumnArray::Offsets & offsets_data = assert_cast &>(*offsets_column).getData(); - offsets_data.reserve(orc_column->numElements); - - for (size_t i = 0; i < orc_column->numElements; ++i) - offsets_data.push_back(orc_column->offsets[i + 1]); - - return offsets_column; + return orc_column->offsets; } +/// The values of the primitive types are decoded directly into the columns (with zeros for the nulls). static ColumnWithTypeAndName -readColumnWithBooleanData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithBooleanData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_bool_column = dynamic_cast(orc_column); - auto internal_type = DataTypeFactory::instance().get("Bool"); - auto internal_column = internal_type->createColumn(); - auto & column_data = assert_cast &>(*internal_column).getData(); - - column_data.reserve(orc_bool_column->numElements); - for (size_t i = 0; i < orc_bool_column->numElements; ++i) - { - if (!orc_bool_column->hasNulls || orc_bool_column->notNull[i]) - column_data.push_back(static_cast(orc_bool_column->data[i])); - else - column_data.push_back(static_cast(0)); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_bool_column = typeid_cast(*orc_column); + return {orc_bool_column.column, DataTypeFactory::instance().get("Bool"), column_name}; } -template +template static ColumnWithTypeAndName -readColumnWithNumericData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithNumericData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - auto internal_type = std::make_shared>(); - auto internal_column = internal_type->createColumn(); - auto & column_data = static_cast &>(*internal_column).getData(); - const auto * orc_int_column = dynamic_cast(orc_column); - - column_data.reserve(orc_int_column->numElements); - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(NumericType(orc_int_column->data[i])); - else - column_data.push_back(NumericType{}); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_numeric_column = typeid_cast &>(*orc_column); + return {orc_numeric_column.column, std::make_shared>(), column_name}; } template static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( - const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name, bool nullable) + const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name, bool nullable) { /// Fill CH holder_column with ORC dictionary /// Note that holder_column is always a ColumnString or ColumnFixedstring whether nullable is true or false, because ORC dictionary doesn't contain null values. @@ -1358,60 +1738,45 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( DataTypePtr nested_type = nullable ? std::make_shared(holder_type) : holder_type; auto internal_type = std::make_shared(std::move(nested_type)); - const auto & orc_str_column = dynamic_cast(*orc_column); + const auto & orc_str_column = dynamic_cast(*orc_column); size_t rows = orc_str_column.numElements; - const auto & orc_dict = *orc_str_column.dictionary; - if (orc_dict.dictionaryOffset.size() <= 1) + const auto & orc_dict = assert_cast(*orc_str_column.dictionary->column); + size_t dict_size = orc_dict.size(); + if (dict_size == 0) { + /// Only nulls can be encoded with an empty dictionary. + for (size_t i = 0; i < rows; ++i) + { + if (!orc_str_column.hasNulls || orc_str_column.notNull[i]) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC dictionary index {} at row {} is out of range [0, 0)", + orc_str_column.index[i], i); + } auto result_column = internal_type->createColumn(); result_column->insertManyDefaults(rows); return {std::move(result_column), internal_type, column_name}; } - size_t dict_size = orc_dict.dictionaryOffset.size() - 1; - auto holder_column = holder_type->createColumn(); + /// The dictionary of ORC is already a `ColumnString`, which is the holder for `String`. + ColumnPtr holder_column = orc_str_column.dictionary->column; if constexpr (fixed_string) { const size_t n = orc_type->getMaximumLength(); - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - size_t reserve_size = dict_size * n; - column_chars.resize_exact(reserve_size); - size_t curr_offset = 0; + auto fixed_holder_column = ColumnFixedString::create(n); + PaddedPODArray & column_chars = fixed_holder_column->getChars(); + column_chars.resize_fill(dict_size * n); for (size_t i = 0; i < dict_size; ++i) { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - if (buf_size > n) + auto value = orc_dict.getDataAt(i); + if (value.size() > n) throw Exception( ErrorCodes::INCORRECT_DATA, "ORC dictionary entry {} has size {} that exceeds the declared FixedString length {}", - i, buf_size, n); - memcpy(&column_chars[curr_offset], buf, buf_size); - /// resize_exact does not zero-initialize, so pad shorter entries to keep FixedString values - /// deterministic and to avoid leaking uninitialized heap memory. - if (buf_size < n) - memset(&column_chars[curr_offset + buf_size], 0, n - buf_size); - curr_offset += n; - } - } - else - { - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - PaddedPODArray & column_offsets = concrete_holder_column.getOffsets(); - - column_chars.resize_exact(orc_dict.dictionaryBlob.size()); - column_offsets.resize_exact(dict_size); - size_t curr_offset = 0; - for (size_t i = 0; i < dict_size; ++i) - { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; + i, value.size(), n); + memcpy(&column_chars[i * n], value.data(), value.size()); } + holder_column = std::move(fixed_holder_column); } /// Insert CH dictionary_column from holder_column @@ -1475,57 +1840,22 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithStringData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static const ColumnString & getStringColumnFromBatch(const ORC::ColumnVectorBatch * orc_column, ColumnPtr & holder) { - auto internal_type = std::make_shared(); - auto internal_column = internal_type->createColumn(); - PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); - PaddedPODArray & column_offsets = assert_cast(*internal_column).getOffsets(); - - const auto * orc_str_column = dynamic_cast(orc_column); - size_t reserve_size = 0; - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - reserve_size += orc_str_column->length[i]; - } - - column_chars.resize_exact(reserve_size); - column_offsets.resize_exact(orc_str_column->numElements); - - size_t curr_offset = 0; - if (!orc_str_column->hasNulls) - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; - } - } - else - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (orc_str_column->notNull[i]) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - } + holder = ORC::getStringColumn(dynamic_cast(*orc_column)); + return assert_cast(*holder); +} - column_offsets[i] = curr_offset; - } - } - return {std::move(internal_column), internal_type, column_name}; +static ColumnWithTypeAndName +readColumnWithStringData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) +{ + ColumnPtr column; + getStringColumnFromBatch(orc_column, column); + return {column, std::make_shared(), column_name}; } static ColumnWithTypeAndName -readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name) +readColumnWithFixedStringData(const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name) { size_t fixed_len = orc_type->getMaximumLength(); auto internal_type = std::make_shared(fixed_len); @@ -1533,25 +1863,22 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); column_chars.reserve(orc_column->numElements * fixed_len); - const auto * orc_str_column = dynamic_cast(orc_column); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - { - const Int64 length = orc_str_column->length[i]; - if (length < 0 || static_cast(length) > fixed_len) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "ORC string value at row {} has size {} that doesn't fit into FixedString({})", - i, length, fixed_len); + /// The null values are empty strings. + auto value = strings.getDataAt(i); + if (value.size() > fixed_len) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC string value at row {} has size {} that doesn't fit into FixedString({})", + i, value.size(), fixed_len); - column_chars.insert_assume_reserved(orc_str_column->data[i], orc_str_column->data[i] + length); - /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. - if (static_cast(length) < fixed_len) - column_chars.resize_fill(column_chars.size() + (fixed_len - static_cast(length))); - } - else - column_chars.resize_fill(column_chars.size() + fixed_len); + column_chars.insert_assume_reserved(value.data(), value.data() + value.size()); + /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. + if (value.size() < fixed_len) + column_chars.resize_fill(column_chars.size() + (fixed_len - value.size())); } return {std::move(internal_column), internal_type, column_name}; @@ -1560,10 +1887,10 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o template static ColumnWithTypeAndName readColumnWithDecimalDataCast( - const orc::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) { using NativeType = typename DecimalType::NativeType; - static_assert(std::is_same_v || std::is_same_v); + static_assert(std::is_same_v || std::is_same_v); auto internal_column = internal_type->createColumn(); auto & column_data = static_cast &>(*internal_column).getData(); @@ -1574,13 +1901,10 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( { if (!orc_decimal_column->hasNulls || orc_decimal_column->notNull[i]) { - DecimalType decimal_value; - if constexpr (std::is_same_v) + DecimalType decimal_value{}; + if constexpr (std::is_same_v) { - Int128 int128_value; - int128_value.items[0] = orc_decimal_column->values[i].getLowBits(); - int128_value.items[1] = orc_decimal_column->values[i].getHighBits(); - decimal_value.value = static_cast(int128_value); + decimal_value.value = static_cast(orc_decimal_column->values[i]); } else decimal_value.value = static_cast(orc_decimal_column->values[i]); @@ -1595,26 +1919,30 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( } static ColumnWithTypeAndName -readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv6ColumnFromBinaryData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { /// If at least one value size is not 16 bytes, fallback to reading String column and further cast to IPv6. - if ((!orc_str_column->hasNulls || orc_str_column->notNull[i]) && orc_str_column->length[i] != sizeof(IPv6)) - return readColumnWithStringData(orc_column, column_name); + if ((!orc_column->hasNulls || orc_column->notNull[i]) && strings.getDataAt(i).size() != sizeof(IPv6)) + return {holder, std::make_shared(), column_name}; } auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & ipv6_column = assert_cast(*internal_column); - ipv6_column.reserve(orc_str_column->numElements); + ipv6_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - ipv6_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + if (!orc_column->hasNulls || orc_column->notNull[i]) + { + auto value = strings.getDataAt(i); + ipv6_column.insertData(value.data(), value.size()); + } else ipv6_column.insertDefault(); } @@ -1623,49 +1951,46 @@ readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const St } static ColumnWithTypeAndName -readIPv4ColumnWithInt32Data(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv4ColumnWithInt32Data(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_int_column = dynamic_cast(orc_column); + const auto & data = typeid_cast(*orc_column).getData(); auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); - column_data.reserve(orc_int_column->numElements); - - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(static_cast(orc_int_column->data[i])); - else - column_data.push_back(0); - } + column_data.resize(data.size()); + /// The null values are zeros. + for (size_t i = 0; i < data.size(); ++i) + column_data[i] = static_cast(data[i]); return {std::move(internal_column), internal_type, column_name}; } template static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); auto internal_column = column_type->createColumn(); auto & integer_column = assert_cast(*internal_column); - integer_column.reserve(orc_str_column->numElements); + integer_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) + if (!orc_column->hasNulls || orc_column->notNull[i]) { - if (sizeof(typename ColumnType::ValueType) != orc_str_column->length[i]) + auto value = strings.getDataAt(i); + if (sizeof(typename ColumnType::ValueType) != value.size()) throw Exception( ErrorCodes::INCORRECT_DATA, "ValueType size {} of column {} is not equal to size of binary data {}", sizeof(typename ColumnType::ValueType), integer_column.getName(), - orc_str_column->length[i]); + value.size()); - integer_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + integer_column.insertData(value.data(), value.size()); } else { @@ -1676,11 +2001,21 @@ static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( } static ColumnWithTypeAndName readColumnWithDateData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & type_hint) + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & raw_type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { + /// The hint is the raw header type: `readColumnFromORCColumn` strips an outer Nullable but not + /// LowCardinality, so e.g. a LowCardinality(DateTime('UTC')) target would fall through to the + /// raw Int32 branch below and the later context-less cast would read the day count as unix + /// seconds. Strip the wrappers so such targets take the same branches as the plain types. + const DataTypePtr type_hint = raw_type_hint ? removeNullable(recursiveRemoveLowCardinality(raw_type_hint)) : nullptr; + DataTypePtr internal_type; bool check_date32_range = false; bool check_date_range = false; + bool check_datetime_range = false; /// Make result type Date32 when requested type is actually Date32 or when we use schema inference if (!type_hint || isDate32(*type_hint)) @@ -1696,12 +2031,23 @@ static ColumnWithTypeAndName readColumnWithDateData( internal_type = std::make_shared(); check_date_range = true; } + else if (isDateTime(*type_hint)) + { + /// Keep the intermediate as Date32, so the later cast converts the day count to midnight + /// of that day instead of reading it as unix seconds. The cast is context-less, so + /// `date_time_overflow_behavior` does not reach it and a day number whose midnight does + /// not fit into DateTime would wrap to an unrelated timestamp. Validate the range here + /// against the same [0, MAX_DATETIME_DAY_NUM] window that `ToDateTimeImpl` uses. + internal_type = std::make_shared(); + check_datetime_range = true; + } else { internal_type = std::make_shared(); } - const auto * orc_int_column = dynamic_cast(orc_column); + const auto * orc_int_column = dynamic_cast(orc_column); + const auto & orc_int_data = orc_int_column->getData(); auto internal_column = internal_type->createColumn(); PaddedPODArray & column_data = assert_cast &>(*internal_column).getData(); column_data.reserve(orc_int_column->numElements); @@ -1710,25 +2056,50 @@ static ColumnWithTypeAndName readColumnWithDateData( { if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) { - Int32 days_num = static_cast(orc_int_column->data[i]); - if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < -DAYNUM_OFFSET_EPOCH)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", - days_num, - column_name, - -DAYNUM_OFFSET_EPOCH, - DATE_LUT_MAX_EXTEND_DAY_NUM); + /// Range-check the original Int64 day count before narrowing to Int32, + /// otherwise a malformed value could wrap into an apparently valid date. + Int64 days_num = orc_int_data[i]; + if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < (-DAYNUM_OFFSET_EPOCH))) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < (-DAYNUM_OFFSET_EPOCH)) ? (-DAYNUM_OFFSET_EPOCH) : DATE_LUT_MAX_EXTEND_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", + days_num, + column_name, + (-DAYNUM_OFFSET_EPOCH), + DATE_LUT_MAX_EXTEND_DAY_NUM); + } if (check_date_range && (days_num > DATE_LUT_MAX_DAY_NUM || days_num < 0)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", - days_num, - column_name, - DATE_LUT_MAX_DAY_NUM); + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : DATE_LUT_MAX_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", + days_num, + column_name, + DATE_LUT_MAX_DAY_NUM); + } + + if (check_datetime_range && (days_num > MAX_DATETIME_DAY_NUM || days_num < 0)) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : MAX_DATETIME_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the day range of type DateTime, which is [0, {}]", + days_num, + column_name, + MAX_DATETIME_DAY_NUM); + } - column_data.push_back(days_num); + column_data.push_back(static_cast(days_num)); } else { @@ -1739,40 +2110,65 @@ static ColumnWithTypeAndName readColumnWithDateData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static ColumnWithTypeAndName readColumnWithTimestampData( + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { - const auto * orc_ts_column = dynamic_cast(orc_column); + const auto * orc_ts_column = dynamic_cast(orc_column); + + /// ORC stores timestamps as (seconds, nanoseconds). ClickHouse used to convert them through a fixed + /// DateTime64(9) intermediate (seconds * 1e9 + nanoseconds), which overflows Int64 for timestamps beyond + /// ~year 2262 even when the requested DateTime64 scale can represent the value (e.g. Iceberg's DateTime64(6)). + /// Read directly at the requested scale so such values round-trip like Parquet, and only handle overflow when + /// even the target scale does not fit Int64. + UInt32 scale = 9; + if (type_hint) + { + const auto * dt64_hint = typeid_cast(removeNullable(recursiveRemoveLowCardinality(type_hint)).get()); + if (dt64_hint) + scale = dt64_hint->getScale(); + } - auto internal_type = std::make_shared(9); + auto internal_type = std::make_shared(scale); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); column_data.reserve(orc_ts_column->numElements); - constexpr Int64 multiplier = 1e9L; + /// Factor to go from nanoseconds down to the target scale (scale is in [0, 9]). + const Int128 divisor = DecimalUtils::scaleMultiplier(9 - scale); + const Int128 int64_min = std::numeric_limits::min(); + const Int128 int64_max = std::numeric_limits::max(); + for (size_t i = 0; i < orc_ts_column->numElements; ++i) { if (!orc_ts_column->hasNulls || orc_ts_column->notNull[i]) { - Int64 timestamp_value; - Int64 seconds = orc_ts_column->data[i]; - Int64 nanoseconds = orc_ts_column->nanoseconds[i]; + const Int64 seconds = orc_ts_column->data[i]; + const Int64 nanoseconds = orc_ts_column->nanoseconds[i]; - /// Check for overflow when converting timestamp to DateTime64(9) - bool overflow = common::mulOverflow(seconds, multiplier, timestamp_value); - overflow |= common::addOverflow(timestamp_value, nanoseconds, timestamp_value); + /// seconds * 1e9 + nanoseconds cannot overflow Int128 (|seconds| < 2^63, product < ~9.2e27 << Int128 max). + const Int128 nanos_total = static_cast(seconds) * 1'000'000'000 + nanoseconds; + /// Integer division truncates toward zero, matching the DateTime64(9) -> DateTime64(scale) cast that ran afterwards. + Int128 value = nanos_total / divisor; - if (overflow) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Timestamp value in column \"{}\" is out of range for DateTime64: seconds={}, nanoseconds={}", - column_name, - seconds, - nanoseconds); + if (value < int64_min || value > int64_max) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + value = value < int64_min ? int64_min : int64_max; + else + /// Throw for both `throw` and `ignore` (the default): keep the historical behavior and never silently corrupt data. + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp value in column \"{}\" is out of range for DateTime64({}): seconds={}, nanoseconds={}", + column_name, + scale, + seconds, + nanoseconds); + } - Decimal64 decimal64; - decimal64.value = timestamp_value; - column_data.emplace_back(std::move(decimal64)); + column_data.push_back(DateTime64(static_cast(value))); } else column_data.push_back(0); @@ -1780,9 +2176,504 @@ readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const Str return {std::move(internal_column), internal_type, column_name}; } +/// Whether a DateTime/DateTime64 target carries an explicit timezone - schema inference produces one +/// (UTC) for the ORC `TIMESTAMP_INSTANT` ("timestamp with local timezone") kind, but an explicit +/// schema may name any timezone. Used to tell the two ORC timestamp kinds apart when matching union +/// branches (see `orcUnionBranchMatchesType`). +static bool orcTimestampTargetHasExplicitTimeZone(const DataTypePtr & type) +{ + const auto * timezone = dynamic_cast(type.get()); + return timezone && timezone->hasExplicitTimeZone(); +} + +/// Whether a ClickHouse numeric type is a widening of an ORC integer branch whose values occupy +/// `orc_size` bytes: a strictly wider integer, or a float that represents every value of that width +/// exactly. The ordinary (non-union) ORC column path gets these conversions for free from the final +/// cast in `orcColumnsToCHChunk`; a union branch has to request them as a per-branch hint, because +/// the final cast of a union column is a `Variant` -> `Variant` cast, which only extends the set of +/// alternatives by exact type name and cannot widen an alternative. Equal-width targets are listed +/// explicitly by the caller (they include the writer's own mappings, such as the unsigned and `Enum` +/// types), so only strictly wider integers are accepted here. +static bool orcIntegerBranchWidensTo(const DataTypePtr & type, size_t orc_size) +{ + const WhichDataType which(type); + if (which.isFloat32()) + return orc_size <= 2; + if (which.isFloat64()) + return orc_size <= 4; + return which.isInteger() && type->getSizeOfValueInMemory() > orc_size; +} + +/// Whether a ClickHouse type can serve as the per-branch type hint for an ORC union branch of the +/// given ORC type. The correspondence is structural (up to Nullable and LowCardinality wrappers), +/// extended with the explicit-schema conversions the reader supports: the integer targets the +/// ordinary column path accepts through the final cast (the unsigned and Enum types of the +/// matching width - they are what the ORC writer maps to these ORC types - int -> IPv4, and the +/// widenings of `orcIntegerBranchWidensTo`, e.g. `Variant(Int64, String)` over +/// `uniontype`) and +/// the special binary readers (binary -> IPv6/Int128/UInt128/Int256/UInt256/Decimal256, +/// char -> big integers and Decimal256). Custom type names matter here: `Bool` is a custom-named +/// `UInt8`, but the writer maps it to BOOLEAN while a plain `UInt8` goes to BYTE, so only BOOLEAN +/// accepts `Bool` - otherwise `Variant(Bool, UInt8)` over `uniontype` would leave +/// both branches ambiguous. The two ORC timestamp kinds need the same care: both read back as plain +/// `DateTime64(9)`, but `TIMESTAMP` is inferred as `DateTime64(9)` and `TIMESTAMP_INSTANT` as +/// `DateTime64(9, 'UTC')`, so `TIMESTAMP_INSTANT` matches only an explicitly time-zoned target while +/// `TIMESTAMP` stays permissive - otherwise `uniontype`, +/// inferred as `Variant(DateTime64(9), DateTime64(9, 'UTC'))`, would leave both branches ambiguous, +/// collapse them to identical `DateTime64(9)`, and be rejected by the duplicate-branch check. Any +/// explicit timezone is accepted (not only `UTC`) so that an explicit schema like +/// `Variant(DateTime64(9), DateTime64(9, 'Europe/Berlin'))` is not rejected; the singles-elimination +/// step decides whether the assignment is forced, and the repair cast relabels the branch to the +/// target timezone (value-preserving for `DateTime64`). Variant sorts its nested types, so the +/// positional correspondence between ORC union branches and Variant alternatives is lost; this +/// predicate is used to reconstruct it. +/// +/// STRUCT branches follow the same named-tuple rules as the non-union ORC struct path: a target +/// tuple with explicit names matches by field name and may project and reorder the ORC struct's +/// fields (the per-branch repair cast then projects/reorders the read tuple to exactly the target), +/// while an unnamed target tuple is matched positionally with the same arity. `case_insensitive` +/// mirrors `input_format_orc_case_insensitive_column_matching` for that name-based matching. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive) +{ + checkStackSize(); + + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + /// A boolean holds only 0 and 1, so every integer type is a widening of it. + return which.isUInt8() || which.isEnum8() || orcIntegerBranchWidensTo(type, 0); + case ORC::TypeKind::BYTE: + return which.isInt8() || (which.isUInt8() && !isBool(type)) || which.isEnum8() || orcIntegerBranchWidensTo(type, 1); + case ORC::TypeKind::SHORT: + return which.isInt16() || which.isUInt16() || which.isEnum16() || orcIntegerBranchWidensTo(type, 2); + case ORC::TypeKind::INT: + return which.isInt32() || which.isUInt32() || which.isIPv4() || orcIntegerBranchWidensTo(type, 4); + case ORC::TypeKind::LONG: + return which.isInt64() || which.isUInt64() || orcIntegerBranchWidensTo(type, 8); + case ORC::TypeKind::FLOAT: + return which.isFloat32() || which.isFloat64(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::DATE: + return which.isDate32() || which.isDate(); + case ORC::TypeKind::TIMESTAMP: + /// Permissive: matches any DateTime/DateTime64 alternative. The repair cast relabels the + /// branch to the alternative's timezone, which is value-preserving for DateTime64. + return which.isDateTime64() || which.isDateTime(); + case ORC::TypeKind::TIMESTAMP_INSTANT: + /// Matches only an explicitly time-zoned target so it stays distinct from a TIMESTAMP + /// branch in the same union (both read back as DateTime64(9)); see the comment above the + /// function. + return (which.isDateTime64() || which.isDateTime()) && orcTimestampTargetHasExplicitTimeZone(type); + case ORC::TypeKind::DECIMAL: + return which.isDecimal(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isStringOrFixedString(); + case ORC::TypeKind::BINARY: + return which.isStringOrFixedString() || which.isIPv6() || which.isInt128() || which.isUInt128() || which.isInt256() + || which.isUInt256() || which.isDecimal256(); + case ORC::TypeKind::CHAR: + return which.isStringOrFixedString() || which.isInt128() || which.isUInt128() || which.isInt256() || which.isUInt256() + || which.isDecimal256(); + case ORC::TypeKind::LIST: + return which.isArray() && orc_branch_type->getSubtypeCount() == 1 + && orcUnionBranchMatchesType( + orc_branch_type->getSubtype(0), assert_cast(*type).getNestedType(), case_insensitive); + case ORC::TypeKind::MAP: + { + if (!which.isMap() || orc_branch_type->getSubtypeCount() != 2) + return false; + const auto & map_type = assert_cast(*type); + return orcUnionBranchMatchesType(orc_branch_type->getSubtype(0), map_type.getKeyType(), case_insensitive) + && orcUnionBranchMatchesType(orc_branch_type->getSubtype(1), map_type.getValueType(), case_insensitive); + } + case ORC::TypeKind::STRUCT: + { + if (!which.isTuple()) + return false; + const auto & tuple_type = assert_cast(*type); + const auto & elements = tuple_type.getElements(); + if (tuple_type.hasExplicitNames()) + { + /// Match by field name, like the non-union ORC struct path: the target tuple may be + /// a subset of the ORC struct's fields, in any order. Each target field must map to + /// an ORC field with a recursively matching type; extra ORC fields are projected out + /// by the repair cast. Build a name -> ORC subtype map for the lookup. + std::unordered_map orc_field_by_name; + orc_field_by_name.reserve(orc_branch_type->getSubtypeCount()); + for (size_t i = 0; i < orc_branch_type->getSubtypeCount(); ++i) + { + String field_name = orc_branch_type->getFieldName(i); + if (case_insensitive) + boost::to_lower(field_name); + orc_field_by_name.emplace(std::move(field_name), orc_branch_type->getSubtype(i)); + } + + const auto & element_names = tuple_type.getElementNames(); + for (size_t i = 0; i < elements.size(); ++i) + { + String element_name = element_names[i]; + if (case_insensitive) + boost::to_lower(element_name); + auto it = orc_field_by_name.find(element_name); + if (it == orc_field_by_name.end() || !orcUnionBranchMatchesType(it->second, elements[i], case_insensitive)) + return false; + } + return true; + } + + /// Unnamed tuple: positional, same arity (no ORC field is silently dropped). + if (elements.size() != orc_branch_type->getSubtypeCount()) + return false; + for (size_t i = 0; i < elements.size(); ++i) + if (!orcUnionBranchMatchesType(orc_branch_type->getSubtype(i), elements[i], case_insensitive)) + return false; + return true; + } + case ORC::TypeKind::UNION: + return which.isVariant(); + case ORC::TypeKind::GEOMETRY: + case ORC::TypeKind::GEOGRAPHY: + /// Added in ORC 2.3. We do not read these, so no target type can match such a branch. + return false; + } + + return false; +} + +/// The natural inference pairing of the string-like ORC kinds, used to tie-break their union-branch +/// matching: CHAR is inferred as FixedString of the same length and STRING/VARCHAR as String, but +/// all of them can be *read* as either (see orcUnionBranchMatchesType), so e.g. +/// uniontype with the inferred Variant(FixedString(1), String) leaves both branches +/// with two candidates. Without a hint each branch would materialize per the current stripe's +/// physical encoding (a dictionary-encoded stripe comes back as LowCardinality), making a supported +/// schema fail depending on per-stripe encoding choices; preferring the natural pairing keeps the +/// assignment stable. The target is inspected with the LowCardinality/Nullable wrappers stripped, +/// so a LowCardinality-wrapped alternative (inferred from a dictionary-encoded stripe) pairs the +/// same way. BINARY deliberately has no preference: it is the conversion-rich kind (IPv6, big +/// integers, Decimal256), so a preference could steal a String alternative from a STRING branch. +/// +/// The numeric kinds are tie-broken the same way, for the same reason: they match their widenings +/// too (see `orcIntegerBranchWidensTo`), so e.g. `uniontype` with the explicit +/// schema `Variant(Int8, Int64)` leaves the `BYTE` branch with two candidates. Preferring the +/// natural pairing keeps the exact-width alternative with its own branch and lets the wider +/// alternative go to the branch that needs it. +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type) +{ + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + return isBool(type); + case ORC::TypeKind::BYTE: + return which.isInt8(); + case ORC::TypeKind::SHORT: + return which.isInt16(); + case ORC::TypeKind::INT: + return which.isInt32(); + case ORC::TypeKind::LONG: + return which.isInt64(); + case ORC::TypeKind::FLOAT: + return which.isFloat32(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::CHAR: + return which.isFixedString() + && assert_cast(*type).getN() == orc_branch_type->getMaximumLength(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isString(); + default: + return false; + } +} + +/// Variant sorts its nested types, so the positional correspondence between ORC union branches +/// and the alternatives of an explicit (or inferred) Variant type hint is lost. Reconstruct it +/// structurally: collect the alternatives each branch can be read as (orcUnionBranchMatchesType), +/// then keep only the forced assignments (a branch takes an alternative when it is its only +/// remaining candidate), tie-breaking the string-like branches by their natural inference pairing +/// (orcUnionBranchPrefersType). A branch whose correspondence stays ambiguous is left without a +/// hint (nullptr in the result), so no guess is ever made. Shared between +/// readColumnFromORCColumn (drives the branch conversions) and updateIncludeTypeIds (prunes a +/// hinted STRUCT branch's fields the same way the read path does), so the two stay in sync. +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching) +{ + const size_t num_children = orc_type->getSubtypeCount(); + DataTypes branch_hints(num_children); + const auto * variant_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; + if (!variant_hint) + return branch_hints; + + const auto & alternatives = variant_hint->getVariants(); + std::vector> candidates(num_children); + for (size_t i = 0; i < num_children; ++i) + for (size_t a = 0; a < alternatives.size(); ++a) + if (orcUnionBranchMatchesType(orc_type->getSubtype(i), alternatives[a], case_insensitive_matching)) + candidates[i].push_back(a); + + std::vector alternative_taken(alternatives.size(), false); + const auto preferred_candidates = [&](size_t i) + { + std::vector preferred; + for (const size_t a : candidates[i]) + if (orcUnionBranchPrefersType(orc_type->getSubtype(i), alternatives[a])) + preferred.push_back(a); + return preferred; + }; + bool changed = true; + while (changed) + { + changed = false; + for (size_t i = 0; i < num_children; ++i) + { + if (branch_hints[i] || candidates[i].size() != 1) + continue; + const size_t a = candidates[i].front(); + if (alternative_taken[a]) + { + /// Another branch already took this alternative; leave this branch without a hint. + candidates[i].clear(); + continue; + } + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + + if (changed) + continue; + + /// The forced assignments are exhausted. Tie-break the string-like branches by their + /// natural inference pairing (see orcUnionBranchPrefersType): a branch takes the single + /// alternative it prefers among its remaining candidates, unless another unassigned + /// branch uniquely prefers the same one - a contested preference is still ambiguous and no + /// guess is ever made. One assignment at a time, then back to the forced-assignment loop + /// to propagate it. + for (size_t i = 0; i < num_children && !changed; ++i) + { + if (branch_hints[i] || candidates[i].size() < 2) + continue; + const auto preferred = preferred_candidates(i); + if (preferred.size() != 1) + continue; + const size_t a = preferred.front(); + bool contested = false; + for (size_t j = 0; j < num_children && !contested; ++j) + { + if (j == i || branch_hints[j]) + continue; + const auto preferred_j = preferred_candidates(j); + contested = preferred_j.size() == 1 && preferred_j.front() == a; + } + if (contested) + continue; + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + } + + return branch_hints; +} + +/// Strips Nullable from a Nullable(Tuple) and propagates the struct null map into its elements. +static ColumnWithTypeAndName unwrapORCNullableTuple(const ColumnWithTypeAndName & column) +{ + const auto * type_nullable = typeid_cast(column.type.get()); + if (!type_nullable) + return column; + + const auto * tuple_type = typeid_cast(type_nullable->getNestedType().get()); + if (!tuple_type) + return column; + + const auto & col_nullable = assert_cast(*column.column); + + const auto & null_map_data = col_nullable.getNullMapData(); + bool has_nulls = !memoryIsZero(null_map_data.data(), 0, null_map_data.size()); + + if (!has_nulls) + { + /// No actual nulls — just strip the Nullable wrapper. + return {col_nullable.getNestedColumnPtr(), type_nullable->getNestedType(), column.name}; + } + + /// Propagate the struct null map to each Tuple element. + const auto & inner_tuple = assert_cast(col_nullable.getNestedColumn()); + const auto & null_map_ptr = col_nullable.getNullMapColumnPtr(); + Columns new_elements; + DataTypes new_types; + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + auto elem_col = inner_tuple.getColumnPtr(i); + auto elem_type = tuple_type->getElement(i); + if (elem_type->isNullable()) + { + /// Element already Nullable — merge null maps (struct null OR element null). + const auto & existing = assert_cast(*elem_col); + auto merged = ColumnUInt8::create(null_map_ptr->size()); + const auto & s = assert_cast(*null_map_ptr).getData(); + const auto & e = existing.getNullMapData(); + auto & m = merged->getData(); + for (size_t j = 0; j < s.size(); ++j) + m[j] = s[j] | e[j]; + new_elements.push_back(ColumnNullable::create(existing.getNestedColumnPtr(), std::move(merged))); + new_types.push_back(elem_type); + } + else if (elem_type->canBeInsideNullable()) + { + new_elements.push_back(ColumnNullable::create(elem_col, null_map_ptr)); + new_types.push_back(std::make_shared(elem_type)); + } + else + { + /// Array, Map, etc. — replace values at null positions with type defaults. + const auto & nm = col_nullable.getNullMapData(); + auto mutable_col = elem_col->cloneEmpty(); + for (size_t j = 0; j < elem_col->size(); ++j) + { + if (nm[j]) + mutable_col->insertDefault(); + else + mutable_col->insertFrom(*elem_col, j); + } + new_elements.push_back(std::move(mutable_col)); + new_types.push_back(elem_type); + } + } + + auto result_type = tuple_type->hasExplicitNames() ? std::make_shared(std::move(new_types), tuple_type->getElementNames()) + : std::make_shared(std::move(new_types)); + return {ColumnTuple::create(std::move(new_elements)), result_type, column.name}; +} + +/// Matches the elements of the tuples in `column` to those of the named tuples in `requested_type` by name, through +/// Nullable, Array and Map: a requested element that was not read is filled with defaults, and an element that is +/// not requested is dropped. A CAST would match tuples with no common element names by position instead. +static ColumnWithTypeAndName +matchORCTupleElementsByName(const ColumnWithTypeAndName & column, const DataTypePtr & requested_type, bool case_insensitive) +{ + if (column.type->equals(*requested_type)) + return column; + + if (const auto * nullable_type = typeid_cast(column.type.get())) + { + const auto & nullable_column = assert_cast(*column.column); + auto nested = matchORCTupleElementsByName( + {nullable_column.getNestedColumnPtr(), nullable_type->getNestedType(), column.name}, + removeNullable(requested_type), + case_insensitive); + return { + ColumnNullable::create(nested.column, nullable_column.getNullMapColumnPtr()), + std::make_shared(nested.type), + column.name}; + } + + const auto requested_non_nullable_type = removeNullable(requested_type); + + if (const auto * array_type = typeid_cast(column.type.get())) + { + const auto * requested_array_type = typeid_cast(requested_non_nullable_type.get()); + if (!requested_array_type) + return column; + const auto & array_column = assert_cast(*column.column); + auto nested = matchORCTupleElementsByName( + {array_column.getDataPtr(), array_type->getNestedType(), column.name}, requested_array_type->getNestedType(), case_insensitive); + return { + ColumnArray::create(nested.column, array_column.getOffsetsPtr()), std::make_shared(nested.type), column.name}; + } + + if (const auto * map_type = typeid_cast(column.type.get())) + { + const auto * requested_map_type = typeid_cast(requested_non_nullable_type.get()); + if (!requested_map_type) + return column; + const auto & map_column = assert_cast(*column.column); + auto keys = matchORCTupleElementsByName( + {map_column.getNestedData().getColumnPtr(0), map_type->getKeyType(), "key"}, requested_map_type->getKeyType(), case_insensitive); + auto values = matchORCTupleElementsByName( + {map_column.getNestedData().getColumnPtr(1), map_type->getValueType(), "value"}, + requested_map_type->getValueType(), + case_insensitive); + return { + ColumnMap::create(keys.column, values.column, map_column.getNestedColumn().getOffsetsPtr()), + std::make_shared(keys.type, values.type), + column.name}; + } + + const auto * tuple_type = typeid_cast(column.type.get()); + const auto * requested_tuple_type = typeid_cast(requested_non_nullable_type.get()); + if (!tuple_type || !requested_tuple_type) + return column; + + const auto & tuple_column = assert_cast(*column.column); + const size_t num_rows = tuple_column.size(); + Columns elements; + DataTypes types; + Strings names; + + /// An unnamed tuple is matched by position and keeps its elements, so the CAST rejects a different number of them. + if (!requested_tuple_type->hasExplicitNames()) + { + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + ColumnWithTypeAndName element{tuple_column.getColumnPtr(i), tuple_type->getElement(i), tuple_type->getNameByPosition(i + 1)}; + if (i < requested_tuple_type->getElements().size()) + element = matchORCTupleElementsByName(element, requested_tuple_type->getElement(i), case_insensitive); + elements.push_back(std::move(element.column)); + types.push_back(std::move(element.type)); + } + auto result_column = elements.empty() ? ColumnTuple::create(num_rows) : ColumnTuple::create(std::move(elements)); + return {std::move(result_column), std::make_shared(std::move(types)), column.name}; + } + + for (size_t i = 0; i < requested_tuple_type->getElements().size(); ++i) + { + const auto & requested_element_type = requested_tuple_type->getElement(i); + const auto & name = requested_tuple_type->getNameByPosition(i + 1); + + auto pos = tuple_type->tryGetPositionByName(name, /*case_insensitive=*/false); + if (!pos && case_insensitive) + pos = tuple_type->tryGetPositionByName(name, /*case_insensitive=*/true); + + if (pos) + { + auto element = matchORCTupleElementsByName( + {tuple_column.getColumnPtr(*pos), tuple_type->getElement(*pos), name}, requested_element_type, case_insensitive); + elements.push_back(std::move(element.column)); + types.push_back(std::move(element.type)); + } + else + { + auto element = requested_element_type->createColumn(); + requested_element_type->insertManyDefaultsInto(*element, num_rows); + elements.push_back(std::move(element)); + types.push_back(requested_element_type); + } + names.push_back(name); + } + + auto result_type = std::make_shared(std::move(types), std::move(names)); + auto result_column = elements.empty() ? ColumnTuple::create(num_rows) : ColumnTuple::create(std::move(elements)); + return {std::move(result_column), std::move(result_type), column.name}; +} + ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint) const @@ -1793,8 +2684,8 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( bool skipped = false; - if (!inside_nullable && (orc_column->hasNulls || (type_hint && type_hint->isNullable())) && !orc_column->isEncoded - && (orc_type->getKind() != orc::LIST && orc_type->getKind() != orc::MAP && orc_type->getKind() != orc::STRUCT)) + if (!inside_nullable && (orc_column->hasNulls || (type_hint && isNullableOrLowCardinalityNullable(type_hint))) && !orc_column->isEncoded + && (orc_type->getKind() != ORC::LIST && orc_type->getKind() != ORC::MAP && orc_type->getKind() != ORC::UNION)) { DataTypePtr nested_type_hint; if (type_hint) @@ -1808,11 +2699,209 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( return {nullable_column, nullable_type, column_name}; } + /// ORC union maps to the ClickHouse Variant type. Handled before the switch below so the switch + /// stays non-exhaustive (its default handles unsupported types). + if (orc_type->getKind() == ORC::UNION) + { + const auto * orc_union_column = dynamic_cast(orc_column); + if (!orc_union_column) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC column for union type must be a UnionVectorBatch"); + + const size_t num_children = orc_type->getSubtypeCount(); + const size_t num_rows = orc_union_column->numElements; + + /// Mirror of the schema-inference guard: a union with more branches than Variant can hold + /// (ColumnVariant::MAX_NESTED_COLUMNS) is rejected explicitly instead of letting the + /// DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an explicit + /// structure, since schema inference already rejects oversized unions. + if (num_children > ColumnVariant::MAX_NESTED_COLUMNS) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported (Variant supports at most {} nested types), while reading column {}", + num_children, ColumnVariant::MAX_NESTED_COLUMNS, column_name); + + /// The hints enable the explicit-schema conversions the scalar readers support (e.g. + /// binary -> IPv6) and keep the branch types aligned with the hinted Variant (e.g. + /// Array(Nullable(...)) produced by schema inference). See computeOrcUnionBranchHints for + /// how a branch's forced alternative is reconstructed; updateIncludeTypeIds calls the same + /// function so a hinted STRUCT branch's field pruning matches what is actually read here. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, type_hint, case_insensitive_matching); + + /// Read each ORC union branch into its own column. ORC keeps a separate physical batch per + /// branch. Variant branches are non-nullable, and an ORC union row can be non-null yet + /// select a branch whose payload is null - such a row is represented by the Variant NULL + /// discriminator (see the row loop below). The branch null map is taken directly from the + /// ORC batch rather than from a Nullable result column: complex (LIST/MAP) and + /// dictionary-encoded branches never come back as ColumnNullable, yet their payload can + /// still be null. inside_nullable is set because nulls are handled here rather than by + /// wrapping the branch value in Nullable. + DataTypes branch_types; + Columns branch_columns; + std::vector branch_null_map_columns(num_children); /// keeps the null maps alive + std::vector branch_null_maps(num_children, nullptr); + branch_types.reserve(num_children); + branch_columns.reserve(num_children); + for (size_t i = 0; i < num_children; ++i) + { + /// A union branch that is itself a union would map to a nested Variant, which Variant + /// forbids; reject it explicitly (matching the schema-inference path) instead of letting + /// the DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an + /// explicit structure, since schema inference already rejects nested unions. + if (orc_type->getSubtype(i)->getKind() == ORC::UNION) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto branch = readColumnFromORCColumn( + orc_union_column->children[i], orc_type->getSubtype(i), column_name, /*inside_nullable=*/true, branch_hints[i]); + + if (orc_union_column->children[i]->hasNulls) + { + branch_null_map_columns[i] = readByteMapFromORCColumn(orc_union_column->children[i]); + branch_null_maps[i] = &assert_cast(*branch_null_map_columns[i]).getData(); + } + + /// A dictionary-encoded branch read without a hint comes back as + /// LowCardinality(Nullable(...)); Variant alternatives cannot be nullable, so strip the + /// inner Nullable (the nulls are tracked by the branch null map above). + ColumnWithTypeAndName branch_non_nullable{ + removeNullableOrLowCardinalityNullable(branch.column), + removeNullableOrLowCardinalityNullable(branch.type), + branch.name}; + + /// With a per-branch hint the branch must end up as exactly that alternative, so that + /// the resulting Variant type equals the hinted one (e.g. a branch of a + /// non-dictionary-encoded file read for a LowCardinality(String) alternative comes + /// back as plain String). Compared by name, not equals: Variant identity is name-based + /// and e.g. equals cannot tell the custom-named Bool from a plain UInt8, which would + /// skip the Bool -> UInt8 repair cast for a boolean branch hinted as UInt8. + if (branch_hints[i] && branch_hints[i]->getName() != branch_non_nullable.type->getName()) + { + if (branch_null_map_columns[i]) + { + /// A value-checking cast (e.g. Int8 -> Enum8, or the same on a nested Tuple + /// field) must not inspect the placeholder values ORC leaves at null-payload + /// positions - those rows become the Variant NULL discriminator below and are + /// never read. Replace them with a valid, castable row before casting. + /// Wrapping the branch in Nullable is not enough: a Nullable(Tuple) cast would + /// still descend into and reject a null nested field. + if (auto safe = replaceNullPayloadRowsWithValidRow(branch_non_nullable.column, *branch_null_maps[i])) + branch_non_nullable.column + = castColumn({safe, branch_non_nullable.type, branch_non_nullable.name}, branch_hints[i]); + else + /// Every row is a null payload and none is read, so a default-valued column + /// of the target type with the same number of rows is enough. + branch_non_nullable.column + = branch_hints[i]->createColumn()->cloneResized(branch_non_nullable.column->size()); + } + else + { + branch_non_nullable.column = castColumn(branch_non_nullable, branch_hints[i]); + } + branch_non_nullable.type = branch_hints[i]; + } + + branch_types.push_back(branch_non_nullable.type); + branch_columns.push_back(std::move(branch_non_nullable.column)); + } + + /// ORC keeps one physical stream per branch, so branches with identical types cannot be + /// represented as a Variant (which de-duplicates types); reject them explicitly. The + /// identity is compared with LowCardinality stripped, so it does not depend on the current + /// stripe's physical encoding (a dictionary-encoded branch materializes as LowCardinality), + /// mirroring the schema-inference check in parseORCType. + std::unordered_set seen_type_names; + for (const auto & branch_type : branch_types) + if (!seen_type_names.insert(recursiveRemoveLowCardinality(branch_type)->getName()).second) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto variant_type = std::make_shared(branch_types); + const auto & global_variants = assert_cast(*variant_type).getVariants(); + + /// Variant stores its branches sorted by type name, so remap ORC tags to global (sorted) + /// discriminators. The Variant sub-columns are built compactly (each must contain exactly + /// the values referenced by its discriminator, in appended order), so they are cloned empty + /// from the ORC branch columns and filled row by row below rather than placed wholesale. + std::unordered_map type_name_to_global; + for (size_t g = 0; g < global_variants.size(); ++g) + type_name_to_global[global_variants[g]->getName()] = static_cast(g); + + MutableColumns variant_columns(global_variants.size()); + std::vector tag_to_global(num_children); + for (size_t i = 0; i < num_children; ++i) + { + auto global = type_name_to_global.at(branch_types[i]->getName()); + tag_to_global[i] = global; + variant_columns[global] = branch_columns[i]->cloneEmpty(); + } + + auto local_discriminators = ColumnVariant::ColumnDiscriminators::create(); + auto & discriminators_data = local_discriminators->getData(); + discriminators_data.resize_exact(num_rows); + + auto offsets = ColumnVariant::ColumnOffsets::create(); + auto & offsets_data = offsets->getData(); + offsets_data.resize_exact(num_rows); + + const UInt8 * tags = orc_union_column->tags.data(); + const uint64_t * orc_offsets = orc_union_column->offsets.data(); + const char * not_null = orc_union_column->hasNulls ? orc_union_column->notNull.data() : nullptr; + + for (size_t row = 0; row < num_rows; ++row) + { + if (not_null && !not_null[row]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const size_t tag = tags[row]; + if (tag >= num_children) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union tag {} for union with {} branches while reading column {}", + tag, num_children, column_name); + + const size_t offset = orc_offsets[row]; + /// A malformed file can point past the selected branch's values; reject it rather than + /// reading out of bounds (the branch column and its null map share this size). + if (offset >= branch_columns[tag]->size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union offset {} into branch {} of size {} while reading column {}", + offset, tag, branch_columns[tag]->size(), column_name); + + /// A non-null union row can still select a branch whose payload is null (ORC keeps the + /// union-level null count at 0 in that case). Variant branches are non-nullable, so + /// represent such a row as a Variant NULL rather than the branch's nested default value. + if (branch_null_maps[tag] && (*branch_null_maps[tag])[offset]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const auto global = tag_to_global[tag]; + auto & variant_column = *variant_columns[global]; + discriminators_data[row] = global; + offsets_data[row] = variant_column.size(); + variant_column.insertFrom(*branch_columns[tag], offset); + } + + auto variant_column = ColumnVariant::create(std::move(local_discriminators), std::move(offsets), std::move(variant_columns)); + return {std::move(variant_column), variant_type, column_name}; + } + switch (orc_type->getKind()) { - case orc::STRING: - case orc::BINARY: - case orc::VARCHAR: + case ORC::STRING: + case ORC::BINARY: + case ORC::VARCHAR: { if (type_hint) { @@ -1844,7 +2933,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithStringData(orc_column, column_name); } - case orc::CHAR: + case ORC::CHAR: { if (type_hint) { @@ -1870,32 +2959,32 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithFixedStringData(orc_column, orc_type, column_name); } - case orc::BOOLEAN: + case ORC::BOOLEAN: return readColumnWithBooleanData(orc_column, column_name); - case orc::BYTE: - return readColumnWithNumericData(orc_column, column_name); - case orc::SHORT: - return readColumnWithNumericData(orc_column, column_name); - case orc::INT: + case ORC::BYTE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::SHORT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::INT: { /// ORC format doesn't have unsigned integers and we output IPv4 as Int32. /// We should allow to read it back from Int32. if (type_hint && isIPv4(type_hint)) return readIPv4ColumnWithInt32Data(orc_column, column_name); - return readColumnWithNumericData(orc_column, column_name); - } - case orc::LONG: - return readColumnWithNumericData(orc_column, column_name); - case orc::FLOAT: - return readColumnWithNumericData(orc_column, column_name); - case orc::DOUBLE: - return readColumnWithNumericData(orc_column, column_name); - case orc::DATE: - return readColumnWithDateData(orc_column, column_name, type_hint); - case orc::TIMESTAMP: [[fallthrough]]; - case orc::TIMESTAMP_INSTANT: - return readColumnWithTimestampData(orc_column, column_name); - case orc::DECIMAL: + return readColumnWithNumericData(orc_column, column_name); + } + case ORC::LONG: + return readColumnWithNumericData(orc_column, column_name); + case ORC::FLOAT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DOUBLE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DATE: + return readColumnWithDateData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::TIMESTAMP: [[fallthrough]]; + case ORC::TIMESTAMP_INSTANT: + return readColumnWithTimestampData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::DECIMAL: { auto interal_type = parseORCType(orc_type, false, false, nullptr, skipped); @@ -1904,15 +2993,15 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( precision = 38; if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); throw Exception( ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal precision {} in ORC type {} is out of bound", precision, orc_type->toString()); } - case orc::MAP: + case ORC::MAP: { DataTypePtr key_type_hint; DataTypePtr value_type_hint; @@ -1926,13 +3015,18 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } } - const auto * orc_map_column = dynamic_cast(orc_column); + const auto * orc_map_column = dynamic_cast(orc_column); const auto * orc_key_column = orc_map_column->keys.get(); const auto * orc_value_column = orc_map_column->elements.get(); const auto * orc_key_type = orc_type->getSubtype(0); const auto * orc_value_type = orc_type->getSubtype(1); auto key_column = readColumnFromORCColumn(orc_key_column, orc_key_type, "key", false, key_type_hint); + /// A map key cannot be Nullable. + if (!key_type_hint && !DataTypeMap::isValidKeyType(key_column.type)) + key_type_hint = removeNullableOrLowCardinalityNullable(key_column.type); + if (key_type_hint) + key_column = matchORCTupleElementsByName(key_column, key_type_hint, case_insensitive_matching); if (key_type_hint && !key_type_hint->equals(*key_column.type)) { /// Cast key column to target type, because it can happen @@ -1950,7 +3044,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( auto map_type = std::make_shared(key_column.type, value_column.type); return {map_column, map_type, column_name}; } - case orc::LIST: + case ORC::LIST: { DataTypePtr nested_type_hint; if (type_hint) @@ -1960,38 +3054,56 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( nested_type_hint = array_type_hint->getNestedType(); } - const auto * orc_list_column = dynamic_cast(orc_column); + const auto * orc_list_column = dynamic_cast(orc_column); const auto * orc_nested_column = getNestedORCColumn(orc_list_column); const auto * orc_nested_type = orc_type->getSubtype(0); auto nested_column = readColumnFromORCColumn(orc_nested_column, orc_nested_type, column_name, false, nested_type_hint); + /// A struct read only for its size has no elements, which `createNested` below rejects. Otherwise the elements + /// are matched after a subcolumn is extracted, as a hint for one can name a path, such as `x.v`. + const auto * read_tuple_type = typeid_cast(removeNullable(nested_column.type).get()); + if (type_hint && isNested(type_hint) && read_tuple_type && read_tuple_type->getElements().empty()) + nested_column = matchORCTupleElementsByName(nested_column, nested_type_hint, case_insensitive_matching); + auto offsets_column = readOffsetsFromORCListColumn(orc_list_column); - auto array_column = ColumnArray::create(nested_column.column, offsets_column); DataTypePtr array_type; - /// If type hint is Nested, we should return Nested type, - /// because we differentiate Nested and simple Array(Tuple) - if (type_hint && isNested(type_hint)) + ColumnPtr array_data_column = nested_column.column; + /// If type hint is Nested and the element is a named Tuple, return the Nested type + /// so that `Nested::flatten` can decompose it into separate arrays. + /// When the element is Nullable(Tuple(...)), unwrap it and propagate the struct null + /// map to each element via `unwrapNullableTuple`. + const auto * tuple_type = type_hint && isNested(type_hint) + ? typeid_cast(removeNullable(nested_column.type).get()) + : nullptr; + if (tuple_type) { - const auto & tuple_type = assert_cast(*nested_column.type); - array_type = createNested(tuple_type.getElements(), tuple_type.getElementNames()); + auto unwrapped = unwrapORCNullableTuple({array_data_column, nested_column.type, column_name}); + array_data_column = unwrapped.column; + const auto & result_tuple = assert_cast(*unwrapped.type); + array_type = createNested(result_tuple.getElements(), result_tuple.getElementNames()); } else { array_type = std::make_shared(nested_column.type); } + auto array_column = ColumnArray::create(array_data_column, offsets_column); return {array_column, array_type, column_name}; } - case orc::STRUCT: + case ORC::STRUCT: { Columns tuple_elements; DataTypes tuple_types; std::vector tuple_names; const auto * tuple_type_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; - const auto * orc_struct_column = dynamic_cast(orc_column); + const auto * orc_struct_column = dynamic_cast(orc_column); for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) { + /// Read only for the size and the null map of the struct, so its values are not converted. + if (count_only_fields.contains(orc_type->getSubtype(i)->getColumnId())) + continue; + auto field_name = orc_type->getFieldName(i); DataTypePtr nested_type_hint; @@ -1999,7 +3111,12 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( { if (tuple_type_hint->hasExplicitNames()) { - auto pos = tuple_type_hint->tryGetPositionByName(field_name, case_insensitive_matching); + /// An element spelled exactly like the field wins over one that only matches + /// case-folded, so two fields whose names differ only by case cannot both + /// claim the same element and leave the other one unread. + auto pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/false); + if (!pos && case_insensitive_matching) + pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/true); if (pos) { nested_type_hint = tuple_type_hint->getElement(*pos); @@ -2034,8 +3151,27 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } void ORCColumnToCHColumn::orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values) { + /// A file field spelled exactly like the request wins over one that only matches case-folded, + /// so two fields whose names differ only by case are not both answered by the same one. Among + /// fields that only match folded, the first in file order answers. + auto find_orc_column = [&](const String & name) + { + auto it = name_to_column_ptr.find(name); + if (it == name_to_column_ptr.end() && case_insensitive_matching) + { + for (const auto & field_name : orc_field_names) + if (boost::iequals(field_name, name)) + return name_to_column_ptr.find(field_name); + } + return it; + }; + Columns columns_list; columns_list.reserve(header.columns()); std::unordered_map>> nested_tables; @@ -2043,23 +3179,20 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( { const ColumnWithTypeAndName & header_column = header.getByPosition(column_i); - auto search_column_name = header_column.name; - if (case_insensitive_matching) - boost::to_lower(search_column_name); - ColumnWithTypeAndName column; - if (!name_to_column_ptr.contains(search_column_name)) + auto orc_column_it = find_orc_column(header_column.name); + if (orc_column_it == name_to_column_ptr.end()) { bool read_from_nested = false; /// Check if it's a column from nested table. String nested_table_name = Nested::extractTableName(header_column.name); - String search_nested_table_name = nested_table_name; - if (case_insensitive_matching) - boost::to_lower(search_nested_table_name); - if (name_to_column_ptr.contains(search_nested_table_name)) + auto orc_nested_column_it = find_orc_column(nested_table_name); + if (orc_nested_column_it != name_to_column_ptr.end()) { - if (!nested_tables.contains(search_nested_table_name)) + /// Keyed by the file's spelling, so requests that differ only by case share one. + const String & resolved_nested_table_name = orc_nested_column_it->first; + if (!nested_tables.contains(resolved_nested_table_name)) { NamesAndTypesList nested_columns; for (const auto & name_and_type : header.getNamesAndTypesList()) @@ -2069,15 +3202,17 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } auto nested_table_type = Nested::collect(nested_columns).front().type; - auto orc_column_with_type = name_to_column_ptr[search_nested_table_name]; + const auto & orc_column_with_type = orc_nested_column_it->second; ColumnsWithTypeAndName cols = {readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, nested_table_name, false, nested_table_type)}; BlockPtr block_ptr = std::make_shared(cols); auto column_extractor = std::make_shared(*block_ptr, case_insensitive_matching); - nested_tables[search_nested_table_name] = {block_ptr, column_extractor}; + nested_tables[resolved_nested_table_name] = {block_ptr, column_extractor}; } - auto nested_column = nested_tables[search_nested_table_name].second->extractColumn(search_column_name); + /// The requested spelling, not the file's one: the helper matches names + /// case-insensitively itself, and an exact element name outranks a folded match. + auto nested_column = nested_tables[resolved_nested_table_name].second->extractColumn(header_column.name); if (nested_column) { column = *nested_column; @@ -2103,11 +3238,12 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } else { - auto orc_column_with_type = name_to_column_ptr[search_column_name]; + const auto & orc_column_with_type = orc_column_it->second; column = readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, header_column.name, false, header_column.type); } + column = matchORCTupleElementsByName(column, header_column.type, case_insensitive_matching); if (null_as_default) insertNullAsDefaultIfNeeded(column, header_column, column_i, block_missing_values); @@ -2118,6 +3254,72 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( res.setColumns(columns_list, num_rows); } +void registerInputFormatORC(FormatFactory & factory); +void registerInputFormatORC(FormatFactory & factory) +{ + factory.registerRandomAccessInputFormat( + "ORC", + [](ReadBuffer & buf, + const Block & sample, + const FormatSettings & settings, + const ReadSettings & read_settings, + bool is_remote_fs, + FormatParserSharedResourcesPtr, + FormatFilterInfoPtr format_filter_info) + { + const bool has_file_size = isBufferWithFileSize(buf); + auto * seekable_in = dynamic_cast(&buf); + const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in + && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; + const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; + return std::make_shared( + buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); + }); + factory.markFormatSupportsSubsetOfColumns("ORC"); +} + +void registerORCSchemaReader(FormatFactory & factory); +void registerORCSchemaReader(FormatFactory & factory) +{ + factory.registerSchemaReader( + "ORC", + [](ReadBuffer & buf, const FormatSettings & settings) + { + return std::make_shared(buf, settings); + } + ); + + factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) + { + return fmt::format( + "schema_inference_make_columns_nullable={};schema_inference_allow_nullable_tuple_type={};" + "dictionary_as_low_cardinality={};skip_columns_with_unsupported_types={};max_parser_depth={}", + settings.schema_inference_make_columns_nullable, + settings.schema_inference_allow_nullable_tuple_type, + settings.orc.dictionary_as_low_cardinality, + settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + settings.max_parser_depth); + }); +} + +} + +#else + +namespace DB +{ + class FormatFactory; + + void registerInputFormatORC(FormatFactory &); + void registerORCSchemaReader(FormatFactory &); + + void registerInputFormatORC(FormatFactory &) + { + } + + void registerORCSchemaReader(FormatFactory &) + { + } } #endif diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h index c58c59889a8c..42cf3556c66e 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h @@ -6,13 +6,12 @@ #include #include -#include #include #include #include #include #include -#include +#include #include namespace DB @@ -20,21 +19,23 @@ namespace DB class KeyCondition; -class ORCInputStream : public orc::InputStream +class ORCInputStream : public ORC::InputStream { public: ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch); - uint64_t getLength() const override; - uint64_t getNaturalReadSize() const override; - void read(void * buf, uint64_t length, uint64_t offset) override; - std::future readAsync(void * buf, uint64_t length, uint64_t offset) override; + UInt64 getLength() const override; + void read(void * buf, UInt64 length, UInt64 offset) override; + std::future readAsync(void * buf, UInt64 length, UInt64 offset) override; const std::string & getName() const override { return name; } protected: SeekableReadBuffer & in; size_t file_size; - bool supports_read_at; + /// Use offset-based reads (ReadBuffer::readBigAt) instead of seek+read; needed for ORC tail. + bool use_offset_based_read; + /// Async wrapper only when caller enabled prefetch and the buffer supports read-at. + bool use_async_prefetch; ThreadPoolCallbackRunnerUnsafe async_runner; std::string name = "ORCInputStream"; @@ -50,22 +51,20 @@ class ORCInputStreamFromString : public ReadBufferFromOwnString, public ORCInput } }; -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled); // Reads the whole file into a memory buffer, owned by the returned RandomAccessFile. -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); -/// The memory pool to set on the options of every ORC reader and writer we create: unlike the -/// default one of the library, it is accounted for by the memory tracker and it throws on failure -/// instead of returning a null pointer that the library dereferences. -orc::MemoryPool & getORCMemoryPool(); +/// Creates an ORC file reader; throws INCORRECT_DATA if the root type of the file is not a struct. +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options); -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings); +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings); class ORCColumnToCHColumn; -class NativeORCBlockInputFormat : public IInputFormat +class NativeORCBlockInputFormat final : public IInputFormat { public: NativeORCBlockInputFormat( @@ -96,14 +95,14 @@ class NativeORCBlockInputFormat : public IInputFormat bool prepareStripeReader(); void prefetchStripes(); - std::unique_ptr file_reader; - std::unique_ptr stripe_reader; + std::unique_ptr file_reader; + std::unique_ptr stripe_reader; std::unique_ptr orc_column_to_ch_column; - std::shared_ptr sargs; + std::shared_ptr sargs; // indices of columns to read from ORC file - std::list include_indices; + std::vector include_indices; BlockMissingValues block_missing_values; size_t approx_bytes_read_for_chunk = 0; @@ -115,30 +114,36 @@ class NativeORCBlockInputFormat : public IInputFormat FormatFilterInfoPtr format_filter_info; std::vector selected_stripes; - size_t read_iterator; - size_t prefetch_iterator; + size_t read_iterator{}; + size_t prefetch_iterator{}; - std::unique_ptr current_stripe_info; + const ORC::Proto::StripeInformation * current_stripe_info = nullptr; std::atomic is_stopped{0}; }; -class NativeORCSchemaReader : public ISchemaReader +class NativeORCSchemaReader final : public ISchemaReader { public: NativeORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); NamesAndTypesList readSchema() override; + std::optional readNumberOrRows() override; private: + void initializeIfNeeded(); + const FormatSettings format_settings; + std::unique_ptr file_reader; + std::atomic is_stopped{0}; + bool initialized = false; }; class ORCColumnToCHColumn { public: - using ORCColumnPtr = const orc::ColumnVectorBatch *; - using ORCTypePtr = const orc::Type *; + using ORCColumnPtr = const ORC::ColumnVectorBatch *; + using ORCTypePtr = const ORC::Type *; using ORCColumnWithType = std::pair; using NameToColumnPtr = std::unordered_map; @@ -147,22 +152,28 @@ class ORCColumnToCHColumn bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_ = false, - bool dictionary_as_low_cardinality_ = false); + bool dictionary_as_low_cardinality_ = false, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_ = FormatSettings::DateTimeOverflowBehavior::Ignore, + std::unordered_set count_only_fields_ = {}); void orcTableToCHChunk( Chunk & res, - const orc::Type * schema, - const orc::ColumnVectorBatch * table, + const ORC::Type * schema, + const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); void orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values = nullptr); private: ColumnWithTypeAndName readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint = nullptr) const; @@ -173,6 +184,9 @@ class ORCColumnToCHColumn bool null_as_default; bool case_insensitive_matching; bool dictionary_as_low_cardinality; + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior; + /// ORC column ids of the struct fields that are read only for the size and the null map of their struct. + const std::unordered_set count_only_fields; }; } #endif diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.cpp b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp new file mode 100644 index 000000000000..f792e8d980ad --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp @@ -0,0 +1,1218 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +RleVersion getRleVersion(const Proto::ColumnEncoding & encoding) +{ + switch (encoding.kind) + { + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DICTIONARY: + return RleVersion::V1; + case Proto::ColumnEncodingKind::DIRECT_V2: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return RleVersion::V2; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding {}", static_cast(encoding.kind)); +} + +std::unique_ptr getRequiredStream(StripeStreams & stripe, UInt64 column_id, Proto::StreamKind kind, const char * stream_name, const char * column_kind) +{ + auto stream = stripe.getStream(column_id, kind); + if (!stream) + throw Exception(ErrorCodes::INCORRECT_DATA, "{} stream not found in ORC {} column {}", stream_name, column_kind, column_id); + return stream; +} + +/// Converts the bytes read into the beginning of a buffer of integers into the integers, in place. +/// BOOLEAN and BYTE: the values are decoded into the bytes of the column. +template +class ByteColumnReaderImpl final : public ColumnReader +{ +public: + ByteColumnReaderImpl(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", type.toString().c_str())) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle.skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle.next(reinterpret_cast(data.data()), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + } + +private: + Decoder rle; +}; + +using BooleanColumnReader = ByteColumnReaderImpl; +using ByteColumnReader = ByteColumnReaderImpl; + +/// SHORT, INT, LONG and DATE: the values are decoded into a column of the matching width. +template +class IntegerColumnReader final : public ColumnReader +{ +public: + IntegerColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "integer"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle->next(data.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + std::unique_ptr rle; +}; + +/// FLOAT and DOUBLE: the values are stored as is (little endian), so they are copied into the column. +template +class FloatingColumnReader final : public ColumnReader +{ +public: + FloatingColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , stream(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "floating point")) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + stream->skipBytes(num_values * sizeof(ItemType)); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & data = typeid_cast &>(batch).prepareColumn(num_values); + ItemType * out = data.data(); + + /// The stream has only the non-null values: read them at once to the beginning of the column. + size_t num_present = num_values; + if (not_null) + num_present = std::count_if(not_null, not_null + num_values, [](char c) { return c != 0; }); + + stream->readBytes(reinterpret_cast(out), num_present * sizeof(ItemType)); + if constexpr (std::endian::native == std::endian::big) + for (size_t i = 0; i < num_present; ++i) + out[i] = std::bit_cast(std::byteswap(std::bit_cast(out[i]))); + + if (!not_null) + return; + + /// Move the values to their rows from the back: the k-th value goes to a row i >= k, so it is not overwritten before it is moved. + size_t next_value = num_present; + for (size_t i = num_values; i-- > 0;) + out[i] = not_null[i] ? out[--next_value] : 0; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + stream->seek(positions.at(column_id)); + } + +private: + using Bits = std::conditional_t; + + std::unique_ptr stream; +}; + +/// Converts the lengths in `offsets` into the end offsets (as in `ColumnString` and `ColumnArray`), starting +/// from `total`, and returns the total length. The lengths of the null values are zeros. +UInt64 lengthsToEndOffsets(UInt64 * offsets, size_t num_values, UInt64 column_id, UInt64 total = 0) +{ + for (size_t i = 0; i < num_values; ++i) + { + /// The lengths are non-negative, a negative one is huge as unsigned. + if (offsets[i] > static_cast(std::numeric_limits::max()) || common::addOverflow(total, offsets[i], total) + || total > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid length {} in ORC column {}", static_cast(offsets[i]), column_id); + offsets[i] = total; + } + return total; +} + +/// Reads the strings with their lengths in a separate stream into a `ColumnString`. +ColumnString::MutablePtr readStrings( + IntRleDecoder & length_rle, InputByteStream & blob_stream, size_t num_values, const char * not_null, UInt64 column_id) +{ + /// The buffers grow as the data is decoded: a malformed count or length must not allocate memory + /// before the streams prove to contain the data. + static constexpr size_t MIN_STEP = 64 * 1024; + auto column = ColumnString::create(); + auto & offsets = column->getOffsets(); + UInt64 total = 0; + while (offsets.size() < num_values) + { + size_t done = offsets.size(); + size_t step = std::min(num_values - done, std::max(MIN_STEP, done)); + offsets.resize(done + step); + length_rle.next(offsets.data() + done, step, not_null ? not_null + done : nullptr); + total = lengthsToEndOffsets(offsets.data() + done, step, column_id, total); + } + auto & chars = column->getChars(); + while (chars.size() < total) + { + size_t done = chars.size(); + size_t step = std::min(total - done, std::max(MIN_STEP, done)); + chars.resize(done + step); + blob_stream.readBytes(reinterpret_cast(chars.data() + done), step); + } + return column; +} + +std::shared_ptr loadStringDictionary(UInt64 column_id, StripeStreams & stripe) +{ + const auto & encoding = stripe.getEncoding(column_id); + /// The dictionary is not bounded by the number of rows of the stripe: a column nested in a list or a map + /// can have more values than the stripe has rows. + UInt32 dictionary_size = encoding.dictionary_size; + + auto dictionary = std::make_shared(); + if (dictionary_size == 0) + { + dictionary->column = ColumnString::create(); + return dictionary; + } + + auto length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string dictionary"), false, getRleVersion(encoding)); + auto blob_stream = stripe.getStream(column_id, Proto::StreamKind::DICTIONARY_DATA); + if (!blob_stream) + { + /// All entries can be empty strings, then the stream is not needed. + blob_stream = std::make_unique(std::string_view{}, CompressionKind::NONE, 0, "empty dictionary"); + } + dictionary->column = readStrings(*length_rle, *blob_stream, dictionary_size, nullptr, column_id); + return dictionary; +} + +class StringDictionaryColumnReader final : public ColumnReader +{ +public: + StringDictionaryColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string dictionary"), + false, getRleVersion(stripe.getEncoding(column_id))); + dictionary = loadStringDictionary(column_id, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & string_batch = dynamic_cast(batch); + index.resize(num_values); + rle->next(index.data(), num_values, not_null); + string_batch.isEncoded = false; + string_batch.column = decodeDictionary(assert_cast(*dictionary->column), index.data(), not_null, num_values); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + readIndex(dynamic_cast(batch), num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + void readIndex(EncodedStringVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + batch.isEncoded = true; + batch.dictionary = dictionary; + batch.column = nullptr; + batch.index.resize(num_values); + rle->next(batch.index.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + std::shared_ptr dictionary; + std::unique_ptr rle; + PaddedPODArray index; +}; + +class StringDirectColumnReader final : public ColumnReader +{ +public: + StringDirectColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string"), + false, getRleVersion(stripe.getEncoding(column_id))); + blob_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string"); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + static constexpr size_t BUFFER_SIZE = 1024; + UInt64 buffer[BUFFER_SIZE]; + size_t done = 0; + size_t total_bytes = 0; + while (done < num_values) + { + size_t step = std::min(BUFFER_SIZE, num_values - done); + length_rle->next(buffer, step, nullptr); + total_bytes += lengthsToEndOffsets(buffer, step, column_id); + done += step; + } + blob_stream->skipBytes(total_bytes); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & string_batch = dynamic_cast(batch); + string_batch.isEncoded = false; + string_batch.column = readStrings(*length_rle, *blob_stream, num_values, batch.hasNulls ? batch.notNull.data() : nullptr, column_id); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + blob_stream->seek(provider); + length_rle->seek(provider); + } + +private: + std::unique_ptr length_rle; + std::unique_ptr blob_stream; +}; + +class TimestampColumnReader final : public ColumnReader +{ +public: + TimestampColumnReader(const Type & type, StripeStreams & stripe, bool is_instant) + : ColumnReader(type, stripe) + , writer_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getWriterTimezone()) + , reader_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getReaderTimezone()) + , same_timezone(&writer_timezone == &reader_timezone || writer_timezone.getTimeZone() == reader_timezone.getTimeZone()) + , writer_offset_of(writer_timezone) + , reader_offset_of(reader_timezone) + { + /// The base of the seconds is 2015-01-01 00:00:00 in the time zone of the writer. + static constexpr Int64 UTC_2015_01_01 = 1420070400; + epoch_offset = UTC_2015_01_01 - writer_timezone.timezoneOffset(UTC_2015_01_01); + + RleVersion version = getRleVersion(stripe.getEncoding(column_id)); + seconds_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "timestamp"), true, version); + nanos_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "timestamp"), false, version); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + seconds_rle->skip(num_values); + nanos_rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & timestamp_batch = typeid_cast(batch); + timestamp_batch.data.resize(num_values); + timestamp_batch.nanoseconds.resize(num_values); + Int64 * seconds = timestamp_batch.data.data(); + Int64 * nanos = timestamp_batch.nanoseconds.data(); + seconds_rle->next(seconds, num_values, not_null); + nanos_rle->next(nanos, num_values, not_null); + + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + + const Int64 encoded_nanos = nanos[i]; + /// The lowest 3 bits are the number of the trailing zeros (minus one) that are removed. + UInt64 zeros = nanos[i] & 0x7; + /// An arithmetic shift, as in the reference implementation: some writers (the Arrow + /// adapter) store negative nanoseconds for the timestamps before the epoch. + nanos[i] >>= 3; + if (zeros != 0 && common::mulOverflow(nanos[i], POWERS_OF_TEN_FOR_NANOS[zeros + 1], nanos[i])) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (nanos[i] < -999'999'999 || nanos[i] > 999'999'999) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + Int64 writer_time = 0; + if (common::addOverflow(seconds[i], epoch_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (writer_time < 0 && nanos[i] > 999999 && common::subOverflow(writer_time, Int64{1}, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + if (!same_timezone) + { + /// Keep the same wall clock time when the writer and the reader time zones differ. + Int64 writer_offset = writer_offset_of(writer_time); + Int64 reader_offset = reader_offset_of(writer_time); + if (writer_offset != reader_offset) + { + /// If the adjustment crosses a DST boundary, the offset has to be reevaluated. + Int64 adjusted_time = 0; + if (common::addOverflow(writer_time, writer_offset - reader_offset, adjusted_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + Int64 adjusted_reader_offset = reader_offset_of(adjusted_time); + if (common::addOverflow(writer_time, writer_offset - adjusted_reader_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + } + } + seconds[i] = writer_time; + } + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + seconds_rle->seek(provider); + nanos_rle->seek(provider); + } + +private: + static constexpr Int64 POWERS_OF_TEN_FOR_NANOS[9] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; + + [[noreturn]] void throwInvalidTimestamp(Int64 seconds, Int64 encoded_nanos) const + { + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid timestamp in ORC column {}: seconds={}, encoded nanoseconds={}", column_id, seconds, encoded_nanos); + } + + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + const bool same_timezone; + const TimezoneOffset writer_offset_of; + const TimezoneOffset reader_offset_of; + Int64 epoch_offset = 0; + std::unique_ptr seconds_rle; + std::unique_ptr nanos_rle; +}; + +constexpr UInt32 MAX_PRECISION_64 = 18; +constexpr UInt32 MAX_PRECISION_128 = 38; + +constexpr Int64 POWERS_OF_TEN[MAX_PRECISION_64 + 1] = { + 1LL, + 10LL, + 100LL, + 1000LL, + 10000LL, + 100000LL, + 1000000LL, + 10000000LL, + 100000000LL, + 1000000000LL, + 10000000000LL, + 100000000000LL, + 1000000000000LL, + 10000000000000LL, + 100000000000000LL, + 1000000000000000LL, + 10000000000000000LL, + 100000000000000000LL, + 1000000000000000000LL}; + +/// The DECIMAL columns: an unbounded signed varint per value in the DATA stream and the scale of +/// each value in the SECONDARY stream. The values are rescaled to the scale of the type. +class DecimalColumnReader : public ColumnReader +{ +public: + DecimalColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getPrecision() > MAX_PRECISION_128 || type.getScale() > MAX_PRECISION_128) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + value_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"); + scale_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "decimal"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + size_t skipped = 0; + while (skipped < num_values) + if (!(value_stream->readByte() & 0x80)) + ++skipped; + scale_decoder->skip(num_values); + return num_values; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + value_stream->seek(provider); + scale_decoder->seek(provider); + } + +protected: + /// Reads the zigzag-encoded varint of up to 128 bits. + Int128 readInt128() + { + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + if (shift < 128) + value |= static_cast(byte & 0x7F) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + return static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + } + + /// The scale of each value is read from the file. The valid scales are from 0 to 38, the bound + /// also keeps the differences of the scales and the rescaling work small. + Int32 getValueScale(Int64 value_scale) const + { + if (value_scale < -Int64(MAX_PRECISION_128) || value_scale > Int64(MAX_PRECISION_128)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", value_scale, column_id); + return static_cast(value_scale); + } + + static void scaleInt128(Int128 & value, Int32 target_scale, Int32 current_scale) + { + while (target_scale > current_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, target_scale - current_scale); + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[adjust])); + current_scale += adjust; + } + while (current_scale > target_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, current_scale - target_scale); + value /= POWERS_OF_TEN[adjust]; + current_scale -= adjust; + } + } + + const Int32 precision; + Int32 scale; + std::unique_ptr value_stream; + std::unique_ptr scale_decoder; + PaddedPODArray scales; +}; + +class Decimal64ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int64 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt64(getValueScale(scales[i])); + } + } + +private: + Int64 readInt64(Int32 current_scale) + { + UInt64 encoded = readVarint(*value_stream); + Int64 value = static_cast((encoded >> 1) ^ (~(encoded & 1) + 1)); + if (scale > current_scale && static_cast(scale - current_scale) <= MAX_PRECISION_64) + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[scale - current_scale])); + else if (scale < current_scale && static_cast(current_scale - scale) <= MAX_PRECISION_64) + value /= POWERS_OF_TEN[current_scale - scale]; + else if (scale != current_scale) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", current_scale, column_id); + return value; + } +}; + +class Decimal128ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt128(); + scaleInt128(values[i], scale, getValueScale(scales[i])); + } + } +}; + +/// The DECIMAL columns with the precision up to 18 in the files of the format version 1.9999 +/// (`UNSTABLE_PRE_2_0`): the unscaled values are signed RLEv2 integers in the DATA stream, +/// all with the scale of the type, and there is no SECONDARY stream. +class Decimal64V2ColumnReader final : public ColumnReader +{ +public: + Decimal64V2ColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getScale() > type.getPrecision()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + /// As in the reference implementation, RLEv2 is used regardless of the column encoding. + value_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"), true, RleVersion::V2); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + value_decoder->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & decimal_batch = typeid_cast(batch); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + value_decoder->next(decimal_batch.values.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + value_decoder->seek(positions.at(column_id)); + } + +private: + const Int32 precision; + const Int32 scale; + std::unique_ptr value_decoder; +}; + +/// The DECIMAL columns written by Hive 0.11, without the precision and the scale in the type. +/// As in the reference implementation, the values are read with the scale 6 and must have at most 38 digits. +class DecimalHive11ColumnReader final : public DecimalColumnReader +{ +public: + DecimalHive11ColumnReader(const Type & type, StripeStreams & stripe) + : DecimalColumnReader(type, stripe) + { + scale = 6; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + + static const Int128 max_value = Int128(10000000000000000000ULL) * Int128(10000000000000000000ULL) - 1; + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + bool overflow = false; + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + UInt32 bits = byte & 0x7F; + if (shift > 128 || (shift == 126 && bits > 3)) + overflow = true; + if (shift < 128) + value |= static_cast(bits) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + Int128 decoded = static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + if (!overflow) + { + scaleInt128(decoded, scale, getValueScale(scales[i])); + overflow = decoded > max_value || decoded < -max_value; + } + if (overflow) + throw Exception(ErrorCodes::INCORRECT_DATA, "Hive 0.11 decimal was more than 38 digits in ORC column {}", column_id); + values[i] = decoded; + } + } +}; + +class StructColumnReader final : public ColumnReader +{ +public: + StructColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + const auto & encoding = stripe.getEncoding(column_id); + if (encoding.kind != Proto::ColumnEncodingKind::DIRECT) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown encoding {} of ORC struct column {}", static_cast(encoding.kind), column_id); + const auto & selected = stripe.getSelectedColumns(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children.push_back(buildColumnReader(child, stripe)); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + for (auto & child : children) + child->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + for (auto & child : children) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & struct_batch = typeid_cast(batch); + for (size_t i = 0; i < children.size(); ++i) + { + if constexpr (encoded) + children[i]->nextEncoded(*struct_batch.fields[i], num_values, not_null); + else + children[i]->next(*struct_batch.fields[i], num_values, not_null); + } + } + + std::vector> children; +}; + +/// Reads the lengths of the lists or maps as the end offsets, returns the total number of the children. +UInt64 readListOffsets(IntRleDecoder & rle, ColumnPtr & result, size_t num_values, const char * not_null, UInt64 column_id) +{ + auto column = ColumnUInt64::create(num_values); + auto & offsets = column->getData(); + rle.next(offsets.data(), num_values, not_null); + UInt64 total = lengthsToEndOffsets(offsets.data(), num_values, column_id); + result = std::move(column); + return total; +} + +UInt64 sumLengths(IntRleDecoder & rle, size_t num_values, UInt64 column_id) +{ + static constexpr size_t BUFFER_SIZE = 1024; + Int64 buffer[BUFFER_SIZE]; + UInt64 total = 0; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + { + if (buffer[i] < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Negative length {} in ORC column {}", buffer[i], column_id); + total += static_cast(buffer[i]); + } + read += chunk; + } + return total; +} + +class ListColumnReader final : public ColumnReader +{ +public: + ListColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "list"), + false, getRleVersion(stripe.getEncoding(column_id))); + const Type & child_type = *type.getSubtype(0); + if (stripe.getSelectedColumns()[child_type.getColumnId()]) + child = buildColumnReader(child_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (child) + child->skip(sumLengths(*rle, num_values, column_id)); + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (child) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & list_batch = typeid_cast(batch); + const char * not_null = list_batch.hasNulls ? list_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, list_batch.offsets, num_values, not_null, column_id); + if (child) + { + if constexpr (encoded) + child->nextEncoded(*list_batch.elements, total, nullptr); + else + child->next(*list_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr child; +}; + +class MapColumnReader final : public ColumnReader +{ +public: + MapColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "map"), + false, getRleVersion(stripe.getEncoding(column_id))); + const auto & selected = stripe.getSelectedColumns(); + const Type & key_type = *type.getSubtype(0); + if (selected[key_type.getColumnId()]) + key_reader = buildColumnReader(key_type, stripe); + const Type & value_type = *type.getSubtype(1); + if (selected[value_type.getColumnId()]) + value_reader = buildColumnReader(value_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (key_reader || value_reader) + { + UInt64 total = sumLengths(*rle, num_values, column_id); + if (key_reader) + key_reader->skip(total); + if (value_reader) + value_reader->skip(total); + } + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (key_reader) + key_reader->seekToRowGroup(positions); + if (value_reader) + value_reader->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & map_batch = typeid_cast(batch); + const char * not_null = map_batch.hasNulls ? map_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, map_batch.offsets, num_values, not_null, column_id); + if (key_reader) + { + if constexpr (encoded) + key_reader->nextEncoded(*map_batch.keys, total, nullptr); + else + key_reader->next(*map_batch.keys, total, nullptr); + } + if (value_reader) + { + if constexpr (encoded) + value_reader->nextEncoded(*map_batch.elements, total, nullptr); + else + value_reader->next(*map_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr key_reader; + std::unique_ptr value_reader; +}; + +class UnionColumnReader final : public ColumnReader +{ +public: + UnionColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "union")) + , num_children(type.getSubtypeCount()) + { + children.resize(num_children); + counts.resize(num_children); + const auto & selected = stripe.getSelectedColumns(); + for (size_t i = 0; i < num_children; ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children[i] = buildColumnReader(child, stripe); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + std::fill(counts.begin(), counts.end(), 0); + static constexpr size_t BUFFER_SIZE = 1024; + char buffer[BUFFER_SIZE]; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + ++counts[checkedTag(static_cast(buffer[i]))]; + read += chunk; + } + for (size_t i = 0; i < num_children; ++i) + if (counts[i] && children[i]) + children[i]->skip(counts[i]); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + for (auto & child : children) + if (child) + child->seekToRowGroup(positions); + } + +private: + size_t checkedTag(UInt8 tag) const + { + if (tag >= num_children) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid union tag {} for union with {} children in ORC column {}", static_cast(tag), num_children, column_id); + return tag; + } + + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & union_batch = typeid_cast(batch); + const char * not_null = union_batch.hasNulls ? union_batch.notNull.data() : nullptr; + union_batch.tags.resize(num_values); + union_batch.offsets.resize(num_values); + UInt8 * tags = union_batch.tags.data(); + UInt64 * offsets = union_batch.offsets.data(); + memset(tags, 0, num_values); + rle.next(reinterpret_cast(tags), num_values, not_null); + std::fill(counts.begin(), counts.end(), 0); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + offsets[i] = counts[checkedTag(tags[i])]++; + } + for (size_t i = 0; i < num_children; ++i) + { + if (!children[i]) + continue; + if constexpr (encoded) + children[i]->nextEncoded(*union_batch.children[i], counts[i], nullptr); + else + children[i]->next(*union_batch.children[i], counts[i], nullptr); + } + } + + ByteRleDecoder rle; + const size_t num_children; + std::vector> children; + std::vector counts; +}; + +} + + +ColumnReader::ColumnReader(const Type & type, StripeStreams & stripe) + : column_id(type.getColumnId()) +{ + if (auto stream = stripe.getStream(column_id, Proto::StreamKind::PRESENT)) + not_null_decoder = std::make_unique(std::move(stream)); +} + +void ColumnReader::next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) +{ + batch.reset(num_values); + + if (not_null_decoder) + { + char * not_null = batch.notNull.data(); + not_null_decoder->next(not_null, num_values, incoming_mask); + batch.hasNulls = memchr(not_null, 0, num_values) != nullptr; + return; + } + if (incoming_mask) + { + batch.hasNulls = true; + memcpy(batch.notNull.data(), incoming_mask, num_values); + return; + } + batch.hasNulls = false; +} + +size_t ColumnReader::skip(size_t num_values) +{ + if (!not_null_decoder) + return num_values; + + static constexpr size_t BUFFER_SIZE = 32768; + char buffer[BUFFER_SIZE]; + size_t remaining = num_values; + while (remaining) + { + size_t chunk = std::min(remaining, BUFFER_SIZE); + not_null_decoder->next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + if (!buffer[i]) + --num_values; + remaining -= chunk; + } + return num_values; +} + +void ColumnReader::seekToRowGroup(std::unordered_map & positions) +{ + if (not_null_decoder) + { + auto it = positions.find(column_id); + if (it == positions.end()) + throw Exception(ErrorCodes::INCORRECT_DATA, "No row index for ORC column {}", column_id); + not_null_decoder->seek(it->second); + } +} + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, stripe); + case BYTE: + return std::make_unique(type, stripe); + case SHORT: + return std::make_unique>(type, stripe); + case INT: + return std::make_unique>(type, stripe); + case LONG: + case DATE: + return std::make_unique>(type, stripe); + case FLOAT: + return std::make_unique>(type, stripe); + case DOUBLE: + return std::make_unique>(type, stripe); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + switch (stripe.getEncoding(type.getColumnId()).kind) + { + case Proto::ColumnEncodingKind::DICTIONARY: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return std::make_unique(type, stripe); + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DIRECT_V2: + return std::make_unique(type, stripe); + } + break; + case TIMESTAMP: + return std::make_unique(type, stripe, false); + case TIMESTAMP_INSTANT: + return std::make_unique(type, stripe, true); + case DECIMAL: + if (type.getPrecision() == 0) + return std::make_unique(type, stripe); + if (type.getPrecision() <= MAX_PRECISION_64) + { + if (stripe.isDecimalAsLong()) + return std::make_unique(type, stripe); + return std::make_unique(type, stripe); + } + return std::make_unique(type, stripe); + case STRUCT: + return std::make_unique(type, stripe); + case LIST: + return std::make_unique(type, stripe); + case MAP: + return std::make_unique(type, stripe); + case UNION: + return std::make_unique(type, stripe); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Reading ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.h b/src/Processors/Formats/Impl/ORC/ColumnReader.h new file mode 100644 index 000000000000..1abaedb6fff5 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +/// Access to the streams of one stripe for the column readers. +class StripeStreams +{ +public: + virtual ~StripeStreams() = default; + + virtual const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const = 0; + /// Returns nullptr if the stripe does not have this stream. + virtual std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const = 0; + virtual const std::vector & getSelectedColumns() const = 0; + /// The time zones for TIMESTAMP (not TIMESTAMP_INSTANT) columns. + virtual const DateLUTImpl & getWriterTimezone() const = 0; + virtual const DateLUTImpl & getReaderTimezone() const = 0; + virtual UInt64 getNumberOfRows() const = 0; + /// Whether the file has the format version 1.9999 (`UNSTABLE_PRE_2_0` in the reference implementation), + /// where DECIMAL columns with the precision up to 18 are written as signed RLEv2 integers in the DATA stream + /// without the SECONDARY stream of scales. + virtual bool isDecimalAsLong() const = 0; +}; + +class ColumnReader +{ +public: + ColumnReader(const Type & type, StripeStreams & stripe); + virtual ~ColumnReader() = default; + + /// Reads the next `num_values` values into `batch`. `incoming_mask` is the mask of the + /// non-null values of the parent (or nullptr). + virtual void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask); + + /// Same, but the string columns with dictionary encoding fill `EncodedStringVectorBatch` + /// without decoding the dictionary. + virtual void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + next(batch, num_values, incoming_mask); + } + + /// Skips `num_values` values, returns the number of the skipped non-null values. + virtual size_t skip(size_t num_values); + + /// Moves to the beginning of a row group, by the positions from the row indexes of the columns. + virtual void seekToRowGroup(std::unordered_map & positions); + +protected: + const UInt64 column_id; + std::unique_ptr not_null_decoder; +}; + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe); + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.cpp b/src/Processors/Formats/Impl/ORC/Compression.cpp new file mode 100644 index 000000000000..cfacdc431ca8 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.cpp @@ -0,0 +1,437 @@ +#include + +#include + +#include +#include +#include +/// For `ZSTD_decompressBound`, which is not in the stable ABI of zstd. It is safe, as zstd is linked statically from contrib. +#define ZSTD_STATIC_LINKING_ONLY +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int CANNOT_COMPRESS; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +[[noreturn]] void throwMalformedLzo(size_t offset) +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed LZO-compressed data in ORC file at offset {}", offset); +} + +/// LZO1X decompressor, as written by the Hadoop codecs (and the ORC Java writer). A chunk can be a +/// concatenation of several LZO blocks, each terminated with the end-of-stream marker. +size_t decompressLzo(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + const UInt8 * input = reinterpret_cast(src); + const UInt8 * const input_begin = input; + const UInt8 * const input_end = input + src_size; + char * output = dst; + char * const output_end = dst + dst_capacity; + + auto offset = [&] { return static_cast(input - input_begin); }; + + auto read_byte = [&]() -> UInt32 + { + if (input >= input_end) + throwMalformedLzo(offset()); + return *input++; + }; + + /// A run of zero bytes extends a length by 255 each, then the next byte is added. + auto read_variable_length = [&](UInt32 base) -> size_t + { + size_t length = base; + UInt32 next = 0; + while ((next = read_byte()) == 0) + { + length += 0xFF; + if (length > dst_capacity) + throwMalformedLzo(offset()); + } + return length + next; + }; + + while (input < input_end) + { + bool first_command = true; + size_t last_literal_length = 0; + + while (true) + { + UInt32 command = read_byte(); + if (command == 0x11) + break; + + size_t match_length = 0; + size_t match_offset = 0; + size_t literal_length = 0; + + if ((command & 0xF0) == 0) + { + if (last_literal_length == 0) + { + /// A long run of literals. + literal_length = command & 0xF; + if (literal_length == 0) + literal_length = read_variable_length(0xF); + literal_length += 3; + } + else if (last_literal_length <= 3) + { + match_length = 3; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + match_offset |= 0x800; + literal_length = command & 0x3; + } + else + { + match_length = 2; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + literal_length = command & 0x3; + } + } + else if (first_command) + { + literal_length = command - 17; + } + else if ((command & 0xF0) == 0x10) + { + match_length = command & 0x7; + if (match_length == 0) + match_length = read_variable_length(0x7); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + match_offset |= (command & 0x8) ? 0x8000 : 0x4000; + --match_offset; + literal_length = trailer & 0x3; + } + else if ((command & 0xE0) == 0x20) + { + match_length = command & 0x1F; + if (match_length == 0) + match_length = read_variable_length(0x1F); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + literal_length = trailer & 0x3; + } + else if ((command & 0xC0) != 0) + { + match_length = ((command & 0xE0) >> 5) + 1; + match_offset = (command & 0x1C) >> 2; + match_offset |= read_byte() << 3; + literal_length = command & 0x3; + } + else + throwMalformedLzo(offset()); + + first_command = false; + + if (match_length != 0) + { + /// LZO encodes the match offset minus one. + ++match_offset; + if (match_offset > static_cast(output - dst) || match_length > static_cast(output_end - output)) + throwMalformedLzo(offset()); + const char * match = output - match_offset; + /// The source can overlap the destination, so copy byte by byte. + for (size_t i = 0; i < match_length; ++i) + output[i] = match[i]; + output += match_length; + } + + if (literal_length > static_cast(output_end - output) || literal_length > static_cast(input_end - input)) + throwMalformedLzo(offset()); + memcpy(output, input, literal_length); + output += literal_length; + input += literal_length; + last_literal_length = literal_length; + } + + /// The end-of-stream marker is 0x11 0x00 0x00. + if (input_end - input < 2 || input[0] != 0 || input[1] != 0) + throwMalformedLzo(offset()); + input += 2; + } + + return output - dst; +} + +size_t decompressZlib(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + z_stream stream{}; + if (inflateInit2(&stream, -15) != Z_OK) + throw Exception(ErrorCodes::INCORRECT_DATA, "Cannot initialize zlib decompression for ORC file"); + + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(dst); + stream.avail_out = static_cast(dst_capacity); + + int ret = inflate(&stream, Z_FINISH); + size_t result = dst_capacity - stream.avail_out; + inflateEnd(&stream); + + if (ret != Z_STREAM_END) + { + if (ret == Z_BUF_ERROR && stream.avail_out == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A zlib-compressed chunk of ORC file decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zlib-compressed data in ORC file (zlib error {})", ret); + } + return result; +} + +size_t decompressSnappy(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + if (uncompressed_size > dst_capacity) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A snappy-compressed chunk of ORC file decompresses to {} bytes, more than the {} bytes allowed for the chunk", + uncompressed_size, dst_capacity); + if (!snappy::RawUncompress(src, src_size, dst)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + return uncompressed_size; +} + +size_t decompressLz4(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + if (src_size > static_cast(std::numeric_limits::max()) || dst_capacity > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "LZ4-compressed chunk of ORC file is too large"); + int res = LZ4_decompress_safe(src, dst, static_cast(src_size), static_cast(dst_capacity)); + if (res < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed LZ4-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + return static_cast(res); +} + +size_t decompressZstd(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t res = ZSTD_decompress(dst, dst_capacity, src, src_size); + if (ZSTD_isError(res)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed zstd-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk: {}", + dst_capacity, ZSTD_getErrorName(res)); + return res; +} + + +class ZlibCompressor final : public Compressor +{ +public: + ZlibCompressor() + { + /// The level and the parameters are the same as in the C++ ORC library with its default + /// compression strategy, "speed". + if (deflateInit2(&stream, Z_BEST_SPEED + 1, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot initialize zlib compression for ORC"); + } + + ~ZlibCompressor() override { deflateEnd(&stream); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + if (deflateReset(&stream) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot reset zlib compression for ORC"); + + size_t old_size = out.size(); + /// Allow only the output smaller than the input. + out.resize(old_size + src_size); + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(out.data() + old_size); + stream.avail_out = static_cast(src_size); + + int ret = deflate(&stream, Z_FINISH); + if (ret == Z_STREAM_END && stream.avail_out > 0) + { + size_t compressed = src_size - stream.avail_out; + out.resize(old_size + compressed); + return compressed; + } + out.resize(old_size); + if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zlib compression failed with error {}", ret); + return 0; + } + +private: + z_stream stream{}; +}; + +class SnappyCompressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + out.resize(old_size + snappy::MaxCompressedLength(src_size)); + size_t compressed = 0; + snappy::RawCompress(src, src_size, out.data() + old_size, &compressed); + return finish(out, old_size, compressed, src_size); + } + + static size_t finish(std::string & out, size_t old_size, size_t compressed, size_t src_size) + { + if (compressed >= src_size) + { + out.resize(old_size); + return 0; + } + out.resize(old_size + compressed); + return compressed; + } +}; + +class Lz4Compressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + int bound = LZ4_compressBound(static_cast(src_size)); + out.resize(old_size + bound); + int compressed = LZ4_compress_default(src, out.data() + old_size, static_cast(src_size), bound); + if (compressed <= 0) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "LZ4 compression failed"); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } +}; + +class ZstdCompressor final : public Compressor +{ +public: + ZstdCompressor() : context(ZSTD_createCCtx()) + { + if (!context) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot create zstd compression context"); + } + + ~ZstdCompressor() override { ZSTD_freeCCtx(context); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + size_t bound = ZSTD_compressBound(src_size); + out.resize(old_size + bound); + /// Level 1, as in the C++ ORC library with its default compression strategy, "speed". + size_t compressed = ZSTD_compressCCtx(context, out.data() + old_size, bound, src, src_size, 1); + if (ZSTD_isError(compressed)) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zstd compression failed: {}", ZSTD_getErrorName(compressed)); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } + +private: + ZSTD_CCtx * context; +}; + +} + + +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size) +{ + /// The ratios are the theoretical maximums of the formats, rounded up, so that valid chunks are never rejected. + /// The sizes stored in the chunks are only trusted below these bounds. + static constexpr size_t SLACK = 1024; + switch (kind) + { + case CompressionKind::NONE: + return src_size; + case CompressionKind::SNAPPY: + { + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + /// A copy of 64 bytes takes at least 3 bytes. + return std::min(uncompressed_size, src_size * 22 + SLACK); + } + case CompressionKind::ZSTD: + { + /// Sums the content sizes of all frames, or 128 KiB per block when a frame omits its size, as in `ArrowIPC/BufferCompression.cpp`. + UInt64 bound = ZSTD_decompressBound(src, src_size); + if (bound == ZSTD_CONTENTSIZE_ERROR) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zstd-compressed data in ORC file"); + /// A block of at most 128 KiB takes at least 4 bytes (an RLE block). + return std::min(bound, src_size * 32768 + SLACK); + } + /// A deflate match of 258 bytes takes at least 2 bits. + case CompressionKind::ZLIB: + return src_size * 1032 + SLACK; + /// Every byte of a match length extension adds at most 255 bytes. + case CompressionKind::LZ4: + case CompressionKind::LZO: + return src_size * 256 + SLACK; + default: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + switch (kind) + { + case CompressionKind::ZLIB: return decompressZlib(src, src_size, dst, dst_capacity); + case CompressionKind::SNAPPY: return decompressSnappy(src, src_size, dst, dst_capacity); + case CompressionKind::LZO: return decompressLzo(src, src_size, dst, dst_capacity); + case CompressionKind::LZ4: return decompressLz4(src, src_size, dst, dst_capacity); + case CompressionKind::ZSTD: return decompressZstd(src, src_size, dst, dst_capacity); + case CompressionKind::NONE: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +std::unique_ptr createCompressor(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return nullptr; + case CompressionKind::ZLIB: return std::make_unique(); + case CompressionKind::SNAPPY: return std::make_unique(); + case CompressionKind::LZ4: return std::make_unique(); + case CompressionKind::ZSTD: return std::make_unique(); + case CompressionKind::LZO: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC with compression {} is not supported", compressionKindToString(kind)); +} + +String compressionKindToString(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return "NONE"; + case CompressionKind::ZLIB: return "ZLIB"; + case CompressionKind::SNAPPY: return "SNAPPY"; + case CompressionKind::LZO: return "LZO"; + case CompressionKind::LZ4: return "LZ4"; + case CompressionKind::ZSTD: return "ZSTD"; + case CompressionKind::BROTLI: return "BROTLI"; + } + return "UNKNOWN(" + std::to_string(static_cast(kind)) + ")"; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.h b/src/Processors/Formats/Impl/ORC/Compression.h new file mode 100644 index 000000000000..7e0ceddb72a7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include +#include + +namespace DB::ORC +{ + +using Proto::CompressionKind; + +/// Every compressed chunk of an ORC stream is prefixed with a 3-byte little-endian header: +/// `(chunk_length << 1) | is_original`, where `is_original` means the chunk is stored as is. +static constexpr size_t COMPRESSION_HEADER_SIZE = 3; + +/// Decompresses one chunk into `dst`, which has room for `dst_capacity` bytes (the compression block +/// size of the file). Returns the decompressed size. Throws `INCORRECT_DATA` on malformed input, +/// including a chunk that decompresses to more than `dst_capacity` bytes. +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity); + +/// An upper bound of the decompressed size of a chunk, from the maximum compression ratio of the codec +/// (and the size stored in the chunk), to avoid allocating the whole compression block for a small chunk. +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size); + +/// Compresses chunks of an ORC stream. +class Compressor +{ +public: + virtual ~Compressor() = default; + + /// Appends the compressed representation of `src` to `out` and returns its size, + /// or appends nothing and returns 0 if it would not be smaller than the input. + virtual size_t compress(const char * src, size_t src_size, std::string & out) = 0; +}; + +/// Returns nullptr for `NONE`. +std::unique_ptr createCompressor(CompressionKind kind); + +String compressionKindToString(CompressionKind kind); + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.cpp b/src/Processors/Formats/Impl/ORC/Proto.cpp new file mode 100644 index 000000000000..19e504dfd365 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.cpp @@ -0,0 +1,944 @@ +#include + +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC::Proto +{ + +void WireReader::check(size_t n) const +{ + if (static_cast(end - pos) < n) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated protobuf message in ORC metadata"); +} + +UInt64 WireReader::readVarint() +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + check(1); + UInt8 byte = static_cast(*pos++); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC metadata"); +} + +UInt64 WireReader::readFixed64() +{ + check(8); + UInt64 v = 0; + memcpy(&v, pos, 8); + pos += 8; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +UInt32 WireReader::readFixed32() +{ + check(4); + UInt32 v = 0; + memcpy(&v, pos, 4); + pos += 4; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +double WireReader::readDouble() +{ + return std::bit_cast(readFixed64()); +} + +std::string_view WireReader::readBytes() +{ + UInt64 size = readVarint(); + check(size); + std::string_view res(pos, size); + pos += size; + return res; +} + +bool WireReader::nextField(UInt32 & field_number, WireType & wire_type) +{ + if (pos == end) + return false; + UInt64 key = readVarint(); + field_number = static_cast(key >> 3); + wire_type = static_cast(key & 7); + if (field_number == 0 || (key >> 3) > std::numeric_limits::max()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed field key in ORC metadata"); + return true; +} + +void WireReader::skip(WireType wire_type) +{ + switch (wire_type) + { + case VARINT: readVarint(); return; + case FIXED64: check(8); pos += 8; return; + case LENGTH_DELIMITED: readBytes(); return; + case FIXED32: check(4); pos += 4; return; + case START_GROUP: + case END_GROUP: + break; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unsupported protobuf wire type {} in ORC metadata", static_cast(wire_type)); +} + +bool WireReader::readRepeatedVarint(WireType wire_type, std::vector & out) +{ + if (wire_type == LENGTH_DELIMITED) + { + WireReader packed(readBytes()); + while (packed.pos != packed.end) + out.push_back(packed.readVarint()); + return true; + } + if (wire_type == VARINT) + { + out.push_back(readVarint()); + return true; + } + return false; +} + + +void WireWriter::appendRawVarint(std::string & s, UInt64 value) +{ + while (value >= 0x80) + { + s.push_back(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + s.push_back(static_cast(value)); +} + +void WireWriter::writeVarint(UInt32 field, UInt64 value) +{ + writeKey(field, WireReader::VARINT); + appendRawVarint(out, value); +} + +void WireWriter::writeDouble(UInt32 field, double value) +{ + writeKey(field, WireReader::FIXED64); + UInt64 v = std::bit_cast(value); + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + out.append(reinterpret_cast(&v), 8); +} + +void WireWriter::writeBytes(UInt32 field, std::string_view value) +{ + writeKey(field, WireReader::LENGTH_DELIMITED); + appendRawVarint(out, value.size()); + out.append(value); +} + +void WireWriter::writePackedVarint(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + appendRawVarint(packed, v); + writeBytes(field, packed); +} + +void WireWriter::writePackedFixed64(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + { + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + packed.append(reinterpret_cast(&v), 8); + } + writeBytes(field, packed); +} + + +namespace +{ + +using WireType = WireReader::WireType; + +/// A field with an unexpected wire type is an unknown field, which the Protocol Buffers rules +/// require to skip. It is detected before anything is read, and handled in `parseMessage`. +struct WireTypeMismatch : std::exception +{ +}; + +void expectWireType(WireType actual, WireType expected) +{ + if (actual != expected) + throw WireTypeMismatch{}; +} + +UInt64 readVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readVarint(); +} + +Int64 readSignedVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readSignedVarint(); +} + +UInt32 readUInt32Field(WireReader & r, WireType t) +{ + /// Protobuf truncates the 64-bit varint for 32-bit fields. + return static_cast(readVarintField(r, t)); +} + +/// For `sint32` fields. +Int32 readSignedVarint32Field(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + UInt32 v = static_cast(r.readVarint()); + return static_cast((v >> 1) ^ (~(v & 1) + 1)); +} + +double readDoubleField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::FIXED64); + return r.readDouble(); +} + +std::string_view readBytesField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::LENGTH_DELIMITED); + return r.readBytes(); +} + +void checkCount(size_t count, size_t max_count, std::string_view what) +{ + if (count >= max_count) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many {} in ORC metadata, at most {} expected", what, max_count); +} + +template +void parseMessage(std::string_view data, F && handle_field) +{ + WireReader r(data); + UInt32 field = 0; + WireType type = WireReader::VARINT; + while (r.nextField(field, type)) + { + bool handled = false; + try + { + handled = handle_field(r, field, type); + } + catch (const WireTypeMismatch &) + { + handled = false; + } + if (!handled) + r.skip(type); + } +} + +IntegerStatistics parseIntegerStatistics(std::string_view data) +{ + IntegerStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +DoubleStatistics parseDoubleStatistics(std::string_view data) +{ + DoubleStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readDoubleField(r, type); return true; + case 2: res.maximum = readDoubleField(r, type); return true; + case 3: res.sum = readDoubleField(r, type); return true; + default: return false; + } + }); + return res; +} + +StringStatistics parseStringStatistics(std::string_view data) +{ + StringStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + case 4: res.lower_bound = std::string(readBytesField(r, type)); return true; + case 5: res.upper_bound = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +BucketStatistics parseBucketStatistics(std::string_view data) +{ + BucketStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + return r.readRepeatedVarint(type, res.count); + }); + return res; +} + +DecimalStatistics parseDecimalStatistics(std::string_view data) +{ + DecimalStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +DateStatistics parseDateStatistics(std::string_view data) +{ + DateStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarint32Field(r, type); return true; + case 2: res.maximum = readSignedVarint32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +TimestampStatistics parseTimestampStatistics(std::string_view data) +{ + TimestampStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.minimum_utc = readSignedVarintField(r, type); return true; + case 4: res.maximum_utc = readSignedVarintField(r, type); return true; + case 5: res.minimum_nanos = readVarintField(r, type); return true; + case 6: res.maximum_nanos = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +BinaryStatistics parseBinaryStatistics(std::string_view data) +{ + BinaryStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + res.sum = readSignedVarintField(r, type); + return true; + }); + return res; +} + +CollectionStatistics parseCollectionStatistics(std::string_view data) +{ + CollectionStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.min_children = readVarintField(r, type); return true; + case 2: res.max_children = readVarintField(r, type); return true; + case 3: res.total_children = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +Stream parseStream(std::string_view data) +{ + Stream res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: res.column = readUInt32Field(r, type); return true; + case 3: res.length = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +ColumnEncoding parseColumnEncoding(std::string_view data) +{ + ColumnEncoding res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: + { + UInt32 kind = readUInt32Field(r, type); + if (kind > static_cast(ColumnEncodingKind::DICTIONARY_V2)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding kind {}", kind); + res.kind = static_cast(kind); + return true; + } + case 2: res.dictionary_size = readUInt32Field(r, type); return true; + case 3: res.bloom_encoding = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +Type parseType(std::string_view data) +{ + Type res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: return r.readRepeatedVarint(type, res.subtypes); + case 3: res.field_names.emplace_back(readBytesField(r, type)); return true; + case 4: res.maximum_length = readUInt32Field(r, type); return true; + case 5: res.precision = readUInt32Field(r, type); return true; + case 6: res.scale = readUInt32Field(r, type); return true; + case 7: + { + StringPair pair; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: pair.key = std::string(readBytesField(rr, t)); return true; + case 2: pair.value = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + res.attributes.push_back(std::move(pair)); + return true; + } + case 8: res.crs = std::string(readBytesField(r, type)); return true; + case 9: res.algorithm = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +StripeInformation parseStripeInformation(std::string_view data) +{ + StripeInformation res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.offset = readVarintField(r, type); return true; + case 2: res.index_length = readVarintField(r, type); return true; + case 3: res.data_length = readVarintField(r, type); return true; + case 4: res.footer_length = readVarintField(r, type); return true; + case 5: res.number_of_rows = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +UserMetadataItem parseUserMetadataItem(std::string_view data) +{ + UserMetadataItem res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.name = std::string(readBytesField(r, type)); return true; + case 2: res.value = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +std::string serializeIntegerStatistics(const IntegerStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + return out; +} + +std::string serializeDoubleStatistics(const DoubleStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeDouble(1, *s.minimum); + if (s.maximum) w.writeDouble(2, *s.maximum); + if (s.sum) w.writeDouble(3, *s.sum); + return out; +} + +std::string serializeStringStatistics(const StringStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + if (s.lower_bound) w.writeBytes(4, *s.lower_bound); + if (s.upper_bound) w.writeBytes(5, *s.upper_bound); + return out; +} + +std::string serializeDecimalStatistics(const DecimalStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeBytes(3, *s.sum); + return out; +} + +std::string serializeDateStatistics(const DateStatistics & s) +{ + std::string out; + WireWriter w(out); + auto zigzag32 = [](Int32 v) { return static_cast((static_cast(v) << 1) ^ static_cast(v >> 31)); }; + if (s.minimum) w.writeVarint(1, zigzag32(*s.minimum)); + if (s.maximum) w.writeVarint(2, zigzag32(*s.maximum)); + return out; +} + +std::string serializeTimestampStatistics(const TimestampStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.minimum_utc) w.writeSignedVarint(3, *s.minimum_utc); + if (s.maximum_utc) w.writeSignedVarint(4, *s.maximum_utc); + /// `int32` fields: negative values are sign-extended to 64 bits. + if (s.minimum_nanos) w.writeVarint(5, *s.minimum_nanos); + if (s.maximum_nanos) w.writeVarint(6, *s.maximum_nanos); + return out; +} + +std::string serializeCollectionStatistics(const CollectionStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.min_children) w.writeVarint(1, *s.min_children); + if (s.max_children) w.writeVarint(2, *s.max_children); + if (s.total_children) w.writeVarint(3, *s.total_children); + return out; +} + +std::string serializeType(const Type & t) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, t.kind); + w.writePackedVarint(2, t.subtypes); + for (const auto & name : t.field_names) + w.writeBytes(3, name); + if (t.maximum_length) w.writeVarint(4, *t.maximum_length); + if (t.precision) w.writeVarint(5, *t.precision); + if (t.scale) w.writeVarint(6, *t.scale); + for (const auto & attr : t.attributes) + { + std::string pair; + WireWriter pw(pair); + pw.writeBytes(1, attr.key); + pw.writeBytes(2, attr.value); + w.writeBytes(7, pair); + } + if (t.crs) w.writeBytes(8, *t.crs); + if (t.algorithm) w.writeVarint(9, *t.algorithm); + return out; +} + +std::string serializeStripeInformation(const StripeInformation & s) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, s.offset); + w.writeVarint(2, s.index_length); + w.writeVarint(3, s.data_length); + w.writeVarint(4, s.footer_length); + w.writeVarint(5, s.number_of_rows); + return out; +} + +} + + +void PostScript::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: footer_length = readVarintField(r, type); return true; + case 2: + { + UInt64 kind = readVarintField(r, type); + if (kind > static_cast(CompressionKind::BROTLI)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC compression kind {}", kind); + compression = static_cast(kind); + return true; + } + case 3: compression_block_size = readVarintField(r, type); return true; + case 4: return r.readRepeatedVarint(type, version); + case 5: metadata_length = readVarintField(r, type); return true; + case 6: writer_version = readUInt32Field(r, type); return true; + case 8000: magic = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string PostScript::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, footer_length); + w.writeVarint(2, static_cast(compression)); + w.writeVarint(3, compression_block_size); + w.writePackedVarint(4, version); + w.writeVarint(5, metadata_length); + w.writeVarint(6, writer_version); + w.writeBytes(8000, magic); + return out; +} + +void ColumnStatistics::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: number_of_values = readVarintField(r, type); return true; + case 2: int_statistics = parseIntegerStatistics(readBytesField(r, type)); return true; + case 3: double_statistics = parseDoubleStatistics(readBytesField(r, type)); return true; + case 4: string_statistics = parseStringStatistics(readBytesField(r, type)); return true; + case 5: bucket_statistics = parseBucketStatistics(readBytesField(r, type)); return true; + case 6: decimal_statistics = parseDecimalStatistics(readBytesField(r, type)); return true; + case 7: date_statistics = parseDateStatistics(readBytesField(r, type)); return true; + case 8: binary_statistics = parseBinaryStatistics(readBytesField(r, type)); return true; + case 9: timestamp_statistics = parseTimestampStatistics(readBytesField(r, type)); return true; + case 10: has_null = readVarintField(r, type) != 0; return true; + case 11: bytes_on_disk = readVarintField(r, type); return true; + case 12: collection_statistics = parseCollectionStatistics(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string ColumnStatistics::serialize() const +{ + std::string out; + WireWriter w(out); + if (number_of_values) w.writeVarint(1, *number_of_values); + if (int_statistics) w.writeBytes(2, serializeIntegerStatistics(*int_statistics)); + if (double_statistics) w.writeBytes(3, serializeDoubleStatistics(*double_statistics)); + if (string_statistics) w.writeBytes(4, serializeStringStatistics(*string_statistics)); + if (bucket_statistics) + { + std::string bucket; + WireWriter(bucket).writePackedVarint(1, bucket_statistics->count); + w.writeBytes(5, bucket); + } + if (decimal_statistics) w.writeBytes(6, serializeDecimalStatistics(*decimal_statistics)); + if (date_statistics) w.writeBytes(7, serializeDateStatistics(*date_statistics)); + if (binary_statistics) + { + std::string binary; + if (binary_statistics->sum) + WireWriter(binary).writeSignedVarint(1, *binary_statistics->sum); + w.writeBytes(8, binary); + } + if (timestamp_statistics) w.writeBytes(9, serializeTimestampStatistics(*timestamp_statistics)); + if (has_null) w.writeVarint(10, *has_null); + if (bytes_on_disk) w.writeVarint(11, *bytes_on_disk); + if (collection_statistics) w.writeBytes(12, serializeCollectionStatistics(*collection_statistics)); + return out; +} + +void RowIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view entry_data = readBytesField(r, type); + checkCount(entry.size(), max_entries, "row index entries"); + auto & e = entry.emplace_back(); + parseMessage(entry_data, [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: return rr.readRepeatedVarint(t, e.positions); + case 2: e.statistics.emplace().parse(readBytesField(rr, t)); return true; + default: return false; + } + }); + return true; + }); +} + +std::string RowIndex::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & e : entry) + { + std::string entry_data; + WireWriter ew(entry_data); + ew.writePackedVarint(1, e.positions); + if (e.statistics) + ew.writeBytes(2, e.statistics->serialize()); + w.writeBytes(1, entry_data); + } + return out; +} + +void BloomFilterIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + checkCount(bloom_filter.size(), max_entries, "bloom filters"); + BloomFilter bf; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: bf.num_hash_functions = readUInt32Field(rr, t); return true; + case 2: + { + if (t == WireReader::LENGTH_DELIMITED) + { + /// Packed fixed64: a sequence of 8-byte little-endian values. + std::string_view bytes = rr.readBytes(); + if (bytes.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed bloom filter bitset in ORC file"); + WireReader packed(bytes); + for (size_t i = 0; i < bytes.size() / 8; ++i) + bf.bitset.push_back(packed.readFixed64()); + } + else + { + expectWireType(t, WireReader::FIXED64); + bf.bitset.push_back(rr.readFixed64()); + } + return true; + } + case 3: bf.utf8bitset = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + bloom_filter.push_back(std::move(bf)); + return true; + }); +} + +void StripeFooter::parse(std::string_view data, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: streams.push_back(parseStream(readBytesField(r, type))); return true; + case 2: + { + std::string_view encoding_data = readBytesField(r, type); + checkCount(columns.size(), max_columns, "column encodings"); + columns.push_back(parseColumnEncoding(encoding_data)); + return true; + } + case 3: writer_timezone = std::string(readBytesField(r, type)); return true; + case 4: readBytesField(r, type); ++encryption_variants; return true; + default: return false; + } + }); +} + +std::string StripeFooter::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & s : streams) + { + std::string stream; + WireWriter sw(stream); + if (s.kind) + sw.writeVarint(1, *s.kind); + sw.writeVarint(2, s.column); + sw.writeVarint(3, s.length); + w.writeBytes(1, stream); + } + for (const auto & c : columns) + { + std::string encoding; + WireWriter ew(encoding); + ew.writeVarint(1, static_cast(c.kind)); + if (c.kind == ColumnEncodingKind::DICTIONARY || c.kind == ColumnEncodingKind::DICTIONARY_V2) + ew.writeVarint(2, c.dictionary_size); + w.writeBytes(2, encoding); + } + if (writer_timezone) + w.writeBytes(3, *writer_timezone); + return out; +} + +void Metadata::parse(std::string_view data, size_t max_stripes, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view stripe_data = readBytesField(r, type); + checkCount(stripe_stats.size(), max_stripes, "stripe statistics"); + StripeStatistics stats; + parseMessage(stripe_data, [&](WireReader & rr, UInt32 f, WireType t) + { + if (f != 1) + return false; + std::string_view column_data = readBytesField(rr, t); + checkCount(stats.col_stats.size(), max_columns, "column statistics"); + stats.col_stats.emplace_back().parse(column_data); + return true; + }); + stripe_stats.push_back(std::move(stats)); + return true; + }); +} + +std::string Metadata::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & stats : stripe_stats) + { + std::string stripe; + WireWriter sw(stripe); + for (const auto & col : stats.col_stats) + sw.writeBytes(1, col.serialize()); + w.writeBytes(1, stripe); + } + return out; +} + +void Footer::parse(std::string_view data) +{ + /// The statistics are parsed after the types, to limit their number by the number of columns. + std::vector statistics_data; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: header_length = readVarintField(r, type); return true; + case 2: content_length = readVarintField(r, type); return true; + case 3: stripes.push_back(parseStripeInformation(readBytesField(r, type))); return true; + case 4: types.push_back(parseType(readBytesField(r, type))); return true; + case 5: metadata.push_back(parseUserMetadataItem(readBytesField(r, type))); return true; + case 6: number_of_rows = readVarintField(r, type); return true; + case 7: statistics_data.push_back(readBytesField(r, type)); return true; + case 8: row_index_stride = readUInt32Field(r, type); return true; + case 9: writer = readUInt32Field(r, type); return true; + case 10: readBytesField(r, type); has_encryption = true; return true; + case 12: software_version = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + if (statistics_data.size() > types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many column statistics in ORC footer: {}, the file has {} columns", + statistics_data.size(), types.size()); + statistics.resize(statistics_data.size()); + for (size_t i = 0; i < statistics_data.size(); ++i) + statistics[i].parse(statistics_data[i]); +} + +std::string Footer::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, header_length); + w.writeVarint(2, content_length); + for (const auto & s : stripes) + w.writeBytes(3, serializeStripeInformation(s)); + for (const auto & t : types) + w.writeBytes(4, serializeType(t)); + for (const auto & item : metadata) + { + std::string m; + WireWriter mw(m); + mw.writeBytes(1, item.name); + mw.writeBytes(2, item.value); + w.writeBytes(5, m); + } + w.writeVarint(6, number_of_rows); + for (const auto & s : statistics) + w.writeBytes(7, s.serialize()); + w.writeVarint(8, row_index_stride); + if (writer) + w.writeVarint(9, *writer); + if (software_version) + w.writeBytes(12, *software_version); + return out; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.h b/src/Processors/Formats/Impl/ORC/Proto.h new file mode 100644 index 000000000000..999839f6ab5d --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.h @@ -0,0 +1,343 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +/// Structures of the ORC file metadata, which is serialized with Protocol Buffers. +/// See `orc_proto.proto` in the ORC specification: https://orc.apache.org/specification/ORCv1/ +/// +/// Only the messages and the fields that are used by the reader and the writer are represented. +/// The parser skips the unknown fields, as required by the Protocol Buffers rules, so the files +/// written by newer writers can be read. + +namespace DB::ORC::Proto +{ + +/// Low-level reader of the Protocol Buffers wire format over a contiguous buffer. +/// Throws `INCORRECT_DATA` on a malformed or truncated message. +class WireReader +{ +public: + enum WireType : UInt8 + { + VARINT = 0, + FIXED64 = 1, + LENGTH_DELIMITED = 2, + START_GROUP = 3, + END_GROUP = 4, + FIXED32 = 5, + }; + + WireReader(const char * begin_, const char * end_) : pos(begin_), end(end_) {} + explicit WireReader(std::string_view data) : pos(data.data()), end(data.data() + data.size()) {} + + /// Reads the next field key. Returns false at the end of the message. + bool nextField(UInt32 & field_number, WireType & wire_type); + + UInt64 readVarint(); + Int64 readSignedVarint() { UInt64 v = readVarint(); return static_cast((v >> 1) ^ (~(v & 1) + 1)); } + UInt64 readFixed64(); + UInt32 readFixed32(); + double readDouble(); + std::string_view readBytes(); + + /// Skips a field of the given wire type. + void skip(WireType wire_type); + + /// Reads a scalar field that can be either packed or not packed. + /// Returns false (and reads nothing) if the wire type is not suitable. + [[nodiscard]] bool readRepeatedVarint(WireType wire_type, std::vector & out); + +private: + void check(size_t n) const; + + const char * pos; + const char * end; +}; + +/// Low-level writer of the Protocol Buffers wire format. +class WireWriter +{ +public: + explicit WireWriter(std::string & out_) : out(out_) {} + + void writeVarint(UInt32 field, UInt64 value); + void writeSignedVarint(UInt32 field, Int64 value) { writeVarint(field, (static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeDouble(UInt32 field, double value); + void writeBytes(UInt32 field, std::string_view value); + void writePackedVarint(UInt32 field, const std::vector & values); + void writePackedFixed64(UInt32 field, const std::vector & values); + + static void appendRawVarint(std::string & s, UInt64 value); + +private: + void writeKey(UInt32 field, UInt8 wire_type) { appendRawVarint(out, (static_cast(field) << 3) | wire_type); } + + std::string & out; +}; + + +enum class CompressionKind : UInt8 +{ + NONE = 0, + ZLIB = 1, + SNAPPY = 2, + LZO = 3, + LZ4 = 4, + ZSTD = 5, + BROTLI = 6, +}; + +struct PostScript +{ + UInt64 footer_length = 0; + CompressionKind compression = CompressionKind::NONE; + /// The default value in the specification. + UInt64 compression_block_size = 256 * 1024; + std::vector version; + UInt64 metadata_length = 0; + UInt32 writer_version = 0; + std::string magic; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct IntegerStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DoubleStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct StringStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; + std::optional lower_bound; + std::optional upper_bound; +}; + +struct BucketStatistics +{ + std::vector count; +}; + +struct DecimalStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DateStatistics +{ + std::optional minimum; + std::optional maximum; +}; + +struct TimestampStatistics +{ + /// In milliseconds, in the local time zone of the writer (deprecated). + std::optional minimum; + std::optional maximum; + /// In milliseconds since the epoch in UTC. + std::optional minimum_utc; + std::optional maximum_utc; + /// The sub-millisecond part of the nanoseconds plus one, if not zero. Unvalidated when read from a file. + std::optional minimum_nanos; + std::optional maximum_nanos; +}; + +struct BinaryStatistics +{ + std::optional sum; +}; + +struct CollectionStatistics +{ + std::optional min_children; + std::optional max_children; + std::optional total_children; +}; + +struct ColumnStatistics +{ + std::optional number_of_values; + std::optional int_statistics; + std::optional double_statistics; + std::optional string_statistics; + std::optional bucket_statistics; + std::optional decimal_statistics; + std::optional date_statistics; + std::optional binary_statistics; + std::optional timestamp_statistics; + std::optional has_null; + std::optional bytes_on_disk; + std::optional collection_statistics; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct RowIndexEntry +{ + std::vector positions; + std::optional statistics; +}; + +struct RowIndex +{ + std::vector entry; + + /// The limits of the number of the repeated objects keep a small malformed message from allocating much memory. + void parse(std::string_view data, size_t max_entries); + std::string serialize() const; +}; + +struct BloomFilter +{ + UInt32 num_hash_functions = 0; + std::vector bitset; + std::optional utf8bitset; +}; + +struct BloomFilterIndex +{ + std::vector bloom_filter; + + void parse(std::string_view data, size_t max_entries); +}; + +enum class StreamKind : UInt32 +{ + PRESENT = 0, + DATA = 1, + LENGTH = 2, + DICTIONARY_DATA = 3, + DICTIONARY_COUNT = 4, + SECONDARY = 5, + ROW_INDEX = 6, + BLOOM_FILTER = 7, + BLOOM_FILTER_UTF8 = 8, + ENCRYPTED_INDEX = 9, + ENCRYPTED_DATA = 10, + STRIPE_STATISTICS = 100, + FILE_STATISTICS = 101, +}; + +struct Stream +{ + std::optional kind; + UInt32 column = 0; + UInt64 length = 0; +}; + +enum class ColumnEncodingKind : UInt32 +{ + DIRECT = 0, + DICTIONARY = 1, + DIRECT_V2 = 2, + DICTIONARY_V2 = 3, +}; + +struct ColumnEncoding +{ + ColumnEncodingKind kind = ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; + /// 1 means the bloom filters use UTF-8 for the strings and UTC for the timestamps. + std::optional bloom_encoding; +}; + +struct StripeFooter +{ + std::vector streams; + std::vector columns; + std::optional writer_timezone; + /// Non-zero if the stripe has encrypted columns, which are not supported. + size_t encryption_variants = 0; + + void parse(std::string_view data, size_t max_columns); + std::string serialize() const; +}; + +struct StringPair +{ + std::string key; + std::string value; +}; + +struct Type +{ + UInt32 kind = 0; + std::vector subtypes; + std::vector field_names; + std::optional maximum_length; + std::optional precision; + std::optional scale; + std::vector attributes; + /// Only for GEOMETRY and GEOGRAPHY. + std::optional crs; + std::optional algorithm; +}; + +struct StripeInformation +{ + UInt64 offset = 0; + UInt64 index_length = 0; + UInt64 data_length = 0; + UInt64 footer_length = 0; + UInt64 number_of_rows = 0; +}; + +struct UserMetadataItem +{ + std::string name; + std::string value; +}; + +struct StripeStatistics +{ + std::vector col_stats; +}; + +struct Metadata +{ + std::vector stripe_stats; + + void parse(std::string_view data, size_t max_stripes, size_t max_columns); + std::string serialize() const; +}; + +struct Footer +{ + UInt64 header_length = 0; + UInt64 content_length = 0; + std::vector stripes; + std::vector types; + std::vector metadata; + UInt64 number_of_rows = 0; + std::vector statistics; + UInt32 row_index_stride = 0; + std::optional writer; + bool has_encryption = false; + std::optional software_version; + + void parse(std::string_view data); + std::string serialize() const; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.cpp b/src/Processors/Formats/Impl/ORC/RLE.cpp new file mode 100644 index 000000000000..7b9762e32de3 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.cpp @@ -0,0 +1,1129 @@ +#include + +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +namespace +{ + +inline Int64 unZigZag(UInt64 value) +{ + return static_cast((value >> 1) ^ (~(value & 1) + 1)); +} + +inline UInt64 zigZag(Int64 value) +{ + return (static_cast(value) << 1) ^ static_cast(value >> 63); +} + +/// The 5-bit codes of the bit widths in RLE v2. +constexpr UInt8 code_to_bit_width[32] = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 40, 48, 56, 64}; + +/// The smallest bit width representable in RLE v2 that fits the given number of bits. +constexpr UInt8 closest_fixed_bits[65] = { + 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 26, 26, 28, 28, 30, 30, 32, 32, 40, 40, 40, 40, 40, 40, 40, 40, 48, 48, 48, + 48, 48, 48, 48, 48, 56, 56, 56, 56, 56, 56, 56, 56, 64, 64, 64, 64, 64, 64, 64, 64}; + +inline UInt32 decodeBitWidth(UInt32 code) +{ + return code_to_bit_width[code & 0x1F]; +} + +inline UInt32 getClosestFixedBits(UInt32 n) +{ + return n <= 64 ? closest_fixed_bits[n] : 64; +} + +inline UInt32 encodeBitWidth(UInt32 width) +{ + width = getClosestFixedBits(width); + if (width <= 24) + return width - 1; + switch (width) + { + case 26: return 24; + case 28: return 25; + case 30: return 26; + case 32: return 27; + case 40: return 28; + case 48: return 29; + case 56: return 30; + default: return 31; + } +} + +/// The number of bits required to represent the value, rounded to a representable bit width. +/// Negative values require 64 bits. +inline UInt32 findClosestNumBits(Int64 value) +{ + if (value < 0) + return 64; + UInt32 count = 64 - static_cast(std::countl_zero(static_cast(value))); + return getClosestFixedBits(count); +} + +} + + +UInt64 readVarint(InputByteStream & stream) +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + UInt8 byte = stream.readByte(); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC stream {}", stream.getName()); +} + +Int64 readSignedVarint(InputByteStream & stream) +{ + return unZigZag(readVarint(stream)); +} + + +void ByteRleDecoder::readHeader() +{ + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + value = static_cast(stream->readByte()); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } +} + +void ByteRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + if (not_null) + memset(data, 0, num_values); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + if (repeating) + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = value; + ++consumed; + } + } + } + else + { + memset(data + position, value, count); + consumed = count; + } + } + else + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = static_cast(stream->readByte()); + ++consumed; + } + } + } + else + { + stream->readBytes(data + position, count); + consumed = count; + } + } + remaining_values -= consumed; + position += count; + } +} + +void ByteRleDecoder::skip(size_t num_values) +{ + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (!repeating) + stream->skipBytes(count); + } +} + +void ByteRleDecoder::seek(PositionProvider & positions) +{ + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); +} + + +void BooleanRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + { + /// The PRESENT stream of a child column is read with the mask of its parent, + /// and the masked positions must be null. + data[i] = 0; + continue; + } + if (remaining_bits == 0) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8; + } + --remaining_bits; + data[i] = (last_byte >> remaining_bits) & 1; + } +} + +void BooleanRleDecoder::skip(size_t num_values) +{ + if (num_values <= remaining_bits) + { + remaining_bits -= num_values; + return; + } + num_values -= remaining_bits; + byte_decoder.skip(num_values / 8); + if (num_values % 8) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - num_values % 8; + } + else + remaining_bits = 0; +} + +void BooleanRleDecoder::seek(PositionProvider & positions) +{ + byte_decoder.seek(positions); + UInt64 consumed = positions.next(); + remaining_bits = 0; + if (consumed > 8) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid seek position {} of a boolean stream in ORC file", consumed); + if (consumed) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - consumed; + } +} + + +namespace +{ + +class IntRleDecoderV1 final : public IntRleDecoder +{ +public: + IntRleDecoderV1(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + for (size_t i = 0; i < count; ++i) + { + if (not_null && !not_null[position + i]) + continue; + if (repeating) + { + data[position + i] = static_cast(value); + value = static_cast(static_cast(value) + static_cast(delta)); + } + else + data[position + i] = static_cast(readValue()); + ++consumed; + } + remaining_values -= consumed; + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (repeating) + value = static_cast(static_cast(value) + static_cast(delta) * count); + else + for (size_t i = 0; i < count; ++i) + readVarint(*stream); + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); + } + +private: + Int64 readValue() + { + return is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + } + + void readHeader() + { + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + delta = static_cast(stream->readByte()); + value = readValue(); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } + } + + std::unique_ptr stream; + const bool is_signed; + size_t remaining_values = 0; + bool repeating = false; + Int64 value = 0; + Int64 delta = 0; +}; + + +class IntRleDecoderV2 final : public IntRleDecoder +{ +public: + IntRleDecoderV2(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (run_read == run_length) + readRun(); + + size_t count = std::min(num_values - position, run_length - run_read); + if (not_null) + { + for (size_t i = position; i < position + count; ++i) + if (not_null[i]) + data[i] = static_cast(literals[run_read++]); + } + else if constexpr (sizeof(T) == sizeof(Int64)) + { + memcpy(static_cast(data + position), literals.data() + run_read, count * sizeof(Int64)); + run_read += count; + } + else + { + for (size_t i = 0; i < count; ++i) + data[position + i] = static_cast(literals[run_read + i]); + run_read += count; + } + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (run_read == run_length) + readRun(); + size_t count = std::min(num_values, run_length - run_read); + run_read += count; + num_values -= count; + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + run_read = run_length = 0; + skip(positions.next()); + } + +private: + enum EncodingType : UInt8 + { + SHORT_REPEAT = 0, + DIRECT = 1, + PATCHED_BASE = 2, + DELTA = 3, + }; + + Int64 readLongBE(size_t num_bytes) + { + UInt64 result = 0; + for (size_t i = 0; i < num_bytes; ++i) + result = (result << 8) | stream->readByte(); + return static_cast(result); + } + + template + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count) + { + for (size_t i = 0; i < count; ++i, in += num_bytes) + { + UInt64 value = 0; + for (size_t j = 0; j < num_bytes; ++j) + value = (value << 8) | in[j]; + out[i] = static_cast(value); + } + } + + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count, size_t num_bytes) + { + switch (num_bytes) + { + case 1: decodeBigEndian<1>(in, out, count); return; + case 2: decodeBigEndian<2>(in, out, count); return; + case 3: decodeBigEndian<3>(in, out, count); return; + case 4: decodeBigEndian<4>(in, out, count); return; + case 5: decodeBigEndian<5>(in, out, count); return; + case 6: decodeBigEndian<6>(in, out, count); return; + case 7: decodeBigEndian<7>(in, out, count); return; + default: decodeBigEndian<8>(in, out, count); return; + } + } + + /// The only bit widths that are not a multiple of 8 are at most 30. + template + static void decodeBitPacked(Int64 * out, size_t count, UInt32 bit_width, ReadByte && read_byte) + { + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + while (bits_in_buffer < bit_width) + { + buffer = (buffer << 8) | read_byte(); + bits_in_buffer += 8; + } + bits_in_buffer -= bit_width; + out[i] = static_cast((buffer >> bits_in_buffer) & mask); + } + } + + /// Reads `count` bit-packed values of `bit_width` bits, starting and ending at a byte boundary. + void readInts(Int64 * out, size_t count, UInt32 bit_width) + { + if (bit_width % 8 == 0) + { + const size_t num_bytes = bit_width / 8; + while (count) + { + /// Decode the values that are entirely in the current chunk directly from it. + size_t in_chunk = std::min(count, static_cast(stream->end - stream->pos) / num_bytes); + if (in_chunk == 0) + { + *out = readLongBE(num_bytes); + ++out; + --count; + continue; + } + decodeBigEndian(reinterpret_cast(stream->pos), out, in_chunk, num_bytes); + stream->pos += in_chunk * num_bytes; + out += in_chunk; + count -= in_chunk; + } + return; + } + + const size_t total_bytes = (count * bit_width + 7) / 8; + if (static_cast(stream->end - stream->pos) >= total_bytes) + { + const UInt8 * in = reinterpret_cast(stream->pos); + decodeBitPacked(out, count, bit_width, [&] { return *in++; }); + stream->pos += total_bytes; + } + else + { + decodeBitPacked(out, count, bit_width, [&] { return stream->readByte(); }); + } + } + + void readRun() + { + UInt8 first_byte = stream->readByte(); + auto encoding = static_cast(first_byte >> 6); + run_read = 0; + switch (encoding) + { + case SHORT_REPEAT: + { + size_t num_bytes = ((first_byte >> 3) & 0x07) + 1; + run_length = (first_byte & 0x07) + 3; + Int64 value = readLongBE(num_bytes); + if (is_signed) + value = unZigZag(static_cast(value)); + std::fill(literals.begin(), literals.begin() + run_length, value); + break; + } + case DIRECT: + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + readInts(literals.data(), run_length, bit_width); + if (is_signed) + for (size_t i = 0; i < run_length; ++i) + literals[i] = unZigZag(static_cast(literals[i])); + break; + } + case PATCHED_BASE: + readPatchedBase(first_byte); + break; + case DELTA: + readDelta(first_byte); + break; + } + } + + void readPatchedBase(UInt8 first_byte) + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + UInt8 third_byte = stream->readByte(); + size_t base_bytes = ((third_byte >> 5) & 0x07) + 1; + UInt32 patch_bit_width = decodeBitWidth(third_byte & 0x1F); + + UInt8 fourth_byte = stream->readByte(); + UInt32 patch_gap_width = ((fourth_byte >> 5) & 0x07) + 1; + size_t patch_list_length = fourth_byte & 0x1F; + if (patch_list_length == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (empty patch list)", stream->getName()); + + Int64 base = readLongBE(base_bytes); + Int64 sign_mask = static_cast(1ULL << (base_bytes * 8 - 1)); + if (base & sign_mask) + { + base &= ~sign_mask; + base = -base; + } + + readInts(literals.data(), run_length, bit_width); + + if (patch_bit_width + patch_gap_width > 64) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Corrupt PATCHED_BASE encoded data in ORC stream {} (patch width + patch gap width > 64)", stream->getName()); + + Int64 patches[32]; + readInts(patches, patch_list_length, getClosestFixedBits(patch_bit_width + patch_gap_width)); + + const Int64 patch_mask = patch_bit_width >= 64 ? -1 : static_cast((1ULL << patch_bit_width) - 1); + size_t patch_index = 0; + Int64 gap = 0; + Int64 patch = 0; + + auto adjust_gap_and_patch = [&] + { + UInt64 current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + Int64 actual_gap = 0; + /// A gap of 255 with a zero patch means that the gap continues in the next entry. + while (current_gap == 255 && patch == 0) + { + actual_gap += 255; + ++patch_index; + if (patch_index >= patch_list_length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (unterminated gap)", stream->getName()); + current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + } + gap = actual_gap + static_cast(current_gap); + }; + + adjust_gap_and_patch(); + for (size_t i = 0; i < run_length; ++i) + { + if (static_cast(i) != gap) + { + literals[i] = static_cast(static_cast(literals[i]) + static_cast(base)); + } + else + { + UInt64 patched = static_cast(literals[i]) | (bit_width < 64 ? static_cast(patch) << bit_width : 0); + literals[i] = static_cast(static_cast(base) + patched); + ++patch_index; + if (patch_index < patch_list_length) + { + adjust_gap_and_patch(); + /// The next gap is relative to the current position. + gap += static_cast(i); + } + } + } + } + + void readDelta(UInt8 first_byte) + { + UInt32 code = (first_byte >> 1) & 0x1F; + UInt32 bit_width = code ? decodeBitWidth(code) : 0; + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + Int64 first_value = is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + literals[0] = first_value; + Int64 delta_base = readSignedVarint(*stream); + + if (bit_width == 0) + { + /// Fixed delta. + for (size_t i = 1; i < run_length; ++i) + literals[i] = static_cast(static_cast(literals[i - 1]) + static_cast(delta_base)); + return; + } + + if (run_length < 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal run length {} for delta encoding in ORC stream {}", run_length, stream->getName()); + + Int64 previous = static_cast(static_cast(first_value) + static_cast(delta_base)); + literals[1] = previous; + readInts(literals.data() + 2, run_length - 2, bit_width); + for (size_t i = 2; i < run_length; ++i) + { + if (delta_base < 0) + previous = static_cast(static_cast(previous) - static_cast(literals[i])); + else + previous = static_cast(static_cast(previous) + static_cast(literals[i])); + literals[i] = previous; + } + } + + std::unique_ptr stream; + const bool is_signed; + std::array literals{}; + size_t run_length = 0; + size_t run_read = 0; +}; + +} + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version) +{ + if (version == RleVersion::V1) + return std::make_unique(std::move(stream), is_signed); + return std::make_unique(std::move(stream), is_signed); +} + + +void ByteRleEncoder::writeValues() +{ + if (num_literals == 0) + return; + if (repeat) + { + stream.writeByte(static_cast(num_literals - MIN_REPEAT)); + stream.writeByte(static_cast(literals[0])); + } + else + { + stream.writeByte(static_cast(-static_cast(num_literals))); + stream.write(literals, num_literals); + } + repeat = false; + tail_run_length = 0; + num_literals = 0; +} + +void ByteRleEncoder::write(char value) +{ + if (num_literals == 0) + { + literals[num_literals++] = value; + tail_run_length = 1; + } + else if (repeat) + { + if (value == literals[0]) + { + ++num_literals; + if (num_literals == MAX_REPEAT_SIZE) + writeValues(); + } + else + { + writeValues(); + literals[num_literals++] = value; + tail_run_length = 1; + } + } + else + { + if (value == literals[num_literals - 1]) + ++tail_run_length; + else + tail_run_length = 1; + + if (tail_run_length == MIN_REPEAT) + { + if (num_literals + 1 == MIN_REPEAT) + { + repeat = true; + ++num_literals; + } + else + { + num_literals -= MIN_REPEAT - 1; + writeValues(); + literals[0] = value; + repeat = true; + num_literals = MIN_REPEAT; + } + } + else + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + writeValues(); + } + } +} + +void ByteRleEncoder::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void ByteRleEncoder::flush() +{ + writeValues(); +} + + +void BooleanRleEncoder::write(bool value) +{ + current = static_cast((current << 1) | (value ? 1 : 0)); + ++bits_in_current; + if (bits_in_current == 8) + { + byte_encoder.write(static_cast(current)); + current = 0; + bits_in_current = 0; + } +} + +void BooleanRleEncoder::recordPosition(std::vector & positions) const +{ + byte_encoder.recordPosition(positions); + positions.push_back(bits_in_current); +} + +void BooleanRleEncoder::flush() +{ + if (bits_in_current) + { + byte_encoder.write(static_cast(current << (8 - bits_in_current))); + current = 0; + bits_in_current = 0; + } + byte_encoder.flush(); +} + + +void IntRleEncoderV2::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void IntRleEncoderV2::flush() +{ + size_t literal_start = 0; + size_t i = 0; + while (i < num_literals) + { + size_t j = i + 1; + while (j < num_literals && literals[j] == literals[i]) + ++j; + if (j - i >= 3) + { + if (literal_start < i) + encodeLiterals(literals + literal_start, i - literal_start); + encodeRepeat(literals[i], j - i); + literal_start = j; + } + i = j; + } + if (literal_start < num_literals) + encodeLiterals(literals + literal_start, num_literals - literal_start); + num_literals = 0; +} + +void IntRleEncoderV2::writeVarint(UInt64 value) +{ + while (value >= 0x80) + { + stream.writeByte(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + stream.writeByte(static_cast(value)); +} + +void IntRleEncoderV2::writeInts(const Int64 * values, size_t count, UInt32 bit_width) +{ + if (bit_width % 8 == 0) + { + size_t num_bytes = bit_width / 8; + for (size_t i = 0; i < count; ++i) + { + UInt64 v = static_cast(values[i]); + for (size_t b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(v >> ((b - 1) * 8))); + } + return; + } + + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + buffer = (buffer << bit_width) | (static_cast(values[i]) & mask); + bits_in_buffer += bit_width; + while (bits_in_buffer >= 8) + { + bits_in_buffer -= 8; + stream.writeByte(static_cast(buffer >> bits_in_buffer)); + } + } + if (bits_in_buffer) + stream.writeByte(static_cast(buffer << (8 - bits_in_buffer))); +} + +void IntRleEncoderV2::encodeRepeat(Int64 value, size_t count) +{ + UInt64 encoded = is_signed ? zigZag(value) : static_cast(value); + if (count <= 10) + { + /// SHORT_REPEAT + UInt32 bits = findClosestNumBits(static_cast(encoded)); + UInt32 num_bytes = (bits + 7) / 8; + stream.writeByte(static_cast(((num_bytes - 1) << 3) | (count - 3))); + for (UInt32 b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(encoded >> ((b - 1) * 8))); + return; + } + + /// DELTA with zero fixed delta. + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeVarint(encoded); + writeSignedVarint(0); +} + +void IntRleEncoderV2::writeDirect(const Int64 * values, size_t count) +{ + Int64 encoded[MAX_LITERAL_SIZE]; + UInt32 bit_width = 1; + for (size_t i = 0; i < count; ++i) + { + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + bit_width = std::max(bit_width, findClosestNumBits(encoded[i])); + } + size_t length = count - 1; + stream.writeByte(static_cast((1 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeInts(encoded, count, bit_width); +} + +namespace +{ + +/// The bit width that is enough for the given fraction `p` of the values (as in the reference implementation). +UInt32 percentileBits(const Int64 * values, size_t count, double p) +{ + UInt32 histogram[32] = {}; + for (size_t i = 0; i < count; ++i) + ++histogram[encodeBitWidth(findClosestNumBits(values[i]))]; + + Int64 per_len = static_cast(static_cast(count) * (1.0 - p)); + for (Int32 i = 31; i >= 0; --i) + { + per_len -= histogram[i]; + if (per_len < 0) + return decodeBitWidth(i); + } + return 0; +} + +} + +void IntRleEncoderV2::encodeLiterals(const Int64 * values, size_t count) +{ + if (count <= 3) + { + writeDirect(values, count); + return; + } + + Int64 min = values[0]; + Int64 max = values[0]; + bool is_increasing = true; + bool is_decreasing = true; + bool is_fixed_delta = true; + bool deltas_overflow = false; + Int64 initial_delta = 0; + if (__builtin_sub_overflow(values[1], values[0], &initial_delta)) + deltas_overflow = true; + + /// Absolute values of the deltas, starting from the second one. + Int64 abs_deltas[MAX_LITERAL_SIZE]; + UInt64 max_abs_delta = 0; + + for (size_t i = 1; i < count; ++i) + { + min = std::min(min, values[i]); + max = std::max(max, values[i]); + is_increasing &= values[i - 1] <= values[i]; + is_decreasing &= values[i - 1] >= values[i]; + + Int64 delta = 0; + if (__builtin_sub_overflow(values[i], values[i - 1], &delta)) + { + deltas_overflow = true; + is_fixed_delta = false; + continue; + } + is_fixed_delta &= (delta == initial_delta); + if (i > 1) + { + UInt64 abs_delta = delta < 0 ? (0 - static_cast(delta)) : static_cast(delta); + abs_deltas[i - 2] = static_cast(abs_delta); + max_abs_delta = std::max(max_abs_delta, abs_delta); + } + } + + Int64 range = 0; + if (__builtin_sub_overflow(max, min, &range)) + { + writeDirect(values, count); + return; + } + + if (!deltas_overflow && is_fixed_delta) + { + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + return; + } + + if (!deltas_overflow && initial_delta != 0 && (is_increasing || is_decreasing) + && max_abs_delta <= static_cast(std::numeric_limits::max())) + { + UInt32 bit_width = findClosestNumBits(static_cast(max_abs_delta)); + /// The bit width code 0 means a fixed delta, so the width 1 is not representable. + if (bit_width == 1) + bit_width = 2; + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + writeInts(abs_deltas, count - 2, bit_width); + return; + } + + /// DIRECT or PATCHED_BASE. + Int64 encoded[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + + UInt32 bits_100p = percentileBits(encoded, count, 1.0); + UInt32 bits_90p = percentileBits(encoded, count, 0.9); + + static constexpr Int64 BASE_VALUE_LIMIT = 1LL << 56; + if (bits_100p - bits_90p <= 1 || min <= -BASE_VALUE_LIMIT || min >= BASE_VALUE_LIMIT) + { + writeDirect(values, count); + return; + } + + Int64 base_reduced[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + base_reduced[i] = values[i] - min; + + UInt32 br_bits_95p = percentileBits(base_reduced, count, 0.95); + UInt32 br_bits_100p = percentileBits(base_reduced, count, 1.0); + if (br_bits_100p == br_bits_95p) + { + writeDirect(values, count); + return; + } + + UInt32 patch_width = getClosestFixedBits(br_bits_100p - br_bits_95p); + if (patch_width == 64) + { + patch_width = 56; + br_bits_95p = 8; + } + const Int64 mask = static_cast((1ULL << br_bits_95p) - 1); + + size_t gaps[MAX_LITERAL_SIZE]; + Int64 patches[MAX_LITERAL_SIZE]; + size_t num_patches = 0; + size_t previous = 0; + size_t max_gap = 0; + for (size_t i = 0; i < count; ++i) + { + if (base_reduced[i] > mask) + { + size_t gap = i - previous; + max_gap = std::max(max_gap, gap); + previous = i; + gaps[num_patches] = gap; + patches[num_patches] = base_reduced[i] >> br_bits_95p; + ++num_patches; + base_reduced[i] &= mask; + } + } + + UInt32 patch_gap_width = (max_gap == 0) ? 1 : findClosestNumBits(static_cast(max_gap)); + patch_gap_width = std::min(patch_gap_width, 8u); + + Int64 patch_list[MAX_LITERAL_SIZE]; + size_t patch_list_length = 0; + for (size_t p = 0; p < num_patches; ++p) + { + size_t gap = gaps[p]; + while (gap > 255) + { + patch_list[patch_list_length++] = static_cast(255ULL << patch_width); + gap -= 255; + } + patch_list[patch_list_length++] = static_cast((static_cast(gap) << patch_width) | static_cast(patches[p])); + } + + /// The length of the patch list is stored in 5 bits. + if (patch_list_length > 31) + { + writeDirect(values, count); + return; + } + + bool is_negative = min < 0; + UInt64 base = is_negative ? static_cast(-min) : static_cast(min); + UInt32 base_width = findClosestNumBits(static_cast(base)) + 1; + UInt32 base_bytes = (base_width + 7) / 8; + if (is_negative) + base |= 1ULL << (base_bytes * 8 - 1); + + size_t length = count - 1; + stream.writeByte(static_cast((2 << 6) | (encodeBitWidth(br_bits_95p) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + stream.writeByte(static_cast(((base_bytes - 1) << 5) | encodeBitWidth(patch_width))); + stream.writeByte(static_cast(((patch_gap_width - 1) << 5) | patch_list_length)); + for (UInt32 b = base_bytes; b > 0; --b) + stream.writeByte(static_cast(base >> ((b - 1) * 8))); + writeInts(base_reduced, count, getClosestFixedBits(br_bits_95p)); + writeInts(patch_list, patch_list_length, getClosestFixedBits(patch_gap_width + patch_width)); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.h b/src/Processors/Formats/Impl/ORC/RLE.h new file mode 100644 index 000000000000..c5212bf5fbf6 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.h @@ -0,0 +1,151 @@ +#pragma once + +#include + +#include +#include + +/// Run-length encodings of ORC: https://orc.apache.org/specification/ORCv1/#run-length-encoding +/// +/// All decoders fill the positions where `not_null` is non-zero (or all positions if it is +/// nullptr), consuming one value from the stream for each of them; the other positions are set to zero. + +namespace DB::ORC +{ + +/// Byte run-length encoding, used for the bytes and for the booleans (packed into bytes). +class ByteRleDecoder +{ +public: + explicit ByteRleDecoder(std::unique_ptr stream_) : stream(std::move(stream_)) {} + + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + void readHeader(); + + std::unique_ptr stream; + size_t remaining_values = 0; + bool repeating = false; + char value = 0; +}; + +/// Booleans packed into bytes, most significant bit first, encoded with the byte run-length encoding. +class BooleanRleDecoder +{ +public: + explicit BooleanRleDecoder(std::unique_ptr stream_) : byte_decoder(std::move(stream_)) {} + + /// Writes 0 or 1. + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + ByteRleDecoder byte_decoder; + size_t remaining_bits = 0; + UInt8 last_byte = 0; +}; + +/// Integer run-length encodings, version 1 and 2. +class IntRleDecoder +{ +public: + virtual ~IntRleDecoder() = default; + /// The values are converted to the type of the output, which can be narrower than the encoded values. + virtual void next(Int64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(UInt64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int32 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int16 * data, size_t num_values, const char * not_null) = 0; + virtual void skip(size_t num_values) = 0; + virtual void seek(PositionProvider & positions) = 0; +}; + +enum class RleVersion : UInt8 +{ + V1, + V2, +}; + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version); + +/// Reads a base 128 varint, as used by the DECIMAL columns. +UInt64 readVarint(InputByteStream & stream); +Int64 readSignedVarint(InputByteStream & stream); + + +class ByteRleEncoder +{ +public: + explicit ByteRleEncoder(OutputByteStream & stream_) : stream(stream_) {} + + void write(char value); + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + +private: + void writeValues(); + + static constexpr size_t MIN_REPEAT = 3; + static constexpr size_t MAX_LITERAL_SIZE = 128; + static constexpr size_t MAX_REPEAT_SIZE = 127 + MIN_REPEAT; + + OutputByteStream & stream; + char literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; + size_t tail_run_length = 0; + bool repeat = false; +}; + +class BooleanRleEncoder +{ +public: + explicit BooleanRleEncoder(OutputByteStream & stream_) : byte_encoder(stream_) {} + + void write(bool value); + void recordPosition(std::vector & positions) const; + void flush(); + +private: + ByteRleEncoder byte_encoder; + UInt8 current = 0; + size_t bits_in_current = 0; +}; + +/// Integer run-length encoding, version 2. +class IntRleEncoderV2 +{ +public: + IntRleEncoderV2(OutputByteStream & stream_, bool is_signed_) : stream(stream_), is_signed(is_signed_) {} + + void write(Int64 value) + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + flush(); + } + + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + + static constexpr size_t MAX_LITERAL_SIZE = 512; + +private: + void encodeLiterals(const Int64 * values, size_t count); + void encodeRepeat(Int64 value, size_t count); + void writeDirect(const Int64 * values, size_t count); + void writeVarint(UInt64 value); + void writeSignedVarint(Int64 value) { writeVarint((static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeInts(const Int64 * values, size_t count, UInt32 bit_width); + + OutputByteStream & stream; + const bool is_signed; + Int64 literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.cpp b/src/Processors/Formats/Impl/ORC/Reader.cpp new file mode 100644 index 000000000000..76c6a432d1b0 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.cpp @@ -0,0 +1,842 @@ +#include + +#include +#include +#include +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +std::future InputStream::readAsync(void * buf, UInt64 length, UInt64 offset) +{ + read(buf, length, offset); + std::promise promise; + promise.set_value(); + return promise.get_future(); +} + + +Reader::Reader(std::unique_ptr stream_, const ReaderOptions & options_) + : stream(std::move(stream_)), options(options_) +{ + readTail(); +} + +Reader::~Reader() +{ + /// The background reads write into the buffers of the cache. + for (auto & range : cache) + if (!range.ready && range.future.valid()) + range.future.wait(); +} + +void Reader::readTail() +{ + const UInt64 file_size = stream->getLength(); + /// The header "ORC" and at least the length of the postscript. + if (file_size < 4) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {} is too small ({} bytes)", stream->getName(), file_size); + + static constexpr UInt64 DIRECTORY_SIZE_GUESS = 16 * 1024; + UInt64 tail_size = std::min(file_size, DIRECTORY_SIZE_GUESS); + std::string tail(tail_size, '\0'); + stream->read(tail.data(), tail_size, file_size - tail_size); + + postscript_length = static_cast(tail.back()); + if (postscript_length + 1 > tail_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid postscript length {} in ORC file {}", postscript_length, stream->getName()); + + postscript.parse(std::string_view(tail).substr(tail_size - 1 - postscript_length, postscript_length)); + + if (postscript.magic != "ORC") + { + /// Very old files do not have the magic in the postscript, but they have it at the beginning. + char header[3]; + stream->read(header, 3, 0); + if (memcmp(header, "ORC", 3) != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {}", stream->getName()); + } + + if (postscript.compression != CompressionKind::NONE) + { + if (postscript.compression_block_size == 0 || postscript.compression_block_size > (1ULL << 30)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid compression block size {} in ORC file {}", postscript.compression_block_size, stream->getName()); + if (postscript.compression == CompressionKind::BROTLI) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "BROTLI compression in ORC files is not supported"); + } + + UInt64 tail_length = 0; + if (__builtin_add_overflow(postscript.footer_length, postscript.metadata_length, &tail_length) + || __builtin_add_overflow(tail_length, postscript_length + 1, &tail_length) + || tail_length > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Invalid footer length {} and metadata length {} in ORC file {} of size {}", + postscript.footer_length, postscript.metadata_length, stream->getName(), file_size); + + if (tail_length > tail_size) + { + tail.resize(tail_length); + tail_size = tail_length; + stream->read(tail.data(), tail_size, file_size - tail_size); + } + + std::string_view footer_data = std::string_view(tail).substr(tail_size - 1 - postscript_length - postscript.footer_length, postscript.footer_length); + footer.parse(decompress(footer_data, "footer")); + + if (footer.has_encryption) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + + schema = Type::fromProto(footer.types); + + /// Validate the stripes once, so that the sums of their offsets and lengths cannot overflow later. + if (footer.stripes.size() > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many stripes {} in ORC file {}", footer.stripes.size(), stream->getName()); + for (size_t i = 0; i < footer.stripes.size(); ++i) + { + const auto & stripe = footer.stripes[i]; + UInt64 stripe_end = 0; + if (common::addOverflow(stripe.offset, stripe.index_length, stripe_end) + || common::addOverflow(stripe_end, stripe.data_length, stripe_end) + || common::addOverflow(stripe_end, stripe.footer_length, stripe_end) + || stripe_end > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + i, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, file_size); + } + + std::string_view metadata_data = std::string_view(tail).substr( + tail_size - 1 - postscript_length - postscript.footer_length - postscript.metadata_length, postscript.metadata_length); + if (!metadata_data.empty()) + metadata.emplace().parse(decompress(metadata_data, "metadata"), footer.stripes.size(), footer.types.size()); + else + metadata.emplace(); +} + +const Proto::Metadata & Reader::getMetadata() +{ + return *metadata; +} + +std::string Reader::decompress(std::string_view data, const std::string & name) const +{ + if (postscript.compression == CompressionKind::NONE) + return std::string(data); + + std::string result; + InputByteStream in(data, postscript.compression, postscript.compression_block_size, name); + while (in.nextChunk()) + result.append(in.pos, in.end); + return result; +} + +Proto::StripeFooter Reader::readStripeFooter(size_t stripe_index) +{ + const auto & stripe = getStripe(stripe_index); + UInt64 offset = stripe.offset + stripe.index_length + stripe.data_length; + UInt64 end = 0; + if (__builtin_add_overflow(offset, stripe.footer_length, &end) || end > stream->getLength() || offset < stripe.offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + stripe_index, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, stream->getLength()); + + auto slices = readRanges({{offset, stripe.footer_length}}); + Proto::StripeFooter result; + result.parse(decompress(slices[0].data, "stripe footer"), footer.types.size()); + if (result.encryption_variants) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + return result; +} + +std::vector> Reader::getStripeRanges( + size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const +{ + const auto & stripe = getStripe(stripe_index); + std::vector> ranges; + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + for (const auto & s : stripe_footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream at offset {} of length {} in stripe {} of ORC file {}", offset, s.length, stripe_index, stream->getName()); + if (s.kind && s.column < selected.size() && selected[s.column] && s.length) + ranges.emplace_back(offset, s.length); + offset = stream_end; + } + return ranges; +} + +std::vector Reader::readRanges(const std::vector> & ranges) +{ + std::vector result(ranges.size()); + + std::vector order(ranges.size()); + for (size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return ranges[a].first < ranges[b].first; }); + + size_t i = 0; + while (i < order.size()) + { + UInt64 begin = ranges[order[i]].first; + UInt64 end = begin + ranges[order[i]].second; + size_t j = i + 1; + while (j < order.size()) + { + UInt64 next_begin = ranges[order[j]].first; + UInt64 next_end = next_begin + ranges[order[j]].second; + UInt64 new_end = std::max(end, next_end); + if (next_begin > end && next_begin - end > options.hole_size_limit) + break; + if (new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + std::shared_ptr> holder; + const char * base = nullptr; + UInt64 base_offset = begin; + { + std::lock_guard lock(cache_mutex); + for (auto & cached : cache) + { + if (cached.offset <= begin && end <= cached.offset + cached.length) + { + if (!cached.ready) + { + cached.ready = true; + cached.future.get(); + } + holder = cached.buffer; + base = cached.buffer->data(); + base_offset = cached.offset; + break; + } + } + } + + if (!holder) + { + if (end > stream->getLength()) + throw Exception(ErrorCodes::INCORRECT_DATA, "A range at {} of length {} goes beyond the end of ORC file {}", begin, end - begin, stream->getName()); + auto buffer = std::make_shared>(end - begin); + if (end > begin) + stream->read(buffer->data(), end - begin, begin); + base = buffer->data(); + holder = std::move(buffer); + } + + for (size_t k = i; k < j; ++k) + { + const auto & range = ranges[order[k]]; + result[order[k]] = Slice{holder, std::string_view(base + (range.first - base_offset), range.second)}; + } + i = j; + } + return result; +} + +void Reader::preBuffer(const std::vector & stripes, const std::vector & include_types) +{ + auto selected = selectColumnsByTypeIds(*schema, include_types); + for (UInt32 stripe_index : stripes) + { + const auto & stripe = getStripe(stripe_index); + auto stripe_footer = readStripeFooter(stripe_index); + auto ranges = getStripeRanges(stripe_index, stripe_footer, selected); + ranges.emplace_back(stripe.offset + stripe.index_length + stripe.data_length, stripe.footer_length); + std::sort(ranges.begin(), ranges.end()); + + size_t i = 0; + while (i < ranges.size()) + { + UInt64 begin = ranges[i].first; + UInt64 end = begin + ranges[i].second; + size_t j = i + 1; + while (j < ranges.size()) + { + UInt64 next_begin = ranges[j].first; + UInt64 new_end = std::max(end, next_begin + ranges[j].second); + if ((next_begin > end && next_begin - end > options.hole_size_limit) || new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + auto buffer = std::make_shared>(end - begin); + { + /// The entry must be owned by the cache before the background read starts, so that + /// the destructor waits for the read even if an exception is thrown in between. + std::lock_guard lock(cache_mutex); + auto & cached = cache.emplace_back(CachedRange{.offset = begin, .length = end - begin, .buffer = std::move(buffer), .future = {}}); + try + { + cached.future = stream->readAsync(cached.buffer->data(), end - begin, begin); + } + catch (...) + { + /// Nothing has been scheduled, so the entry can be removed safely. + cache.pop_back(); + throw; + } + } + i = j; + } + } +} + +void Reader::releaseBuffer(UInt64 boundary) +{ + std::lock_guard lock(cache_mutex); + for (auto it = cache.begin(); it != cache.end();) + { + if (it->offset + it->length <= boundary) + { + /// The buffer can be destroyed only after the background read finishes. The data has + /// not been used, so an error of reading it does not matter. + if (!it->ready && it->future.valid()) + it->future.wait(); + it = cache.erase(it); + } + else + ++it; + } +} + +std::unique_ptr Reader::createRowReader(const RowReaderOptions & row_options) +{ + return std::make_unique(*this, row_options); +} + + +class RowReader::StripeStreamsImpl final : public StripeStreams +{ +public: + StripeStreamsImpl( + Reader & reader_, + size_t stripe_index_, + Proto::StripeFooter footer_, + const std::vector & selected_columns_, + const DateLUTImpl & writer_timezone_, + const DateLUTImpl & reader_timezone_) + : reader(reader_) + , stripe_index(stripe_index_) + , footer(std::move(footer_)) + , selected_columns(selected_columns_) + , writer_timezone(writer_timezone_) + , reader_timezone(reader_timezone_) + { + const auto & stripe = reader.getStripe(stripe_index); + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + + for (const auto & s : footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: streamOffset={}, streamLength={}, stripeOffset={}, stripeIndexLength={}, stripeDataLength={}", + stripe_index, offset, s.length, stripe.offset, stripe.index_length, stripe.data_length); + if (s.kind && s.column < selected_columns.size() && selected_columns[s.column]) + { + /// Use the first stream if there are several of the same kind, as the reference implementation. + stream_ranges.try_emplace({static_cast(s.column), *s.kind}, offset, s.length); + } + else if (s.kind && s.column >= selected_columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: column {} is out of range, the file has {} columns", + stripe_index, s.column, selected_columns.size()); + offset = stream_end; + } + } + + static bool isIndexStream(UInt32 kind) + { + return kind == static_cast(Proto::StreamKind::ROW_INDEX) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER_UTF8); + } + + /// Reads the streams into memory at once, only the index streams or all of them. The streams + /// that are not read are loaded on demand by `getStream`. + void loadStreams(bool only_index) + { + std::vector> ranges; + std::vector> keys; + for (const auto & [key, range] : stream_ranges) + { + if (streams.contains(key) || (only_index && !isIndexStream(key.second))) + continue; + keys.push_back(key); + ranges.push_back(range); + } + + auto new_slices = reader.readRanges(ranges); + for (size_t i = 0; i < keys.size(); ++i) + streams.emplace(keys[i], new_slices[i].data); + slices.insert(slices.end(), std::make_move_iterator(new_slices.begin()), std::make_move_iterator(new_slices.end())); + } + + const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const override + { + if (column_id >= footer.columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC stripe {} has no encoding for column {}, it has {} column encodings", stripe_index, column_id, footer.columns.size()); + return footer.columns[column_id]; + } + + std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const override + { + std::pair key{column_id, static_cast(kind)}; + auto name = fmt::format("column {} kind {} in stripe {}", column_id, static_cast(kind), stripe_index); + if (auto it = streams.find(key); it != streams.end()) + return std::make_unique(it->second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + + auto it = stream_ranges.find(key); + if (it == stream_ranges.end()) + return nullptr; + auto loader = [&file_reader = reader, stream_offset = it->second.first](UInt64 offset, UInt64 length) + { + auto loaded = file_reader.readRanges({{stream_offset + offset, length}}); + return LoadedRange{std::move(loaded[0].holder), loaded[0].data}; + }; + return std::make_unique( + std::move(loader), it->second.second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + } + + std::optional getStreamData(UInt64 column_id, Proto::StreamKind kind) const + { + auto it = streams.find({column_id, static_cast(kind)}); + if (it == streams.end()) + return {}; + return it->second; + } + + const std::vector & getSelectedColumns() const override { return selected_columns; } + const DateLUTImpl & getWriterTimezone() const override { return writer_timezone; } + const DateLUTImpl & getReaderTimezone() const override { return reader_timezone; } + UInt64 getNumberOfRows() const override { return reader.getStripe(stripe_index).number_of_rows; } + bool isDecimalAsLong() const override + { + const auto & version = reader.getPostScript().version; + return version.size() == 2 && version[0] == 1 && version[1] == 9999; + } + + const Proto::StripeFooter & getFooter() const { return footer; } + +private: + Reader & reader; + size_t stripe_index; + Proto::StripeFooter footer; + const std::vector & selected_columns; + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + /// The offset in the file and the length of each selected stream. + std::map, std::pair> stream_ranges; + /// The streams read into memory. + std::vector slices; + std::map, std::string_view> streams; +}; + + +RowReader::RowReader(Reader & reader_, const RowReaderOptions & options_) + : reader(reader_) + , options(options_) + , reader_timezone(DateLUT::instance(options.timezone_name)) +{ + const Type & schema = reader.getType(); + if (options.include_types) + selected_columns = selectColumnsByTypeIds(schema, *options.include_types); + else + selected_columns.assign(schema.getMaximumColumnId() + 1, true); + selected_type = Type::buildSelectedType(schema, selected_columns); + + UInt64 range_end = options.range_offset + std::min(options.range_length, std::numeric_limits::max() - options.range_offset); + const auto & stripes = reader.getFooter().stripes; + current_stripe = stripes.size(); + last_stripe = 0; + for (size_t i = 0; i < stripes.size(); ++i) + { + if (stripes[i].offset >= options.range_offset && stripes[i].offset < range_end) + { + current_stripe = std::min(current_stripe, i); + last_stripe = std::max(last_stripe, i + 1); + } + } + if (current_stripe >= last_stripe) + current_stripe = last_stripe = 0; + + /// The search argument can be applied only if there are row indexes. + if (reader.getFooter().row_index_stride == 0) + options.search_argument.reset(); +} + +RowReader::~RowReader() = default; + +std::unique_ptr RowReader::createRowBatch() const +{ + return ORC::createRowBatch(*selected_type, options.enable_lazy_decoding); +} + +bool Reader::hasBadBloomFilters() const +{ + /// Same as in the reference implementation. Only the C++ writer (id 1) of some old releases wrote bad bloom filters. + if (footer.writer.value_or(0) != 1) + return false; + /// `software_version` is written since 1.5.13, 1.6.11 and 1.7.0, and the C++ writer supports bloom filters since 1.6.0, + /// so the files of the C++ writer without `software_version` have bad bloom filters. + if (!footer.software_version) + return true; + /// Strip the suffix of snapshot versions, like 1.6.12-SNAPSHOT. + std::string_view version = *footer.software_version; + version = version.substr(0, version.find('-')); + static constexpr std::string_view bad_versions[] = { + "1.6.0", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.6.7", "1.6.8", "1.6.9", "1.6.10", "1.6.11", "1.7.0"}; + return std::find(std::begin(bad_versions), std::end(bad_versions), version) != std::end(bad_versions); +} + +const DateLUTImpl & RowReader::getWriterTimezone(const Proto::StripeFooter & stripe_footer) const +{ + if (stripe_footer.writer_timezone) + return DateLUT::instance(*stripe_footer.writer_timezone); + /// The reference implementation uses the local time zone of the reader if the file does not specify it. + return DateLUT::serverTimezoneInstance(); +} + +bool RowReader::evaluateStatistics(const std::vector & stats) const +{ + const auto & leaves = options.search_argument->getLeaves(); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + UInt32 writer_version = reader.getPostScript().writer_version; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + if (column < stats.size()) + values[i] = leaves[i].evaluate(writer_version, stats[column], nullptr); + } + return isNeeded(options.search_argument->evaluate(values)); +} + +UInt64 RowReader::numberOfRowGroups() const +{ + const UInt64 stride = reader.getFooter().row_index_stride; + return rows_in_current_stripe / stride + (rows_in_current_stripe % stride != 0); +} + +void RowReader::loadStripeIndex() +{ + row_indexes.clear(); + bloom_filters.clear(); + /// One extra entry is accepted from lenient writers. + const UInt64 max_entries = std::min(numberOfRowGroups(), std::numeric_limits::max() - 1) + 1; + const bool use_bloom_filters = !reader.hasBadBloomFilters(); + const auto & stripe_footer = stripe_streams->getFooter(); + for (const auto & s : stripe_footer.streams) + { + if (!s.kind || s.column >= selected_columns.size() || !selected_columns[s.column]) + continue; + auto kind = static_cast(*s.kind); + if (kind == Proto::StreamKind::ROW_INDEX) + { + if (row_indexes.contains(s.column)) + continue; + auto data = stripe_streams->getStreamData(s.column, kind); + row_indexes[s.column].parse(reader.decompress(data.value_or(std::string_view{}), "row index"), max_entries); + } + else if (kind == Proto::StreamKind::BLOOM_FILTER_UTF8 && use_bloom_filters) + { + if (bloom_filters.contains(s.column)) + continue; + const auto & encoding = stripe_streams->getEncoding(s.column); + Proto::BloomFilterIndex index; + auto data = stripe_streams->getStreamData(s.column, kind); + index.parse(reader.decompress(data.value_or(std::string_view{}), "bloom filter"), max_entries); + auto & filters = bloom_filters[s.column]; + for (const auto & bf : index.bloom_filter) + { + /// Only the bloom filters with the UTF-8 strings and UTC timestamps can be used. + if (encoding.bloom_encoding.value_or(0) == 1 && bf.num_hash_functions && bf.utf8bitset) + filters.push_back(std::make_shared(bf)); + else + filters.push_back(nullptr); + } + } + } +} + +void RowReader::pickRowGroups() +{ + const UInt64 stride = reader.getFooter().row_index_stride; + const UInt64 groups = numberOfRowGroups(); + const auto & leaves = options.search_argument->getLeaves(); + + /// The number of the row groups comes from the file. Check it against the row indexes, which are already + /// read, before allocating memory for it. + bool has_leaf_index = false; + for (const auto & leaf : leaves) + { + auto it = row_indexes.find(leaf.getColumnId()); + if (it == row_indexes.end()) + continue; + has_leaf_index = true; + if (it->second.entry.size() < groups) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + it->first, it->second.entry.size(), groups, current_stripe); + } + + if (!has_leaf_index) + { + /// Without the row indexes all row groups are read. + next_skipped_rows.clear(); + return; + } + + next_skipped_rows.assign(groups, 0); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + const UInt32 writer_version = reader.getPostScript().writer_version; + const Proto::ColumnStatistics empty_statistics; + + UInt64 next_skipped_group = groups; + for (UInt64 group = groups; group > 0;) + { + --group; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + auto it = row_indexes.find(column); + if (it == row_indexes.end()) + { + values[i] = TruthValue::YES_NO_NULL; + continue; + } + if (group >= it->second.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + column, it->second.entry.size(), groups, current_stripe); + const auto & entry = it->second.entry[group]; + const BloomFilter * bloom_filter = nullptr; + if (auto bf = bloom_filters.find(column); bf != bloom_filters.end() && group < bf->second.size()) + bloom_filter = bf->second[group].get(); + values[i] = leaves[i].evaluate(writer_version, entry.statistics ? *entry.statistics : empty_statistics, bloom_filter); + } + + bool needed = isNeeded(options.search_argument->evaluate(values)); + if (!needed) + { + next_skipped_rows[group] = 0; + next_skipped_group = group; + } + else + next_skipped_rows[group] = (next_skipped_group == groups) ? rows_in_current_stripe : next_skipped_group * stride; + } +} + +UInt64 RowReader::advanceToNextRowGroup(UInt64 current_row) const +{ + const UInt64 groups = next_skipped_rows.size(); + if (groups == 0) + return std::min(current_row, rows_in_current_stripe); + + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return rows_in_current_stripe; + if (next_skipped_rows[group] != 0) + return current_row; + while (group < groups && next_skipped_rows[group] == 0) + ++group; + if (group < groups) + return group * stride; + return rows_in_current_stripe; +} + +UInt64 RowReader::computeBatchSize(UInt64 requested, UInt64 current_row) const +{ + UInt64 end_row = rows_in_current_stripe; + const UInt64 groups = next_skipped_rows.size(); + if (groups > 0) + { + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return 0; + UInt64 next_skipped_row = next_skipped_rows[group]; + if (next_skipped_row == 0) + return 0; + end_row = next_skipped_row; + } + return std::min(requested, end_row - current_row); +} + +void RowReader::seekToRowGroup(size_t row_group) +{ + std::unordered_map positions; + for (const auto & [column, index] : row_indexes) + { + if (row_group >= index.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, the row group {} is requested", column, index.entry.size(), row_group); + positions.emplace(column, PositionProvider(index.entry[row_group].positions)); + } + column_reader->seekToRowGroup(positions); +} + +void RowReader::startNextStripe() +{ + column_reader.reset(); + stripe_streams.reset(); + row_indexes.clear(); + bloom_filters.clear(); + next_skipped_rows.clear(); + + const auto & search_argument = options.search_argument; + const auto & footer = reader.getFooter(); + + if (search_argument && !file_statistics_evaluated) + { + file_statistics_result = footer.statistics.empty() || evaluateStatistics(footer.statistics); + file_statistics_evaluated = true; + } + if (search_argument && !file_statistics_result) + { + current_stripe = last_stripe; + return; + } + + do + { + const auto & stripe = footer.stripes[current_stripe]; + rows_in_current_stripe = stripe.number_of_rows; + + bool is_stripe_needed = true; + const auto & stripe_statistics = reader.getMetadata().stripe_stats; + if (search_argument && stripe_statistics.size() == footer.stripes.size()) + { + const auto & stats = stripe_statistics[current_stripe].col_stats; + is_stripe_needed = stats.empty() || evaluateStatistics(stats); + } + + if (is_stripe_needed) + { + auto stripe_footer = reader.readStripeFooter(current_stripe); + const DateLUTImpl & writer_timezone = getWriterTimezone(stripe_footer); + stripe_streams = std::make_unique( + reader, current_stripe, std::move(stripe_footer), selected_columns, writer_timezone, reader_timezone); + if (!search_argument) + stripe_streams->loadStreams(/* only_index */ false); + + if (search_argument) + { + stripe_streams->loadStreams(/* only_index */ true); + loadStripeIndex(); + pickRowGroups(); + bool has_selected = next_skipped_rows.empty(); + for (UInt64 group = current_row_in_stripe / footer.row_index_stride; !has_selected && group < next_skipped_rows.size(); ++group) + has_selected = next_skipped_rows[group] != 0; + if (has_selected) + { + /// If some row groups are skipped, the data is loaded on demand, only around the + /// selected row groups. Otherwise the whole stripe is read at once. + bool has_skipped = std::find(next_skipped_rows.begin(), next_skipped_rows.end(), 0) != next_skipped_rows.end(); + if (!has_skipped) + stripe_streams->loadStreams(/* only_index */ false); + break; + } + is_stripe_needed = false; + stripe_streams.reset(); + } + } + + if (!is_stripe_needed) + { + ++current_stripe; + current_row_in_stripe = 0; + } + } while (search_argument && current_stripe < last_stripe); + + if (current_stripe >= last_stripe) + return; + + column_reader = buildColumnReader(reader.getType(), *stripe_streams); + + if (search_argument) + { + current_row_in_stripe = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe > 0) + seekToRowGroup(current_row_in_stripe / footer.row_index_stride); + } +} + +bool RowReader::next(ColumnVectorBatch & batch, size_t max_rows) +{ + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + if (current_row_in_stripe == 0) + startNextStripe(); + + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + UInt64 rows_to_read = std::min(max_rows, rows_in_current_stripe - current_row_in_stripe); + if (options.search_argument && rows_to_read > 0) + rows_to_read = computeBatchSize(rows_to_read, current_row_in_stripe); + + batch.numElements = rows_to_read; + if (rows_to_read == 0) + { + current_stripe = last_stripe; + return false; + } + + if (options.enable_lazy_decoding) + column_reader->nextEncoded(batch, rows_to_read, nullptr); + else + column_reader->next(batch, rows_to_read, nullptr); + + current_row_in_stripe += rows_to_read; + + if (options.search_argument) + { + UInt64 next_row = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe != next_row) + { + current_row_in_stripe = next_row; + if (current_row_in_stripe < rows_in_current_stripe) + seekToRowGroup(current_row_in_stripe / reader.getFooter().row_index_stride); + } + } + + if (current_row_in_stripe >= rows_in_current_stripe) + { + ++current_stripe; + current_row_in_stripe = 0; + } + return true; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.h b/src/Processors/Formats/Impl/ORC/Reader.h new file mode 100644 index 000000000000..981ab8c5c799 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.h @@ -0,0 +1,188 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/// The reader of the ORC files: https://orc.apache.org/specification/ORCv1/ + +namespace DB::ORC +{ + +/// Random access to the file. +class InputStream +{ +public: + virtual ~InputStream() = default; + + virtual UInt64 getLength() const = 0; + /// Reads exactly `length` bytes at `offset`. Must be thread-safe if `readAsync` is used. + virtual void read(void * buf, UInt64 length, UInt64 offset) = 0; + /// Reads in the background. The default implementation reads synchronously. + virtual std::future readAsync(void * buf, UInt64 length, UInt64 offset); + virtual const std::string & getName() const = 0; +}; + +struct ReaderOptions +{ + /// Two ranges are read with one request if the gap between them is at most this size... + UInt64 hole_size_limit = 8192; + /// ... and the combined range is at most this size. + UInt64 range_size_limit = 32 * 1024 * 1024; +}; + +struct RowReaderOptions +{ + /// The ids of the columns to read, with the same semantics as in the reference implementation + /// (see `selectColumnsByTypeIds`). If not set, all columns are read. + std::optional> include_types; + /// Read only the stripes that start in `[range_offset, range_offset + range_length)`. + UInt64 range_offset = 0; + UInt64 range_length = std::numeric_limits::max(); + /// For the dictionary-encoded string columns, fill `EncodedStringVectorBatch`. + bool enable_lazy_decoding = false; + /// The time zone to show the values of the TIMESTAMP (not TIMESTAMP_INSTANT) columns in. + std::string timezone_name = "GMT"; + std::shared_ptr search_argument; +}; + +class RowReader; + +class Reader +{ +public: + Reader(std::unique_ptr stream_, const ReaderOptions & options_); + ~Reader(); + + const Type & getType() const { return *schema; } + UInt64 getNumberOfRows() const { return footer.number_of_rows; } + UInt64 getNumberOfStripes() const { return footer.stripes.size(); } + const Proto::StripeInformation & getStripe(size_t index) const { return footer.stripes.at(index); } + static UInt64 getStripeLength(const Proto::StripeInformation & stripe) { return stripe.index_length + stripe.data_length + stripe.footer_length; } + + const Proto::Footer & getFooter() const { return footer; } + const Proto::PostScript & getPostScript() const { return postscript; } + CompressionKind getCompression() const { return postscript.compression; } + /// Whether the bloom filters of the file were written by a version of the C++ writer + /// that hashed the integers incorrectly (ORC-1024), so they must not be used. + bool hasBadBloomFilters() const; + UInt64 getCompressionBlockSize() const { return postscript.compression_block_size; } + + /// The statistics of the whole file, one per column. + const std::vector & getStatistics() const { return footer.statistics; } + /// The statistics of the stripes, read on the first call. Can be empty. + const Proto::Metadata & getMetadata(); + + /// Reads the stripe footer. Not thread-safe. + Proto::StripeFooter readStripeFooter(size_t stripe_index); + + std::unique_ptr createRowReader(const RowReaderOptions & options); + + /// Starts reading the data of the selected columns of the stripes in the background. + void preBuffer(const std::vector & stripes, const std::vector & include_types); + /// Releases the prefetched data that ends before `boundary`. + void releaseBuffer(UInt64 boundary); + + /// A piece of the file in memory. + struct Slice + { + std::shared_ptr> holder; + std::string_view data; + }; + + /// Reads the ranges `(offset, length)` of the file, from the prefetched data if possible. + /// The adjacent ranges are coalesced according to the options. + std::vector readRanges(const std::vector> & ranges); + + /// Decompresses a whole metadata stream (a footer, an index). + std::string decompress(std::string_view data, const std::string & name) const; + +private: + void readTail(); + + struct CachedRange + { + UInt64 offset; + UInt64 length; + std::shared_ptr> buffer; + std::future future; + bool ready = false; + }; + + /// Returns the ranges of the streams of the selected columns in the stripe, and the stripe footer. + std::vector> getStripeRanges(size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const; + + std::unique_ptr stream; + ReaderOptions options; + Proto::PostScript postscript; + UInt64 postscript_length = 0; + Proto::Footer footer; + std::optional metadata; + std::unique_ptr schema; + + std::mutex cache_mutex; + std::list cache; +}; + +/// Reads the rows of the selected stripes and columns in batches. +class RowReader +{ +public: + RowReader(Reader & reader_, const RowReaderOptions & options_); + ~RowReader(); + + std::unique_ptr createRowBatch() const; + + /// Fills the batch with the next rows, at most `max_rows`. Returns false at the end. + bool next(ColumnVectorBatch & batch, size_t max_rows); + + /// The type of the file with only the selected columns. The batches have this structure. + const Type & getSelectedType() const { return *selected_type; } + +private: + class StripeStreamsImpl; + + void startNextStripe(); + void loadStripeIndex(); + UInt64 numberOfRowGroups() const; + void pickRowGroups(); + void seekToRowGroup(size_t row_group); + UInt64 advanceToNextRowGroup(UInt64 current_row) const; + UInt64 computeBatchSize(UInt64 requested, UInt64 current_row) const; + bool evaluateStatistics(const std::vector & stats) const; + const DateLUTImpl & getWriterTimezone(const Proto::StripeFooter & stripe_footer) const; + + Reader & reader; + RowReaderOptions options; + std::vector selected_columns; + std::unique_ptr selected_type; + const DateLUTImpl & reader_timezone; + + UInt64 current_stripe = 0; + UInt64 last_stripe = 0; + UInt64 rows_in_current_stripe = 0; + UInt64 current_row_in_stripe = 0; + bool file_statistics_evaluated = false; + bool file_statistics_result = true; + + std::unique_ptr stripe_streams; + std::unique_ptr column_reader; + + /// For the predicate pushdown, by the column id. + std::unordered_map row_indexes; + std::unordered_map>> bloom_filters; + /// For each row group of the current stripe: zero if it is skipped, otherwise the row (in the + /// stripe) of the next skipped row group or the number of rows in the stripe. + std::vector next_skipped_rows; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.cpp b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp new file mode 100644 index 000000000000..e0543230c614 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp @@ -0,0 +1,1075 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +TruthValue operator||(TruthValue left, TruthValue right) +{ + if (right == TruthValue::YES || left == TruthValue::YES) + return TruthValue::YES; + if (right == TruthValue::YES_NULL || left == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + if (right == TruthValue::NO) + return left; + if (left == TruthValue::NO) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::NO_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::NO_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (left == TruthValue::NO_NULL && right == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator&&(TruthValue left, TruthValue right) +{ + if (right == TruthValue::NO || left == TruthValue::NO) + return TruthValue::NO; + if (right == TruthValue::NO_NULL || left == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + if (right == TruthValue::YES) + return left; + if (left == TruthValue::YES) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::YES_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::YES_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (left == TruthValue::YES_NULL && right == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator!(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: return TruthValue::YES; + case TruthValue::YES: return TruthValue::NO; + case TruthValue::IS_NULL: + case TruthValue::YES_NO: + case TruthValue::YES_NO_NULL: + return value; + case TruthValue::NO_NULL: return TruthValue::YES_NULL; + case TruthValue::YES_NULL: return TruthValue::NO_NULL; + } + return value; +} + +bool isNeeded(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: + case TruthValue::IS_NULL: + case TruthValue::NO_NULL: + return false; + default: + return true; + } +} + + +bool Literal::Decimal::parse(std::string_view s) +{ + bool negative = false; + size_t i = 0; + if (i < s.size() && (s[i] == '-' || s[i] == '+')) + { + negative = s[i] == '-'; + ++i; + } + Int256 result = 0; + bool has_digits = false; + bool has_point = false; + Int32 result_scale = 0; + for (; i < s.size(); ++i) + { + char c = s[i]; + if (c == '.' && !has_point) + { + has_point = true; + continue; + } + if (c < '0' || c > '9') + return false; + has_digits = true; + result = result * 10 + (c - '0'); + if (has_point) + ++result_scale; + /// More than 38 digits do not fit into the 128-bit value. + if (result > Int256(std::numeric_limits::max())) + return false; + } + if (!has_digits) + return false; + value = static_cast(negative ? -result : result); + scale = result_scale; + return true; +} + +std::string Literal::Decimal::toString() const +{ + bool negative = value < 0; + std::string digits = DB::toString(negative ? -Int256(value) : Int256(value)); + std::string result; + if (scale <= 0) + result = digits; + else + { + if (digits.size() <= static_cast(scale)) + digits = std::string(scale - digits.size() + 1, '0') + digits; + result = digits.substr(0, digits.size() - scale) + "." + digits.substr(digits.size() - scale); + size_t last = result.find_last_not_of('0'); + if (result[last] == '.') + result.resize(last); + else + result.resize(last + 1); + } + return negative ? "-" + result : result; +} + +namespace +{ + +int compareDecimals(const Literal::Decimal & a, const Literal::Decimal & b) +{ + Int256 left = a.value; + Int256 right = b.value; + for (Int32 s = a.scale; s < b.scale; ++s) + left *= 10; + for (Int32 s = b.scale; s < a.scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +} + +Literal::Literal(bool value) : type(PredicateDataType::BOOLEAN), int_value(value) {} +Literal::Literal(Int64 value) : type(PredicateDataType::LONG), int_value(value) {} +Literal::Literal(double value) : type(PredicateDataType::FLOAT), float_value(value) {} +Literal::Literal(const char * data, size_t size) : type(PredicateDataType::STRING), string_value(data, size) {} + +Literal::Literal(PredicateDataType type_, Int64 value) : type(type_), int_value(value) +{ + if (type != PredicateDataType::DATE) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Only DATE literals can be created from a type and an integer"); +} + +Literal::Literal(Int64 second, Int32 nanos) : type(PredicateDataType::TIMESTAMP), timestamp_value{second, nanos} {} + +Literal::Literal(Int128 value, Int32 /*precision*/, Int32 scale) : type(PredicateDataType::DECIMAL), decimal_value{value, scale} {} + + +namespace +{ + +/// Where a point is relative to the range [min, max]. +enum class Location : UInt8 +{ + BEFORE, + MIN, + MIDDLE, + MAX, + AFTER, +}; + +template +Location compareToRange(const T & point, const T & min, const T & max, Less less, Equal equal) +{ + if (less(point, min)) + return Location::BEFORE; + if (equal(point, min)) + return Location::MIN; + if (less(max, point)) + return Location::AFTER; + if (equal(point, max)) + return Location::MAX; + return Location::MIDDLE; +} + +template +TruthValue evaluatePredicateRange( + PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null, Less less, Equal equal) +{ + auto loc_of = [&](const T & v) { return compareToRange(v, min_value, max_value, less, equal); }; + bool min_equals_max = equal(min_value, max_value); + + switch (op) + { + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::AFTER) + return TruthValue::NO; + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + auto loc = loc_of(values.at(0)); + if (min_equals_max && loc == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::MIN) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER || loc == Location::MAX || (loc == Location::MIN && min_equals_max)) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IN: + { + if (min_equals_max) + { + for (const auto & value : values) + if (loc_of(value) == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + for (const auto & value : values) + { + auto loc = loc_of(value); + if (loc == Location::MIN || loc == Location::MIDDLE || loc == Location::MAX) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + case PredicateLeaf::Operator::BETWEEN: + { + if (values.empty()) + return TruthValue::YES_NO; + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::MIN) + { + auto loc2 = loc_of(values.at(1)); + if (loc2 == Location::AFTER || loc2 == Location::MAX) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc2 == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + if (loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; +} + +template +TruthValue evaluateRange(PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null) +{ + return evaluatePredicateRange(op, values, min_value, max_value, has_null, + [](const T & a, const T & b) { return a < b; }, + [](const T & a, const T & b) { return a == b; }); +} + +TruthValue evaluateBoolPredicate(PredicateLeaf::Operator op, const std::vector & literals, const Proto::ColumnStatistics & stats) +{ + bool has_null = stats.has_null.value_or(false); + if (!stats.bucket_statistics || stats.bucket_statistics->count.empty()) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + + UInt64 true_count = stats.bucket_statistics->count[0]; + UInt64 false_count = stats.number_of_values.value_or(0) - true_count; + switch (op) + { + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return TruthValue::NO; + if (false_count == 0) + return TruthValue::YES; + } + else + { + if (false_count == 0) + return TruthValue::NO; + if (true_count == 0) + return TruthValue::YES; + } + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (false_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + else + { + if (false_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (true_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +template +std::vector literalsTo(const std::vector & literals, Get get) +{ + std::vector result; + for (const auto & literal : literals) + if (!literal.isNull()) + result.push_back(get(literal)); + return result; +} + +/// From the reference implementation: the writer version that fixed the timestamp statistics. +constexpr UInt32 WRITER_VERSION_ORC_135 = 6; + +} + +TruthValue PredicateLeaf::evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const +{ + TruthValue result = TruthValue::YES_NO_NULL; + bool has_null = stats.has_null.value_or(false); + + switch (type) + { + case PredicateDataType::LONG: + { + if (stats.int_statistics && stats.int_statistics->minimum && stats.int_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getLong(); }), + *stats.int_statistics->minimum, *stats.int_statistics->maximum, has_null); + break; + } + case PredicateDataType::FLOAT: + { + if (stats.double_statistics && stats.double_statistics->minimum && stats.double_statistics->maximum) + { + if (!std::isfinite(stats.double_statistics->sum.value_or(0))) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + else + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getFloat(); }), + *stats.double_statistics->minimum, *stats.double_statistics->maximum, has_null); + } + break; + } + case PredicateDataType::STRING: + { + if (stats.string_statistics && stats.string_statistics->minimum && stats.string_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getString(); }), + *stats.string_statistics->minimum, *stats.string_statistics->maximum, has_null); + break; + } + case PredicateDataType::DATE: + { + if (stats.date_statistics && stats.date_statistics->minimum && stats.date_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getDate(); }), + static_cast(*stats.date_statistics->minimum), static_cast(*stats.date_statistics->maximum), has_null); + break; + } + case PredicateDataType::TIMESTAMP: + { + const auto & ts = stats.timestamp_statistics; + /// The stored nanoseconds are the sub-millisecond part plus one; malformed ones disable the pruning. + auto valid_nanos = [](const std::optional & nanos) { return !nanos || (*nanos >= 1 && *nanos <= 1'000'000); }; + if (ts && ts->minimum_utc && ts->maximum_utc && valid_nanos(ts->minimum_nanos) && valid_nanos(ts->maximum_nanos)) + { + Int32 min_nanos = ts->minimum_nanos ? static_cast(*ts->minimum_nanos) - 1 : 0; + Int32 max_nanos = ts->maximum_nanos ? static_cast(*ts->maximum_nanos) - 1 : 999999; + /// The milliseconds are rounded down, so the nanoseconds are not negative, as in the literals. + auto to_timestamp = [](Int64 millis, Int32 nanos) + { + Int64 second = millis / 1000; + Int64 rest = millis % 1000; + if (rest < 0) + { + rest += 1000; + --second; + } + return Literal::Timestamp{second, static_cast(rest * 1000000) + nanos}; + }; + Literal::Timestamp min = to_timestamp(*ts->minimum_utc, min_nanos); + Literal::Timestamp max = to_timestamp(*ts->maximum_utc, max_nanos); + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getTimestamp(); }), + min, max, has_null); + } + break; + } + case PredicateDataType::DECIMAL: + { + const auto & ds = stats.decimal_statistics; + if (ds && ds->minimum && ds->maximum) + { + Literal::Decimal min; + Literal::Decimal max; + if (min.parse(*ds->minimum) && max.parse(*ds->maximum)) + result = evaluatePredicateRange(op, + literalsTo(literals, [](const Literal & l) { return l.getDecimal(); }), + min, max, has_null, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) < 0; }, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) == 0; }); + } + break; + } + case PredicateDataType::BOOLEAN: + { + if (stats.bucket_statistics) + result = evaluateBoolPredicate(op, literals, stats); + break; + } + } + + /// Respect a null literal for IN. + if (op == Operator::IN && has_null) + for (const auto & literal : literals) + if (literal.isNull()) + return TruthValue::YES_NO_NULL; + + return result; +} + +namespace +{ + +TruthValue checkInBloomFilter(PredicateDataType type, const Literal & literal, const BloomFilter & bf, bool has_null) +{ + TruthValue result = has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (literal.isNull()) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::NO; + else + { + bool found = true; + switch (type) + { + case PredicateDataType::LONG: found = bf.testLong(literal.getLong()); break; + case PredicateDataType::FLOAT: found = bf.testDouble(literal.getFloat()); break; + case PredicateDataType::STRING: found = bf.testBytes(literal.getString().data(), literal.getString().size()); break; + case PredicateDataType::DECIMAL: + { + std::string s = literal.getDecimal().toString(); + found = bf.testBytes(s.data(), s.size()); + break; + } + case PredicateDataType::TIMESTAMP: + { + /// The writers round the negative milliseconds differently: the Java one down, the C++ one toward zero. + const auto timestamp = literal.getTimestamp(); + const Int64 millis_down = timestamp.getMillis(); + const bool has_fraction = timestamp.second < 0 && timestamp.nanos % 1000000 != 0; + found = bf.testLong(millis_down) || (has_fraction && bf.testLong(millis_down + 1)); + break; + } + case PredicateDataType::DATE: found = bf.testLong(literal.getDate()); break; + case PredicateDataType::BOOLEAN: found = true; break; + } + if (found) + result = TruthValue::YES_NO_NULL; + } + + if (result == TruthValue::YES_NO_NULL && !has_null) + result = TruthValue::YES_NO; + return result; +} + +} + +TruthValue PredicateLeaf::evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const +{ + switch (op) + { + case Operator::NULL_SAFE_EQUALS: + /// Null-safe equals does not return the `*_NULL` variants. + return checkInBloomFilter(type, literals.front(), bloom_filter, false); + case Operator::EQUALS: + return checkInBloomFilter(type, literals.front(), bloom_filter, has_null); + case Operator::IN: + for (const auto & literal : literals) + { + TruthValue result = checkInBloomFilter(type, literal, bloom_filter, has_null); + if (result == TruthValue::YES_NO_NULL || result == TruthValue::YES_NO) + return result; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +TruthValue PredicateLeaf::evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const +{ + /// The files written before ORC-135 store the timestamps in the local time zone of the writer. + if (type == PredicateDataType::TIMESTAMP && writer_version < WRITER_VERSION_ORC_135) + return TruthValue::YES_NO_NULL; + + /// The files written by some writers do not have the `has_null` field. + if (!stats.has_null) + return TruthValue::YES_NO_NULL; + + bool has_null = *stats.has_null; + bool all_null = has_null && stats.number_of_values.value_or(0) == 0; + if (op == Operator::IS_NULL || ((op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS) && literals.at(0).isNull())) + return all_null ? TruthValue::YES : (has_null ? TruthValue::YES_NO : TruthValue::NO); + if (all_null) + return TruthValue::IS_NULL; + + TruthValue result = evaluatePredicateMinMax(stats); + if (bloom_filter && result != TruthValue::NO_NULL && result != TruthValue::NO + && (op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS || op == Operator::IN)) + return evaluatePredicateBloomFilter(*bloom_filter, has_null); + return result; +} + + +class ExpressionTree +{ +public: + enum class Operator : UInt8 + { + OR, + AND, + NOT, + LEAF, + CONSTANT, + }; + + explicit ExpressionTree(Operator op_) : op(op_) {} + explicit ExpressionTree(TruthValue constant_) : op(Operator::CONSTANT), constant(constant_) {} + explicit ExpressionTree(size_t leaf_) : op(Operator::LEAF), leaf(leaf_) {} + ExpressionTree(Operator op_, std::vector children_) : op(op_), children(std::move(children_)) {} + + TruthValue evaluate(const std::vector & leaves) const + { + switch (op) + { + case Operator::OR: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && !isNeeded(result); ++i) + result = children[i]->evaluate(leaves) || result; + return result; + } + case Operator::AND: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && isNeeded(result); ++i) + result = children[i]->evaluate(leaves) && result; + return result; + } + case Operator::NOT: + return !children.at(0)->evaluate(leaves); + case Operator::LEAF: + return leaves.at(leaf); + case Operator::CONSTANT: + return constant; + } + return TruthValue::YES_NO_NULL; + } + + Operator op; + TruthValue constant = TruthValue::YES_NO_NULL; + size_t leaf = 0; + std::vector children; +}; + + +SearchArgument::SearchArgument(ExpressionTreePtr root_, std::vector leaves_) + : root(std::move(root_)), leaves(std::move(leaves_)) +{ +} + +TruthValue SearchArgument::evaluate(const std::vector & leaf_values) const +{ + return root ? root->evaluate(leaf_values) : TruthValue::YES_NO_NULL; +} + + +namespace +{ + +using Op = ExpressionTree::Operator; + +/// Pushes the negations down to the leaves and removes the double negations. +ExpressionTreePtr pushDownNot(ExpressionTreePtr root) +{ + if (root->op == Op::NOT) + { + ExpressionTreePtr child = root->children.at(0); + switch (child->op) + { + case Op::NOT: + return pushDownNot(child->children.at(0)); + case Op::CONSTANT: + return std::make_shared(!child->constant); + case Op::AND: + case Op::OR: + { + auto result = std::make_shared(child->op == Op::AND ? Op::OR : Op::AND); + for (const auto & kid : child->children) + result->children.push_back(pushDownNot(std::make_shared(Op::NOT, std::vector{kid}))); + return result; + } + case Op::LEAF: + break; + } + } + else + { + for (auto & kid : root->children) + kid = pushDownNot(kid); + } + return root; +} + +/// Removes the MAYBE (YES_NO_NULL) constants: they are dropped from AND and they replace OR. +ExpressionTreePtr foldMaybe(ExpressionTreePtr expr) +{ + for (auto & kid : expr->children) + { + ExpressionTreePtr child = foldMaybe(kid); + if (child->op == Op::CONSTANT && child->constant == TruthValue::YES_NO_NULL) + { + if (expr->op == Op::AND) + kid = nullptr; + else if (expr->op == Op::OR) + return child; + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Got a maybe as a child of a NOT in ORC search argument"); + } + else + kid = child; + } + + if (!expr->children.empty()) + { + std::erase(expr->children, nullptr); + if (expr->children.empty()) + return std::make_shared(TruthValue::YES_NO_NULL); + } + return expr; +} + +/// Converts multi-level ANDs and ORs into single level ones. +ExpressionTreePtr flatten(ExpressionTreePtr root) +{ + std::vector nodes; + for (auto & kid : root->children) + { + ExpressionTreePtr child = flatten(kid); + if (child->op == root->op && child->op != Op::NOT) + nodes.insert(nodes.end(), child->children.begin(), child->children.end()); + else + nodes.push_back(child); + } + root->children = std::move(nodes); + if ((root->op == Op::OR || root->op == Op::AND) && root->children.size() == 1) + return root->children[0]; + return root; +} + +ExpressionTreePtr copyTree(const ExpressionTreePtr & node) +{ + auto result = std::make_shared(*node); + return result; +} + +void generateAllCombinations( + std::vector & result, const std::vector & and_list, size_t and_index, const std::vector & non_and_list) +{ + const auto & kids = and_list[and_index]->children; + if (result.empty()) + { + for (const auto & kid : kids) + { + auto node = std::make_shared(Op::OR); + for (const auto & non_and : non_and_list) + node->children.push_back(copyTree(non_and)); + node->children.push_back(kid); + result.push_back(node); + } + } + else + { + std::vector work = std::move(result); + result.clear(); + for (const auto & kid : kids) + { + for (const auto & node : work) + { + auto copy = copyTree(node); + copy->children.push_back(kid); + result.push_back(copy); + } + } + } + if (and_index + 1 < and_list.size()) + generateAllCombinations(result, and_list, and_index + 1, non_and_list); +} + +constexpr size_t CNF_COMBINATIONS_THRESHOLD = 256; + +/// Converts the expression into the conjunctive normal form, if it is not too large. +ExpressionTreePtr convertToCNF(ExpressionTreePtr root) +{ + for (auto & kid : root->children) + kid = convertToCNF(kid); + + if (root->op != Op::OR) + return root; + + std::vector non_and_list; + std::vector and_list; + for (const auto & child : root->children) + { + if (child->op == Op::AND) + and_list.push_back(child); + else if (child->op == Op::OR) + non_and_list.insert(non_and_list.end(), child->children.begin(), child->children.end()); + else + non_and_list.push_back(child); + } + + if (and_list.empty()) + return root; + + size_t num_combinations = 1; + for (const auto & node : and_list) + { + num_combinations *= node->children.size(); + if (num_combinations > CNF_COMBINATIONS_THRESHOLD) + return std::make_shared(TruthValue::YES_NO_NULL); + } + + auto result = std::make_shared(Op::AND); + generateAllCombinations(result->children, and_list, 0, non_and_list); + return result; +} + +void collectUsedLeaves(const ExpressionTreePtr & node, std::vector & reorder, size_t & next) +{ + if (node->op == Op::LEAF) + { + if (reorder[node->leaf] == std::numeric_limits::max()) + reorder[node->leaf] = next++; + return; + } + for (const auto & kid : node->children) + collectUsedLeaves(kid, reorder, next); +} + +/// The trees can share nodes after the CNF conversion, so rewrite every leaf node exactly once. +void rewriteLeaves(const ExpressionTreePtr & root, const std::vector & reorder) +{ + std::unordered_set leaves; + std::deque nodes{root.get()}; + while (!nodes.empty()) + { + ExpressionTree * node = nodes.front(); + nodes.pop_front(); + if (node->op == Op::LEAF) + leaves.insert(node); + else + for (const auto & kid : node->children) + nodes.push_back(kid.get()); + } + for (auto * leaf : leaves) + leaf->leaf = reorder[leaf->leaf]; +} + +} + + +SearchArgumentBuilder::SearchArgumentBuilder() +{ + root = std::make_shared(Op::AND); + stack.push_back(root); +} + +SearchArgumentBuilder & SearchArgumentBuilder::start(UInt8 op) +{ + auto node = std::make_shared(static_cast(op)); + stack.back()->children.push_back(node); + stack.push_back(node); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::startOr() { return start(static_cast(Op::OR)); } +SearchArgumentBuilder & SearchArgumentBuilder::startAnd() { return start(static_cast(Op::AND)); } +SearchArgumentBuilder & SearchArgumentBuilder::startNot() { return start(static_cast(Op::NOT)); } + +SearchArgumentBuilder & SearchArgumentBuilder::end() +{ + auto current = stack.back(); + stack.pop_back(); + if (stack.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unbalanced end() in ORC search argument builder"); + if (current->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an expression with no children in ORC search argument builder"); + if (current->op == Op::NOT && current->children.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "A NOT expression must have exactly one child in ORC search argument builder"); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::literal(TruthValue value) +{ + stack.back()->children.push_back(std::make_shared(value)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::addLeaf(PredicateLeaf leaf) +{ + size_t index = leaves.size(); + leaves.push_back(std::move(leaf)); + stack.back()->children.push_back(std::make_shared(index)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThan(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::equals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::NULL_SAFE_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::in(UInt64 column_id, PredicateDataType type, const std::vector & values) +{ + if (values.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an IN expression with no arguments in ORC search argument builder"); + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IN, type, column_id, values)); +} + +SearchArgumentBuilder & SearchArgumentBuilder::isNull(UInt64 column_id, PredicateDataType type) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IS_NULL, type, column_id, {})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::BETWEEN, type, column_id, {std::move(lower), std::move(upper)})); +} + +std::unique_ptr SearchArgumentBuilder::build() +{ + if (stack.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to end {} operations in ORC search argument builder", stack.size() - 1); + if (root->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Empty ORC search argument"); + + root = pushDownNot(root); + root = foldMaybe(root); + root = flatten(root); + root = convertToCNF(root); + root = flatten(root); + + std::vector reorder(leaves.size(), std::numeric_limits::max()); + size_t num_used = 0; + collectUsedLeaves(root, reorder, num_used); + rewriteLeaves(root, reorder); + + std::vector used_leaves; + used_leaves.reserve(num_used); + std::vector by_new_index(num_used); + for (size_t i = 0; i < leaves.size(); ++i) + if (reorder[i] != std::numeric_limits::max()) + by_new_index[reorder[i]] = &leaves[i]; + for (const auto * leaf : by_new_index) + used_leaves.push_back(*leaf); + + return std::make_unique(root, std::move(used_leaves)); +} + + +namespace +{ + +constexpr UInt32 MURMUR3_DEFAULT_SEED = 104729; + +inline UInt64 rotl64(UInt64 x, int r) +{ + return (x << r) | (x >> (64 - r)); +} + +inline UInt64 fmix64(UInt64 value) +{ + value ^= (value >> 33); + value *= 0xff51afd7ed558ccdULL; + value ^= (value >> 33); + value *= 0xc4ceb9fe1a85ec53ULL; + value ^= (value >> 33); + return value; +} + +/// The 64-bit variant of Murmur3 used by ORC (the lower half of the 128-bit hash with one state). +UInt64 murmur3Hash64(const UInt8 * data, size_t size) +{ + UInt64 h = MURMUR3_DEFAULT_SEED; + const UInt64 c1 = 0x87c37b91114253d5ULL; + const UInt64 c2 = 0x4cf5ad432745937fULL; + size_t blocks = size >> 3; + for (size_t i = 0; i < blocks; ++i) + { + UInt64 k = 0; + memcpy(&k, data + i * 8, 8); + if constexpr (std::endian::native == std::endian::big) + k = std::byteswap(k); + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + h = rotl64(h, 27); + h = h * 5 + 0x52dce729; + } + + UInt64 k = 0; + size_t idx = blocks << 3; + size_t tail = size - idx; + for (size_t i = tail; i > 0; --i) + k ^= static_cast(data[idx + i - 1]) << ((i - 1) * 8); + if (tail) + { + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + } + + h ^= static_cast(size); + return fmix64(h); +} + +/// Thomas Wang's 64-bit integer hash, as in the reference implementation. +Int64 getLongHash(Int64 key) +{ + UInt64 k = static_cast(key); + k = (~k) + (k << 21); + k = k ^ static_cast(static_cast(k) >> 24); + k = (k + (k << 3)) + (k << 8); + k = k ^ static_cast(static_cast(k) >> 14); + k = (k + (k << 2)) + (k << 4); + k = k ^ static_cast(static_cast(k) >> 28); + k = k + (k << 31); + return static_cast(k); +} + +} + +BloomFilter::BloomFilter(const Proto::BloomFilter & proto) : num_hash_functions(proto.num_hash_functions) +{ + /// The writers use a few hash functions (the optimal number for the false positive probability), + /// a huge number from a corrupt file would make every probe extremely slow. + static constexpr UInt32 MAX_HASH_FUNCTIONS = 256; + if (num_hash_functions == 0 || num_hash_functions > MAX_HASH_FUNCTIONS) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid number of hash functions {} of a bloom filter in ORC file, must be from 1 to {}", + num_hash_functions, MAX_HASH_FUNCTIONS); + const std::string & bitset = proto.utf8bitset.value(); + if (bitset.empty() || bitset.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "The size of a bloom filter in ORC file must be a positive multiple of 8 bytes"); + bits.resize(bitset.size() / 8); + memcpy(bits.data(), bitset.data(), bitset.size()); + if constexpr (std::endian::native == std::endian::big) + for (auto & word : bits) + word = std::byteswap(word); +} + +bool BloomFilter::testHash(Int64 hash) const +{ + Int32 hash1 = static_cast(hash & 0xffffffff); + Int32 hash2 = static_cast(static_cast(hash) >> 32); + UInt64 num_bits = bits.size() * 64; + for (UInt32 i = 1; i <= num_hash_functions; ++i) + { + Int32 combined = static_cast(static_cast(hash1) + i * static_cast(hash2)); + if (combined < 0) + combined = ~combined; + UInt64 pos = static_cast(combined) % num_bits; + if (!(bits[pos >> 6] & (1ULL << (pos % 64)))) + return false; + } + return true; +} + +bool BloomFilter::testLong(Int64 value) const +{ + return testHash(getLongHash(value)); +} + +bool BloomFilter::testDouble(double value) const +{ + return testLong(std::bit_cast(value)); +} + +bool BloomFilter::testBytes(const char * data, size_t size) const +{ + return testHash(static_cast(murmur3Hash64(reinterpret_cast(data), size))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.h b/src/Processors/Formats/Impl/ORC/SearchArgument.h new file mode 100644 index 000000000000..da19904275e7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.h @@ -0,0 +1,198 @@ +#pragma once + +#include + +#include +#include +#include + +/// Predicates for skipping stripes and row groups by the column statistics and the bloom filters. +/// The semantics (the truth values, the normalization of the expression, the evaluation of each +/// predicate against the statistics) are the same as in the reference implementation. + +namespace DB::ORC +{ + +/// The possible outcomes of a predicate over a set of rows: whether any row can satisfy it (YES), +/// fail it (NO), or evaluate it to NULL. +enum class TruthValue : UInt8 +{ + YES, + NO, + IS_NULL, + YES_NULL, + NO_NULL, + YES_NO, + YES_NO_NULL, +}; + +TruthValue operator||(TruthValue left, TruthValue right); +TruthValue operator&&(TruthValue left, TruthValue right); +TruthValue operator!(TruthValue value); +/// Whether the rows have to be read. +bool isNeeded(TruthValue value); + +enum class PredicateDataType : UInt8 +{ + LONG, + FLOAT, + STRING, + DATE, + DECIMAL, + TIMESTAMP, + BOOLEAN, +}; + +class Literal +{ +public: + struct Timestamp + { + Int64 second = 0; + Int32 nanos = 0; + + /// Rounded down, as the nanoseconds are not negative. + Int64 getMillis() const { return second * 1000 + nanos / 1000000; } + auto operator<=>(const Timestamp &) const = default; + }; + + struct Decimal + { + Int128 value = 0; + Int32 scale = 0; + + /// Parses a decimal number like `-123.45`. Returns false if it is malformed. + bool parse(std::string_view s); + /// Without the trailing zeros in the fraction, as in the bloom filters. + std::string toString() const; + }; + + explicit Literal(bool value); + explicit Literal(Int64 value); + explicit Literal(double value); + Literal(const char * data, size_t size); + /// Only for DATE: the number of days since the epoch. + Literal(PredicateDataType type, Int64 value); + /// TIMESTAMP: the seconds since the epoch in UTC and the nanoseconds. + Literal(Int64 second, Int32 nanos); + Literal(Int128 value, Int32 precision, Int32 scale); + + PredicateDataType getType() const { return type; } + bool isNull() const { return is_null; } + + bool getBool() const { return int_value != 0; } + Int64 getLong() const { return int_value; } + Int64 getDate() const { return int_value; } + double getFloat() const { return float_value; } + const std::string & getString() const { return string_value; } + Timestamp getTimestamp() const { return timestamp_value; } + Decimal getDecimal() const { return decimal_value; } + +private: + PredicateDataType type; + bool is_null = false; + Int64 int_value = 0; + double float_value = 0; + std::string string_value; + Timestamp timestamp_value; + Decimal decimal_value; +}; + +class BloomFilter; + +class PredicateLeaf +{ +public: + enum class Operator : UInt8 + { + EQUALS, + NULL_SAFE_EQUALS, + LESS_THAN, + LESS_THAN_EQUALS, + IN, + BETWEEN, + IS_NULL, + }; + + PredicateLeaf(Operator op_, PredicateDataType type_, UInt64 column_id_, std::vector literals_) + : op(op_), type(type_), column_id(column_id_), literals(std::move(literals_)) {} + + UInt64 getColumnId() const { return column_id; } + + /// `writer_version` is from the postscript of the file. `bloom_filter` can be nullptr. + TruthValue evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const; + +private: + TruthValue evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const; + TruthValue evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const; + + Operator op; + PredicateDataType type; + UInt64 column_id; + std::vector literals; +}; + +class ExpressionTree; +using ExpressionTreePtr = std::shared_ptr; + +class SearchArgument +{ +public: + SearchArgument(ExpressionTreePtr root_, std::vector leaves_); + + const std::vector & getLeaves() const { return leaves; } + TruthValue evaluate(const std::vector & leaf_values) const; + +private: + ExpressionTreePtr root; + std::vector leaves; +}; + +class SearchArgumentBuilder +{ +public: + SearchArgumentBuilder(); + + SearchArgumentBuilder & startOr(); + SearchArgumentBuilder & startAnd(); + SearchArgumentBuilder & startNot(); + SearchArgumentBuilder & end(); + + SearchArgumentBuilder & literal(TruthValue value); + SearchArgumentBuilder & lessThan(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & equals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & in(UInt64 column_id, PredicateDataType type, const std::vector & values); + SearchArgumentBuilder & isNull(UInt64 column_id, PredicateDataType type); + SearchArgumentBuilder & between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper); + + std::unique_ptr build(); + +private: + SearchArgumentBuilder & start(UInt8 op); + SearchArgumentBuilder & addLeaf(PredicateLeaf leaf); + + std::vector stack; + ExpressionTreePtr root; + std::vector leaves; +}; + +/// A bloom filter of a row group (or a stripe), from the BLOOM_FILTER_UTF8 stream. +class BloomFilter +{ +public: + explicit BloomFilter(const Proto::BloomFilter & proto); + + bool testLong(Int64 value) const; + bool testDouble(double value) const; + bool testBytes(const char * data, size_t size) const; + +private: + bool testHash(Int64 hash) const; + + UInt32 num_hash_functions; + std::vector bits; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.cpp b/src/Processors/Formats/Impl/ORC/Statistics.cpp new file mode 100644 index 000000000000..0b1b4c86cd9b --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.cpp @@ -0,0 +1,462 @@ +#include +#include + +#include + +#include + + +namespace DB::ORC +{ + +namespace +{ + +int compareDecimals(Int128 a, Int32 a_scale, Int128 b, Int32 b_scale) +{ + Int256 left = a; + Int256 right = b; + for (Int32 s = a_scale; s < b_scale; ++s) + left *= 10; + for (Int32 s = b_scale; s < a_scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +std::string decimalToString(Int128 value, Int32 scale) +{ + return Literal::Decimal{value, scale}.toString(); +} + +} + +void StatisticsBuilder::updateInteger(Int64 value) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + if (has_int_sum && __builtin_add_overflow(int_sum, value, &int_sum)) + has_int_sum = false; +} + +void StatisticsBuilder::updateDouble(double value) +{ + if (!has_minimum) + { + has_minimum = true; + double_minimum = double_maximum = value; + } + else + { + double_minimum = std::min(double_minimum, value); + double_maximum = std::max(double_maximum, value); + } + double_sum += value; +} + +void StatisticsBuilder::updateString(std::string_view value) +{ + if (!has_minimum) + { + has_minimum = true; + string_minimum = value; + string_maximum = value; + } + else + { + if (value < std::string_view(string_minimum)) + string_minimum = value; + if (value > std::string_view(string_maximum)) + string_maximum = value; + } + total_length += value.size(); +} + +void StatisticsBuilder::updateBinary(size_t length) +{ + total_length += length; +} + +void StatisticsBuilder::updateBoolean(bool value) +{ + if (value) + ++true_count; +} + +void StatisticsBuilder::updateDate(Int32 value) +{ + updateInteger(value); +} + +void StatisticsBuilder::updateDecimal(Int128 value, Int32 scale) +{ + if (!has_minimum) + { + has_minimum = true; + decimal_minimum = decimal_maximum = value; + decimal_minimum_scale = decimal_maximum_scale = scale; + } + else + { + if (compareDecimals(value, scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = value; + decimal_minimum_scale = scale; + } + if (compareDecimals(value, scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = value; + decimal_maximum_scale = scale; + } + } + + if (has_decimal_sum) + { + Int256 sum = decimal_sum; + Int256 addend = value; + Int32 result_scale = std::max(decimal_sum_scale, scale); + for (Int32 s = decimal_sum_scale; s < result_scale; ++s) + sum *= 10; + for (Int32 s = scale; s < result_scale; ++s) + addend *= 10; + sum += addend; + if (sum > Int256(std::numeric_limits::max()) || sum < Int256(std::numeric_limits::min())) + has_decimal_sum = false; + else + { + decimal_sum = static_cast(sum); + decimal_sum_scale = result_scale; + } + } +} + +void StatisticsBuilder::updateTimestamp(Int64 millis, Int32 nanos) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = millis; + minimum_nanos = maximum_nanos = nanos; + return; + } + if (millis <= int_minimum) + { + if (millis < int_minimum || nanos < minimum_nanos) + minimum_nanos = nanos; + int_minimum = millis; + } + if (millis >= int_maximum) + { + if (millis > int_maximum || nanos > maximum_nanos) + maximum_nanos = nanos; + int_maximum = millis; + } +} + +void StatisticsBuilder::updateCollection(UInt64 children) +{ + Int64 value = static_cast(children); + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + total_children += children; +} + +void StatisticsBuilder::merge(const StatisticsBuilder & other) +{ + number_of_values += other.number_of_values; + has_null |= other.has_null; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + case DATE: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + has_int_sum = has_int_sum && other.has_int_sum; + if (has_int_sum && __builtin_add_overflow(int_sum, other.int_sum, &int_sum)) + has_int_sum = false; + break; + case FLOAT: + case DOUBLE: + if (other.has_minimum) + { + if (!has_minimum) + { + double_minimum = other.double_minimum; + double_maximum = other.double_maximum; + } + else + { + double_minimum = std::min(double_minimum, other.double_minimum); + double_maximum = std::max(double_maximum, other.double_maximum); + } + has_minimum = true; + } + double_sum += other.double_sum; + break; + case STRING: + case CHAR: + case VARCHAR: + if (other.has_minimum) + { + if (!has_minimum) + { + string_minimum = other.string_minimum; + string_maximum = other.string_maximum; + } + else + { + if (other.string_minimum < string_minimum) + string_minimum = other.string_minimum; + if (other.string_maximum > string_maximum) + string_maximum = other.string_maximum; + } + has_minimum = true; + } + total_length += other.total_length; + break; + case BINARY: + total_length += other.total_length; + break; + case BOOLEAN: + true_count += other.true_count; + break; + case DECIMAL: + if (other.has_minimum) + { + if (!has_minimum) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + else + { + if (compareDecimals(other.decimal_minimum, other.decimal_minimum_scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + } + if (compareDecimals(other.decimal_maximum, other.decimal_maximum_scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + } + has_minimum = true; + } + has_decimal_sum = has_decimal_sum && other.has_decimal_sum; + if (has_decimal_sum) + { + /// Reuse the update of the sum without touching the minimum and the maximum. + bool saved_has_minimum = has_minimum; + Int128 saved_min = decimal_minimum; + Int32 saved_min_scale = decimal_minimum_scale; + Int128 saved_max = decimal_maximum; + Int32 saved_max_scale = decimal_maximum_scale; + updateDecimal(other.decimal_sum, other.decimal_sum_scale); + has_minimum = saved_has_minimum; + decimal_minimum = saved_min; + decimal_minimum_scale = saved_min_scale; + decimal_maximum = saved_max; + decimal_maximum_scale = saved_max_scale; + } + break; + case TIMESTAMP: + case TIMESTAMP_INSTANT: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + minimum_nanos = other.minimum_nanos; + maximum_nanos = other.maximum_nanos; + has_minimum = true; + } + else + { + if (other.int_minimum <= int_minimum) + { + if (other.int_minimum < int_minimum || other.minimum_nanos < minimum_nanos) + minimum_nanos = other.minimum_nanos; + int_minimum = other.int_minimum; + } + if (other.int_maximum >= int_maximum) + { + if (other.int_maximum > int_maximum || other.maximum_nanos > maximum_nanos) + maximum_nanos = other.maximum_nanos; + int_maximum = other.int_maximum; + } + } + } + break; + case LIST: + case MAP: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + total_children += other.total_children; + break; + default: + break; + } +} + +void StatisticsBuilder::reset() +{ + *this = StatisticsBuilder(kind); +} + +Proto::ColumnStatistics StatisticsBuilder::toProto() const +{ + Proto::ColumnStatistics res; + res.has_null = has_null; + res.number_of_values = number_of_values; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + { + auto & stats = res.int_statistics.emplace(); + if (has_minimum) + { + stats.minimum = int_minimum; + stats.maximum = int_maximum; + } + if (has_int_sum) + stats.sum = int_sum; + break; + } + case DATE: + { + auto & stats = res.date_statistics.emplace(); + if (has_minimum) + { + stats.minimum = static_cast(int_minimum); + stats.maximum = static_cast(int_maximum); + } + break; + } + case FLOAT: + case DOUBLE: + { + auto & stats = res.double_statistics.emplace(); + if (has_minimum) + { + stats.minimum = double_minimum; + stats.maximum = double_maximum; + } + stats.sum = double_sum; + break; + } + case STRING: + case CHAR: + case VARCHAR: + { + auto & stats = res.string_statistics.emplace(); + if (has_minimum) + { + stats.minimum = string_minimum; + stats.maximum = string_maximum; + } + stats.sum = static_cast(total_length); + break; + } + case BINARY: + res.binary_statistics.emplace().sum = static_cast(total_length); + break; + case BOOLEAN: + res.bucket_statistics.emplace().count.push_back(true_count); + break; + case DECIMAL: + { + auto & stats = res.decimal_statistics.emplace(); + if (has_minimum) + { + stats.minimum = decimalToString(decimal_minimum, decimal_minimum_scale); + stats.maximum = decimalToString(decimal_maximum, decimal_maximum_scale); + } + if (has_decimal_sum) + stats.sum = decimalToString(decimal_sum, decimal_sum_scale); + break; + } + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + auto & stats = res.timestamp_statistics.emplace(); + if (has_minimum) + { + stats.minimum_utc = int_minimum; + stats.maximum_utc = int_maximum; + if (minimum_nanos != 0) + stats.minimum_nanos = static_cast(minimum_nanos) + 1; + if (maximum_nanos != 999999) + stats.maximum_nanos = static_cast(maximum_nanos) + 1; + } + break; + } + case LIST: + case MAP: + { + auto & stats = res.collection_statistics.emplace(); + if (has_minimum) + { + stats.min_children = static_cast(int_minimum); + stats.max_children = static_cast(int_maximum); + } + stats.total_children = total_children; + break; + } + default: + break; + } + return res; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.h b/src/Processors/Formats/Impl/ORC/Statistics.h new file mode 100644 index 000000000000..c00c00e07b94 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.h @@ -0,0 +1,71 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// Accumulates the statistics of a column for a row group, a stripe or the whole file, +/// in the same way as the reference implementation. +class StatisticsBuilder +{ +public: + explicit StatisticsBuilder(TypeKind kind_) : kind(kind_) {} + + void increase(UInt64 count) { number_of_values += count; } + void setHasNull() { has_null = true; } + + void updateInteger(Int64 value); + void updateDouble(double value); + void updateString(std::string_view value); + void updateBinary(size_t length); + void updateBoolean(bool value); + void updateDate(Int32 value); + void updateDecimal(Int128 value, Int32 scale); + /// `millis` since the epoch in UTC, `nanos` is the sub-millisecond part. + void updateTimestamp(Int64 millis, Int32 nanos); + void updateCollection(UInt64 children); + + void merge(const StatisticsBuilder & other); + void reset(); + + Proto::ColumnStatistics toProto() const; + +private: + TypeKind kind; + UInt64 number_of_values = 0; + bool has_null = false; + bool has_minimum = false; + + Int64 int_minimum = 0; + Int64 int_maximum = 0; + Int64 int_sum = 0; + bool has_int_sum = true; + + double double_minimum = 0; + double double_maximum = 0; + double double_sum = 0; + + std::string string_minimum; + std::string string_maximum; + UInt64 total_length = 0; + + UInt64 true_count = 0; + + Int128 decimal_minimum = 0; + Int32 decimal_minimum_scale = 0; + Int128 decimal_maximum = 0; + Int32 decimal_maximum_scale = 0; + Int128 decimal_sum = 0; + Int32 decimal_sum_scale = 0; + bool has_decimal_sum = true; + + Int32 minimum_nanos = 0; + Int32 maximum_nanos = 999999; + + UInt64 total_children = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.cpp b/src/Processors/Formats/Impl/ORC/Stream.cpp new file mode 100644 index 000000000000..275e75915dca --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.cpp @@ -0,0 +1,248 @@ +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +UInt64 PositionProvider::next() +{ + if (index >= positions.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not enough positions in a row index entry of ORC file"); + return positions[index++]; +} + + +InputByteStream::InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_) + : data(data_), length(data_.size()), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +InputByteStream::InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_) + : length(length_), loader(std::move(loader_)), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +std::string_view InputByteStream::getRange(UInt64 offset, UInt64 size) +{ + if (!loader) + return data.substr(offset, size); + + if (offset < window_offset || offset + size > window_offset + data.size()) + { + UInt64 load_size = std::min(length - offset, std::max(size, LAZY_READ_SIZE)); + auto range = loader(offset, load_size); + if (range.data.size() != load_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Loaded {} bytes instead of {} from ORC stream {}", range.data.size(), load_size, name); + window_holder = std::move(range.holder); + data = range.data; + window_offset = offset; + } + return data.substr(offset - window_offset, size); +} + +bool InputByteStream::nextChunk() +{ + while (next_chunk_offset < length) + { + if (compression == CompressionKind::NONE) + { + UInt64 size = length - next_chunk_offset; + if (loader) + size = std::min(size, LAZY_READ_SIZE); + pos = getRange(next_chunk_offset, size).data(); + end = pos + size; + next_chunk_offset += size; + return true; + } + + if (length - next_chunk_offset < COMPRESSION_HEADER_SIZE) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated compression chunk header in ORC stream {}", name); + + const UInt8 * header = reinterpret_cast(getRange(next_chunk_offset, COMPRESSION_HEADER_SIZE).data()); + UInt32 header_value = header[0] | (header[1] << 8) | (header[2] << 16); + bool is_original = header_value & 1; + size_t chunk_length = header_value >> 1; + size_t chunk_offset = next_chunk_offset + COMPRESSION_HEADER_SIZE; + + if (chunk_length > length - chunk_offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Compression chunk of size {} at offset {} goes beyond the end of ORC stream {} of size {}", + chunk_length, next_chunk_offset, name, length); + + next_chunk_offset = chunk_offset + chunk_length; + const char * chunk = getRange(chunk_offset, chunk_length).data(); + + if (is_original) + { + pos = chunk; + end = chunk + chunk_length; + } + else + { + /// The chunk length is at most 8 MiB, so the bound does not overflow. + size_t capacity = std::min(block_size, maxDecompressedSize(compression, chunk, chunk_length)); + if (decompressed.size() < capacity) + decompressed.resize(capacity); + size_t size = decompressChunk(compression, chunk, chunk_length, decompressed.data(), capacity); + pos = decompressed.data(); + end = decompressed.data() + size; + } + + if (pos != end) + return true; + } + + pos = end = nullptr; + return false; +} + +void InputByteStream::readBytes(char * to, size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + memcpy(to, pos, count); + pos += count; + to += count; + n -= count; + } +} + +void InputByteStream::skipBytes(size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + pos += count; + n -= count; + } +} + +void InputByteStream::seek(PositionProvider & positions) +{ + if (compression == CompressionKind::NONE) + { + UInt64 offset = positions.next(); + if (offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", offset, name, length); + next_chunk_offset = offset; + pos = end = nullptr; + nextChunk(); + return; + } + + UInt64 chunk_offset = positions.next(); + UInt64 uncompressed_offset = positions.next(); + if (chunk_offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", chunk_offset, name, length); + + next_chunk_offset = chunk_offset; + pos = end = nullptr; + if (!nextChunk()) + { + if (uncompressed_offset != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {}", uncompressed_offset, name); + return; + } + + if (uncompressed_offset > static_cast(end - pos)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Seek position {} is beyond the end of the compression chunk of size {} in ORC stream {}", + uncompressed_offset, end - pos, name); + pos += uncompressed_offset; +} + +void InputByteStream::throwUnexpectedEnd() const +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected end of ORC stream {}", name); +} + + +OutputByteStream::OutputByteStream(Compressor * compressor_, size_t block_size_) + : compressor(compressor_), block_size(block_size_) +{ + buffer.reserve(std::min(block_size, 64 * 1024)); +} + +void OutputByteStream::write(const char * data, size_t size) +{ + while (size) + { + if (buffer.size() == block_size) + flushChunk(); + size_t count = std::min(size, block_size - buffer.size()); + buffer.append(data, count); + data += count; + size -= count; + } +} + +void OutputByteStream::recordPosition(std::vector & positions) const +{ + if (compressor) + { + positions.push_back(output.size()); + positions.push_back(buffer.size()); + } + else + positions.push_back(output.size() + buffer.size()); +} + +void OutputByteStream::flushChunk() +{ + if (buffer.empty()) + return; + + if (!compressor) + { + output.append(buffer); + buffer.clear(); + return; + } + + size_t header_offset = output.size(); + output.append(COMPRESSION_HEADER_SIZE, '\0'); + size_t compressed_size = compressor->compress(buffer.data(), buffer.size(), output); + + UInt32 header_value = 0; + if (compressed_size) + header_value = static_cast(compressed_size << 1); + else + { + output.append(buffer); + header_value = static_cast((buffer.size() << 1) | 1); + } + + output[header_offset] = static_cast(header_value & 0xFF); + output[header_offset + 1] = static_cast((header_value >> 8) & 0xFF); + output[header_offset + 2] = static_cast((header_value >> 16) & 0xFF); + buffer.clear(); +} + +size_t OutputByteStream::finish() +{ + flushChunk(); + return output.size(); +} + +void OutputByteStream::reset() +{ + buffer.clear(); + output.clear(); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.h b/src/Processors/Formats/Impl/ORC/Stream.h new file mode 100644 index 000000000000..44d209d38321 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace DB::ORC +{ + +/// A sequence of positions from a row index entry, consumed by the streams and the decoders of a +/// column in their order. +class PositionProvider +{ +public: + explicit PositionProvider(const std::vector & positions_) : positions(positions_) {} + UInt64 next(); + +private: + const std::vector & positions; + size_t index = 0; +}; + +/// A piece of a stream loaded from the file. `data` is valid while `holder` is alive. +struct LoadedRange +{ + std::shared_ptr holder; + std::string_view data; +}; + +/// Loads the range `(offset, length)` of a stream from the file. +using RangeLoader = std::function; + +/// A stream of an ORC column, such as PRESENT or DATA, decompressed chunk by chunk. The decoders +/// read from the buffer `[pos, end)` of the current chunk directly. +class InputByteStream +{ +public: + /// The whole stream in memory. `data` must outlive the stream. + InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_); + /// The stream of `length_` bytes is loaded from the file on demand, by `loader_`, a window of + /// at least `LAZY_READ_SIZE` bytes at a time. Used when only some row groups are read. + InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_); + + static constexpr size_t LAZY_READ_SIZE = 1024 * 1024; + + /// Loads the next chunk. Returns false at the end of the stream. + bool nextChunk(); + + bool eof() + { + return pos == end && !nextChunk(); + } + + UInt8 readByte() + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + return static_cast(*pos++); + } + + void readBytes(char * to, size_t n); + void skipBytes(size_t n); + + /// Moves to the position from the row index: one value (the byte offset) for an uncompressed + /// stream, two values (the offset of the compressed chunk and the offset in its decompressed + /// data) for a compressed one. + void seek(PositionProvider & positions); + + [[noreturn]] void throwUnexpectedEnd() const; + + const std::string & getName() const { return name; } + + const char * pos = nullptr; + const char * end = nullptr; + +private: + /// Returns the range `[offset, offset + length)` of the stream. It is valid until the next call. + std::string_view getRange(UInt64 offset, UInt64 length); + + /// The stream in memory, or the currently loaded window of a lazily loaded stream. + std::string_view data; + UInt64 length; + RangeLoader loader; + /// For a lazily loaded stream: the offset of `data` in the stream, and its owner. + UInt64 window_offset = 0; + std::shared_ptr window_holder; + + CompressionKind compression; + size_t block_size; + std::string name; + + /// The offset of the next chunk to read in `data`. + size_t next_chunk_offset = 0; + PODArray decompressed; +}; + +/// Accumulates a stream of an ORC column, compressing it chunk by chunk. +class OutputByteStream +{ +public: + /// `compressor` can be nullptr, which means no compression. + OutputByteStream(Compressor * compressor_, size_t block_size_); + + void writeByte(UInt8 byte) + { + if (buffer.size() == block_size) + flushChunk(); + buffer.push_back(static_cast(byte)); + } + + void write(const char * data, size_t size); + + /// Appends the current position to `positions`, in the format that `InputByteStream::seek` expects. + void recordPosition(std::vector & positions) const; + + /// Finishes the stream and returns its size in bytes. + size_t finish(); + + const std::string & getOutput() const { return output; } + + /// Clears the stream to start a new stripe. + void reset(); + + size_t estimateSize() const { return output.size() + buffer.size(); } + +private: + void flushChunk(); + + Compressor * compressor; + size_t block_size; + std::string buffer; + std::string output; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.cpp b/src/Processors/Formats/Impl/ORC/Timezone.cpp new file mode 100644 index 000000000000..33a1574507d2 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.cpp @@ -0,0 +1,87 @@ +#include + +#include +#include + +#include + +/// The embedded time zone files, see `DateLUTImpl.cpp`. +std::string_view getTimeZone(const char * name); /// NOLINT(misc-use-internal-linkage) + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +TimezoneOffset::TimezoneOffset(const DateLUTImpl & lut_) + : lut(lut_) +{ + const std::string & name = lut.getTimeZone(); + const std::string_view file = getTimeZone(name.c_str()); + /// `Fixed/UTC±HH:MM:SS` zones have no file. On this branch `DateLUT` also loads zones that are not embedded + /// (`libc:` names, the host database), so keep the offsets of `DateLUTImpl` for all of them. + if (file.empty()) + return; + + /// Raw records, as `cctz::time_zone::next_transition` skips no-op ones (Europe/Lisbon has one in 1884). + static constexpr size_t header_size = 44; + size_t pos = 0; + auto check = [&](size_t size) + { + if (size > file.size() - pos) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + }; + auto read_count = [&](size_t index) { return unalignedLoadBigEndian(file.data() + pos + 20 + index * 4); }; + + check(header_size); + if (!file.starts_with("TZif")) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + size_t time_size = 4; + /// Version 2 and later repeat the data with 64-bit times after the 32-bit section. + if (file[4] != '\0') + { + const size_t v1_size = read_count(3) * 5 + read_count(4) * 6 + read_count(5) + read_count(2) * 8 + read_count(1) + read_count(0); + check(header_size + v1_size); + pos += header_size + v1_size; + check(header_size); + time_size = 8; + } + const size_t time_count = read_count(3); + const size_t type_count = read_count(4); + pos += header_size; + check(time_count * (time_size + 1) + type_count * 6); + if (time_count == 0) + return; + + const char * times = file.data() + pos; + const auto * type_indices = reinterpret_cast(times + time_count * time_size); + const char * types = times + time_count * (time_size + 1); + auto type_record = [&](size_t type) + { + if (type >= type_count) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + return types + type * 6; + }; + + first_transition = time_size == 8 ? unalignedLoadBigEndian(times) : unalignedLoadBigEndian(times); + /// The oldest standard time, or the first type if all of them are daylight saving time. + const char * ancient = type_record(0); + for (size_t i = 0; i < time_count; ++i) + { + const char * record = type_record(type_indices[i]); + if (record[4] == 0) + { + ancient = record; + break; + } + } + ancient_offset = unalignedLoadBigEndian(ancient); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.h b/src/Processors/Formats/Impl/ORC/Timezone.h new file mode 100644 index 000000000000..8a7dbd7361fd --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// The UTC offset as in the reference implementation: before the first transition record it is the oldest +/// standard time, not the local mean time (Asia/Shanghai +08:00, not +08:05:43). Shared by reader and writer. +class TimezoneOffset +{ +public: + explicit TimezoneOffset(const DateLUTImpl & lut_); + + Int64 operator()(Int64 t) const { return t < first_transition ? ancient_offset : lut.timezoneOffset(t); } + +private: + const DateLUTImpl & lut; + Int64 first_transition = std::numeric_limits::min(); + Int64 ancient_offset = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.cpp b/src/Processors/Formats/Impl/ORC/Type.cpp new file mode 100644 index 000000000000..b716b8c9ccb1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.cpp @@ -0,0 +1,380 @@ +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int UNKNOWN_TYPE; + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +namespace +{ + +bool isUnquotedFieldName(const std::string & name) +{ + for (char c : name) + if (!isalnum(static_cast(c)) && c != '_') + return false; + return true; +} + +std::string algorithmToString(UInt32 algorithm) +{ + switch (algorithm) + { + case 0: return "spherical"; + case 1: return "vincenty"; + case 2: return "thomas"; + case 3: return "andoyer"; + case 4: return "karney"; + default: return std::to_string(algorithm); + } +} + +/// The same limit as in the reference implementation. +constexpr size_t MAX_TYPE_NESTING_DEPTH = 2000; + +std::unique_ptr convertType(const std::vector & types, UInt64 index, UInt64 & next_id, size_t depth) +{ + checkStackSize(); + + if (depth > MAX_TYPE_NESTING_DEPTH) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: type nesting depth exceeds the limit of {}", MAX_TYPE_NESTING_DEPTH); + + /// The types are listed in pre-order and the column id of each type is its index in the list. + if (index != next_id || index >= types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: the types are not a tree listed in pre-order (type {} is referenced at position {})", + index, next_id); + ++next_id; + + const auto & proto = types[index]; + if (proto.kind > GEOGRAPHY) + throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown ORC type kind {}", proto.kind); + + auto kind = static_cast(proto.kind); + auto result = std::make_unique(kind); + + switch (kind) + { + case LIST: + if (proto.subtypes.size() != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC LIST type that doesn't contain one subtype"); + break; + case MAP: + if (proto.subtypes.size() != 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC MAP type that doesn't contain two subtypes"); + break; + case UNION: + if (proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type that doesn't contain any subtypes"); + /// The tags of a union are bytes. + if (proto.subtypes.size() > 256) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type with {} subtypes, more than 256", proto.subtypes.size()); + break; + case STRUCT: + if (proto.subtypes.size() > proto.field_names.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC STRUCT type that contains less field names than subtypes"); + break; + default: + if (!proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC type {} with subtypes", proto.kind); + break; + } + + if (kind == CHAR || kind == VARCHAR) + result->setMaximumLength(proto.maximum_length.value_or(0)); + if (kind == DECIMAL) + result->setPrecisionAndScale(proto.precision.value_or(0), proto.scale.value_or(0)); + if (kind == GEOMETRY || kind == GEOGRAPHY) + result->setGeospatial(proto.crs.value_or("OGC:CRS84"), proto.algorithm.value_or(0)); + + for (size_t i = 0; i < proto.subtypes.size(); ++i) + { + auto child = convertType(types, proto.subtypes[i], next_id, depth + 1); + if (kind == STRUCT) + result->addStructField(proto.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + + for (const auto & attribute : proto.attributes) + result->setAttribute(attribute.key, attribute.value); + + return result; +} + +void selectChildren(std::vector & selected, const Type & type) +{ + for (UInt64 c = type.getColumnId(); c <= type.getMaximumColumnId(); ++c) + selected[c] = true; +} + +bool selectParents(std::vector & selected, const Type & type) +{ + size_t id = type.getColumnId(); + bool result = selected[id]; + size_t num_selected_subtypes = 0; + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + { + if (selectParents(selected, *type.getSubtype(c))) + { + result = true; + ++num_selected_subtypes; + } + } + selected[id] = result; + + /// The branches of a union are either all selected or all not selected. + if (type.getKind() == UNION && result && num_selected_subtypes > 0 && num_selected_subtypes < type.getSubtypeCount()) + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + selectChildren(selected, *type.getSubtype(c)); + + return result; +} + +} + + +std::string Type::toString() const +{ + switch (kind) + { + case BOOLEAN: return "boolean"; + case BYTE: return "tinyint"; + case SHORT: return "smallint"; + case INT: return "int"; + case LONG: return "bigint"; + case FLOAT: return "float"; + case DOUBLE: return "double"; + case STRING: return "string"; + case BINARY: return "binary"; + case TIMESTAMP: return "timestamp"; + case TIMESTAMP_INSTANT: return "timestamp with local time zone"; + case LIST: return "array<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + ">"; + case MAP: + return "map<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + "," + + (subtypes.size() < 2 ? std::string("void") : subtypes[1]->toString()) + ">"; + case STRUCT: + { + std::string result = "struct<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + if (isUnquotedFieldName(field_names[i])) + result += field_names[i]; + else + { + result += "`"; + for (char c : field_names[i]) + { + if (c == '`') + result += "``"; + else + result += c; + } + result += "`"; + } + result += ":"; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case UNION: + { + std::string result = "uniontype<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case DECIMAL: return "decimal(" + std::to_string(precision) + "," + std::to_string(scale) + ")"; + case DATE: return "date"; + case VARCHAR: return "varchar(" + std::to_string(maximum_length) + ")"; + case CHAR: return "char(" + std::to_string(maximum_length) + ")"; + case GEOMETRY: return "geometry(" + crs + ")"; + case GEOGRAPHY: return "geography(" + crs + "," + algorithmToString(algorithm) + ")"; + } + return "unknown"; +} + +Type * Type::addStructField(const std::string & name, std::unique_ptr field) +{ + field_names.push_back(name); + return addChild(std::move(field)); +} + +Type * Type::addChild(std::unique_ptr child) +{ + subtypes.push_back(std::move(child)); + return subtypes.back().get(); +} + +UInt64 Type::assignIds(UInt64 start) +{ + column_id = start; + UInt64 next = start + 1; + for (auto & subtype : subtypes) + next = subtype->assignIds(next); + maximum_column_id = next - 1; + return next; +} + +void Type::toProto(std::vector & out) const +{ + size_t index = out.size(); + if (index != column_id) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type ids are not assigned in pre-order"); + out.emplace_back(); + { + auto & proto = out.back(); + proto.kind = kind; + for (const auto & subtype : subtypes) + proto.subtypes.push_back(subtype->getColumnId()); + proto.field_names = field_names; + if (kind == CHAR || kind == VARCHAR) + proto.maximum_length = static_cast(maximum_length); + if (kind == DECIMAL) + { + proto.precision = static_cast(precision); + proto.scale = static_cast(scale); + } + for (const auto & [key, value] : attributes) + proto.attributes.push_back({key, value}); + } + /// `out` may be reallocated by the recursive calls, so do not keep the reference. + for (const auto & subtype : subtypes) + subtype->toProto(out); +} + +std::unique_ptr Type::createPrimitiveType(TypeKind kind) +{ + return std::make_unique(kind); +} + +std::unique_ptr Type::createCharType(TypeKind kind, UInt64 maximum_length) +{ + auto result = std::make_unique(kind); + result->maximum_length = maximum_length; + return result; +} + +std::unique_ptr Type::createDecimalType(UInt64 precision, UInt64 scale) +{ + auto result = std::make_unique(DECIMAL); + result->precision = precision; + result->scale = scale; + return result; +} + +std::unique_ptr Type::createStructType() +{ + return std::make_unique(STRUCT); +} + +std::unique_ptr Type::createListType(std::unique_ptr element) +{ + auto result = std::make_unique(LIST); + result->addChild(std::move(element)); + return result; +} + +std::unique_ptr Type::createMapType(std::unique_ptr key, std::unique_ptr value) +{ + auto result = std::make_unique(MAP); + result->addChild(std::move(key)); + result->addChild(std::move(value)); + return result; +} + +std::unique_ptr Type::createUnionType() +{ + return std::make_unique(UNION); +} + +std::unique_ptr Type::fromProto(const std::vector & types) +{ + if (types.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: it has no types"); + UInt64 next_id = 0; + auto root = convertType(types, 0, next_id, 0); + if (next_id != types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: {} of {} types are not reachable from the root type", types.size() - next_id, types.size()); + root->assignIds(0); + return root; +} + +std::unique_ptr Type::buildSelectedType(const Type & type, const std::vector & selected) +{ + if (!selected.at(type.column_id)) + return nullptr; + + auto result = std::make_unique(type.kind); + result->maximum_length = type.maximum_length; + result->precision = type.precision; + result->scale = type.scale; + result->crs = type.crs; + result->algorithm = type.algorithm; + result->attributes = type.attributes; + result->column_id = type.column_id; + result->maximum_column_id = type.maximum_column_id; + + for (size_t i = 0; i < type.subtypes.size(); ++i) + { + auto child = buildSelectedType(*type.subtypes[i], selected); + if (!child) + continue; + if (type.kind == STRUCT) + result->addStructField(type.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + return result; +} + +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids) +{ + std::vector selected(root.getMaximumColumnId() + 1, false); + + /// Find the types by ids with a walk over the tree. + std::vector by_id(selected.size()); + std::vector stack{&root}; + while (!stack.empty()) + { + const Type * type = stack.back(); + stack.pop_back(); + by_id[type->getColumnId()] = type; + for (UInt64 i = 0; i < type->getSubtypeCount(); ++i) + stack.push_back(type->getSubtype(i)); + } + + for (UInt64 id : type_ids) + { + if (id >= selected.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid ORC type id {} selected out of {}", id, selected.size()); + selectChildren(selected, *by_id[id]); + } + + selectParents(selected, root); + selected[0] = true; + return selected; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.h b/src/Processors/Formats/Impl/ORC/Type.h new file mode 100644 index 000000000000..9a30f4455076 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.h @@ -0,0 +1,114 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace DB::ORC +{ + +enum TypeKind : UInt32 +{ + BOOLEAN = 0, + BYTE = 1, + SHORT = 2, + INT = 3, + LONG = 4, + FLOAT = 5, + DOUBLE = 6, + STRING = 7, + BINARY = 8, + TIMESTAMP = 9, + LIST = 10, + MAP = 11, + STRUCT = 12, + UNION = 13, + DECIMAL = 14, + DATE = 15, + VARCHAR = 16, + CHAR = 17, + TIMESTAMP_INSTANT = 18, + GEOMETRY = 19, + GEOGRAPHY = 20, +}; + +/// A node of the type tree of an ORC file. Every node is a column of the file; the column ids are +/// assigned in pre-order, so the subtree of a column `c` occupies the ids `[c, c.getMaximumColumnId()]`. +class Type +{ +public: + explicit Type(TypeKind kind_) : kind(kind_) {} + + TypeKind getKind() const { return kind; } + UInt64 getColumnId() const { return column_id; } + UInt64 getMaximumColumnId() const { return maximum_column_id; } + UInt64 getSubtypeCount() const { return subtypes.size(); } + const Type * getSubtype(UInt64 i) const { return subtypes.at(i).get(); } + /// Only for STRUCT. + const std::string & getFieldName(UInt64 i) const { return field_names.at(i); } + /// Only for CHAR and VARCHAR. + UInt64 getMaximumLength() const { return maximum_length; } + /// Only for DECIMAL. + UInt64 getPrecision() const { return precision; } + UInt64 getScale() const { return scale; } + + bool hasAttributeKey(const std::string & key) const { return attributes.contains(key); } + const std::string & getAttributeValue(const std::string & key) const { return attributes.at(key); } + void setAttribute(const std::string & key, const std::string & value) { attributes[key] = value; } + const std::map & getAttributes() const { return attributes; } + + /// The type name in the same format as in the reference implementation (Hive type names). + std::string toString() const; + + void setMaximumLength(UInt64 value) { maximum_length = value; } + void setPrecisionAndScale(UInt64 precision_, UInt64 scale_) { precision = precision_; scale = scale_; } + void setGeospatial(std::string crs_, UInt32 algorithm_) { crs = std::move(crs_); algorithm = algorithm_; } + + Type * addStructField(const std::string & name, std::unique_ptr field); + Type * addChild(std::unique_ptr child); + + /// Assigns the column ids in pre-order, starting from `start`. Returns the next free id. + UInt64 assignIds(UInt64 start); + + /// Appends the types of this subtree to `out` in pre-order. The ids must be assigned. + void toProto(std::vector & out) const; + + static std::unique_ptr createPrimitiveType(TypeKind kind); + static std::unique_ptr createCharType(TypeKind kind, UInt64 maximum_length); + static std::unique_ptr createDecimalType(UInt64 precision, UInt64 scale); + static std::unique_ptr createStructType(); + static std::unique_ptr createListType(std::unique_ptr element); + static std::unique_ptr createMapType(std::unique_ptr key, std::unique_ptr value); + static std::unique_ptr createUnionType(); + + /// Builds the type tree from the types in the file footer. Throws `INCORRECT_DATA` if they do + /// not form a tree with the ids in pre-order. + static std::unique_ptr fromProto(const std::vector & types); + + /// Builds a copy of the tree with only the selected columns (by id). The parent of every + /// selected column must also be selected. Returns nullptr if the root is not selected. + static std::unique_ptr buildSelectedType(const Type & type, const std::vector & selected); + +private: + TypeKind kind; + UInt64 column_id = 0; + UInt64 maximum_column_id = 0; + std::vector> subtypes; + std::vector field_names; + UInt64 maximum_length = 0; + UInt64 precision = 0; + UInt64 scale = 0; + std::string crs; + UInt32 algorithm = 0; + std::map attributes; +}; + +/// The column selection with the same semantics as in the reference implementation: +/// selecting a column selects its whole subtree, and then all parents of the selected columns +/// are selected. If only some branches of a UNION are selected, all its branches are selected. +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids); + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.cpp b/src/Processors/Formats/Impl/ORC/Vector.cpp new file mode 100644 index 000000000000..ce7b5cdac8de --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int NOT_IMPLEMENTED; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values) +{ + const size_t dictionary_size = dictionary.size(); + const auto & dictionary_offsets = dictionary.getOffsets(); + const auto & dictionary_chars = dictionary.getChars(); + + auto result = ColumnString::create(); + auto & chars = result->getChars(); + auto & offsets = result->getOffsets(); + offsets.resize(num_values); + + size_t total = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + Int64 entry = index[i]; + if (entry < 0 || static_cast(entry) >= dictionary_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC dictionary index {} at row {} is out of range [0, {})", entry, i, dictionary_size); + total += dictionary_offsets[entry] - dictionary_offsets[entry - 1]; + } + offsets[i] = total; + } + + chars.resize(total); + UInt8 * out = chars.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + size_t begin = dictionary_offsets[index[i] - 1]; + size_t size = dictionary_offsets[index[i]] - begin; + memcpy(out, dictionary_chars.data() + begin, size); + out += size; + } + } + return result; +} + +ColumnPtr getStringColumn(const StringVectorBatch & batch) +{ + if (!batch.isEncoded) + return batch.column; + + const auto & encoded = typeid_cast(batch); + return decodeDictionary( + assert_cast(*encoded.dictionary->column), + encoded.index.data(), + batch.hasNulls ? batch.notNull.data() : nullptr, + batch.numElements); +} + +std::unique_ptr createRowBatch(const Type & type, bool encoded) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(); + case BYTE: + return std::make_unique(); + case SHORT: + return std::make_unique(); + case INT: + return std::make_unique(); + case LONG: + case DATE: + return std::make_unique(); + case FLOAT: + return std::make_unique(); + case DOUBLE: + return std::make_unique(); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + if (encoded) + return std::make_unique(); + return std::make_unique(); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + return std::make_unique(); + case STRUCT: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addField(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case LIST: + { + auto result = std::make_unique(); + if (type.getSubtypeCount()) + result->elements = createRowBatch(*type.getSubtype(0), encoded); + return result; + } + case MAP: + { + auto result = std::make_unique(); + if (type.getSubtypeCount() > 0) + result->keys = createRowBatch(*type.getSubtype(0), encoded); + if (type.getSubtypeCount() > 1) + result->elements = createRowBatch(*type.getSubtype(1), encoded); + return result; + } + case UNION: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addChild(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case DECIMAL: + if (type.getPrecision() == 0 || type.getPrecision() > 18) + return std::make_unique(); + return std::make_unique(); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.h b/src/Processors/Formats/Impl/ORC/Vector.h new file mode 100644 index 000000000000..1e44a80a61d1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.h @@ -0,0 +1,174 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +/// Batches of column values filled by the reader. The values of the primitive types are decoded +/// directly into ClickHouse columns, which the conversion to the requested types takes without +/// copying. The structure follows the reference implementation: a batch has the null mask of its +/// values, and the batches of the compound types have the batches of their children. + +namespace DB::ORC +{ + +struct ColumnVectorBatch +{ + ColumnVectorBatch() = default; + virtual ~ColumnVectorBatch() = default; + + ColumnVectorBatch(const ColumnVectorBatch &) = delete; + ColumnVectorBatch & operator=(const ColumnVectorBatch &) = delete; + + /// Prepares the batch for `num_values` values. + void reset(size_t num_values) + { + numElements = num_values; + notNull.resize(num_values); + } + + size_t numElements = 0; + /// Non-zero for the non-null values, valid only if `hasNulls`. + PaddedPODArray notNull; + bool hasNulls = false; + /// For string batches read with lazy dictionary decoding. + bool isEncoded = false; +}; + +/// The values of a primitive type in a ClickHouse column (`ColumnVector` of `T`). The null values are zeros. +template +struct NumericVectorBatch : public ColumnVectorBatch +{ + using Container = PaddedPODArray; + + /// Creates a new column for the next values: the previous column can be still referenced. + Container & prepareColumn(size_t num_values) + { + auto new_column = ColumnVector::create(num_values); + auto & data = new_column->getData(); + column = std::move(new_column); + return data; + } + + const Container & getData() const { return assert_cast &>(*column).getData(); } + + ColumnPtr column; +}; + +/// BOOLEAN: 0 or 1. +using BoolVectorBatch = NumericVectorBatch; +using ByteVectorBatch = NumericVectorBatch; +using ShortVectorBatch = NumericVectorBatch; +using IntVectorBatch = NumericVectorBatch; +/// LONG and DATE (days since the epoch, not narrowed, so that the range can be checked). +using LongVectorBatch = NumericVectorBatch; +using FloatVectorBatch = NumericVectorBatch; +using DoubleVectorBatch = NumericVectorBatch; + +/// The values in a `ColumnString`. The null values are empty strings. +struct StringVectorBatch : public ColumnVectorBatch +{ + ColumnPtr column; +}; + +struct StringDictionary +{ + /// The entries of the dictionary. + ColumnPtr column; +}; + +/// A string batch with the dictionary indices, without decoding the values. `column` is not set. +struct EncodedStringVectorBatch : public StringVectorBatch +{ + std::shared_ptr dictionary; + PaddedPODArray index; +}; + +/// Builds a `ColumnString` from the dictionary entries by the indices (the null values are empty strings). +/// Throws `INCORRECT_DATA` if an index is out of range. +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values); + +/// Returns the values of a string batch as a `ColumnString`, decoding the dictionary for an encoded batch. +ColumnPtr getStringColumn(const StringVectorBatch & batch); + +struct StructVectorBatch : public ColumnVectorBatch +{ + void addField(std::unique_ptr field) + { + fields.push_back(field.get()); + owned_fields.push_back(std::move(field)); + } + + std::vector fields; + +private: + std::vector> owned_fields; +}; + +/// LIST and MAP: the end offsets of the values in the children, as in `ColumnArray`. +struct ListVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr elements; +}; + +struct MapVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr keys; + std::unique_ptr elements; +}; + +struct UnionVectorBatch : public ColumnVectorBatch +{ + void addChild(std::unique_ptr child) + { + children.push_back(child.get()); + owned_children.push_back(std::move(child)); + } + + /// The branch of each value. + PaddedPODArray tags; + /// The position of each value in its branch. + PaddedPODArray offsets; + std::vector children; + +private: + std::vector> owned_children; +}; + +/// For DECIMAL with the precision at most 18. +struct Decimal64VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +/// For DECIMAL with the precision above 18 or unspecified (zero). +struct Decimal128VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +struct TimestampVectorBatch : public ColumnVectorBatch +{ + /// Seconds since the epoch in UTC. + PaddedPODArray data; + PaddedPODArray nanoseconds; +}; + +/// Creates a batch tree matching the type. With `encoded`, the string columns get +/// `EncodedStringVectorBatch`, which the reader fills without decoding the dictionaries. +std::unique_ptr createRowBatch(const Type & type, bool encoded = false); + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.cpp b/src/Processors/Formats/Impl/ORC/Writer.cpp new file mode 100644 index 000000000000..cfab65634955 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.cpp @@ -0,0 +1,1493 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; + extern const int LOGICAL_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE; +} +} + +namespace DB::ORC +{ + +struct WriterContext +{ + Compressor * compressor = nullptr; + size_t block_size = 0; + bool enable_index = false; + double dictionary_key_size_threshold = 0; + std::optional timezone_offset; + bool timezone_is_utc = true; + /// 2015-01-01 00:00:00 in the time zone of the writer, as seconds since the epoch. + Int64 epoch_offset = 0; +}; + +namespace +{ + +struct StreamData +{ + Proto::StreamKind kind; + UInt32 column; + std::string data; +}; + +std::string compressWhole(const WriterContext & context, const std::string & data) +{ + OutputByteStream stream(context.compressor, context.block_size); + stream.write(data.data(), data.size()); + stream.finish(); + return stream.getOutput(); +} + +} + +class ColumnWriter +{ +public: + ColumnWriter(const Type & type, WriterContext & context_) + : column_id(type.getColumnId()) + , context(context_) + , present_stream(context.compressor, context.block_size) + , present_encoder(present_stream) + , index_statistics(type.getKind()) + , stripe_statistics(type.getKind()) + , file_statistics(type.getKind()) + { + } + + virtual ~ColumnWriter() = default; + + /// Must be called by the most derived constructor, after the streams are created. + void init() + { + if (context.enable_index) + recordPositions(); + } + + /// Adds the values `[offset, offset + num_values)` of `column`, which is not `Nullable`. + /// `null_map` (1 for a null) and `parent_null_map` (1 for a null in the parent struct, for which + /// no value is written at all) are for these values only, so they start at the first value. + virtual void add(const IColumn & /*column*/, const UInt8 * null_map, size_t /*offset*/, size_t num_values, const UInt8 * parent_null_map) + { + addPresent(null_map, num_values, parent_null_map); + } + + /// Writes the PRESENT stream for the values. + void addPresent(const UInt8 * null_map, size_t num_values, const UInt8 * parent_null_map) + { + for (size_t i = 0; i < num_values; ++i) + { + if (parent_null_map && parent_null_map[i]) + continue; + present_encoder.write(!null_map || !null_map[i]); + } + if (null_map) + { + for (size_t i = 0; i < num_values && !has_null_value; ++i) + if (null_map[i]) + has_null_value = true; + } + } + + virtual void createRowIndexEntry() + { + entries.push_back(Entry{std::move(current_present_positions), std::move(current_data_positions), index_statistics.toProto()}); + current_present_positions.clear(); + current_data_positions.clear(); + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + recordPositions(); + } + + virtual void mergeRowGroupStatsIntoStripeStats() + { + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + } + + /// Encodes the deferred data of the stripe. + virtual void finalizeStripe() {} + + virtual void writeIndex(std::vector & streams) + { + Proto::RowIndex index; + for (const auto & entry : entries) + { + auto & proto_entry = index.entry.emplace_back(); + /// The positions of the PRESENT stream are written only if the stream is written. + if (has_null_value) + proto_entry.positions = entry.present_positions; + proto_entry.positions.insert(proto_entry.positions.end(), entry.data_positions.begin(), entry.data_positions.end()); + proto_entry.statistics = entry.statistics; + } + streams.push_back({Proto::StreamKind::ROW_INDEX, static_cast(column_id), compressWhole(context, index.serialize())}); + } + + virtual void flush(std::vector & streams) + { + present_encoder.flush(); + present_stream.finish(); + if (has_null_value) + streams.push_back({Proto::StreamKind::PRESENT, static_cast(column_id), present_stream.getOutput()}); + } + + virtual void getColumnEncodings(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + + virtual void getStripeStatistics(std::vector & stats) const + { + stats.push_back(stripe_statistics.toProto()); + } + + virtual void getFileStatistics(std::vector & stats) const + { + stats.push_back(file_statistics.toProto()); + } + + virtual void mergeStripeStatsIntoFileStats() + { + file_statistics.merge(stripe_statistics); + stripe_statistics.reset(); + } + + virtual size_t estimateSize() const + { + return present_stream.estimateSize(); + } + + /// Starts a new stripe. + virtual void reset() + { + present_stream.reset(); + has_null_value = false; + entries.clear(); + current_present_positions.clear(); + current_data_positions.clear(); + resetStreams(); + if (context.enable_index) + recordPositions(); + } + +protected: + /// Appends the positions of the data streams, in the order the reader seeks them. + virtual void recordDataPositions(std::vector & positions) = 0; + /// Clears the data streams for a new stripe. + virtual void resetStreams() = 0; + + /// The number of the non-null values, also updates the statistics with the count. + size_t countValues(const UInt8 * null_map, size_t num_values) + { + size_t count = num_values; + if (null_map) + { + count = 0; + for (size_t i = 0; i < num_values; ++i) + count += !null_map[i]; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + return count; + } + + struct Entry + { + std::vector present_positions; + std::vector data_positions; + Proto::ColumnStatistics statistics; + }; + + const UInt64 column_id; + WriterContext & context; + OutputByteStream present_stream; + BooleanRleEncoder present_encoder; + bool has_null_value = false; + StatisticsBuilder index_statistics; + StatisticsBuilder stripe_statistics; + StatisticsBuilder file_statistics; + std::vector entries; + +private: + void recordPositions() + { + present_encoder.recordPosition(current_present_positions); + recordDataPositions(current_data_positions); + } + + std::vector current_present_positions; + std::vector current_data_positions; +}; + +namespace +{ + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type, WriterContext & context); + +/// Adds the values of a column that can be `Nullable`. The values that are null in the parent +/// (`outer_null_map`, for the fields of a struct) are null as well. +void addColumn( + ColumnWriter & writer, const IColumn & column, const UInt8 * outer_null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) +{ + if (const auto * nullable = typeid_cast(&column)) + { + const UInt8 * null_map = nullable->getNullMapData().data() + offset; + if (!outer_null_map) + { + writer.add(nullable->getNestedColumn(), null_map, offset, num_values, parent_null_map); + return; + } + PaddedPODArray merged(num_values); + for (size_t i = 0; i < num_values; ++i) + merged[i] = null_map[i] | outer_null_map[i]; + writer.add(nullable->getNestedColumn(), merged.data(), offset, num_values, parent_null_map); + return; + } + writer.add(column, outer_null_map, offset, num_values, parent_null_map); +} + +/// The raw values of a column with fixed-size values. +template +const T * getRawValues(const IColumn & column) +{ + auto raw = column.getRawData(); + if (column.sizeOfValueIfFixed() != sizeof(T)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} with values of size {} for ORC (expected {})", + column.getName(), column.sizeOfValueIfFixed(), sizeof(T)); + return reinterpret_cast(raw.data()); +} + +/// The value of the integer column (of any width up to 8 bytes) as a signed number of the same width, +/// as ORC does not have unsigned types. +Int64 readSignedValue(const char * data, size_t width, size_t row) +{ + switch (width) + { + case 1: return unalignedLoad(data + row); + case 2: return unalignedLoad(data + row * 2); + case 4: return unalignedLoad(data + row * 4); + default: return unalignedLoad(data + row * 8); + } +} + +/// The writers that have children call the same methods for them. +class CompoundColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void createRowIndexEntry() override + { + ColumnWriter::createRowIndexEntry(); + for (auto & child : children) + child->createRowIndexEntry(); + } + + void mergeRowGroupStatsIntoStripeStats() override + { + ColumnWriter::mergeRowGroupStatsIntoStripeStats(); + for (auto & child : children) + child->mergeRowGroupStatsIntoStripeStats(); + } + + void finalizeStripe() override + { + for (auto & child : children) + child->finalizeStripe(); + } + + void writeIndex(std::vector & streams) override + { + ColumnWriter::writeIndex(streams); + for (auto & child : children) + child->writeIndex(streams); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + flushOwnStreams(streams); + for (auto & child : children) + child->flush(streams); + } + + void getColumnEncodings(std::vector & encodings) const override + { + getOwnColumnEncoding(encodings); + for (const auto & child : children) + child->getColumnEncodings(encodings); + } + + void getStripeStatistics(std::vector & stats) const override + { + ColumnWriter::getStripeStatistics(stats); + for (const auto & child : children) + child->getStripeStatistics(stats); + } + + void getFileStatistics(std::vector & stats) const override + { + ColumnWriter::getFileStatistics(stats); + for (const auto & child : children) + child->getFileStatistics(stats); + } + + void mergeStripeStatsIntoFileStats() override + { + ColumnWriter::mergeStripeStatsIntoFileStats(); + for (auto & child : children) + child->mergeStripeStatsIntoFileStats(); + } + + size_t estimateSize() const override + { + size_t size = ColumnWriter::estimateSize() + estimateOwnSize(); + for (const auto & child : children) + size += child->estimateSize(); + return size; + } + + void reset() override + { + ColumnWriter::reset(); + for (auto & child : children) + (*child).reset(); + } + +protected: + virtual void flushOwnStreams(std::vector &) {} + virtual void getOwnColumnEncoding(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + virtual size_t estimateOwnSize() const { return 0; } + + std::vector> children; +}; + +class StructColumnWriter final : public CompoundColumnWriter +{ +public: + StructColumnWriter(const Type & type, const DataTypes & field_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + { + if (field_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC struct {} has {} fields, the ClickHouse type has {}", + type.toString(), type.getSubtypeCount(), field_types.size()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), field_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & tuple = assert_cast(column); + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The fields of the null values are null, and they are not written. + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], tuple.getColumn(i), null_map, offset, num_values, null_map); + countValues(null_map, num_values); + } + + /// Adds the rows of the root struct, which are the columns of the file. + void addRoot(const Columns & columns, size_t offset, size_t num_values) + { + if (columns.size() != children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Expected {} columns for ORC, got {}", children.size(), columns.size()); + addPresent(nullptr, num_values, nullptr); + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], *columns[i], nullptr, offset, num_values, nullptr); + countValues(nullptr, num_values); + } + +protected: + void recordDataPositions(std::vector &) override {} + void resetStreams() override {} +}; + +template +class CollectionColumnWriter final : public CompoundColumnWriter +{ +public: + CollectionColumnWriter(const Type & type, const DataTypes & child_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , length_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + { + if (child_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), child_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const ColumnArray & array = is_map ? assert_cast(column).getNestedColumn() : assert_cast(column); + /// The offsets of `ColumnArray` are the end offsets, and the one before the first is zero. + const auto & offsets = array.getOffsets(); + + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + + UInt64 element_offset = offsets[static_cast(offset) - 1]; + UInt64 total_elements = offsets[offset + num_values - 1] - element_offset; + + if constexpr (is_map) + { + const auto & key_value = assert_cast(array.getData()); + addColumn(*children[0], key_value.getColumn(0), nullptr, element_offset, total_elements, nullptr); + addColumn(*children[1], key_value.getColumn(1), nullptr, element_offset, total_elements, nullptr); + } + else + { + addColumn(*children[0], array.getData(), nullptr, element_offset, total_elements, nullptr); + } + + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + UInt64 length = offsets[row] - offsets[static_cast(row) - 1]; + length_encoder.write(static_cast(length)); + index_statistics.updateCollection(length); + ++count; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + length_encoder.recordPosition(positions); + } + + void resetStreams() override + { + length_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + + void getOwnColumnEncoding(std::vector & encodings) const override + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT_V2, 0, {}}); + } + + size_t estimateOwnSize() const override { return length_stream.estimateSize(); } + +private: + OutputByteStream length_stream; + IntRleEncoderV2 length_encoder; +}; + +class UnionColumnWriter final : public CompoundColumnWriter +{ +public: + /// The branches of the union are in the same order as the variants of the `Variant` type, + /// so the global discriminator of a value is its tag. + UnionColumnWriter(const Type & type, const DataTypes & variant_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , tag_stream(context.compressor, context.block_size) + , tag_encoder(tag_stream) + { + if (variant_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC union {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), variant_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & variant = assert_cast(column); + + /// A `NULL` of `Variant` is a null value of the union. + PaddedPODArray union_null_map(num_values); + bool has_nulls = false; + for (size_t i = 0; i < num_values; ++i) + { + union_null_map[i] = (null_map && null_map[i]) || variant.globalDiscriminatorAt(offset + i) == ColumnVariant::NULL_DISCRIMINATOR; + has_nulls |= union_null_map[i]; + } + const UInt8 * union_nulls = has_nulls ? union_null_map.data() : nullptr; + + ColumnWriter::add(column, union_nulls, offset, num_values, parent_null_map); + + std::vector child_offset(children.size(), -1); + std::vector child_length(children.size(), 0); + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (union_nulls && union_nulls[i]) + continue; + size_t row = offset + i; + auto tag = variant.globalDiscriminatorAt(row); + if (tag >= children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid union tag {} for union with {} children", static_cast(tag), children.size()); + if (child_offset[tag] == -1) + child_offset[tag] = static_cast(variant.offsetAt(row)); + ++child_length[tag]; + tag_encoder.write(static_cast(tag)); + ++count; + } + + /// The values of each branch are consecutive in its column. + for (size_t i = 0; i < children.size(); ++i) + if (child_length[i]) + addColumn(*children[i], variant.getVariantByGlobalDiscriminator(i), nullptr, static_cast(child_offset[i]), child_length[i], nullptr); + + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + tag_encoder.recordPosition(positions); + } + + void resetStreams() override + { + tag_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + tag_encoder.flush(); + tag_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), tag_stream.getOutput()}); + } + + size_t estimateOwnSize() const override { return tag_stream.estimateSize(); } + +private: + OutputByteStream tag_stream; + ByteRleEncoder tag_encoder; +}; + + +/// The writers of the primitive columns. +class PrimitiveColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void getColumnEncodings(std::vector & encodings) const override + { + encodings.push_back({encoding_kind, dictionary_size, {}}); + } + +protected: + Proto::ColumnEncodingKind encoding_kind = Proto::ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; +}; + +class BooleanColumnWriter final : public PrimitiveColumnWriter +{ +public: + BooleanColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const UInt8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(data[i] != 0); + index_statistics.updateBoolean(data[i] != 0); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + BooleanRleEncoder encoder; +}; + +class ByteColumnWriter final : public PrimitiveColumnWriter +{ +public: + ByteColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width. + const Int8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(static_cast(data[i])); + index_statistics.updateInteger(data[i]); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + ByteRleEncoder encoder; +}; + +/// SHORT, INT, LONG and DATE. +class IntegerColumnWriter final : public PrimitiveColumnWriter +{ +public: + IntegerColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream, true) + , is_date(type.getKind() == DATE) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width (except `Date`). + const size_t width = column.sizeOfValueIfFixed(); + if (width != 2 && width != 4 && width != 8) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC integer", column.getName()); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + /// `Date` is the unsigned number of days (up to 2149), which must not wrap around + /// to the negative ones after 2059. `Date32` is signed, as the other integers. + Int64 value = (is_date && width == 2) + ? unalignedLoad(data + (offset + i) * sizeof(UInt16)) + : readSignedValue(data, width, offset + i); + encoder.write(value); + if (is_date) + index_statistics.updateDate(static_cast(value)); + else + index_statistics.updateInteger(value); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + IntRleEncoderV2 encoder; + const bool is_date; +}; + +template +class FloatingColumnWriter final : public PrimitiveColumnWriter +{ +public: + FloatingColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const ItemType * data = getRawValues(column) + offset; + if (!null_map && std::endian::native == std::endian::little) + { + data_stream.write(reinterpret_cast(data), num_values * sizeof(ItemType)); + for (size_t i = 0; i < num_values; ++i) + index_statistics.updateDouble(static_cast(data[i])); + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + ItemType value = data[i]; + if constexpr (std::endian::native == std::endian::big) + value = std::bit_cast(std::byteswap(std::bit_cast>(value))); + data_stream.write(reinterpret_cast(&value), sizeof(value)); + index_statistics.updateDouble(static_cast(data[i])); + } + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { data_stream.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; +}; + +/// STRING, VARCHAR, CHAR and BINARY. The values of a stripe are kept in memory and encoded at the +/// end of the stripe, either directly or with a dictionary. +class StringColumnWriter final : public PrimitiveColumnWriter +{ +public: + StringColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , is_binary(type.getKind() == BINARY) + , data_stream(context.compressor, context.block_size) + , length_stream(context.compressor, context.block_size) + , dictionary_data_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + , index_encoder(data_stream, false) + { + /// The binary columns never use dictionaries, as in the reference implementation. + if (is_binary || context.dictionary_key_size_threshold <= 0) + use_dictionary = false; + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `String`, or the raw bytes of the values of fixed size (`FixedString`, `IPv6`, big integers). + auto add_value = [&](std::string_view value) + { + blob.append(value); + value_ends.push_back(blob.size()); + if (is_binary) + index_statistics.updateBinary(value.size()); + else + index_statistics.updateString(value); + }; + + if (const auto * strings = typeid_cast(&column)) + { + const auto & offsets = strings->getOffsets(); + const auto * chars = reinterpret_cast(strings->getChars().data()); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + add_value(std::string_view(chars + offsets[row - 1], offsets[row] - offsets[row - 1])); + } + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + add_value(column.getDataAt(offset + i)); + } + } + countValues(null_map, num_values); + } + + void createRowIndexEntry() override + { + if (!use_dictionary) + decideDictionary(); + ColumnWriter::createRowIndexEntry(); + } + + void finalizeStripe() override + { + if (!use_dictionary) + decideDictionary(); + + /// The start of the group without an entry is not needed. + group_starts.resize(entries.size()); + + if (*use_dictionary) + encodeWithDictionary(); + else + encodeDirect(); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + if (*use_dictionary) + { + index_encoder.flush(); + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + dictionary_data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::DICTIONARY_DATA, static_cast(column_id), dictionary_data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + else + { + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + blob.size() + value_ends.size() * sizeof(UInt64); + } + +protected: + void recordDataPositions(std::vector &) override + { + /// The positions are known only after the encoding, at the end of the stripe. + group_starts.push_back(value_ends.size()); + } + + void resetStreams() override + { + data_stream.reset(); + length_stream.reset(); + dictionary_data_stream.reset(); + blob.clear(); + value_ends.clear(); + group_starts.clear(); + dictionary_size = 0; + } + +private: + std::string_view getValue(size_t i) const + { + size_t begin = i ? value_ends[i - 1] : 0; + return std::string_view(blob.data() + begin, value_ends[i] - begin); + } + + /// The decision is made once for the file, by the values of the first row group (or the first + /// stripe without the row index), as in the reference implementation. + void decideDictionary() + { + std::unordered_set distinct; + for (size_t i = 0; i < value_ends.size(); ++i) + distinct.insert(getValue(i)); + /// Compare as doubles: the threshold is user-provided and the product may not fit in `size_t`. + use_dictionary = static_cast(distinct.size()) <= static_cast(value_ends.size()) * context.dictionary_key_size_threshold; + } + + void encodeDirect() + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + auto & positions = entries[group].data_positions; + data_stream.recordPosition(positions); + length_encoder.recordPosition(positions); + ++group; + } + if (i == value_ends.size()) + break; + auto value = getValue(i); + data_stream.write(value.data(), value.size()); + length_encoder.write(static_cast(value.size())); + } + } + + void encodeWithDictionary() + { + encoding_kind = Proto::ColumnEncodingKind::DICTIONARY_V2; + + /// The dictionary is sorted, as in the reference implementation. + std::unordered_map index_of; + std::vector keys; + for (size_t i = 0; i < value_ends.size(); ++i) + { + auto value = getValue(i); + if (index_of.emplace(value, 0).second) + keys.push_back(value); + } + std::sort(keys.begin(), keys.end()); + for (size_t i = 0; i < keys.size(); ++i) + index_of[keys[i]] = static_cast(i); + dictionary_size = static_cast(keys.size()); + + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + index_encoder.recordPosition(entries[group].data_positions); + ++group; + } + if (i == value_ends.size()) + break; + index_encoder.write(index_of[getValue(i)]); + } + + for (const auto & key : keys) + { + dictionary_data_stream.write(key.data(), key.size()); + length_encoder.write(static_cast(key.size())); + } + } + + const bool is_binary; + std::optional use_dictionary; + OutputByteStream data_stream; + OutputByteStream length_stream; + OutputByteStream dictionary_data_stream; + IntRleEncoderV2 length_encoder; + IntRleEncoderV2 index_encoder; + + std::string blob; + std::vector value_ends; + /// The index of the first value of each row group. + std::vector group_starts; +}; + +class TimestampColumnWriter final : public PrimitiveColumnWriter +{ +public: + /// `scale` is of `DateTime64`, or nullopt for `DateTime` (`UInt32` seconds). + TimestampColumnWriter(const Type & type, std::optional scale_, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(scale_) + , seconds_stream(context.compressor, context.block_size) + , nanos_stream(context.compressor, context.block_size) + , seconds_encoder(seconds_stream, true) + , nanos_encoder(nanos_stream, false) + , is_utc(type.getKind() == TIMESTAMP_INSTANT || context.timezone_is_utc) + , epoch_offset(type.getKind() == TIMESTAMP_INSTANT ? 1420070400 : context.epoch_offset) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const char * data = column.getRawData().data(); + const Int64 multiplier = scale ? common::exp10_i64(static_cast(*scale)) : 1; + const Int64 nanos_multiplier = scale ? common::exp10_i64(9 - static_cast(*scale)) : 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + Int64 secs = 0; + Int64 nano = 0; + if (scale) + { + /// For the values before the epoch, the nanoseconds are negative (as in the Arrow ORC adapter). + Int64 value = unalignedLoad(data + (offset + i) * sizeof(Int64)); + secs = value / multiplier; + nano = (value % multiplier) * nanos_multiplier; + } + else + { + secs = unalignedLoad(data + (offset + i) * sizeof(UInt32)); + nano = 0; + } + + /// The statistics have the milliseconds rounded down and the rest of the nanoseconds, which is not negative. + Int64 nano_millis = nano / 1000000; + Int64 nano_rest = nano % 1000000; + if (nano_rest < 0) + { + nano_rest += 1000000; + --nano_millis; + } + Int64 utc_seconds = secs; + Int64 millis = 0; + Int64 encoded_seconds = 0; + if ((!is_utc && common::addOverflow(secs, (*context.timezone_offset)(secs), utc_seconds)) + || common::mulOverflow(utc_seconds, Int64{1000}, millis) + || common::addOverflow(millis, nano_millis, millis) + || common::subOverflow(secs + (secs < 0 && nano > 999999), epoch_offset, encoded_seconds)) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp (seconds={}, nanoseconds={}) in ORC column {} is out of the range supported by the ORC format", secs, nano, column_id); + index_statistics.updateTimestamp(millis, static_cast(nano_rest)); + + seconds_encoder.write(encoded_seconds); + nanos_encoder.write(formatNanos(nano)); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + seconds_encoder.flush(); + seconds_stream.finish(); + nanos_encoder.flush(); + nanos_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), seconds_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), nanos_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + seconds_stream.estimateSize() + nanos_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + seconds_encoder.recordPosition(positions); + nanos_encoder.recordPosition(positions); + } + + void resetStreams() override + { + seconds_stream.reset(); + nanos_stream.reset(); + } + +private: + /// The trailing zeros are removed and their number is kept in the lowest 3 bits. + static Int64 formatNanos(Int64 nanos) + { + if (nanos == 0) + return 0; + if (nanos % 100 != 0) + return nanos << 3; + nanos /= 100; + Int64 trailing_zeros = 1; + while (nanos % 10 == 0 && trailing_zeros < 7) + { + nanos /= 10; + ++trailing_zeros; + } + return (nanos << 3) | trailing_zeros; + } + + const std::optional scale; + OutputByteStream seconds_stream; + OutputByteStream nanos_stream; + IntRleEncoderV2 seconds_encoder; + IntRleEncoderV2 nanos_encoder; + const bool is_utc; + const Int64 epoch_offset; +}; + +class DecimalColumnWriter final : public PrimitiveColumnWriter +{ +public: + DecimalColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(static_cast(type.getScale())) + , value_stream(context.compressor, context.block_size) + , scale_stream(context.compressor, context.block_size) + , scale_encoder(scale_stream, true) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `Decimal32`, `Decimal64` or `Decimal128`. + const size_t width = column.sizeOfValueIfFixed(); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + Int128 value; + if (width == 16) + value = unalignedLoad(data + row * 16); + else if (width == 8) + value = unalignedLoad(data + row * 8); + else if (width == 4) + value = unalignedLoad(data + row * 4); + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC decimal", column.getName()); + + /// Zigzag-encoded base 128 varint. + UInt128 encoded = (static_cast(value) << 1) ^ static_cast(value >> 127); + while (encoded >= 0x80) + { + char byte = static_cast(static_cast(encoded & 0x7F) | 0x80); + value_stream.write(&byte, 1); + encoded >>= 7; + } + char last = static_cast(static_cast(encoded)); + value_stream.write(&last, 1); + + scale_encoder.write(scale); + index_statistics.updateDecimal(value, scale); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + value_stream.finish(); + scale_encoder.flush(); + scale_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), value_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), scale_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + value_stream.estimateSize() + scale_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + value_stream.recordPosition(positions); + scale_encoder.recordPosition(positions); + } + + void resetStreams() override + { + value_stream.reset(); + scale_stream.reset(); + } + +private: + const Int32 scale; + OutputByteStream value_stream; + OutputByteStream scale_stream; + IntRleEncoderV2 scale_encoder; +}; + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type_with_nulls, WriterContext & context) +{ + checkStackSize(); + + /// The nulls are handled by `addColumn`. + DataTypePtr data_type = removeNullable(data_type_with_nulls); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, context); + case BYTE: + return std::make_unique(type, context); + case SHORT: + case INT: + case LONG: + case DATE: + return std::make_unique(type, context); + case FLOAT: + return std::make_unique>(type, context); + case DOUBLE: + return std::make_unique>(type, context); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + return std::make_unique(type, context); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + std::optional scale; + if (const auto * datetime64 = typeid_cast(data_type.get())) + scale = datetime64->getScale(); + return std::make_unique(type, scale, context); + } + case DECIMAL: + return std::make_unique(type, context); + case STRUCT: + return std::make_unique(type, assert_cast(*data_type).getElements(), context); + case LIST: + return std::make_unique>( + type, DataTypes{assert_cast(*data_type).getNestedType()}, context); + case MAP: + { + const auto & map_type = assert_cast(*data_type); + return std::make_unique>(type, DataTypes{map_type.getKeyType(), map_type.getValueType()}, context); + } + case UNION: + return std::make_unique(type, assert_cast(*data_type).getVariants(), context); + case GEOMETRY: + case GEOGRAPHY: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC type {} is not supported", type.toString()); +} + +} + + +Writer::Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_) + : out(out_), options(options_) +{ + if (options.compression_block_size == 0 || options.compression_block_size >= (1ULL << 23)) + throw Exception(ErrorCodes::BAD_ARGUMENTS, + "The ORC compression block size must be positive and less than 8 MiB, got {}", options.compression_block_size); + + schema = Type::buildSelectedType(schema_, std::vector(schema_.getMaximumColumnId() + 1, true)); + schema->assignIds(0); + + compressor = createCompressor(options.compression); + + context = std::make_unique(); + context->compressor = compressor.get(); + context->block_size = options.compression_block_size; + context->enable_index = options.row_index_stride > 0; + context->dictionary_key_size_threshold = options.dictionary_key_size_threshold; + context->timezone_offset.emplace(DateLUT::instance(options.timezone_name)); + context->timezone_is_utc = options.timezone_name == "GMT" || options.timezone_name == "UTC"; + static constexpr Int64 UTC_2015_01_01 = 1420070400; + context->epoch_offset = UTC_2015_01_01 - (*context->timezone_offset)(UTC_2015_01_01); + + if (schema->getKind() != STRUCT) + throw Exception(ErrorCodes::LOGICAL_ERROR, "The root type of ORC file must be a struct"); + column_writer = std::make_unique(*schema, column_types, *context); + + write("ORC"); + footer.header_length = current_offset; + footer.row_index_stride = static_cast(options.row_index_stride); + /// The identifier of the C++ writer of the reference implementation, which this writer follows. + footer.writer = 1; + footer.software_version = "ClickHouse"; + schema->toProto(footer.types); +} + +Writer::~Writer() = default; + +void Writer::write(const std::string & data) +{ + out.write(data.data(), data.size()); + current_offset += data.size(); +} + +void Writer::add(const Columns & columns, size_t num_rows) +{ + auto & root = typeid_cast(*column_writer); + + if (context->enable_index) + { + size_t position = 0; + while (position < num_rows) + { + size_t chunk = std::min(num_rows - position, options.row_index_stride - index_rows); + root.addRoot(columns, position, chunk); + position += chunk; + index_rows += chunk; + stripe_rows += chunk; + if (index_rows >= options.row_index_stride) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + } + } + else + { + stripe_rows += num_rows; + root.addRoot(columns, 0, num_rows); + } + + if (column_writer->estimateSize() >= options.stripe_size) + writeStripe(); +} + +void Writer::writeStripe() +{ + if (context->enable_index && index_rows != 0) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + else + column_writer->mergeRowGroupStatsIntoStripeStats(); + + column_writer->finalizeStripe(); + + std::vector index_streams; + std::vector data_streams; + if (context->enable_index) + column_writer->writeIndex(index_streams); + column_writer->flush(data_streams); + + Proto::StripeFooter stripe_footer; + UInt64 index_length = 0; + UInt64 data_length = 0; + for (const auto & s : index_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + index_length += s.data.size(); + } + for (const auto & s : data_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + data_length += s.data.size(); + } + column_writer->getColumnEncodings(stripe_footer.columns); + stripe_footer.writer_timezone = options.timezone_name; + + auto & stripe_statistics = metadata.stripe_stats.emplace_back(); + column_writer->getStripeStatistics(stripe_statistics.col_stats); + column_writer->mergeStripeStatsIntoFileStats(); + + Proto::StripeInformation stripe; + stripe.offset = current_offset; + + for (const auto & s : index_streams) + write(s.data); + for (const auto & s : data_streams) + write(s.data); + + std::string footer_data = compressWhole(*context, stripe_footer.serialize()); + write(footer_data); + + stripe.index_length = index_length; + stripe.data_length = data_length; + stripe.footer_length = footer_data.size(); + stripe.number_of_rows = stripe_rows; + footer.stripes.push_back(stripe); + + total_rows += stripe_rows; + stripe_rows = 0; + index_rows = 0; + (*column_writer).reset(); +} + +void Writer::close() +{ + if (stripe_rows > 0) + writeStripe(); + + Proto::PostScript postscript; + + /// The content length covers only the stripes, not the metadata section with the stripe statistics. + footer.content_length = current_offset - footer.header_length; + + std::string metadata_data = compressWhole(*context, metadata.serialize()); + write(metadata_data); + postscript.metadata_length = metadata_data.size(); + + footer.number_of_rows = total_rows; + footer.statistics.clear(); + column_writer->getFileStatistics(footer.statistics); + std::string footer_data = compressWhole(*context, footer.serialize()); + write(footer_data); + + postscript.footer_length = footer_data.size(); + postscript.compression = options.compression; + postscript.compression_block_size = options.compression_block_size; + postscript.version = {0, 12}; + /// ORC-135: the timestamp statistics are in UTC. + postscript.writer_version = 6; + postscript.magic = "ORC"; + std::string postscript_data = postscript.serialize(); + if (postscript_data.size() > 255) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC postscript is too large: {} bytes", postscript_data.size()); + write(postscript_data); + write(std::string(1, static_cast(postscript_data.size()))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.h b/src/Processors/Formats/Impl/ORC/Writer.h new file mode 100644 index 000000000000..111c20ac0fab --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +class OutputStream +{ +public: + virtual ~OutputStream() = default; + virtual void write(const void * buf, size_t length) = 0; +}; + +struct WriterOptions +{ + CompressionKind compression = CompressionKind::ZSTD; + UInt64 compression_block_size = 256 * 1024; + /// The number of rows between the row index entries; 0 means no row index. + UInt64 row_index_stride = 10000; + /// Use the dictionary encoding for a string column if the number of distinct values in the + /// first row group is at most this fraction of the number of values. 0 disables the dictionaries. + double dictionary_key_size_threshold = 0.0; + /// The time zone of the writer, which is written into the stripe footers. + std::string timezone_name = "GMT"; + /// A stripe is written when the estimated size of its data reaches this size. + UInt64 stripe_size = 64 * 1024 * 1024; +}; + +class ColumnWriter; +struct WriterContext; + +class Writer +{ +public: + /// `column_types` are the ClickHouse types (without `LowCardinality`) of the columns of the file, + /// which are the fields of `schema` (a struct). The values are converted as follows: + /// the unsigned integers are written as the signed ones of the same width (but `Date` as is); + /// `DateTime` and `DateTime64` as TIMESTAMP; `FixedString`, `IPv6` and the big integers + /// as their raw bytes; `Variant` as UNION with the branches in the order of its variants. + Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_); + ~Writer(); + + /// Adds the rows of the columns (in the order of the fields of the schema). + void add(const Columns & columns, size_t num_rows); + + /// Writes the remaining data and the file footer. + void close(); + +private: + void writeStripe(); + void write(const std::string & data); + + std::unique_ptr schema; + OutputStream & out; + WriterOptions options; + std::unique_ptr compressor; + std::unique_ptr context; + std::unique_ptr column_writer; + + Proto::Footer footer; + Proto::Metadata metadata; + UInt64 current_offset = 0; + UInt64 stripe_rows = 0; + UInt64 index_rows = 0; + UInt64 total_rows = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp deleted file mode 100644 index 95d9cd537d74..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp +++ /dev/null @@ -1,276 +0,0 @@ -#include -#include - -#if USE_ORC -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -namespace DB -{ - -namespace ErrorCodes -{ - extern const int BAD_ARGUMENTS; - extern const int CANNOT_READ_ALL_DATA; -} - -ORCBlockInputFormat::ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_) - : IInputFormat(std::move(header_), &in_) - , block_missing_values(getPort().getHeader().columns()) - , format_settings(format_settings_) - , skip_stripes(format_settings.orc.skip_stripes) -{ -} - -Chunk ORCBlockInputFormat::read() -{ - block_missing_values.clear(); - - if (!file_reader) - prepareReader(); - - if (is_stopped) - return {}; - - for (; stripe_current < stripe_total && skip_stripes.contains(stripe_current); ++stripe_current) - ; - - if (stripe_current >= stripe_total) - return {}; - - if (need_only_count) - return getChunkForCount(file_reader->GetRawORCReader()->getStripe(stripe_current++)->getNumberOfRows()); - - auto batch_result = file_reader->ReadStripe(stripe_current, include_indices); - if (!batch_result.ok()) - throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Failed to create batch reader: {}", batch_result.status().ToString()); - - auto batch = batch_result.ValueOrDie(); - if (!batch) - return {}; - - /// Validate validity bitmaps before building the table: Table::FromRecordBatches computes - /// each column's null_count, and Arrow derives an unknown FieldNode null_count by scanning - /// the bitmap over the declared length, which reads out of bounds on a truncated bitmap. - ArrowColumnToCHColumn::checkRecordBatchValidityBitmaps(*batch); - - auto table_result = arrow::Table::FromRecordBatches({batch}); - if (!table_result.ok()) - throw Exception( - ErrorCodes::CANNOT_READ_ALL_DATA, "Error while reading batch of ORC data: {}", table_result.status().ToString()); - - /// We should extract the number of rows directly from the stripe, because in case when - /// record batch contains 0 columns (for example if we requested only columns that - /// are not presented in data) the number of rows in record batch will be 0. - size_t num_rows = file_reader->GetRawORCReader()->getStripe(stripe_current)->getNumberOfRows(); - - const auto & table = table_result.ValueOrDie(); - if (!table || !num_rows) - return {}; - - approx_bytes_read_for_chunk = file_reader->GetRawORCReader()->getStripe(stripe_current)->getDataLength(); - ++stripe_current; - - /// If defaults_for_omitted_fields is true, calculate the default values from default expression for omitted fields. - /// Otherwise fill the missing columns with zero values of its type. - BlockMissingValues * block_missing_values_ptr = format_settings.defaults_for_omitted_fields ? &block_missing_values : nullptr; - std::shared_ptr metadata; - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueOrDie(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected error while reading parquet metadata {}", status.status().message()); - - return arrow_column_to_ch_column->arrowTableToCHChunk(table, num_rows, metadata, block_missing_values_ptr); -} - -void ORCBlockInputFormat::resetParser() -{ - IInputFormat::resetParser(); - - file_reader.reset(); - include_indices.clear(); - block_missing_values.clear(); -} - -const BlockMissingValues * ORCBlockInputFormat::getMissingValues() const -{ - return &block_missing_values; -} - - -static void getFileReaderAndSchema( - ReadBuffer & in, - std::unique_ptr & file_reader, - std::shared_ptr & schema, - const FormatSettings & format_settings, - std::atomic & is_stopped) -{ - auto arrow_file = asArrowFile(in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES); - if (is_stopped) - return; - - auto result = arrow::adapters::orc::ORCFileReader::Open(arrow_file, ArrowMemoryPool::instance()); - if (!result.ok()) - throw Exception::createDeprecated(result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - file_reader = std::move(result).ValueOrDie(); - - auto read_schema_result = file_reader->ReadSchema(); - if (!read_schema_result.ok()) - throw Exception::createDeprecated(read_schema_result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - schema = std::move(read_schema_result).ValueOrDie(); -} - -void ORCBlockInputFormat::prepareReader() -{ - std::shared_ptr schema; - getFileReaderAndSchema(*in, file_reader, schema, format_settings, is_stopped); - if (is_stopped) - return; - - stripe_total = static_cast(file_reader->NumberOfStripes()); - stripe_current = 0; - - arrow_column_to_ch_column = std::make_unique( - getPort().getHeader(), - "ORC", - format_settings, - std::nullopt, - std::nullopt, - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.date_time_overflow_behavior, - format_settings.parquet.allow_geoparquet_parser, - format_settings.orc.case_insensitive_column_matching); - - const bool ignore_case = format_settings.orc.case_insensitive_column_matching; - std::unordered_set nested_table_names = Nested::getAllTableNames(getPort().getHeader(), ignore_case); - for (int i = 0; i < schema->num_fields(); ++i) - { - const auto & name = schema->field(i)->name(); - if (getPort().getHeader().has(name, ignore_case) || nested_table_names.contains(ignore_case ? boost::to_lower_copy(name) : name)) - include_indices.push_back(i); - } -} - -ORCSchemaReader::ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_) - : ISchemaReader(in_), format_settings(format_settings_) -{ -} - -void ORCSchemaReader::initializeIfNeeded() -{ - if (file_reader) - return; - - std::atomic is_stopped = 0; - getFileReaderAndSchema(in, file_reader, schema, format_settings, is_stopped); - - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueUnsafe(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Error while reading incorrect metadata of ORC {}", status.status().message()); -} - -NamesAndTypesList ORCSchemaReader::readSchema() -{ - initializeIfNeeded(); - - auto header = ArrowColumnToCHColumn::arrowSchemaToCHHeader( - *schema, - metadata, - "ORC", - format_settings, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.schema_inference_make_columns_nullable != 0, - false, - format_settings.parquet.allow_geoparquet_parser); - if (format_settings.schema_inference_make_columns_nullable == 1) - return getNamesAndRecursivelyNullableTypes(header, format_settings); - return header.getNamesAndTypesList(); -} - -std::optional ORCSchemaReader::readNumberOrRows() -{ - initializeIfNeeded(); - return file_reader->NumberOfRows(); -} - -void registerInputFormatORC(FormatFactory & factory) -{ - factory.registerRandomAccessInputFormat( - "ORC", - [](ReadBuffer & buf, - const Block & sample, - const FormatSettings & settings, - const ReadSettings & read_settings, - bool is_remote_fs, - FormatParserSharedResourcesPtr, - FormatFilterInfoPtr format_filter_info) - { - InputFormatPtr res; - if (settings.orc.use_fast_decoder) - { - const bool has_file_size = isBufferWithFileSize(buf); - auto * seekable_in = dynamic_cast(&buf); - const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in - && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; - const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; - res = std::make_shared( - buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); - } - else - res = std::make_shared(buf, std::make_shared(sample), settings); - - return res; - }); - factory.markFormatSupportsSubsetOfColumns("ORC"); -} - -void registerORCSchemaReader(FormatFactory & factory) -{ - factory.registerSchemaReader( - "ORC", - [](ReadBuffer & buf, const FormatSettings & settings) - { - SchemaReaderPtr res; - if (settings.orc.use_fast_decoder) - res = std::make_shared(buf, settings); - else - res = std::make_shared(buf, settings); - - return res; - } - ); - - factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) - { - return fmt::format("schema_inference_make_columns_nullable={}", settings.schema_inference_make_columns_nullable); - }); -} - -} -#else - -namespace DB -{ - class FormatFactory; - void registerInputFormatORC(FormatFactory &) - { - } - - void registerORCSchemaReader(FormatFactory &) - { - } -} - -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.h b/src/Processors/Formats/Impl/ORCBlockInputFormat.h deleted file mode 100644 index 622a6276c344..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once -#include "config.h" -#if USE_ORC - -#include -#include -#include -#include - -#include - -namespace arrow::adapters::orc -{ - class ORCFileReader; -} - -namespace DB -{ - -class ArrowColumnToCHColumn; - -class ORCBlockInputFormat : public IInputFormat -{ -public: - ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_); - - String getName() const override { return "ORCBlockInputFormat"; } - - void resetParser() override; - - const BlockMissingValues * getMissingValues() const override; - - size_t getApproxBytesReadForChunk() const override { return approx_bytes_read_for_chunk; } - -protected: - Chunk read() override; - - void onCancel() noexcept override - { - is_stopped = 1; - } - -private: - void prepareReader(); - - // TODO: check that this class implements every part of its parent - - std::unique_ptr file_reader; - - std::unique_ptr arrow_column_to_ch_column; - - // indices of columns to read from ORC file - std::vector include_indices; - - BlockMissingValues block_missing_values; - size_t approx_bytes_read_for_chunk = 0; - - const FormatSettings format_settings; - const std::unordered_set & skip_stripes; - - int stripe_total = 0; - int stripe_current = 0; - - std::atomic is_stopped{0}; -}; - -class ORCSchemaReader : public ISchemaReader -{ -public: - ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); - - NamesAndTypesList readSchema() override; - std::optional readNumberOrRows() override; - -private: - void initializeIfNeeded(); - - std::unique_ptr file_reader; - std::shared_ptr metadata; - std::shared_ptr schema; - const FormatSettings format_settings; -}; - -} -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp index b9f8bd463152..acf3371b9249 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp @@ -1,5 +1,9 @@ #include +#include + +#include + #if USE_ORC #include @@ -11,6 +15,7 @@ #include #include #include +#include #include #include @@ -20,8 +25,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -38,495 +45,257 @@ namespace ErrorCodes namespace { -orc::CompressionKind getORCCompression(FormatSettings::ORCCompression method) +ORC::CompressionKind getORCCompression(FormatSettings::ORCCompression method) { if (method == FormatSettings::ORCCompression::NONE) - return orc::CompressionKind::CompressionKind_NONE; + return ORC::CompressionKind::NONE; #if USE_SNAPPY if (method == FormatSettings::ORCCompression::SNAPPY) - return orc::CompressionKind::CompressionKind_SNAPPY; + return ORC::CompressionKind::SNAPPY; #endif if (method == FormatSettings::ORCCompression::ZSTD) - return orc::CompressionKind::CompressionKind_ZSTD; + return ORC::CompressionKind::ZSTD; if (method == FormatSettings::ORCCompression::LZ4) - return orc::CompressionKind::CompressionKind_LZ4; + return ORC::CompressionKind::LZ4; if (method == FormatSettings::ORCCompression::ZLIB) - return orc::CompressionKind::CompressionKind_ZLIB; + return ORC::CompressionKind::ZLIB; throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported compression method"); } -} - -ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} - -uint64_t ORCOutputStream::getLength() const +/// Two ORC types get the same key exactly when `parseORCType` (NativeORCBlockInputFormat.cpp) reads +/// them back as the same ClickHouse type: `BINARY` and `STRING` both read as `String`, and a nested +/// `UNION` reads as a `Variant`, which sorts its branches, while ORC keeps them positional. +/// A field name is length-prefixed so a name containing `:` or `,` cannot forge another key. +String orcTypeDedupKey(const ORC::Type & type) { - return out.count(); + const auto kind = type.getKind(); + if (kind == ORC::TypeKind::BINARY || kind == ORC::TypeKind::STRING) + return "string"; + if (kind == ORC::TypeKind::DECIMAL) + return fmt::format("decimal({},{})", type.getPrecision(), type.getScale()); + + std::vector children; + for (size_t i = 0; i < type.getSubtypeCount(); ++i) + { + auto child = orcTypeDedupKey(*type.getSubtype(i)); + if (kind == ORC::TypeKind::STRUCT) + child = fmt::format("{}:{}:{}", type.getFieldName(i).size(), type.getFieldName(i), child); + children.push_back(std::move(child)); + } + if (kind == ORC::TypeKind::UNION) + std::sort(children.begin(), children.end()); + /// Every remaining kind the writer emits is a parameterless primitive mapping to a distinct + /// ClickHouse type, so for those the kind alone is the key and there are no children. + return fmt::format("{}<{}>", static_cast(kind), fmt::join(children, ",")); } -uint64_t ORCOutputStream::getNaturalWriteSize() const -{ - out.nextIfAtEnd(); - return out.available(); } +ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} + void ORCOutputStream::write(const void* buf, size_t length) { out.write(static_cast(buf), length); } -ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_) +ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_) : IOutputFormat(header_, out_) , format_settings{format_settings_} , output_stream(out_) + , column_mapper(std::move(column_mapper_)) { for (const auto & type : header_->getDataTypes()) data_types.push_back(recursiveRemoveLowCardinality(type)); } -std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type) +std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type, const String & column_path) { - switch (type->getTypeId()) + /// Nullable(T) maps to the same ORC node as T; only the Iceberg `required` flag differs. + bool required = !type->isNullable(); + const DataTypePtr unwrapped = removeNullable(type); + + std::unique_ptr result; + switch (unwrapped->getTypeId()) { case TypeIndex::UInt8: { - if (isBool(type)) - return orc::createPrimitiveType(orc::TypeKind::BOOLEAN); - return orc::createPrimitiveType(orc::TypeKind::BYTE); + if (isBool(unwrapped)) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BOOLEAN); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum8: [[fallthrough]]; case TypeIndex::Int8: { - return orc::createPrimitiveType(orc::TypeKind::BYTE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum16: [[fallthrough]]; case TypeIndex::UInt16: [[fallthrough]]; case TypeIndex::Int16: { - return orc::createPrimitiveType(orc::TypeKind::SHORT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::SHORT); + break; } case TypeIndex::UInt32: [[fallthrough]]; case TypeIndex::IPv4: [[fallthrough]]; case TypeIndex::Int32: { - return orc::createPrimitiveType(orc::TypeKind::INT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::INT); + break; } case TypeIndex::UInt64: [[fallthrough]]; case TypeIndex::Int64: { - return orc::createPrimitiveType(orc::TypeKind::LONG); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::LONG); + break; } case TypeIndex::Float32: { - return orc::createPrimitiveType(orc::TypeKind::FLOAT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::FLOAT); + break; } case TypeIndex::Float64: { - return orc::createPrimitiveType(orc::TypeKind::DOUBLE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DOUBLE); + break; } case TypeIndex::Date32: [[fallthrough]]; case TypeIndex::Date: { - return orc::createPrimitiveType(orc::TypeKind::DATE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DATE); + break; } case TypeIndex::DateTime: [[fallthrough]]; case TypeIndex::DateTime64: { - return orc::createPrimitiveType(orc::TypeKind::TIMESTAMP); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::TIMESTAMP); + break; } case TypeIndex::Int128: [[fallthrough]]; case TypeIndex::UInt128: [[fallthrough]]; case TypeIndex::Int256: [[fallthrough]]; case TypeIndex::UInt256: [[fallthrough]]; case TypeIndex::Decimal256: - return orc::createPrimitiveType(orc::TypeKind::BINARY); - case TypeIndex::FixedString: [[fallthrough]]; - case TypeIndex::String: - { - if (format_settings.orc.output_string_as_string) - return orc::createPrimitiveType(orc::TypeKind::STRING); - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::IPv6: - { - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::Nullable: - { - return getORCType(removeNullable(type)); - } - case TypeIndex::Array: - { - const auto * array_type = assert_cast(type.get()); - return orc::createListType(getORCType(array_type->getNestedType())); - } - case TypeIndex::Decimal32: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal64: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal128: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Tuple: - { - const auto * tuple_type = assert_cast(type.get()); - const auto & nested_names = tuple_type->getElementNames(); - const auto & nested_types = tuple_type->getElements(); - auto struct_type = orc::createStructType(); - for (size_t i = 0; i < nested_types.size(); ++i) - struct_type->addStructField(nested_names[i], getORCType(nested_types[i])); - return struct_type; - } - case TypeIndex::Map: - { - const auto * map_type = assert_cast(type.get()); - return orc::createMapType( - getORCType(map_type->getKeyType()), - getORCType(map_type->getValueType()) - ); - } - default: - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); - } - } -} - -template -void ORCBlockOutputFormat::writeNumbers( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - NumberVectorBatch & number_orc_column = dynamic_cast(orc_column); - const auto & number_column = assert_cast &>(column); - - number_orc_column.data.resize(number_column.size()); - for (size_t i = 0; i != number_column.size(); ++i) - number_orc_column.data[i] = convert(number_column.getElement(i)); -} - -template -void ORCBlockOutputFormat::writeDecimals( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - DecimalVectorBatch & decimal_orc_column = dynamic_cast(orc_column); - const auto & decimal_column = assert_cast &>(column); - const auto * decimal_type = assert_cast *>(type.get()); - decimal_orc_column.precision = decimal_type->getPrecision(); - decimal_orc_column.scale = decimal_type->getScale(); - decimal_orc_column.resize(decimal_column.size()); - - decimal_orc_column.values.resize(decimal_column.size()); - for (size_t i = 0; i != decimal_column.size(); ++i) - decimal_orc_column.values[i] = convert(decimal_column.getElement(i).value); -} - -template -void ORCBlockOutputFormat::writeStrings( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * null_bytemap) -{ - orc::StringVectorBatch & string_orc_column = dynamic_cast(orc_column); - const auto & string_column = assert_cast(column); - - string_orc_column.data.resize(string_column.size()); - string_orc_column.length.resize(string_column.size()); - for (size_t i = 0; i != string_column.size(); ++i) - { - const std::string_view string = string_column.getDataAt(i); - string_orc_column.data[i] = (null_bytemap && (*null_bytemap)[i]) ? nullptr : const_cast(string.data()); - string_orc_column.length[i] = string.size(); - } -} - -template -void ORCBlockOutputFormat::writeDateTimes( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - GetSecondsFunc get_seconds, - GetNanosecondsFunc get_nanoseconds) -{ - orc::TimestampVectorBatch & timestamp_orc_column = dynamic_cast(orc_column); - const auto & timestamp_column = assert_cast(column); - - timestamp_orc_column.data.resize(timestamp_column.size()); - timestamp_orc_column.nanoseconds.resize(timestamp_column.size()); - for (size_t i = 0; i != timestamp_column.size(); ++i) - { - timestamp_orc_column.data[i] = static_cast(get_seconds(timestamp_column.getElement(i))); - timestamp_orc_column.nanoseconds[i] = static_cast(get_nanoseconds(timestamp_column.getElement(i))); - } -} - -void ORCBlockOutputFormat::writeColumn( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * null_bytemap) -{ - size_t rows = column.size(); - orc_column.resize(rows); - orc_column.numElements = rows; - - /// Calculate orc_column.hasNulls - if (null_bytemap) - orc_column.hasNulls = !memoryIsZero(null_bytemap->data(), 0, null_bytemap->size()); - else - orc_column.hasNulls = false; - - /// Fill orc_column.notNull - if (orc_column.hasNulls) - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = !(*null_bytemap)[i]; - } - else - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = 1; - } - - /// ORC doesn't have unsigned types, so cast everything to signed and sign-extend to Int64 to - /// make the ORC library calculate min and max correctly. - switch (type->getTypeId()) - { - case TypeIndex::Enum8: [[fallthrough]]; - case TypeIndex::Int8: - { - /// Note: Explicit cast to avoid clang-tidy error: 'signed char' to 'long' conversion; consider casting to 'unsigned char' first. - writeNumbers(orc_column, column, null_bytemap, [](const Int8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::UInt8: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::Enum16: [[fallthrough]]; - case TypeIndex::Int16: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int16 & value){ return value; }); - break; - } - case TypeIndex::Date: [[fallthrough]]; - case TypeIndex::UInt16: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt16 & value){ return Int64(Int16(value)); }); - break; - } - case TypeIndex::Date32: [[fallthrough]]; - case TypeIndex::Int32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int32 & value){ return value; }); - break; - } - case TypeIndex::UInt32: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt32 & value){ return Int64(Int32(value)); }); - break; - } - case TypeIndex::IPv4: - { - writeNumbers(orc_column, column, null_bytemap, [](const IPv4 & value){ return Int64(Int32(value.toUnderType())); }); - break; - } - case TypeIndex::Int64: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int64 & value){ return value; }); - break; - } - case TypeIndex::UInt64: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt64 & value){ return value; }); - break; - } - case TypeIndex::Int128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Int256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Float32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Float32 & value){ return value; }); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; - } - case TypeIndex::Float64: + case TypeIndex::String: { - writeNumbers(orc_column, column, null_bytemap, [](const Float64 & value){ return value; }); + bool force_string = format_settings.orc.output_string_as_string; + result = ORC::Type::createPrimitiveType(force_string ? ORC::TypeKind::STRING : ORC::TypeKind::BINARY); break; } case TypeIndex::FixedString: { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::String: - { - writeStrings(orc_column, column, null_bytemap); + /// Iceberg `fixed[L]` (FixedString) must stay ORC `binary`, so for Iceberg writes + /// force `binary` regardless of the setting; keep the setting-driven choice otherwise. + if (format_settings.orc.output_string_as_string && !column_mapper) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::STRING); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } case TypeIndex::IPv6: { - writeStrings(orc_column, column, null_bytemap); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } - case TypeIndex::DateTime: + case TypeIndex::Array: { - writeDateTimes( - orc_column, - column, null_bytemap, - [](UInt32 value){ return value; }, - [](UInt32){ return 0; }); + const auto * array_type = assert_cast(unwrapped.get()); + result = ORC::Type::createListType(getORCType(array_type->getNestedType(), Nested::concatenateName(column_path, "element"))); break; } - case TypeIndex::DateTime64: + case TypeIndex::Decimal32: { - const auto * timestamp_type = assert_cast(type.get()); - UInt32 scale = timestamp_type->getScale(); - writeDateTimes( - orc_column, - column, - null_bytemap, - [scale](Int64 value) { return value / Int64(std::pow(10, scale)); }, - [scale](Int64 value) { return (value % Int64(std::pow(10, scale))) * Int64(std::pow(10, 9 - scale)); }); - break; - } - case TypeIndex::Decimal32: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int32 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal64: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int64 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal128: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int128 value){ return orc::Int128(static_cast(value >> 64), static_cast((value << 64) >> 64)); }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } - case TypeIndex::Decimal256: + case TypeIndex::Tuple: { - writeStrings>(orc_column, column, null_bytemap); + const auto * tuple_type = assert_cast(unwrapped.get()); + const auto & nested_names = tuple_type->getElementNames(); + const auto & nested_types = tuple_type->getElements(); + auto struct_type = ORC::Type::createStructType(); + for (size_t i = 0; i < nested_types.size(); ++i) + struct_type->addStructField(nested_names[i], getORCType(nested_types[i], Nested::concatenateName(column_path, nested_names[i]))); + result = std::move(struct_type); break; } - case TypeIndex::Nullable: + case TypeIndex::Map: { - chassert(!null_bytemap); - const auto & nullable_column = assert_cast(column); - const PaddedPODArray & new_null_bytemap = assert_cast &>(*nullable_column.getNullMapColumnPtr()).getData(); - auto nested_type = removeNullable(type); - writeColumn(orc_column, nullable_column.getNestedColumn(), nested_type, &new_null_bytemap); + const auto * map_type = assert_cast(unwrapped.get()); + result = ORC::Type::createMapType( + getORCType(map_type->getKeyType(), Nested::concatenateName(column_path, "key")), + getORCType(map_type->getValueType(), Nested::concatenateName(column_path, "value")) + ); break; } - case TypeIndex::Array: - { - orc::ListVectorBatch & list_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column); - auto nested_type = assert_cast(*type).getNestedType(); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - list_orc_column.offsets.resize(column_size + 1); - - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - list_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - list_orc_column.offsets[i + 1] = offsets[i]; - - orc::ColumnVectorBatch & nested_orc_column = *list_orc_column.elements; - writeColumn(nested_orc_column, list_column.getData(), nested_type, nullptr); + case TypeIndex::Variant: + { + const auto & variant_type = assert_cast(*unwrapped); + auto union_type = ORC::Type::createUnionType(); + /// ORC keeps one physical stream per union branch and identifies a branch only by its + /// ORC type, so two variants that map to the same ORC type (e.g. `Int32` and `UInt32`, + /// both ORC `int`) would produce a union with duplicate branches, which the reader + /// rejects. Branches whose ORC types merely read back as one ClickHouse type collide the + /// same way, so they are keyed by `orcTypeDedupKey` rather than by the ORC type itself. + std::unordered_map> variant_by_orc_type; + /// A union child is addressed by its type name, the way a `Variant` subcolumn is + /// (`v.Int32`). Iceberg has no union type, so no field id is expected to be found there. + for (const auto & nested_type : variant_type.getVariants()) + { + auto child_type = getORCType(nested_type, Nested::concatenateName(column_path, nested_type->getName())); + auto [it, inserted] = variant_by_orc_type.emplace( + orcTypeDedupKey(*child_type), std::pair{nested_type->getName(), child_type->toString()}); + if (!inserted) + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Type {} is not supported for ORC output format: variant {} is written as ORC type '{}' and variant {} as " + "'{}', which are read back as the same type, and ORC unions with duplicate branch types cannot be read back", + unwrapped->getName(), it->second.first, it->second.second, nested_type->getName(), child_type->toString()); + union_type->addChild(std::move(child_type)); + } + result = std::move(union_type); break; } - case TypeIndex::Tuple: + default: { - orc::StructVectorBatch & struct_orc_column = dynamic_cast(orc_column); - const auto & tuple_column = assert_cast(column); - auto nested_types = assert_cast(type.get())->getElements(); - for (size_t i = 0; i != tuple_column.tupleSize(); ++i) - writeColumn(*struct_orc_column.fields[i], tuple_column.getColumn(i), nested_types[i], nullptr); - break; + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", unwrapped->getName()); } - case TypeIndex::Map: - { - orc::MapVectorBatch & map_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column).getNestedColumn(); - const auto & map_type = assert_cast(*type); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - - map_orc_column.offsets.resize(column_size + 1); - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - map_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - map_orc_column.offsets[i + 1] = offsets[i]; - - const auto nested_columns = assert_cast(list_column.getDataPtr().get())->getColumns(); - - orc::ColumnVectorBatch & keys_orc_column = *map_orc_column.keys; - auto key_type = map_type.getKeyType(); - writeColumn(keys_orc_column, *nested_columns[0], key_type, nullptr); + } - orc::ColumnVectorBatch & values_orc_column = *map_orc_column.elements; - auto value_type = map_type.getValueType(); - writeColumn(values_orc_column, *nested_columns[1], value_type, nullptr); - break; + /// Attach Iceberg field-id attributes so spec-compliant readers project columns by id. + if (column_mapper) + { + const auto & encoding = column_mapper->getStorageColumnEncoding(); + if (auto it = encoding.find(column_path); it != encoding.end()) + { + result->setAttribute("iceberg.id", std::to_string(it->second)); + result->setAttribute("iceberg.required", required ? "true" : "false"); } - default: - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); } + + return result; } void ORCBlockOutputFormat::consume(Chunk chunk) @@ -534,21 +303,13 @@ void ORCBlockOutputFormat::consume(Chunk chunk) if (!writer) prepareWriter(); - size_t columns_num = chunk.getNumColumns(); size_t rows_num = chunk.getNumRows(); - - std::unique_ptr batch = writer->createRowBatch(chunk.getNumRows()); - orc::StructVectorBatch & root = dynamic_cast(*batch); - auto columns = chunk.detachColumns(); for (auto & column : columns) column = recursiveRemoveLowCardinality(column); - for (size_t i = 0; i != columns_num; ++i) - writeColumn(*root.fields[i], *columns[i], data_types[i], nullptr); - - root.numElements = rows_num; - writer->add(*batch); + /// The values are encoded directly from the columns. + writer->add(columns, rows_num); } void ORCBlockOutputFormat::finalizeImpl() @@ -567,19 +328,22 @@ void ORCBlockOutputFormat::resetFormatterImpl() void ORCBlockOutputFormat::prepareWriter() { const Block & header = getPort(PortKind::Main).getHeader(); - schema = orc::createStructType(); - options.setMemoryPool(&getORCMemoryPool()); - options.setCompression(getORCCompression(format_settings.orc.output_compression_method)); - options.setRowIndexStride(format_settings.orc.output_row_index_stride); - options.setDictionaryKeySizeThreshold(format_settings.orc.output_dictionary_key_size_threshold); - options.setCompressionBlockSize(format_settings.orc.output_compression_block_size); - options.setTimezoneName(format_settings.orc.writer_time_zone_name); + schema = ORC::Type::createStructType(); + options.compression = getORCCompression(format_settings.orc.output_compression_method); + options.row_index_stride = format_settings.orc.output_row_index_stride; + options.dictionary_key_size_threshold = format_settings.orc.output_dictionary_key_size_threshold; + options.compression_block_size = format_settings.orc.output_compression_block_size; + options.timezone_name = format_settings.orc.writer_time_zone_name; size_t columns_count = header.columns(); for (size_t i = 0; i != columns_count; ++i) - schema->addStructField(header.safeGetByPosition(i).name, getORCType(recursiveRemoveLowCardinality(data_types[i]))); - writer = orc::createWriter(*schema, &output_stream, options); + { + const auto & column_name = header.safeGetByPosition(i).name; + schema->addStructField(column_name, getORCType(recursiveRemoveLowCardinality(data_types[i]), column_name)); + } + writer = std::make_unique(*schema, data_types, output_stream, options); } +void registerOutputFormatORC(FormatFactory & factory); void registerOutputFormatORC(FormatFactory & factory) { factory.registerOutputFormat("ORC", []( @@ -603,6 +367,7 @@ void registerOutputFormatORC(FormatFactory & factory) namespace DB { class FormatFactory; + void registerOutputFormatORC(FormatFactory &); void registerOutputFormatORC(FormatFactory &) { } diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h index 0e47f7333d9d..5c9ebc4da420 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h @@ -7,7 +7,8 @@ #include #include #include -#include +#include +#include namespace DB @@ -19,29 +20,22 @@ using DataTypes = std::vector; class WriteBuffer; -/// orc::Writer writes only in orc::OutputStream -class ORCOutputStream : public orc::OutputStream +class ORCOutputStream : public ORC::OutputStream { public: explicit ORCOutputStream(WriteBuffer & out_); - uint64_t getLength() const override; - uint64_t getNaturalWriteSize() const override; void write(const void * buf, size_t length) override; - void close() override {} - const std::string& getName() const override { return name; } - private: WriteBuffer & out; - std::string name = "ORCOutputStream"; }; -class ORCBlockOutputFormat : public IOutputFormat +class ORCBlockOutputFormat final : public IOutputFormat { public: - ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_); + ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_ = nullptr); String getName() const override { return "ORCBlockOutputFormat"; } @@ -50,37 +44,20 @@ class ORCBlockOutputFormat : public IOutputFormat void finalizeImpl() override; void resetFormatterImpl() override; - std::unique_ptr getORCType(const DataTypePtr & type); - - /// ConvertFunc is needed for type UInt8, because firstly UInt8 (char8_t) must be - /// converted to unsigned char (bugprone-signed-char-misuse in clang). - template - void writeNumbers(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, ConvertFunc convert); - - /// ConvertFunc is needed to convert ClickHouse Int128 to ORC Int128. - template - void writeDecimals(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, - const PaddedPODArray * null_bytemap, ConvertFunc convert); - - template - void writeStrings(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap); - - /// ORC column TimestampVectorBatch stores only seconds and nanoseconds, - /// GetSecondsFunc and GetNanosecondsFunc are needed to extract them from DateTime type. - template - void writeDateTimes(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, - GetSecondsFunc get_seconds, GetNanosecondsFunc get_nanoseconds); - - void writeColumn(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, const PaddedPODArray * null_bytemap); + /// For Iceberg writes, attaches the field-id `iceberg.id` type attribute so readers project + /// by id. `column_path` is the dotted name (`t.x`, `arr.element`) used to look the id up. + std::unique_ptr getORCType(const DataTypePtr & type, const String & column_path); void prepareWriter(); const FormatSettings format_settings; ORCOutputStream output_stream; DataTypes data_types; - std::unique_ptr writer; - std::unique_ptr schema; - orc::WriterOptions options; + std::unique_ptr writer; + std::unique_ptr schema; + ORC::WriterOptions options; + /// Non-null only for Iceberg writes; maps dotted column name -> Iceberg field-id. + ColumnMapperPtr column_mapper; }; } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.cpp b/src/Processors/Formats/Impl/Parquet/Decoding.cpp index 840abe3265b2..e52e24dce6a8 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp +++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp @@ -1676,6 +1676,8 @@ Int96Converter::Int96Converter() void Int96Converter::convertColumn(std::span data, size_t num_values, IColumn & col) const { + const bool saturate = overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate; + std::span to_span = col.insertRawUninitialized(num_values); Int64 * to = reinterpret_cast(to_span.data()); for (size_t i = 0; i < num_values; ++i) @@ -1700,16 +1702,17 @@ void Int96Converter::convertColumn(std::span data, size_t num_values /// This interpretation is consistent with the arrow reader code (DecodeInt96Timestamp in /// arrow/cpp/src/parquet/types.h) and with a test file written by spark /// (tests/queries/0_stateless/02998_native_parquet_reader.sh). - bool overflow = false; - Int64 x; - overflow |= common::subOverflow(julian_day, static_cast(2440588l), x); // unix day number - overflow |= common::mulOverflow(x, day_nanos, x); // unix nanoseconds - overflow |= common::addOverflow(x, nanos, x); - - if (overflow) - throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); - to[i] = x; + /// julian_day comes from Int32, so neither the subtraction nor the product can overflow Int128. + const Int128 total = Int128(julian_day - 2440588l) * day_nanos + nanos; + if (total < std::numeric_limits::min() || total > std::numeric_limits::max()) + { + if (!saturate) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); + to[i] = julian_day < 2440588l ? std::numeric_limits::min() : std::numeric_limits::max(); + } + else + to[i] = static_cast(total); } } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.h b/src/Processors/Formats/Impl/Parquet/Decoding.h index 05f6ef6a2e02..266176171e45 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.h +++ b/src/Processors/Formats/Impl/Parquet/Decoding.h @@ -298,6 +298,9 @@ extern template struct BigEndianDecimalStringConverter; struct Int96Converter : public FixedSizeConverter { + /// A value that does not fit into Int64 nanoseconds is clamped to the `DateTime64(9)` range with Saturate, otherwise throws. + FormatSettings::DateTimeOverflowBehavior overflow_behavior = FormatSettings::DateTimeOverflowBehavior::Ignore; + Int96Converter(); void convertColumn(std::span data, size_t num_values, IColumn & col) const override; diff --git a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp index 8053f644407c..b1633c13f7e2 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp @@ -1258,7 +1258,9 @@ void SchemaConverter::processPrimitiveColumn( case parq::Type::INT96: { out_inferred_type = std::make_shared(9, "UTC"); - out_decoder.fixed_size_converter = std::make_shared(); + auto converter = std::make_shared(); + converter->overflow_behavior = options.format.date_time_overflow_behavior; + out_decoder.fixed_size_converter = std::move(converter); /// (Leaving allow_stats == false because INT96 sort order is undefined.) return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp index 3e938fddea10..317478590c98 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp @@ -6,21 +6,17 @@ #include #include +#include #include #include +#include + #include #include #include -namespace CurrentMetrics -{ - extern const Metric ParquetEncoderThreads; - extern const Metric ParquetEncoderThreadsActive; - extern const Metric ParquetEncoderThreadsScheduled; -} - namespace DB { @@ -87,11 +83,10 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Custom parquet encoder doesn't support parquet versions < 2.6. Use output_format_parquet_use_custom_encoder = 0."); if (format_settings.parquet.parallel_encoding && format_settings.max_threads > 1) - pool = std::make_unique( - CurrentMetrics::ParquetEncoderThreads, - CurrentMetrics::ParquetEncoderThreadsActive, - CurrentMetrics::ParquetEncoderThreadsScheduled, - format_settings.max_threads); + { + getParquetEncoderThreadPool().initializeWithDefaultSettingsIfNotInitialized(); + pool = &getParquetEncoderThreadPool().get(); + } using C = FormatSettings::ParquetCompression; switch (format_settings.parquet.output_compression_method) @@ -130,10 +125,14 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea ParquetBlockOutputFormat::~ParquetBlockOutputFormat() { if (pool) - { - is_stopped = true; - pool->wait(); - } + stopThreads(); +} + +void ParquetBlockOutputFormat::stopThreads() +{ + is_stopped = true; + std::unique_lock lock(mutex); + condvar.wait(lock, [this] { return threads_running == 0; }); } void ParquetBlockOutputFormat::consume(Chunk chunk) @@ -279,8 +278,7 @@ void ParquetBlockOutputFormat::resetFormatterImpl() { if (pool) { - is_stopped = true; - pool->wait(); + stopThreads(); is_stopped = false; } @@ -497,17 +495,16 @@ void ParquetBlockOutputFormat::startMoreThreadsIfNeeded(const std::unique_locktrySchedule(job)) break; + ++threads_running; } } } -void ParquetBlockOutputFormat::threadFunction() +void ParquetBlockOutputFormat::threadFunction(ThreadGroupPtr & thread_group) { + std::optional switcher; + switcher.emplace(thread_group, ThreadName::PARQUET_ENCODER); + std::unique_lock lock(mutex); while (true) @@ -540,7 +541,12 @@ void ParquetBlockOutputFormat::threadFunction() { /// The check and the decrement need to be in the same critical section, to make sure /// we never get stuck with tasks but no threads. + /// Leave the query's thread group before stopThreads() can see the decrement. + switcher.reset(); + thread_group.reset(); --threads_running; + if (threads_running == 0) + condvar.notify_all(); return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h index f22447850e82..b553a00ba391 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h @@ -28,6 +28,9 @@ namespace DB class CHColumnToArrowColumn; +class ThreadGroup; +using ThreadGroupPtr = std::shared_ptr; + class ParquetBlockOutputFormat : public IOutputFormat { public: @@ -118,8 +121,9 @@ class ParquetBlockOutputFormat : public IOutputFormat void writeRowGroupInOneThread(Chunk chunk); void writeRowGroupInParallel(std::vector chunks); - void threadFunction(); + void threadFunction(ThreadGroupPtr & thread_group); void startMoreThreadsIfNeeded(const std::unique_lock & lock); + void stopThreads(); /// Called in single-threaded fashion. Writes to the file. void reapCompletedRowGroups(std::unique_lock & lock); @@ -140,13 +144,15 @@ class ParquetBlockOutputFormat : public IOutputFormat size_t base_offset = 0; // initial out.count(), just for assert std::mutex mutex; - std::condition_variable condvar; // wakes up consume() - std::unique_ptr pool; + std::condition_variable condvar; // wakes up consume() and stopThreads() + /// Shared by all Parquet writers of the process (`getParquetEncoderThreadPool`). + ThreadPool * pool = nullptr; std::atomic_bool is_stopped{false}; std::exception_ptr background_exception = nullptr; /// Invariant: if there's at least one task then there's at least one thread. + /// Counts the jobs scheduled on `pool` until they exit, queued ones included. size_t threads_running = 0; std::atomic bytes_in_flight{0}; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 5e9a4bfd7565..119112f9838a 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -56,9 +56,16 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat( format_filter_info = std::make_shared(); } -void ParquetV3BlockInputFormat::initializeIfNeeded() +void ParquetV3BlockInputFormat::prefetch() { - if (!reader) + if (need_only_count) + return; + readFileFooterIfNeeded(); +} + +void ParquetV3BlockInputFormat::readFileFooterIfNeeded() +{ + if (!reader && !reader_with_footer) { format_filter_info->initKeyConditionOnce(getPort().getHeader()); parser_shared_resources->initOnce([&] @@ -87,11 +94,24 @@ void ParquetV3BlockInputFormat::initializeIfNeeded() parser_shared_resources->opaque = ext; }); + auto new_reader = std::make_unique(); + new_reader->reader.prefetcher.init(in, read_options, parser_shared_resources); + new_reader->reader.file_metadata = getFileMetadata(new_reader->reader.prefetcher); + + std::lock_guard lock(reader_mutex); + reader_with_footer = std::move(new_reader); + } +} + +void ParquetV3BlockInputFormat::initializeIfNeeded() +{ + if (!reader) + { + readFileFooterIfNeeded(); + { std::lock_guard lock(reader_mutex); - reader.emplace(); - reader->reader.prefetcher.init(in, read_options, parser_shared_resources); - reader->reader.file_metadata = getFileMetadata(reader->reader.prefetcher); + reader = std::move(reader_with_footer); reader->reader.init(read_options, getPort().getHeader(), format_filter_info); reader->init(parser_shared_resources, buckets_to_read ? std::optional(buckets_to_read->row_group_ids) : std::nullopt); } @@ -169,6 +189,7 @@ void ParquetV3BlockInputFormat::resetReadBuffer() std::lock_guard lock(reader_mutex); if (reader) reader->shutdownTasks(); + reader_with_footer.reset(); } IInputFormat::resetReadBuffer(); } @@ -178,6 +199,7 @@ void ParquetV3BlockInputFormat::resetParser() { std::lock_guard lock(reader_mutex); reader.reset(); + reader_with_footer.reset(); } previous_block_missing_values.clear(); IInputFormat::resetParser(); diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h index a66ea4d97c2e..892771da231f 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h @@ -43,6 +43,8 @@ class ParquetV3BlockInputFormat : public IInputFormat private: Chunk read() override; + void prefetch() override; + void onCancel() noexcept override; const FormatSettings format_settings; @@ -52,17 +54,20 @@ class ParquetV3BlockInputFormat : public IInputFormat ParquetMetadataCachePtr metadata_cache; const std::optional object_with_metadata; - /// (This mutex is not important. It protects `reader.emplace` in a weird case where onCancel() + /// (This mutex is not important. It protects setting `reader` in a weird case where onCancel() /// may be called in parallel with first read(). ReadManager itself is thread safe for that, - /// but initializing vs checking the std::optional would race without this mutex.) + /// but initializing vs checking the pointer would race without this mutex.) std::mutex reader_mutex; - std::optional reader; + std::unique_ptr reader; + /// Has the file footer, but is not initialized: initializing it starts reading and decoding the column chunks. + std::unique_ptr reader_with_footer; bool reported_count = false; // if need_only_count BlockMissingValues previous_block_missing_values; size_t previous_approx_bytes_read_for_chunk = 0; + void readFileFooterIfNeeded(); void initializeIfNeeded(); std::shared_ptr buckets_to_read; diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp index a2c57cf0ed3a..48d880484d33 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include #include #include @@ -10,14 +12,24 @@ namespace DB RawBLOBRowOutputFormat::RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_) + SharedHeader header_, + const FormatSettings & format_settings_) : IRowOutputFormat(header_, out_) + , format_settings(format_settings_) { } -void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization &, size_t row_num) +void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) { + /// `getDataAt` of `ColumnAggregateFunction` returns the bytes of the pointer to the state, not the state itself. + /// Write the serialized state, the same as its conversion to `String`. + if (typeid_cast(&column)) + { + serialization.serializeBinary(column, row_num, out, format_settings); + return; + } + if (!column.isNullAt(row_num)) { auto value = column.getDataAt(row_num); @@ -31,10 +43,10 @@ void registerOutputFormatRawBLOB(FormatFactory & factory) factory.registerOutputFormat("RawBLOB", []( WriteBuffer & buf, const Block & sample, - const FormatSettings &, + const FormatSettings & settings, FormatFilterInfoPtr /*format_filter_info*/) { - return std::make_shared(buf, std::make_shared(sample)); + return std::make_shared(buf, std::make_shared(sample), settings); }); } diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h index e2afa209faaa..9418d3c33028 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h @@ -1,5 +1,6 @@ #pragma once +#include #include @@ -28,12 +29,15 @@ class RawBLOBRowOutputFormat final : public IRowOutputFormat public: RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_); + SharedHeader header_, + const FormatSettings & format_settings_); String getName() const override { return "RawBLOBRowOutputFormat"; } private: - void writeField(const IColumn & column, const ISerialization &, size_t row_num) override; + void writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) override; + + const FormatSettings format_settings; }; } diff --git a/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp b/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp index c7ab86e4056c..328efe3b04ae 100644 --- a/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp +++ b/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp @@ -863,6 +863,10 @@ QueryPlan::Node chooseJoinOrder(QueryGraphBuilder query_graph_builder, QueryPlan QueryGraph query_graph; query_graph.relation_stats = std::move(query_graph_builder.relation_stats); query_graph.edges = std::move(query_graph_builder.join_edges); + BitSet null_supplying_relations; + for (const auto & [relation, restriction] : query_graph_builder.join_kinds) + if (restriction.second != JoinKind::Inner) + null_supplying_relations.set(relation); query_graph.join_kinds = std::move(query_graph_builder.join_kinds); query_graph.pinned = std::move(query_graph_builder.pinned); @@ -1031,11 +1035,13 @@ QueryPlan::Node chooseJoinOrder(QueryGraphBuilder query_graph_builder, QueryPlan /// input pos -> new input node std::unordered_map current_step_type_changes; - for (auto rel_id : {left_rels.getSingleBit(), right_rels.getSingleBit()}) + /// NULL padding applies where the relation is joined alone; other type changes only after all predicates on original columns. + const bool is_last_step = entry_idx + 1 == sequence.size(); + for (const auto & [relation, new_inputs] : query_graph_builder.type_changes) { - if (!rel_id.has_value()) + const bool joined_alone = left_rels.getSingleBit() == relation || right_rels.getSingleBit() == relation; + if (!(null_supplying_relations.test(relation) ? joined_alone : is_last_step)) continue; - const auto & new_inputs = query_graph_builder.type_changes[rel_id.value()]; for (const auto * new_input : new_inputs) { const auto * input_node = trackInputColumn(new_input); diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp index 8fd5aba82710..005d5379243a 100644 --- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp +++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp @@ -49,7 +49,6 @@ #include #include #include -#include #include #include #include @@ -520,9 +519,7 @@ Pipe ReadFromMergeTree::readFromPoolParallelReplicas( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); pipes.emplace_back(std::move(source)); @@ -631,9 +628,7 @@ Pipe ReadFromMergeTree::readFromPool( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); @@ -750,9 +745,7 @@ Pipe ReadFromMergeTree::readInOrder( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); processor->addPartLevelToChunk(isQueryWithFinal()); diff --git a/src/Processors/Transforms/AddingDefaultsTransform.cpp b/src/Processors/Transforms/AddingDefaultsTransform.cpp index 9e0fe0f5c260..9650df7204bb 100644 --- a/src/Processors/Transforms/AddingDefaultsTransform.cpp +++ b/src/Processors/Transforms/AddingDefaultsTransform.cpp @@ -157,7 +157,8 @@ void AddingDefaultsTransform::transform(Chunk & chunk) return; const auto * block_missing_values = input_format.getMissingValues(); - if (!block_missing_values) + /// `BlockMissingValues::empty` is also true when the mask holds no columns at all, where the lookups below would be out of range. + if (!block_missing_values || block_missing_values->empty()) return; const auto & header = getOutputPort().getHeader(); diff --git a/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp new file mode 100644 index 000000000000..89e4391079a6 --- /dev/null +++ b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp @@ -0,0 +1,127 @@ +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, so a chunk holding more +/// than that becomes several record batches, each covering a row range. A range not starting at row 0 has +/// to rebase those offsets against the row before it. Reaching the real limit needs more than 2 GiB of +/// data, so these tests lower it. +/// +/// `CHColumnToArrowColumn` is the Apache Arrow library writer, used by the `Arrow` output format, +/// `ArrowFlight`, `StorageArrowFlight` and Delta Lake writes. + +namespace DB +{ + +namespace +{ + +constexpr size_t NUM_ROWS = 8; +constexpr size_t VALUE_SIZE = 16; + +std::string valueAt(size_t row) +{ + return std::string(VALUE_SIZE, static_cast('a' + row)); +} + +CHColumnToArrowColumn::Settings settingsWithLimit(UInt64 max_record_batch_bytes) +{ + CHColumnToArrowColumn::Settings settings; + settings.output_string_as_string = true; + settings.output_max_record_batch_bytes = max_record_batch_bytes; + return settings; +} + +std::shared_ptr convertToArrow(const DataTypePtr & type, MutableColumnPtr column, UInt64 max_record_batch_bytes) +{ + ColumnsWithTypeAndName header_columns{ColumnWithTypeAndName(type->createColumn(), type, "t")}; + + Columns columns; + columns.emplace_back(std::move(column)); + + std::vector chunks; + chunks.emplace_back(std::move(columns), NUM_ROWS); + + CHColumnToArrowColumn converter(header_columns, "Arrow", settingsWithLimit(max_record_batch_bytes)); + std::shared_ptr arrow_table; + converter.chChunkToArrowTable(arrow_table, chunks, 1); + return arrow_table; +} + +} + +TEST(CHColumnToArrowColumn, StringSplitAcrossRecordBatches) +{ + auto type = std::make_shared(); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(valueAt(row)); + + /// Two values per batch, so most batches start past row 0. + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & array = assert_cast(*chunked.chunk(chunk_i)); + /// Every batch addresses its own values from zero. + ASSERT_EQ(array.value_offset(0), 0); + for (int64_t i = 0; i < array.length(); ++i, ++row) + ASSERT_EQ(array.GetString(i), valueAt(row)); + } + ASSERT_EQ(row, NUM_ROWS); +} + +TEST(CHColumnToArrowColumn, ArraySplitAcrossRecordBatches) +{ + auto type = std::make_shared(std::make_shared()); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(Array{Field(valueAt(row)), Field(valueAt(row))}); + + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & list = assert_cast(*chunked.chunk(chunk_i)); + ASSERT_EQ(list.value_offset(0), 0); + for (int64_t i = 0; i < list.length(); ++i, ++row) + { + /// `value_slice` returns a new array by value: keep it alive while it is inspected. + const auto values_holder = list.value_slice(i); + const auto & values = assert_cast(*values_holder); + ASSERT_EQ(values.length(), 2); + ASSERT_EQ(values.GetString(0), valueAt(row)); + ASSERT_EQ(values.GetString(1), valueAt(row)); + } + } + ASSERT_EQ(row, NUM_ROWS); +} + +} + +#endif diff --git a/src/Server/HTTP/ReadHeaders.cpp b/src/Server/HTTP/ReadHeaders.cpp index 142b47a8d6d2..4a5ef642b68b 100644 --- a/src/Server/HTTP/ReadHeaders.cpp +++ b/src/Server/HTTP/ReadHeaders.cpp @@ -87,7 +87,12 @@ void readHeaders( skipToNextLineOrEOF(in); Poco::trimRightInPlace(value); - headers.add(name, Poco::Net::MessageHeader::decodeWord(value)); + std::string decoded_value = Poco::Net::MessageHeader::decodeWord(value); + /// RFC 2047 decoding can produce bytes that are forbidden in a field value (RFC 9110, section 5.5), + /// e.g. `=0D=0A` would become a line break that splits the header when it is written out again. + if (decoded_value.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Poco::Net::MessageException(fmt::format("Value of field \"{}\" contains CR, LF or NUL", name)); + headers.add(name, decoded_value); ++fields; } } diff --git a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp index f17e4f25ce44..d93ae95ec67b 100644 --- a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp +++ b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp @@ -59,6 +59,7 @@ namespace ErrorCodes extern const int WRONG_PASSWORD; extern const int REQUIRED_PASSWORD; extern const int AUTHENTICATION_FAILED; + extern const int REQUIRED_SECOND_FACTOR; extern const int SET_NON_GRANTED_ROLE; extern const int HTTP_LENGTH_REQUIRED; @@ -76,7 +77,8 @@ Poco::Net::HTTPResponse::HTTPStatus exceptionCodeToHTTPStatus(int exception_code return HTTPResponse::HTTP_UNAUTHORIZED; } if (exception_code == ErrorCodes::UNKNOWN_USER || exception_code == ErrorCodes::WRONG_PASSWORD - || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE) + || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE + || exception_code == ErrorCodes::REQUIRED_SECOND_FACTOR) { return HTTPResponse::HTTP_FORBIDDEN; } diff --git a/src/Server/PostgreSQLHandler.cpp b/src/Server/PostgreSQLHandler.cpp index c8e2fe902361..c49afe8df5cd 100644 --- a/src/Server/PostgreSQLHandler.cpp +++ b/src/Server/PostgreSQLHandler.cpp @@ -678,8 +678,8 @@ void PostgreSQLHandler::cancelRequest() inline std::unique_ptr PostgreSQLHandler::receiveStartupMessage(int payload_size) { /// The declared size is read from the wire before any authentication, and the message is read - /// into memory in full, so it has to be bounded. PostgreSQL uses the same limit. - static constexpr Int32 max_startup_message_size = 10000; + /// into memory in full, so it has to be bounded (`max_unauthenticated_message_size`). + static constexpr Int32 max_startup_message_size = PostgreSQLProtocol::Messaging::max_unauthenticated_message_size; std::unique_ptr message; try diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index 1d7b6d09bf16..92be0d801fac 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2525,8 +2525,10 @@ bool TCPHandler::processData(QueryState & state, bool scalar) if (scalar) { - /// Scalar value - state.query_context->addScalar(temporary_id.table_name, block); + /// Scalar value received from the client over the wire. It must not be trusted as a + /// server-computed scalar-subquery result (see Context::addClientScalar): otherwise a client + /// could name it with a row policy's scalar-subquery hash and forge the policy's result. + state.query_context->addClientScalar(temporary_id.table_name, block); } else if (!state.need_receive_data_for_insert && !state.need_receive_data_for_input) { diff --git a/src/Storages/AlterCommands.cpp b/src/Storages/AlterCommands.cpp index b1661cffc376..c026d44cb772 100644 --- a/src/Storages/AlterCommands.cpp +++ b/src/Storages/AlterCommands.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -1314,6 +1315,33 @@ bool AlterCommands::hasVectorSimilarityIndex(const StorageInMemoryMetadata & met return false; } +NameSet AlterCommands::getAddedIndexNames(const IndicesDescription & existing) const +{ + NameSet present; + for (const auto & index : existing) + present.insert(index.name); + + NameSet added; + for (const AlterCommand & command : *this) + { + if (command.ignore) + continue; + + if (command.type == AlterCommand::ADD_INDEX) + { + /// Otherwise `AlterCommand::apply` either skips it, with `IF NOT EXISTS`, or throws. + if (present.insert(command.index_name).second) + added.insert(command.index_name); + } + else if (command.type == AlterCommand::DROP_INDEX && !command.partition && !command.clear) + { + present.erase(command.index_name); + added.erase(command.index_name); + } + } + return added; +} + void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context) const { if (!prepared) @@ -1371,6 +1399,16 @@ void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context } } + /// Only the declared ones, and only now: the rebuild above resolves them against the schema every + /// command produced, which is what gets stored. Existing indices stay unauthorised on purpose. + const NameSet declared_indices = getAddedIndexNames(metadata.secondary_indices); + + for (const auto & index : metadata_copy.secondary_indices) + { + if (declared_indices.contains(index.name)) + checkTextIndexPreAndPostProcessorPermissions(index, context); + } + /// Changes in columns may lead to changes in projections ProjectionsDescription new_projections; for (const auto & projection : metadata_copy.projections) diff --git a/src/Storages/AlterCommands.h b/src/Storages/AlterCommands.h index 22a9253baa10..82501af8dd29 100644 --- a/src/Storages/AlterCommands.h +++ b/src/Storages/AlterCommands.h @@ -219,6 +219,9 @@ class AlterCommands : public std::vector /// Commands have to be prepared before apply. void apply(StorageInMemoryMetadata & metadata, ContextPtr context) const; + /// Indices the commands actually add: `ADD INDEX IF NOT EXISTS` of an existing name adds nothing. + NameSet getAddedIndexNames(const IndicesDescription & existing) const; + /// At least one command modify settings or comments. bool hasNonReplicatedAlterCommand() const; diff --git a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp index 7b54bd1a72fc..d2b3e89891d2 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp @@ -21,6 +21,7 @@ #include #include +#include #include namespace CurrentMetrics @@ -217,6 +218,11 @@ bool DistributedAsyncInsertBatch::recoverBatch() } files.erase(files.begin(), first_existing_file); + /// The batch is sent with the `ClientInfo` of its first file. Older servers could put files of different + /// users (or originating hosts) into one batch, so a restored batch of mixed identities must not be resent + /// as a whole: it is dropped, and its files are batched again by identity like any other pending files. + std::optional> batch_identity; + /// A missing file inside the surviving suffix cannot be recovered safely. for (const auto & file : files) { @@ -228,13 +234,25 @@ bool DistributedAsyncInsertBatch::recoverBatch() try { - ReadBufferFromFile header_buffer(files.back()); + ReadBufferFromFile header_buffer(file); const DistributedAsyncInsertHeader & header = DistributedAsyncInsertHeader::read(header_buffer, parent.log); if (header.rows) { total_rows += header.rows; total_bytes += header.bytes; } + + auto identity = getRemoteAuthenticationIdentity(header.client_info); + if (!batch_identity) + { + batch_identity = std::move(identity); + } + else if (identity != *batch_identity) + { + LOG_WARNING(parent.log, "File {} has a different user or originating host than the first file of the batch, " + "the files of the batch will be sent in new batches", file); + return false; + } } catch (Exception & e) { diff --git a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp index 172028d48813..c94608ea330d 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp @@ -494,8 +494,11 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader bool operator==(const BatchHeader & other) const { + /// The whole batch is sent with the `ClientInfo` of its first file, so files that the shard would + /// authenticate differently must never be merged into one batch. return std::tie(settings, query, client_info.query_kind) == std::tie(other.settings, other.query, other.client_info.query_kind) && + getRemoteAuthenticationIdentity(client_info) == getRemoteAuthenticationIdentity(other.client_info) && blocksHaveEqualStructure(header, other.header); } @@ -505,6 +508,9 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader { SipHash hash_state; hash_state.update(batch_header.query.data(), batch_header.query.size()); + const auto [initial_user, initial_host] = getRemoteAuthenticationIdentity(batch_header.client_info); + hash_state.update(initial_user.data(), initial_user.size()); + hash_state.update(initial_host.data(), initial_host.size()); batch_header.header.updateHash(hash_state); return hash_state.get64(); } diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp index e14d376583c7..ef6564f896e7 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp @@ -68,6 +68,14 @@ void writeAndConvert(RemoteInserter & remote, const DistributedAsyncInsertHeader } } +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info) +{ + String initial_host; + if (client_info.initial_address) + initial_host = client_info.initial_address->host().toString(); + return {client_info.initial_user, initial_host}; +} + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h index 202d9ff6fff8..3cc335c169f9 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h @@ -1,12 +1,16 @@ #pragma once #include +#include + +#include namespace DB { struct DistributedAsyncInsertHeader; +class ClientInfo; class ReadBufferFromFile; class RemoteInserter; @@ -23,6 +27,11 @@ class RemoteInserter; /// and mark batch as broken. bool isDistributedSendBroken(int code, bool remote_error); +/// The identity the shard authenticates a queued insert as (with the interserver ``): `initial_user` +/// and the host of `initial_address`, which is checked against the allowed hosts of that user. +/// A batch is sent with the `ClientInfo` of its first file, so all files of a batch must have the same identity. +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info); + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedSink.cpp b/src/Storages/Distributed/DistributedSink.cpp index dc3fa7f31036..b0d05d4d5ebb 100644 --- a/src/Storages/Distributed/DistributedSink.cpp +++ b/src/Storages/Distributed/DistributedSink.cpp @@ -864,17 +864,21 @@ void DistributedSink::writeToShard(const Cluster::ShardInfo & shard_info, const writeStringBinary(query_string, header_buf); context->getSettingsRef().write(header_buf); - if (OpenTelemetry::CurrentContext().isTraceEnabled()) { - // if the distributed tracing is enabled, use the trace context in current thread as parent of next span auto client_info = context->getClientInfo(); - client_info.client_trace_context = OpenTelemetry::CurrentContext(); + // if the distributed tracing is enabled, use the trace context in current thread as parent of next span + if (OpenTelemetry::CurrentContext().isTraceEnabled()) + client_info.client_trace_context = OpenTelemetry::CurrentContext(); + /// Background contexts (e.g. the ones of `Kafka` / `RabbitMQ` streaming into views) have + /// `query_kind = NO_QUERY`, for which `ClientInfo::write` stores nothing but the kind. The + /// replayed insert would then reach the shard with an empty `initial_user`, which a shard + /// accepting the interserver `` executes with full access, losing the identity + /// (e.g. the definer of a `SQL SECURITY DEFINER` view) that the query is bound to. + /// `RemoteInserter` sends the insert as a secondary query anyway, so persist it as such. + if (client_info.query_kind == ClientInfo::QueryKind::NO_QUERY) + client_info.query_kind = ClientInfo::QueryKind::SECONDARY_QUERY; client_info.write(header_buf, DBMS_TCP_PROTOCOL_VERSION); } - else - { - context->getClientInfo().write(header_buf, DBMS_TCP_PROTOCOL_VERSION); - } writeVarUInt(block.rows(), header_buf); writeVarUInt(block.bytes(), header_buf); diff --git a/src/Storages/Hive/HiveFile.cpp b/src/Storages/Hive/HiveFile.cpp index 18c9bf27a6f6..f2c467937ddb 100644 --- a/src/Storages/Hive/HiveFile.cpp +++ b/src/Storages/Hive/HiveFile.cpp @@ -8,12 +8,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -33,31 +33,16 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } -#define THROW_ARROW_NOT_OK(status) \ - do \ - { \ - if (const ::arrow::Status & _s = (status); !_s.ok()) \ - throw Exception::createDeprecated(_s.ToString(), ErrorCodes::BAD_ARGUMENTS); \ - } while (false) - - -template -Range createRangeFromOrcStatistics(const StatisticsType * stats) +template +Range createRangeFromOrcStatistics(const std::optional & minimum, const std::optional & maximum) { /// Null values or NaN/Inf values of double type. - if (stats->hasMinimum() && stats->hasMaximum()) - { - return Range(FieldType(stats->getMinimum()), true, FieldType(stats->getMaximum()), true); - } - if (stats->hasMinimum()) - { - return Range::createLeftBounded(FieldType(stats->getMinimum()), true); - } - if (stats->hasMaximum()) - { - return Range::createRightBounded(FieldType(stats->getMaximum()), true); - } - + if (minimum && maximum) + return Range(FieldType(*minimum), true, FieldType(*maximum), true); + if (minimum) + return Range::createLeftBounded(FieldType(*minimum), true); + if (maximum) + return Range::createRightBounded(FieldType(*maximum), true); return Range::createWholeUniverseWithoutNull(); } @@ -116,48 +101,40 @@ void IHiveFile::loadSplitMinMaxIndexes() split_minmax_idxes_loaded = true; } -Range HiveORCFile::buildRange(const orc::ColumnStatistics * col_stats) +Range HiveORCFile::buildRange(const ORC::Proto::ColumnStatistics * col_stats) { - if (!col_stats || col_stats->hasNull()) + /// A missing `has_null` means that the column may contain nulls. + if (!col_stats || col_stats->has_null.value_or(true)) return Range::createWholeUniverseWithoutNull(); - if (const auto * int_stats = dynamic_cast(col_stats)) + if (const auto & int_stats = col_stats->int_statistics) + return createRangeFromOrcStatistics(int_stats->minimum, int_stats->maximum); + if (const auto & double_stats = col_stats->double_statistics) + return createRangeFromOrcStatistics(double_stats->minimum, double_stats->maximum); + if (const auto & string_stats = col_stats->string_statistics) + return createRangeFromOrcStatistics(string_stats->minimum, string_stats->maximum); + if (const auto & bool_stats = col_stats->bucket_statistics) { - return createRangeFromOrcStatistics(int_stats); - } - if (const auto * double_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(double_stats); - } - if (const auto * string_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(string_stats); - } - if (const auto * bool_stats = dynamic_cast(col_stats)) - { - auto false_cnt = bool_stats->getFalseCount(); - auto true_cnt = bool_stats->getTrueCount(); + if (bool_stats->count.empty()) + return Range::createWholeUniverseWithoutNull(); + UInt64 true_cnt = bool_stats->count[0]; + UInt64 false_cnt = col_stats->number_of_values.value_or(0) - true_cnt; if (false_cnt && true_cnt) - { return Range(UInt8(0), true, UInt8(1), true); - } if (false_cnt) - { return Range::createLeftBounded(UInt8(0), true); - } if (true_cnt) - { return Range::createRightBounded(UInt8(1), true); - } - } - else if (const auto * timestamp_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(timestamp_stats); + return Range::createWholeUniverseWithoutNull(); } - else if (const auto * date_stats = dynamic_cast(col_stats)) + if (const auto & timestamp_stats = col_stats->timestamp_statistics) { - return createRangeFromOrcStatistics(date_stats); + /// The deprecated `minimum` and `maximum` are in the local time zone of the writer, which is + /// unknown for the statistics of the whole file, so only the UTC bounds are usable. + return createRangeFromOrcStatistics(timestamp_stats->minimum_utc, timestamp_stats->maximum_utc); } + if (const auto & date_stats = col_stats->date_statistics) + return createRangeFromOrcStatistics(date_stats->minimum, date_stats->maximum); return Range::createWholeUniverseWithoutNull(); } @@ -166,14 +143,12 @@ void HiveORCFile::prepareReader() in = std::make_unique(namenode_url, path, getContext()->getGlobalContext()->getConfigRef(), getContext()->getReadSettings()); auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; - auto result = arrow::adapters::orc::ORCFileReader::Open(asArrowFile(*in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(result.status()); - reader = std::move(result).ValueOrDie(); + reader = createORCReader(asORCInputStream(*in, format_settings, /*use_prefetch=*/false, is_stopped), ORC::ReaderOptions{}); } void HiveORCFile::prepareColumnMapping() { - const orc::Type & type = reader->GetRawORCReader()->getType(); + const ORC::Type & type = reader->getType(); size_t count = type.getSubtypeCount(); for (size_t pos = 0; pos < count; pos++) { @@ -190,7 +165,7 @@ bool HiveORCFile::useFileMinMaxIndex() const } -std::unique_ptr HiveORCFile::buildMinMaxIndex(const orc::Statistics * statistics) +std::unique_ptr HiveORCFile::buildMinMaxIndex(const std::vector * statistics) { if (!statistics) return nullptr; @@ -213,7 +188,7 @@ std::unique_ptr HiveORCFile::buildMinMaxIndex(c { size_t pos = it->second; /// Attention: column statistics start from 1. 0 has special purpose. - const orc::ColumnStatistics * col_stats = statistics->getColumnStatistics(static_cast(pos + 1)); + const ORC::Proto::ColumnStatistics * col_stats = pos + 1 < statistics->size() ? &(*statistics)[pos + 1] : nullptr; idx->hyperrectangle[i] = buildRange(col_stats); } ++i; @@ -230,8 +205,7 @@ void HiveORCFile::loadFileMinMaxIndexImpl() prepareColumnMapping(); } - auto statistics = reader->GetRawORCReader()->getStatistics(); - file_minmax_idx = buildMinMaxIndex(statistics.get()); + file_minmax_idx = buildMinMaxIndex(&reader->getStatistics()); } bool HiveORCFile::useSplitMinMaxIndex() const @@ -248,9 +222,10 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); auto stripe_num = raw_reader->getNumberOfStripes(); - auto stripe_stats_num = raw_reader->getNumberOfStripeStatistics(); + const auto & stripe_statistics = raw_reader->getMetadata().stripe_stats; + auto stripe_stats_num = stripe_statistics.size(); if (stripe_num != stripe_stats_num) throw Exception(ErrorCodes::BAD_ARGUMENTS, "orc file:{} has different strip num {} and strip statistics num {}", path, stripe_num, stripe_stats_num); @@ -258,8 +233,7 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() split_minmax_idxes.resize(stripe_num); for (size_t i = 0; i < stripe_num; ++i) { - auto stripe_stats = raw_reader->getStripeStatistics(i); - split_minmax_idxes[i] = buildMinMaxIndex(stripe_stats.get()); + split_minmax_idxes[i] = buildMinMaxIndex(&stripe_statistics[i].col_stats); } } @@ -271,7 +245,7 @@ std::optional HiveORCFile::getRowsImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); return raw_reader->getNumberOfRows(); } @@ -286,7 +260,8 @@ void HiveParquetFile::prepareReader() auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; auto open_file_res = parquet::arrow::OpenFile(asArrowFile(*in, format_settings, is_stopped, "Parquet", PARQUET_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(open_file_res.status()); + if (!open_file_res.ok()) + throw Exception::createDeprecated(open_file_res.status().ToString(), ErrorCodes::BAD_ARGUMENTS); reader = *std::move(open_file_res); } diff --git a/src/Storages/Hive/HiveFile.h b/src/Storages/Hive/HiveFile.h index 611302693b1d..50d9e0cbc6c2 100644 --- a/src/Storages/Hive/HiveFile.h +++ b/src/Storages/Hive/HiveFile.h @@ -5,9 +5,10 @@ #include #include +#include #include -#include +#include #include #include @@ -217,18 +218,18 @@ class HiveORCFile : public IHiveFile bool useSplitMinMaxIndex() const override; private: - static Range buildRange(const orc::ColumnStatistics * col_stats); + static Range buildRange(const ORC::Proto::ColumnStatistics * col_stats); void loadFileMinMaxIndexImpl() override; void loadSplitMinMaxIndexesImpl() override; - std::unique_ptr buildMinMaxIndex(const orc::Statistics * statistics); + std::unique_ptr buildMinMaxIndex(const std::vector * statistics); void prepareReader(); void prepareColumnMapping(); std::optional getRowsImpl() override; std::unique_ptr in; - std::unique_ptr reader; + std::unique_ptr reader; std::map orc_column_positions; }; diff --git a/src/Storages/Hive/StorageHive.cpp b/src/Storages/Hive/StorageHive.cpp index fccccb7c7fca..15e23429c5ad 100644 --- a/src/Storages/Hive/StorageHive.cpp +++ b/src/Storages/Hive/StorageHive.cpp @@ -608,6 +608,10 @@ HiveFiles StorageHive::collectHiveFilesFromPartition( throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, "Partition value size not match, expect {}, but got {}", partition_names.size(), partition.values.size()); + if (!partition_key_expr) + throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, + "Hive metastore returned a partition for table {}.{}, but the table has no partition key", hive_database, hive_table); + /// Join partition values in CSV format WriteBufferFromOwnString wb; for (size_t i = 0; i < partition.values.size(); ++i) diff --git a/src/Storages/IStorage.h b/src/Storages/IStorage.h index 8c58fa27b6a5..e10d484de8b3 100644 --- a/src/Storages/IStorage.h +++ b/src/Storages/IStorage.h @@ -167,6 +167,9 @@ class IStorage : public std::enable_shared_from_this, public TypePromo virtual bool supportsSubcolumns() const { return false; } /// Returns true if storage supports optimizations of functions by reading subcolumns. virtual bool supportsOptimizationToSubcolumns() const { return supportsSubcolumns(); } + /// Returns true if the storage writes `Map` columns with the bucketed serialization, where a single key + /// can be read without reading the whole column. Gates the `m['key']` -> `m.key_` rewrite. + virtual bool hasBucketedMapSerialization() const { return false; } /// Returns true if the storage supports transactions for SELECT, INSERT and ALTER queries. /// Storage may throw an exception later if some query kind is not fully supported. diff --git a/src/Storages/IndicesDescription.cpp b/src/Storages/IndicesDescription.cpp index 9d716df4428b..6bdb804cd4c6 100644 --- a/src/Storages/IndicesDescription.cpp +++ b/src/Storages/IndicesDescription.cpp @@ -1,12 +1,20 @@ #include #include +#include #include +#include #include +#include +#include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -25,6 +33,122 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } +namespace +{ + +/// Calls `fn` with the value of each `preprocessor` / `postprocessor` argument of a text index. +template +void forEachTransformArgument(const ASTPtr & arguments, F && fn) +{ + for (const auto & child : arguments->children) + { + auto * func = child->as(); + if (!func || func->name != "equals" || !func->arguments || func->arguments->children.size() != 2) + continue; + + const auto * key = func->arguments->children[0]->as(); + if (key && (key->name() == "preprocessor" || key->name() == "postprocessor")) + fn(func->arguments->children[1]); + } +} + +/// Resolving a name runs the function's `create`, where `checkAccess` lives. Names only: building the +/// expression would report its type errors from here, not from the validator. +/// +/// A transform is analysed under the global context, so reading a table or a dictionary during analysis +/// would happen with full access. Such access depends on the arguments, not the function name, so +/// authorizing names cannot cover it, and these constructs are refused. Only here, where a user declares +/// the index: metadata stored by an older version must still load and stay alterable. +void checkFunctionsAsUser(const ASTPtr & ast, const ContextPtr & context) +{ + if (ast->as() || ast->as() || ast->as() || ast->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, "A text index transform expression must not contain subqueries or table references"); + + if (const auto * function = ast->as()) + { + if (functionIsInOrGlobalInOperator(function->name) && function->arguments && function->arguments->children.size() == 2) + { + const auto & set = function->arguments->children[1]; + if (set->as() || set->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not use a table or a set as the right side of `{}`", function->name); + } + + /// Only the name, which for `dictGet` and the like does not touch the dictionary; analysis would. + if (auto resolver = FunctionFactory::instance().tryGet(function->name, context); resolver && !resolver->isDeterministic()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not contain non-deterministic functions. Got `{}`", function->name); + } + + for (const auto & child : ast->children) + checkFunctionsAsUser(child, context); +} + +void checkTransformPermissions(const ASTPtr & arguments, const ContextPtr & context) +{ + forEachTransformArgument(arguments, [&](ASTPtr & argument) + { + auto expression = argument->clone(); + /// Inlines SQL UDF bodies, as `TreeRewriter` does, so a function used only inside one is seen. + if (!UserDefinedSQLFunctionFactory::instance().empty()) + UserDefinedSQLFunctionVisitor::visit(expression, context); + + checkFunctionsAsUser(expression, context); + }); +} + +} + +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context) +{ + if (index.type == TEXT_INDEX_NAME && index.arguments) + checkTransformPermissions(index.arguments, context); +} + +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index) +{ + if (index.type != TEXT_INDEX_NAME || !index.arguments) + return false; + + bool found = false; + forEachTransformArgument(index.arguments, [&](ASTPtr &) { found = true; }); + return found; +} + +[[noreturn]] static void throwTransformNeedsInitiatorUser() +{ + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "A text index preprocessor or postprocessor is authorized on the host the query is submitted to, and the " + "other hosts resolve it against their own schema without that user. Let every host run the query as the " + "initiating user instead: enable the server setting distributed_ddl_use_initial_user_and_roles on every " + "host, and set distributed_ddl_entry_format_version to at least {}", + DDLLogEntry::INITIATOR_USER_VERSION); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration) +{ + if (hasTextIndexPreOrPostProcessor(declaration)) + throwTransformNeedsInitiatorUser(); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index) +{ + if (hasTextIndexPreOrPostProcessor(index)) + throwTransformNeedsInitiatorUser(); +} + +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration) +{ + const auto * type = declaration.getType() ? declaration.getType()->as() : nullptr; + if (!type || Poco::toLower(type->name) != TEXT_INDEX_NAME || !type->arguments) + return false; + + bool found = false; + forEachTransformArgument(type->arguments, [&](ASTPtr &) { found = true; }); + return found; +} + IndexDescription::IndexDescription(const IndexDescription & other) : definition_ast(other.definition_ast ? other.definition_ast->clone() : nullptr) , expression_list_ast(other.expression_list_ast ? other.expression_list_ast->clone() : nullptr) diff --git a/src/Storages/IndicesDescription.h b/src/Storages/IndicesDescription.h index 207e3c76b154..5d1daf8affaa 100644 --- a/src/Storages/IndicesDescription.h +++ b/src/Storages/IndicesDescription.h @@ -16,6 +16,7 @@ namespace DB class ExpressionActions; using ExpressionActionsPtr = std::shared_ptr; +class ASTIndexDeclaration; /// Description of non-primary index for Storage struct IndexDescription @@ -86,6 +87,20 @@ struct IndexDescription bool isSimpleSingleColumnIndex() const; }; +/// Checks that the functions referenced by the text index preprocessor and postprocessor expressions +/// may run with the permissions of `context`, and that they read no table, set or dictionary. Call only +/// where a user declares an index, on the node they submitted it to; elsewhere these resolve under the +/// global context, and stored metadata is not re-checked. +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context); + +/// Refuses a transform when the other hosts of an `ON CLUSTER` query do not run it as the initiator. +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration); +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index); + +/// Whether the declaration is a text index with a `preprocessor` or a `postprocessor` argument. +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration); +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index); + /// All secondary indices in storage struct IndicesDescription : public std::vector, IHints<> { diff --git a/src/Storages/MergeTree/KeyCondition.cpp b/src/Storages/MergeTree/KeyCondition.cpp index 2d6ff22b1111..1fb619b3cdc4 100644 --- a/src/Storages/MergeTree/KeyCondition.cpp +++ b/src/Storages/MergeTree/KeyCondition.cpp @@ -3775,6 +3775,11 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( DataTypePtr current_type, bool single_point) { + /// A bound where `isNull()` holds stands in for NULL or for an infinity, and is left untransformed below, + /// so no transformed value would remain to compare against an atom in the function's result domain. + if (single_point && (key_range.left.isNull() || key_range.right.isNull())) + return {}; + for (const auto & func : functions) { /// We check the monotonicity of each function on a specific range. @@ -3791,17 +3796,21 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( /// If we apply function to open interval, we can get empty intervals in result. /// E.g. for ('2020-01-03', '2020-01-20') after applying 'toYYYYMM' we will get ('202001', '202001'). /// To avoid this we make range left and right included. - /// Any function that treats NULL specially is not monotonic. - /// Thus we can safely use isNull() as an -Inf/+Inf indicator here. + /// A NULL bound is an -inf/+inf stand-in and is left as is. A function that returns NULL for a non-NULL + /// argument leaves a bound with no position in the `Range` order, so the range cannot be analyzed. if (!key_range.left.isNull()) { key_range.left = applyFunction(func, current_type, key_range.left); + if (key_range.left.isNull()) + return {}; key_range.left_included = true; } if (!key_range.right.isNull()) { key_range.right = applyFunction(func, current_type, key_range.right); + if (key_range.right.isNull()) + return {}; key_range.right_included = true; } diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp index 5b0543026617..b0cf4a2bb646 100644 --- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp +++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp @@ -540,8 +540,7 @@ MergeTreeReadTaskColumns getReadTaskColumns( index_read_tasks, actions_settings, reader_settings.enable_multiple_prewhere_read_steps, - reader_settings.force_short_circuit_execution, - &storage_snapshot->metadata->getColumns()); + reader_settings.force_short_circuit_execution); for (const auto & step : prewhere_actions.steps) add_step(*step); diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index fd61defc239a..7c8f71bd5502 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -293,6 +293,7 @@ namespace MergeTreeSetting extern const MergeTreeSettingsMergeTreeStringSerializationVersion string_serialization_version; extern const MergeTreeSettingsMergeTreeNullableSerializationVersion nullable_serialization_version; extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version; + extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version_for_zero_level_parts; extern const MergeTreeSettingsUInt32 min_level_for_wide_part; extern const MergeTreeSettingsBool propagate_types_serialization_versions_to_nested_types; } @@ -894,6 +895,14 @@ bool MergeTreeData::supportsFinal() const || merging_params.mode == MergingParams::VersionedCollapsing; } +bool MergeTreeData::hasBucketedMapSerialization() const +{ + /// Inserted parts use the zero-level setting, merged parts the other one. + auto settings = getSettings(); + return (*settings)[MergeTreeSetting::map_serialization_version] == MergeTreeMapSerializationVersion::WITH_BUCKETS + || (*settings)[MergeTreeSetting::map_serialization_version_for_zero_level_parts] == MergeTreeMapSerializationVersion::WITH_BUCKETS; +} + static void checkKeyExpression(const ExpressionActions & expr, const Block & sample_block, const String & key_name, bool allow_nullable_key) { if (expr.hasArrayJoin()) @@ -10134,7 +10143,7 @@ QueryPipeline MergeTreeData::updateLightweightImpl(const MutationCommands & comm if (it != commands.end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Got unexpected command with type {} in lightweight update", it->type); - LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.toString(false)); + LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.ast(false)->formatForLogging()); MutationCommands commands_to_run; const auto & system_columns = getPatchPartSystemColumns(); @@ -10665,6 +10674,16 @@ StorageSnapshotPtr MergeTreeData::getStorageSnapshot(const StorageMetadataPtr & return cache->emplace(this, createStorageSnapshot(metadata_snapshot, query_context, false)).first->second; } +void MergeTreeData::discardSharedStorageSnapshot(const ContextPtr & query_context) const +{ + auto query_metadata_cache = query_context->getQueryMetadataCache(); + if (!query_metadata_cache) + return; + + auto [cache, lock] = query_metadata_cache->getStorageSnapshotCache(); + cache->erase(this); +} + StorageSnapshotPtr MergeTreeData::getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const { diff --git a/src/Storages/MergeTree/MergeTreeData.h b/src/Storages/MergeTree/MergeTreeData.h index 24c347de459d..c19156cfd60f 100644 --- a/src/Storages/MergeTree/MergeTreeData.h +++ b/src/Storages/MergeTree/MergeTreeData.h @@ -548,6 +548,8 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; + bool supportsTTL() const override { return true; } bool supportsColumnsWithDynamicStructure() const override { return true; } @@ -648,6 +650,11 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr /// The same as above but does not hold vector of data parts. StorageSnapshotPtr getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const override; + /// Removes the snapshot of this table from the query-scoped snapshot cache of + /// `enable_shared_storage_snapshot_in_query`, so that the next `getStorageSnapshot` in the query + /// takes a fresh one. Holders of the removed snapshot keep it. + void discardSharedStorageSnapshot(const ContextPtr & query_context) const; + /// Load the set of data parts from disk. Call once - immediately after the object is created. void loadDataParts(bool skip_sanity_checks, std::optional> expected_parts); diff --git a/src/Storages/MergeTree/MergeTreeDataWriter.cpp b/src/Storages/MergeTree/MergeTreeDataWriter.cpp index 0eda0376f9db..94aa1b21eb17 100644 --- a/src/Storages/MergeTree/MergeTreeDataWriter.cpp +++ b/src/Storages/MergeTree/MergeTreeDataWriter.cpp @@ -514,6 +514,11 @@ Block MergeTreeDataWriter::mergeBlock( span.addAttribute("clickhouse.rows", block_size); span.addAttribute("clickhouse.columns", header->columns()); + /// The block can lose all its rows before this point, e.g. when insert deduplication removes + /// duplicate rows of a materialized view block. Merging algorithms do not expect an empty input. + if (block_size == 0) + return *header; + auto get_merging_algorithm = [&]() -> std::shared_ptr { switch (merging_params.mode) diff --git a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp index 8d0538e64453..1964c89f521f 100644 --- a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace DB @@ -28,6 +29,7 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int CORRUPTED_DATA; extern const int ILLEGAL_COLUMN; extern const int INCORRECT_QUERY; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; @@ -87,9 +89,22 @@ void MergeTreeIndexGranuleBloomFilter::deserializeBinary(ReadBuffer & istr, Merg throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown index version {}.", version); readVarUInt(total_rows, istr); + if (total_rows == 0) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Bloom filter index granule has zero rows"); - static size_t atom_size = 8; - size_t bytes_size = (bits_per_row * total_rows + atom_size - 1) / atom_size; + static constexpr size_t atom_size = 8; + size_t bits_size = 0; + if (common::mulOverflow(bits_per_row, total_rows, bits_size) + || common::addOverflow(bits_size, atom_size - 1, bits_size)) + { + throw Exception( + ErrorCodes::CORRUPTED_DATA, + "Bloom filter index granule size overflows for {} rows and {} bits per row", + total_rows, + bits_per_row); + } + + size_t bytes_size = bits_size / atom_size; size_t read_size = bytes_size; for (auto & filter : bloom_filters) { diff --git a/src/Storages/MergeTree/MergeTreeIndexSet.cpp b/src/Storages/MergeTree/MergeTreeIndexSet.cpp index 91ea8793399b..61443eea6299 100644 --- a/src/Storages/MergeTree/MergeTreeIndexSet.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexSet.cpp @@ -572,6 +572,21 @@ const ActionsDAG::Node & MergeTreeIndexConditionSet::traverseDAG(const ActionsDA { auto bit_wrapper_function = FunctionFactory::instance().get("__bitWrapperFunc", context); result_node = &result_dag.addFunction(bit_wrapper_function, {atom_node_ptr}, {}); + + /// A NULL atom value yields a NULL from `__bitWrapperFunc` rather than a BoolMask. + /// That NULL propagates through `__bitBoolMaskAnd`/`Or` and wrongly prunes a granule + /// the atom does not exclude. Map a NULL mask to `UNKNOWN_FIELD` (can be true or false). + if (isNullableOrLowCardinalityNullable(result_node->result_type)) + { + ColumnWithTypeAndName unknown_field_column_with_type; + unknown_field_column_with_type.name = calculateConstantActionNodeName(UNKNOWN_FIELD); + unknown_field_column_with_type.type = std::make_shared(); + unknown_field_column_with_type.column = unknown_field_column_with_type.type->createColumnConst(1, UNKNOWN_FIELD); + const auto & unknown_node = result_dag.addColumn(unknown_field_column_with_type); + + auto if_null_function = FunctionFactory::instance().get("ifNull", context); + result_node = &result_dag.addFunction(if_null_function, {result_node, &unknown_node}, {}); + } } else { diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp index db7da52fdaf7..a4e9b9a702a5 100644 --- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp +++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp @@ -1596,6 +1596,14 @@ void MergeTreeRangeReader::executePrewhereActionsAndFilterColumns(ReadResult & r /// Columns might be projected out. We need to store them here so that default columns can be evaluated later. Block additional_columns = block; + /// Carry over columns projected out at earlier steps: they may be needed + /// to evaluate defaults of columns missing in the part. + for (const auto & col : result.additional_columns) + { + if (!additional_columns.has(col.name)) + additional_columns.insert(col); + } + if (prewhere_info->actions) { const String dummy_column = addDummyColumnWithRowCount(block, result.num_rows); diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp index 147e7778daad..f20a455b4f2b 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp @@ -132,8 +132,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_, - LazyMaterializingRowsPtr lazy_materializing_rows_, - const ColumnsDescription * columns_) + LazyMaterializingRowsPtr lazy_materializing_rows_) : pool(std::move(pool_)) , algorithm(std::move(algorithm_)) , row_level_filter(row_level_filter_) @@ -145,8 +144,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( index_read_tasks_, actions_settings, reader_settings_.enable_multiple_prewhere_read_steps, - reader_settings_.force_short_circuit_execution, - columns_)) + reader_settings_.force_short_circuit_execution)) , reader_settings(reader_settings_) , result_header(transformHeader(pool->getHeader(), row_level_filter, prewhere_info)) , merge_tree_index_build_context(std::move(merge_tree_index_build_context_)) @@ -174,8 +172,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { PrewhereExprInfo prewhere_actions; @@ -208,7 +205,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( } if (prewhere_info && - (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution, columns))) + (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution))) { PrewhereExprStep prewhere_step { diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.h b/src/Storages/MergeTree/MergeTreeSelectProcessor.h index b044ff67fc1f..5909f164ed45 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.h +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.h @@ -108,8 +108,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_ = {}, - LazyMaterializingRowsPtr lazy_materializing_rows_ = {}, - const ColumnsDescription * columns_ = nullptr); + LazyMaterializingRowsPtr lazy_materializing_rows_ = {}); String getName() const; @@ -138,8 +137,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); void addPartLevelToChunk(bool add_part_level_) { add_part_level = add_part_level_; } diff --git a/src/Storages/MergeTree/MergeTreeSettings.cpp b/src/Storages/MergeTree/MergeTreeSettings.cpp index d6317adfe555..edb023a8c897 100644 --- a/src/Storages/MergeTree/MergeTreeSettings.cpp +++ b/src/Storages/MergeTree/MergeTreeSettings.cpp @@ -1171,7 +1171,7 @@ namespace ErrorCodes in the Keeper, the cache will update as soon as possible, so that we are able to filter the duplicated inserts in the memory. )", 0) \ - DECLARE(UInt64, max_replicated_logs_to_keep, 1000, R"( + DECLARE(NonZeroUInt64, max_replicated_logs_to_keep, 1000, R"( How many records may be in the ClickHouse Keeper log if there is inactive replica. An inactive replica becomes lost when when this number exceed. diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp index 52c20d4ee7d8..abf6b4c90f7e 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp @@ -1,8 +1,5 @@ #include -#include -#include - namespace DB { @@ -22,29 +19,10 @@ namespace struct NodeInfo { NameSet required_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column are placed into one step. - NameSet required_storage_columns; }; -/// Resolves a column name to its storage (physical) name. -/// For subcolumns like `map.key_k0`, returns `map`. -/// For regular columns, returns the name unchanged. -String resolveStorageColumnName(const String & column_name, const ColumnsDescription * columns) -{ - if (columns) - { - if (auto col = columns->tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, column_name)) - return col->getNameInStorage(); - } - return column_name; -} - /// Fills the list of required columns for a node in the DAG. -void fillRequiredColumns( - const ActionsDAG::Node * node, - std::unordered_map & nodes_info, - const ColumnsDescription * columns) +void fillRequiredColumns(const ActionsDAG::Node * node, std::unordered_map & nodes_info) { if (nodes_info.contains(node)) return; @@ -54,16 +32,14 @@ void fillRequiredColumns( if (node->type == ActionsDAG::ActionType::INPUT) { node_info.required_columns.insert(node->result_name); - node_info.required_storage_columns.insert(resolveStorageColumnName(node->result_name, columns)); return; } for (const auto & child : node->children) { - fillRequiredColumns(child, nodes_info, columns); + fillRequiredColumns(child, nodes_info); const auto & child_info = nodes_info[child]; node_info.required_columns.insert(child_info.required_columns.begin(), child_info.required_columns.end()); - node_info.required_storage_columns.insert(child_info.required_storage_columns.begin(), child_info.required_storage_columns.end()); } } @@ -226,8 +202,7 @@ bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { if (!prewhere_info) return true; @@ -243,37 +218,21 @@ bool tryBuildPrewhereSteps( std::unordered_map nodes_info; for (const auto & node : condition_nodes) { - fillRequiredColumns(node, nodes_info, columns); + fillRequiredColumns(node, nodes_info); } /// 3. Sort condition nodes by the number of columns used in them and the overall size of those columns /// TODO: not sorting for now because the conditions are already sorted by Where Optimizer - /// 4. Group adjacent conditions that read from the same set of physical storage columns into a single step. - /// Conditions on subcolumns of the same column (e.g. `map.key_k0` and `map.key_k1`) are placed into one group - /// when they appear next to each other in the condition list. - /// - /// Only adjacent conditions are merged to preserve the user's explicit PREWHERE evaluation order. - /// Non-adjacent conditions on the same storage column are kept in separate steps even though this - /// may cause redundant reads, because the user may have intentionally interleaved a guard predicate - /// (e.g. `PREWHERE tags['safe'] != '' AND value > 0 AND toUInt64(tags['unsafe']) > 0` — the - /// `value > 0` step must filter rows before evaluating the potentially-throwing conversion). - /// - /// For the WHERE-to-PREWHERE path this is not a problem: `MergeTreeWhereOptimizer` already groups - /// conditions by their physical storage columns, so subcolumns of the same column arrive here adjacent. + /// 4. Group conditions with the same set of columns into a single read/compute step std::vector> condition_groups; for (const auto & node : condition_nodes) { const auto & node_info = nodes_info[node]; - if (!condition_groups.empty() - && nodes_info[condition_groups.back().front()].required_storage_columns == node_info.required_storage_columns) - { - condition_groups.back().push_back(node); - } + if (!condition_groups.empty() && nodes_info[condition_groups.back().back()].required_columns == node_info.required_columns) + condition_groups.back().push_back(node); /// Add to the last group else - { - condition_groups.push_back({node}); - } + condition_groups.push_back({node}); /// Start new group } /// 5. Build DAGs for each step diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h index 4d3845a7e048..833e6f506992 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h @@ -13,13 +13,10 @@ namespace DB { -class ColumnsDescription; - bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index dbfc28547453..39df2ecbc8ef 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -338,17 +338,6 @@ void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const RPNBuilderTree cond.columns_size = getColumnsSize(cond.table_columns); - /// Resolve each column to its physical storage name so that subcolumns - /// of the same column (e.g. `map.key_k0`, `map.key_k1`) share one group. - const auto & storage_columns_description = storage_metadata->getColumns(); - for (const auto & col : cond.table_columns) - { - if (auto resolved = storage_columns_description.tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, col)) - cond.table_storage_columns.insert(resolved->getNameInStorage()); - else - cond.table_storage_columns.insert(col); - } - cond.viable = !has_invalid_column /// Condition depend on some column. Constant expressions are not moved. @@ -495,20 +484,17 @@ std::optional MergeTreeWhereOptimizer:: } }; - /// Move condition and all other conditions that depend on the same set of physical storage columns. - /// Grouping by storage columns (rather than the exact column set) keeps subcolumns of the - /// same column (e.g. `map.key_k0` and `map.key_k1`) in one group, so they are moved to - /// PREWHERE together and arrive adjacent for the prewhere-splitting step. + /// Move condition and all other conditions depend on the same set of columns. auto move_condition = [&](Conditions::iterator cond_it) { move_to_prewhere_conditions(cond_it); total_size_of_moved_conditions += cond_it->columns_size; total_number_of_moved_columns += cond_it->table_columns.size(); - /// Move all other viable conditions that depend on the same set of storage columns. + /// Move all other viable conditions that depend on the same set of columns. for (auto jt = where_conditions.begin(); jt != where_conditions.end();) { - if (jt->viable && jt->table_storage_columns == cond_it->table_storage_columns) + if (jt->viable && jt->columns_size == cond_it->columns_size && jt->table_columns == cond_it->table_columns) { move_to_prewhere_conditions(jt++); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h index bf2b97b3640d..b0a8bfdb2173 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h @@ -69,10 +69,6 @@ class MergeTreeWhereOptimizer : private boost::noncopyable UInt64 columns_size = 0; NameSet table_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column - /// (e.g. `map.key_k0` and `map.key_k1`) are grouped and moved to PREWHERE together. - NameSet table_storage_columns; /// Can condition be moved to prewhere? bool viable = false; diff --git a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp index 3f8edc6d4cc1..c94d1390bf19 100644 --- a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp +++ b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp @@ -144,7 +144,7 @@ ReplicatedMergeMutateTaskBase::PrepareResult MutateFromLogEntryTask::prepare() Strings mutation_ids; commands = std::make_shared(storage.queue.getMutationCommands(source_part, new_part_info.mutation, mutation_ids)); LOG_TRACE(log, "Mutating part {} with mutation commands from {} mutations ({}): {}", - entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->toString(true)); + entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->ast(true)->formatForLogging()); /// mutation_ids can be empty here. mutation_ids_for_log = mutation_ids; diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index 3735c427cffc..a2490c3ec29e 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -12,7 +12,7 @@ namespace MergeTreeSetting { extern const MergeTreeSettingsUInt64 finished_mutations_to_keep; extern const MergeTreeSettingsSeconds lock_acquire_timeout_for_background_operations; - extern const MergeTreeSettingsUInt64 max_replicated_logs_to_keep; + extern const MergeTreeSettingsNonZeroUInt64 max_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 min_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 replicated_deduplication_window; extern const MergeTreeSettingsUInt64 replicated_deduplication_window_for_async_inserts; diff --git a/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp new file mode 100644 index 000000000000..007d155521ef --- /dev/null +++ b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include +#include + +#include + +using namespace DB; + +namespace DB::ErrorCodes +{ + extern const int CORRUPTED_DATA; +} + +namespace +{ + +String encodeRowCount(size_t row_count) +{ + WriteBufferFromOwnString out; + writeVarUInt(row_count, out); + return out.str(); +} + +void expectCorruptedRowCount(size_t bits_per_row, size_t row_count) +{ + MergeTreeIndexGranuleBloomFilter granule(bits_per_row, 3, 1); + String encoded = encodeRowCount(row_count); + ReadBufferFromString in(encoded); + + try + { + granule.deserializeBinary(in, 1); + FAIL() << "Expected a corrupted Bloom-filter granule to be rejected"; + } + catch (const Exception & exception) + { + EXPECT_EQ(exception.code(), ErrorCodes::CORRUPTED_DATA); + } +} + +} + +TEST(MergeTreeIndexBloomFilterTest, DeserializesValidGranule) +{ + String encoded = encodeRowCount(1); + encoded.append(sizeof(BloomFilter::UnderType), '\0'); + + MergeTreeIndexGranuleBloomFilter granule(12, 3, 1); + ReadBufferFromString in(encoded); + + EXPECT_NO_THROW(granule.deserializeBinary(in, 1)); + EXPECT_FALSE(granule.empty()); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsZeroRowGranule) +{ + expectCorruptedRowCount(12, 0); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsFilterSizeOverflow) +{ + constexpr size_t bits_per_row = 12; + constexpr size_t overflowing_rows = std::numeric_limits::max() / bits_per_row + 1; + expectCorruptedRowCount(bits_per_row, overflowing_rows); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsRoundedFilterSizeOverflow) +{ + expectCorruptedRowCount(1, std::numeric_limits::max()); +} diff --git a/src/Storages/ObjectStorage/Azure/Configuration.cpp b/src/Storages/ObjectStorage/Azure/Configuration.cpp index 574921743d36..03767ddf2d66 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.cpp +++ b/src/Storages/ObjectStorage/Azure/Configuration.cpp @@ -44,7 +44,6 @@ namespace ErrorCodes { extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; - extern const int LOGICAL_ERROR; } const std::unordered_set required_configuration_keys = { @@ -69,7 +68,7 @@ const std::unordered_set optional_configuration_keys = { void StorageAzureConfiguration::check(ContextPtr context) { - auto url = Poco::URI(connection_params.getConnectionURL()); + auto url = Poco::URI(connection_params.getConnectionURLWithoutQuery()); context->getGlobalContext()->getRemoteHostFilter().checkURL(url); StorageObjectStorageConfiguration::check(context); } @@ -163,9 +162,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url if (pos_container != std::string::npos) { - String container_blob_path = connection_url.substr(pos_container+5); - connection_url = connection_url.substr(0,pos_container+4); - container_name = connection_url.substr(pos_container+4); + size_t host_end = pos_container + suffix.size(); + String container_blob_path = host_end < connection_url.size() ? connection_url.substr(host_end + 1) : ""; + connection_url.resize(host_end); auto pos_blob_path = container_blob_path.find('/'); if (pos_blob_path != std::string::npos) @@ -185,9 +184,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url auto pos_net = connection_url.find(suffix); if (pos_slash == std::string::npos || pos_at == std::string::npos|| pos_dot == std::string::npos || pos_net == std::string::npos - || pos_at-pos_slash-3 <= 0 || pos_dot-pos_at-1 <= 0) + || pos_at <= pos_slash + 3 || pos_dot <= pos_at + 1) { - throw Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect url format for a abfss url {}", connection_url); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Incorrect url format for a abfss url {}", connection_url); } auto container_name_abfss = connection_url.substr(pos_slash+3, pos_at-pos_slash-3); auto name = connection_url.substr(pos_at+1, pos_dot-pos_at-1); diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 3a346c1d28f2..08aa8818f4a3 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -106,7 +106,7 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration void setPaths(const Paths & paths) override { blobs_paths = paths; } String getNamespace() const override { return connection_params.getContainer(); } - String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURL()) / connection_params.getContainer(); } + String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURLWithoutQuery()) / connection_params.getContainer(); } StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; void check(ContextPtr context) override; diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp index e7b956fd20c6..28c9ba764fd3 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp @@ -51,6 +51,7 @@ try } metadata = manifest_file_reader->metadata(); + bytes_read = buffer->count(); parsed_column = std::move(columns[0]); parsed_column_data_type = std::dynamic_pointer_cast(data_type); parsed_manifest_file_entries.resize(parsed_column->size()); diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h index 2cf4c8a61d61..997c587f1880 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h @@ -45,6 +45,8 @@ class AvroForIcebergDeserializer std::map> metadata; + size_t bytes_read = 0; + /// Shared mutex to protect mutable cache members for thread safety mutable SharedMutex cache_mutex; @@ -71,6 +73,9 @@ class AvroForIcebergDeserializer size_t rows() const; + /// The constructor consumes the whole file, so this is its size on storage. + size_t bytesRead() const { return bytes_read; } + /// Allow to access avro paths like "a.b.c" bool hasPath(const std::string & path) const; DB::TypeIndex getTypeForPath(const std::string & path) const; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp index 3e9dd4058b3f..cac54224ac17 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp @@ -90,6 +90,30 @@ Field parseFieldFromString(const String & value, DB::DataTypePtr data_type) namespace DeltaLake { +namespace +{ + +/// A data file with the size its `add` action records. +struct DataObjectInfo : public DB::ObjectInfo +{ + DataObjectInfo(std::string path_, int64_t size_) + : DB::ObjectInfo(DB::RelativePathWithMetadata(std::move(path_))) + , size(size_) + { + } + + std::optional getFileSizeHint() const override + { + if (size > 0) + return static_cast(size); + return std::nullopt; + } + + const int64_t size; +}; + +} + class TableSnapshot::Iterator final : public DB::IObjectIterator { private: @@ -120,7 +144,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator const TableSchema & table_schema_, const DB::NameToNameMap & physical_names_map_, const DB::Names & partition_columns_, - DB::ObjectStoragePtr object_storage_, const DB::ActionsDAG * filter_, DB::IDataLakeMetadata::FileProgressCallback callback_, size_t list_batch_size_, @@ -135,7 +158,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator , read_schema(read_schema_) , expression_schema(table_schema_) , partition_columns(partition_columns_) - , object_storage(object_storage_) , callback(callback_) , list_batch_size(list_batch_size_) , log(log_) @@ -437,13 +459,9 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator } parseDVHandle(*scan_item, object); - object->setObjectMetadata(object_storage->getObjectMetadata(object->getPath(), /*with_tags=*/ false)); if (callback) - { - chassert(object->getObjectMetadata()); - callback(DB::FileProgress(0, object->getObjectMetadata()->size_bytes)); - } + callback(DB::FileProgress(0, object->getFileSizeHint().value_or(0))); return object; } } @@ -597,7 +615,7 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator std::string full_path = DB::resolvePathInsideTable( context->getDataPath(), DB::unescapeForFileName(KernelUtils::fromDeltaString(path))); - auto object = std::make_shared(DB::RelativePathWithMetadata(std::move(full_path))); + auto object = std::make_shared(std::move(full_path), size); object->data_lake_metadata.emplace(); LOG_TEST( @@ -641,7 +659,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator DB::NamesAndTypesList read_schema; DB::NamesAndTypesList expression_schema; DB::Names partition_columns; - const DB::ObjectStoragePtr object_storage; const DB::IDataLakeMetadata::FileProgressCallback callback; const size_t list_batch_size; const LoggerPtr log; @@ -966,7 +983,6 @@ DB::ObjectIterator TableSnapshot::iterate( schema->table_schema, schema->physical_names_map, schema->partition_columns, - object_storage, filter_dag, callback, list_batch_size, diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp index 94c263c0e7e7..dc22ef8c5954 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp @@ -45,18 +45,13 @@ UInt64 getCurrentTime() return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } -void exportTable( - std::shared_ptr table, +void exportRecordBatch( + const arrow::RecordBatch & batch, ffi::FFI_ArrowArray & array, ffi::FFI_ArrowSchema & schema) { - auto batch = table->CombineChunksToBatch(); - if (!batch.ok()) - throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, - "Failed to create chunks batch: {}", batch.status().ToString()); - arrow::Status status = arrow::ExportRecordBatch( - **batch, + batch, reinterpret_cast(&array), reinterpret_cast(&schema)); @@ -230,30 +225,61 @@ void WriteTransaction::commit(const std::vector & files) LOG_TEST(log, "Will commit {} files", files.size()); auto write_metadata = getWriteMetadata(files, log); - ffi::FFI_ArrowArray array; - ffi::FFI_ArrowSchema schema; - SCOPE_EXIT({ - if (schema.release) - schema.release(&schema); - }); - exportTable(write_metadata, array, schema); - - KernelEngineData engine_data; - try + /// Metadata too large for one Arrow record batch comes back as several table chunks. Recombining them + /// would hit the same 32-bit offset limit, so each record batch is added to the transaction on its own. + /// `TableBatchReader` yields nothing for an empty table, which still has to reach the kernel as before. + arrow::RecordBatchVector batches; + if (write_metadata->num_rows() == 0) { - /// Takes ownership of `array` (but not`schema`) if successfully called. - engine_data = DeltaLake::KernelUtils::unwrapResult( - ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), - "get_engine_data"); + auto empty_batch = arrow::RecordBatch::MakeEmpty(write_metadata->schema()); + if (!empty_batch.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to create an empty record batch: {}", empty_batch.status().ToString()); + batches.push_back(*std::move(empty_batch)); } - catch (...) + else { - if (array.release) - array.release(&array); - throw; + arrow::TableBatchReader batch_reader(*write_metadata); + while (true) + { + std::shared_ptr batch; + arrow::Status read_status = batch_reader.ReadNext(&batch); + if (!read_status.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to read a record batch: {}", read_status.ToString()); + if (!batch) + break; + batches.push_back(std::move(batch)); + } } - ffi::add_files(transaction.get(), engine_data.release()); + for (const auto & batch : batches) + { + ffi::FFI_ArrowArray array{}; + ffi::FFI_ArrowSchema schema{}; + SCOPE_EXIT({ + if (schema.release) + schema.release(&schema); + }); + exportRecordBatch(*batch, array, schema); + + KernelEngineData engine_data; + try + { + /// Takes ownership of `array` (but not`schema`) if successfully called. + engine_data = DeltaLake::KernelUtils::unwrapResult( + ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), + "get_engine_data"); + } + catch (...) + { + if (array.release) + array.release(&array); + throw; + } + + ffi::add_files(transaction.get(), engine_data.release()); + } auto version = DeltaLake::KernelUtils::unwrapResult(ffi::commit(transaction.release(), engine.get()), "commit"); LOG_TEST(log, "Commit version: {}", version); diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp index 201f2ca83f09..820fc10e2426 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp @@ -599,10 +599,17 @@ ReadFromFormatInfo DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat( info.format_header.insert(ColumnWithTypeAndName{result_name_and_type.type, result_name_and_type.name}); } - for (const auto & name_and_type : info.columns_description) - info.columns_description.rename( - name_and_type.name, - DeltaLake::getPhysicalName(name_and_type.name, physical_names_map)); + /// Build a new description rather than rename in place: the physical name of a column may be the logical name of + /// another column that is not renamed yet (`k` renamed to `k_old` under column mapping keeps the physical name `k`), + /// and `ColumnsDescription::rename` to an existing name erases the column, under the iteration over the description. + ColumnsDescription physical_columns_description; + for (const auto & column : info.columns_description) + { + ColumnDescription physical_column = column; + physical_column.name = DeltaLake::getPhysicalName(column.name, physical_names_map); + physical_columns_description.add(std::move(physical_column)); + } + info.columns_description = std::move(physical_columns_description); LOG_TEST(log, "Format header: {}", info.format_header.dumpStructure()); LOG_TEST(log, "Source header: {}", info.source_header.dumpStructure()); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp index c0072e3e576b..74fcc2accefb 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp @@ -182,8 +182,7 @@ std::optional SingleThreadIcebergKeysIterator::ne persistent_components, local_context, log, - mle.manifest_file_path, - mle.manifest_file_byte_size); + mle.manifest_file_path); current_manifest_file_iterator = Iceberg::ManifestFileIterator::create( manifest_file_cacheable_part.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h index 44309f94e60a..63479720f676 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h @@ -74,7 +74,7 @@ struct IcebergMetadataFilesCacheCell : private boost::noncopyable /// - manifest list consists of cache keys which will retrieve the manifest file from cache [file_path --> ManifestFileCacheKeys] /// - manifest file [file_path --> Iceberg::ManifestFileCacheableInfo] std::variant cached_element; - Int64 memory_bytes; + size_t memory_bytes; explicit IcebergMetadataFilesCacheCell(String && metadata_json_str) : cached_element(std::move(metadata_json_str)) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp index e8226dadcd76..fd279ca1936a 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp @@ -74,6 +74,9 @@ void MultipleFileWriter::finalize() output_format->finalize(); buffer->finalize(); total_bytes += buffer->count(); + + /// A finished format can still hold resources: a Parquet one keeps its idle encoder threads. + release(); } void MultipleFileWriter::release() diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp index 5039abab707a..859b46f2b219 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp @@ -259,6 +259,8 @@ static std::optional writeDataFiles( delete_data_writers[partition_key]->finalize(); delete_data_write_buffers[partition_key]->finalize(); delete_data_result[partition_key].total_bytes = static_cast(delete_data_write_buffers[partition_key]->count()); + delete_data_writers[partition_key].reset(); + delete_data_write_buffers[partition_key].reset(); } } @@ -317,6 +319,8 @@ static std::optional writeDataFiles( update_data_writers[partition_key]->finalize(); update_data_write_buffers[partition_key]->finalize(); update_data_result[partition_key].total_bytes = static_cast(update_data_write_buffers[partition_key]->count()); + update_data_writers[partition_key].reset(); + update_data_write_buffers[partition_key].reset(); } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp index b65109e9f697..d342906b3302 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp @@ -69,8 +69,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size) + const String & filename) { auto log_level = local_context->getSettingsRef()[Setting::iceberg_metadata_log_level].value; @@ -90,7 +89,8 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( auto manifest_file_deserializer = std::make_unique( std::move(buffer), filename, getFormatSettings(local_context)); - return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), bytes_size}; + const size_t manifest_file_bytes = manifest_file_deserializer->bytesRead(); + return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), manifest_file_bytes}; }; if (use_iceberg_metadata_cache && persistent_table_components.table_uuid.has_value()) @@ -115,8 +115,7 @@ Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesH persistent_table_components, local_context, log, - cache_key.manifest_file_path, - static_cast(cache_key.manifest_file_byte_size)); + cache_key.manifest_file_path); auto iterator = Iceberg::ManifestFileIterator::create( cacheable_info.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h index ac5a7f7bc06e..5df057a2bb49 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h @@ -28,8 +28,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size); + const String & filename); /// Creates a fully initialized ManifestFileIterator from a cache key. /// All entries are drained so that aggregate methods (e.g. getRowsCountInAllFilesExcludingDeleted) diff --git a/src/Storages/ObjectStorage/IObjectIterator.h b/src/Storages/ObjectStorage/IObjectIterator.h index 83c645e915fd..1b191139ce67 100644 --- a/src/Storages/ObjectStorage/IObjectIterator.h +++ b/src/Storages/ObjectStorage/IObjectIterator.h @@ -41,6 +41,7 @@ struct ObjectInfo virtual size_t fileSizeInArchive() const { throw Exception(ErrorCodes::LOGICAL_ERROR, "Not an archive"); } virtual std::string getPathOrPathToArchiveIfArchive() const; virtual std::optional getFileFormat() const { return std::nullopt; } + virtual std::optional getFileSizeHint() const { return std::nullopt; } std::optional getObjectMetadata() const { return relative_path_with_metadata.metadata; } void setObjectMetadata(const ObjectMetadata & metadata) { relative_path_with_metadata.metadata = metadata; } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp index 2acdbf6da675..1d4de8b623cd 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp @@ -95,6 +95,15 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + String getObjectStorageHash(const IObjectStorage & object_storage) + { + const String description = object_storage.getDescription(); + return sipHash128String(description.substr(0, description.find('?')) + '\0' + object_storage.getObjectsNamespace()); + } +} + StorageObjectStorageSource::StorageObjectStorageSource( String name_, ObjectStoragePtr object_storage_, @@ -536,7 +545,7 @@ void StorageObjectStorageSource::addNumRowsToCache(const ObjectInfo & object_inf schema_cache.addNumRows(cache_key, num_rows); } -StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader() +StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader(bool prefetch_input_format) { return createReader( 0, @@ -551,7 +560,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade max_block_size, parser_shared_resources, format_filter_info, - need_only_count); + need_only_count, + prefetch_input_format); } StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader( @@ -567,7 +577,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count) + bool need_only_count, + bool prefetch_input_format) { ObjectInfoPtr object_info; auto query_settings = configuration->getQuerySettings(context_); @@ -832,6 +843,9 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade if (need_only_count) input_format->needOnlyCount(); + if (prefetch_input_format) + input_format->prefetch(); + builder.init(Pipe(input_format)); configuration->addDeleteTransformers(object_info, builder, format_settings, parser_shared_resources, context_); @@ -977,7 +991,7 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade std::future StorageObjectStorageSource::createReaderAsync() { - return create_reader_scheduler([=, this] { return createReader(); }, Priority{}); + return create_reader_scheduler([=, this] { return createReader(/* prefetch_input_format */ true); }, Priority{}); } std::unique_ptr createReadBuffer( @@ -1099,6 +1113,7 @@ std::unique_ptr createReadBuffer( else { SipHash hash; + hash.update(getObjectStorageHash(*object_storage)); hash.update(object_info.getPath()); hash.update(object_info.metadata->etag); @@ -1147,7 +1162,9 @@ std::unique_ptr createReadBuffer( if (use_page_cache) { - PageCacheKey key = {.path = "s3:" + object_info.getPath(), .file_version = "etag:" + object_info.metadata->etag}; + PageCacheKey key = { + .path = fmt::format("s3:{}:{}", getObjectStorageHash(*object_storage), object_info.getPath()), + .file_version = "etag:" + object_info.metadata->etag}; impl = std::make_unique(key, effective_read_settings.page_cache, std::move(impl), modified_read_settings); } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.h b/src/Storages/ObjectStorage/StorageObjectStorageSource.h index 5cbe931a047e..375187276c51 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.h @@ -136,9 +136,10 @@ class StorageObjectStorageSource : public ISource size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count); + bool need_only_count, + bool prefetch_input_format = false); - ReaderHolder createReader(); + ReaderHolder createReader(bool prefetch_input_format = false); std::future createReaderAsync(); diff --git a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h index e9d9bd0f7414..a338ae7dead0 100644 --- a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h +++ b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h @@ -1,7 +1,7 @@ #pragma once #include #include -#include +#include #include namespace AzureQueue @@ -20,10 +20,7 @@ static inline std::unordered_map SETTINGS_TO_HIDE = std::string masked_value; if (!value.tryGet(masked_value)) return {}; - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - RE2::Replace(&masked_value, account_key_pattern, "AccountKey=[HIDDEN]\\1"); - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - RE2::Replace(&masked_value, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1"); + DB::maskAzureConnectionStringSecrets(masked_value); return fmt::format("'{}'", masked_value); }}, }; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp new file mode 100644 index 000000000000..e845fa34a6c0 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -0,0 +1,119 @@ +#include + +#include "config.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include + + +namespace DB +{ + +namespace +{ + +enum class MoveDestinationKind : uint8_t +{ + S3, + Azure, +}; + +std::optional getMoveDestinationKind(std::string_view name) +{ + /// The prefix is accepted for every queue setting, see `normalizeSetting` in `StorageObjectStorageQueue.cpp`. + static constexpr std::string_view legacy_prefix = "s3queue_"; + if (name.starts_with(legacy_prefix)) + name.remove_prefix(legacy_prefix.size()); + + if (name == "after_processing_move_uri") + return MoveDestinationKind::S3; + if (name == "after_processing_move_connection_string" || name == "after_processing_move_container") + return MoveDestinationKind::Azure; + return std::nullopt; +} + +AccessTypeObjects::Source getAccessSource(MoveDestinationKind kind) +{ + switch (kind) + { + case MoveDestinationKind::S3: + return AccessTypeObjects::Source::S3; + case MoveDestinationKind::Azure: + return AccessTypeObjects::Source::AZURE; + } +} + +/// A value that is not a `String` is never empty here: it is checked like a destination that cannot be parsed. +bool isEmptyValue(const Field & value) +{ + return value.getType() == Field::Types::String && value.safeGet().empty(); +} + +/// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +{ + const bool sets_destination = std::ranges::any_of( + changes, + [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); + if (!sets_destination) + return {}; + + /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only + /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against + /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). + const auto source = getAccessSource(table_kind); + AccessRightsElements res; + res.emplace_back(AccessType::WRITE, AccessTypeObjects::toStringSource(source)); + return res; +} + +} + +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::S3); +} + +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); +} + +void checkObjectStorageQueueS3MoveDestinationHost( + [[maybe_unused]] const String & move_uri, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AWS_S3 + if (!move_uri.empty()) + S3::URI(move_uri).checkRemoteHostFilter(filter); +#endif +} + +void checkObjectStorageQueueAzureMoveDestinationHost( + [[maybe_unused]] const String & move_connection_string, + [[maybe_unused]] const String & move_container, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AZURE_BLOB_STORAGE + if (!move_connection_string.empty()) + { + AzureBlobStorage::ConnectionParams connection_params; + AzureBlobStorage::processURL(move_connection_string, move_container, connection_params.endpoint, connection_params.auth_method); + /// Without the query: a connection string can carry a SAS, which the message of `checkURL` must not show. + String url = connection_params.getConnectionURL(); + url = url.substr(0, url.find_first_of("?#")); + filter.checkURL(Poco::URI(url)); + } +#endif +} + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h new file mode 100644 index 000000000000..40601b4b1145 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +namespace DB +{ + +class RemoteHostFilter; + +/// The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +/// `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads every processed file +/// with its own source credentials and writes it to the destination. So setting the destination needs +/// `WRITE` on the `S3` (or `AZURE`) source without a URL filter: the move writes keys built from +/// `after_processing_move_prefix` and the source keys, not from the URI, so a filtered grant cannot authorize them. +/// For `ALTER` it also needs `SELECT` on the table, because the creator of the table, not the user of the `ALTER`, +/// supplied the source and its credentials. + +/// The `StorageFactory::GetExportAccessFn` of `S3Queue` and `AzureQueue`: unfiltered `WRITE` if a setting moves files outside +/// the source bucket or container. Only these settings choose such a destination: `after_processing_move_uri` for S3, +/// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy +/// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. +/// An empty value disables the move destination, so it is not a destination and needs no grant. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); + +/// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. +/// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. +/// Does nothing when `move_uri` is empty. +void checkObjectStorageQueueS3MoveDestinationHost(const String & move_uri, const RemoteHostFilter & filter); + +/// The same for a move to another Azure container (see `StorageAzureConfiguration::check`). +/// Does nothing when `move_connection_string` is empty. +void checkObjectStorageQueueAzureMoveDestinationHost( + const String & move_connection_string, const String & move_container, const RemoteHostFilter & filter); + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp index cd48a45926ea..a89c5ec4923a 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,11 @@ namespace S3AuthSetting extern const S3AuthSettingsString secret_access_key; } +namespace S3RequestSetting +{ + extern const S3RequestSettingsBool allow_native_copy; +} + #endif namespace ErrorCodes @@ -285,6 +291,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move S3 objects"); } + /// The settings are checked at `CREATE` and `ALTER` too. This is defense in depth for a table that was created before + /// those checks existed, or before the list of allowed hosts was tightened. If it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueS3MoveDestinationHost(move_uri, getContext()->getRemoteHostFilter()); + if (auto * s3_storage = dynamic_cast(object_storage.get()); s3_storage != nullptr) { auto src_client = s3_storage->getS3StorageClient(); @@ -304,6 +314,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object /* for_disk_s3 */ false ); auto dst_uri = S3::URI(move_uri); + /// Native copy sends `CopyObject` through the source client, so it writes to the source endpoint. That is the checked + /// destination only if both clients use the same endpoint, otherwise use the buffered copy, which uploads with `dst_client`. + if (src_client->getInitialEndpoint() != dst_client->getInitialEndpoint()) + s3_settings->request_settings[S3RequestSetting::allow_native_copy] = false; auto read_settings = getReadSettings(); const auto read_settings_to_use = s3_storage->patchSettings(read_settings); auto scheduler = threadPoolCallbackRunnerUnsafe( @@ -391,6 +405,9 @@ void ObjectStorageQueuePostProcessor::moveAzureBlobs(const StoredObjects & objec throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move Azure blobs"); } + /// See the comment in `moveS3Objects`: if it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, getContext()->getRemoteHostFilter()); + if (auto * azure_storage = dynamic_cast(object_storage.get()); azure_storage != nullptr) { auto contextPtr = getContext(); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp index 643418d037d7..45987c8046d3 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp @@ -5,7 +5,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -58,14 +60,14 @@ namespace ErrorCodes DECLARE(String, partition_component, "", "Name of the capture group from partition_regex to use as partition key. Required when using partitioning_mode='regex'. Example: 'hostname'", 0) \ DECLARE(ObjectStorageQueueBucketingMode, bucketing_mode, ObjectStorageQueueBucketingMode::PATH, "Bucketing strategy for Ordered mode parallel processing: PATH (hash full file path, default), PARTITION (hash partition key, requires partitioning_mode != NONE)", 0) \ DECLARE(UInt32, after_processing_retries, 10, "Number of retries for the after_processing action before giving up", 0) \ - DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to", 0) \ + DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to. Setting it requires the `WRITE` grant on the `S3` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The URL must be allowed by `remote_url_allow_hosts`", 0) \ DECLARE(String, after_processing_move_prefix, "", "Path prefix to move processed files to", 0) \ DECLARE(String, after_processing_tag_key, "", "Tag key to tag processed files in the storage", 0) \ DECLARE(String, after_processing_tag_value, "", "Tag value to tag processed files in the storage", 0) \ DECLARE(String, after_processing_move_access_key_id, "", "S3 Access Key ID accompanying after_processing_move_uri", 0) \ DECLARE(String, after_processing_move_secret_access_key, "", "S3 Secret Access Key accompanying after_processing_move_uri", 0) \ - DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to", 0) \ - DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string", 0) \ + DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The endpoint must be allowed by `remote_url_allow_hosts`", 0) \ + DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table", 0) \ DECLARE(Bool, use_hive_partitioning, false, "DEPRECATED: Use partitioning_mode='hive' instead. Whether path contains hive partitioning and this engine should process such files with a separate processed files tracking per partition.", 0) \ #define LIST_OF_OBJECT_STORAGE_QUEUE_SETTINGS(M, ALIAS) \ @@ -107,7 +109,8 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const + const StorageObjectStorageQueue & storage, + bool display_secrets) const { MutableColumns & res_columns = params.res_columns; auto settings_changes_ast = storage.getInMemoryMetadataPtr()->settings_changes; @@ -127,6 +130,23 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( { return StorageObjectStorageQueue::isSettingChangeable(setting_name, (*this)[ObjectStorageQueueSetting::mode]); }; + /// Hides what `SHOW CREATE TABLE` hides. A secret is hidden whole, as its masker renders SQL. + auto render_value = [&](const std::string & setting_name, const Field & value) -> String + { + static constexpr std::string_view hidden_secret = "[HIDDEN]"; + if (!display_secrets) + { + for (const auto * settings_to_hide : {&S3Queue::SETTINGS_TO_HIDE, &AzureQueue::SETTINGS_TO_HIDE}) + { + auto it = settings_to_hide->find(setting_name); + if (it == settings_to_hide->end()) + continue; + if (auto masked = it->second(value); masked && masked->contains(hidden_secret)) + return String(hidden_secret); + } + } + return convertFieldToString(value); + }; for (const auto & change : impl->all()) { @@ -135,7 +155,7 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( res_columns[i++]->insert(database_name); res_columns[i++]->insert(table_name); res_columns[i++]->insert(name); - res_columns[i++]->insert(convertFieldToString(change.getValue())); + res_columns[i++]->insert(render_value(name, change.getValue())); res_columns[i++]->insert(change.getTypeName()); res_columns[i++]->insert(is_changed(name)); res_columns[i++]->insert(change.getDescription()); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h index dad7144540bc..37c784da6d07 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h @@ -61,7 +61,8 @@ struct ObjectStorageQueueSettings MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const; + const StorageObjectStorageQueue & storage, + bool display_secrets) const; void loadFromQuery(ASTStorage & storage_def, bool is_attach, const StorageID & storage_id); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 10e4f39ec00e..718da1abc8cf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include @@ -22,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -140,9 +144,26 @@ namespace ErrorCodes namespace { + /// The move uses only the destination of the storage type of the table, so only that one is checked. + void checkMoveDestinationHost( + ObjectStorageType type, + const String & move_uri, + const String & move_connection_string, + const String & move_container, + const RemoteHostFilter & filter) + { + if (type == ObjectStorageType::S3) + checkObjectStorageQueueS3MoveDestinationHost(move_uri, filter); + else if (type == ObjectStorageType::Azure) + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, filter); + } + void validateSettings( ObjectStorageQueueSettings & queue_settings, - bool is_attach) + ObjectStorageType type, + const RemoteHostFilter & remote_host_filter, + bool is_attach, + bool is_loading_from_existing_metadata) { if (!is_attach && !queue_settings[ObjectStorageQueueSetting::mode].changed) { @@ -201,6 +222,21 @@ namespace "Move of processed objects requires specifying target bucket/container or prefix"); } } + + /// The host filter of `configuration` covers the source only, so the move destination is checked here. + /// It is checked whenever it is set, not only for `after_processing = 'move'`: otherwise a table created with + /// `after_processing = 'keep'` and a destination that is not allowed could be switched to `move` by an `ALTER` + /// that does not change the destination. A table loaded from existing metadata must never fail to load. + if (!is_loading_from_existing_metadata) + { + checkMoveDestinationHost( + type, + queue_settings[ObjectStorageQueueSetting::after_processing_move_uri].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_connection_string].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_container].value, + remote_host_filter); + } + if (queue_settings[ObjectStorageQueueSetting::after_processing] == ObjectStorageQueueAction::TAG) { if (queue_settings[ObjectStorageQueueSetting::after_processing_tag_key].toString().empty()) @@ -307,7 +343,7 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( } const bool is_attach = mode > LoadingStrictnessLevel::CREATE; - validateSettings(*queue_settings_, is_attach); + validateSettings(*queue_settings_, type, context_->getRemoteHostFilter(), is_attach, isLoadingFromExistingMetadata(mode)); object_storage = configuration->createObjectStorage(context_, /* is_readonly */true, std::nullopt); FormatFactory::instance().checkFormatName(configuration->format); @@ -413,12 +449,18 @@ void StorageObjectStorageQueue::startup() /// Create metadata in keeper if it does not exits yet. /// Create a persistent node for the table under /registry node. bool created_new_metadata = false; - files_metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( + /// Keep a local handle: the factory call and the startup below do keeper I/O, which must not + /// run under `mutex`. + auto metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( zookeeper_name, zk_path, std::move(temp_metadata), getStorageID(), created_new_metadata); + { + std::lock_guard lock(mutex); + files_metadata = metadata; + } /// Register the metadata in startup(), unregister in shutdown. /// (If startup is never called, shutdown also won't be called.) @@ -435,6 +477,7 @@ void StorageObjectStorageQueue::startup() /* is_drop */created_new_metadata, /* keep_data_in_keeper */false); + std::lock_guard lock(mutex); files_metadata.reset(); } }); @@ -453,7 +496,7 @@ void StorageObjectStorageQueue::startup() }); /// Start background tasks. - files_metadata->startup(); + metadata->startup(); for (auto & task : streaming_tasks) task->activateAndSchedule(); @@ -496,11 +539,19 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) tryLogCurrentException(log); } - if (files_metadata) + /// Drop the handle before the keeper cleanup below, so a concurrent reader sees the + /// shut-down state. The local copy keeps the metadata alive for that cleanup. + std::shared_ptr metadata; + { + std::lock_guard lock(mutex); + metadata = std::move(files_metadata); + } + + if (metadata) { try { - files_metadata->unregisterActive(getStorageID()); + metadata->unregisterActive(getStorageID()); } catch (...) { @@ -508,8 +559,6 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) } ObjectStorageQueueMetadataFactory::instance().remove(zookeeper_name, zk_path, getStorageID(), is_drop, keep_data_in_keeper); - - files_metadata.reset(); } LOG_TRACE(log, "Shut down storage"); } @@ -1316,6 +1365,35 @@ void StorageObjectStorageQueue::checkAlterIsPossible(const AlterCommands & comma } } } + + /// The host filter of `configuration` covers the source only, so a new move destination is checked here. + /// `checkAlterIsPossible` runs on every host and the check depends only on the server config, so it is correct everywhere. + static constexpr std::array move_destination_settings{ + "after_processing_move_uri", "after_processing_move_connection_string", "after_processing_move_container"}; + + auto get_move_destination_value = [](const SettingsChanges * settings, std::string_view name) -> String + { + const Field * value = settings ? settings->tryGet(name) : nullptr; + return value ? convertFieldToString(*value) : String{}; + }; + + const bool move_destination_changed = std::ranges::any_of( + move_destination_settings, + [&](std::string_view name) + { return get_move_destination_value(old_settings, name) != get_move_destination_value(&new_settings, name); }); + + if (move_destination_changed) + { + const String move_connection_string = get_move_destination_value(&new_settings, "after_processing_move_connection_string"); + const String move_container = get_move_destination_value(&new_settings, "after_processing_move_container"); + + checkMoveDestinationHost( + type, + get_move_destination_value(&new_settings, "after_processing_move_uri"), + move_connection_string, + move_container, + local_context->getRemoteHostFilter()); + } } void StorageObjectStorageQueue::alter( @@ -1532,6 +1610,12 @@ const ObjectStorageQueueTableMetadata & StorageObjectStorageQueue::getTableMetad return files_metadata->getTableMetadata(); } +std::shared_ptr StorageObjectStorageQueue::tryGetFilesMetadata() const +{ + std::lock_guard lock(mutex); + return files_metadata; +} + std::shared_ptr StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate) { @@ -1571,11 +1655,16 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), /// so let's reconstruct. ObjectStorageQueueSettings settings; - /// If startup() for a table was not called, just use the default queue settings + /// If startup() for a table was not called, just use the default queue settings. + /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. if (!startup_finished) return settings; - const auto & table_metadata = getTableMetadata(); + auto metadata = tryGetFilesMetadata(); + if (!metadata) + return settings; + + const auto & table_metadata = metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) @@ -1591,12 +1680,12 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const settings[ObjectStorageQueueSetting::tracked_files_limit] = table_metadata.tracked_files_limit; settings[ObjectStorageQueueSetting::buckets] = table_metadata.buckets; - auto cleanup_interval_ms = files_metadata->getCleanupIntervalMS(); + auto cleanup_interval_ms = metadata->getCleanupIntervalMS(); settings[ObjectStorageQueueSetting::cleanup_interval_min_ms] = static_cast(cleanup_interval_ms.first); settings[ObjectStorageQueueSetting::cleanup_interval_max_ms] = static_cast(cleanup_interval_ms.second); - settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(files_metadata->getPersistentProcessingNodeTTLSeconds()); - settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = files_metadata->usePersistentProcessingNode(); - const auto & file_statuses_cache = files_metadata->getFileStatusesCache(); + settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(metadata->getPersistentProcessingNodeTTLSeconds()); + settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = metadata->usePersistentProcessingNode(); + const auto & file_statuses_cache = metadata->getFileStatusesCache(); settings[ObjectStorageQueueSetting::metadata_cache_size_bytes] = file_statuses_cache.maxSizeInBytes(); settings[ObjectStorageQueueSetting::metadata_cache_size_elements] = file_statuses_cache.maxCount(); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index 5a251e7b7e16..902ec55b54bf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -147,6 +147,8 @@ class StorageObjectStorageQueue : public IStorage, WithContext bool supportsColumnsWithDynamicStructure() const override { return true; } const ObjectStorageQueueTableMetadata & getTableMetadata() const; + /// Returns nullptr if the table is not started up or is already shut down. + std::shared_ptr tryGetFilesMetadata() const; std::shared_ptr createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate); std::shared_ptr createSource( diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 27f3c6004559..d7ddf6e5d128 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -143,6 +144,7 @@ void registerStorageS3Queue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::S3, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getS3QueueMoveDestinationAccess, }); } #endif @@ -161,6 +163,7 @@ void registerStorageAzureQueue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::AZURE, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getAzureQueueMoveDestinationAccess, }); } #endif diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp index f5e81a4a4843..ec0c6ea0433a 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp @@ -275,6 +275,14 @@ void StorageMaterializedPostgreSQL::dropInnerTableIfAny(bool sync, ContextPtr lo } +bool StorageMaterializedPostgreSQL::hasBucketedMapSerialization() const +{ + if (auto nested = tryGetNested()) + return nested->hasBucketedMapSerialization(); + return false; +} + + bool StorageMaterializedPostgreSQL::needRewriteQueryWithFinal(const Names & column_names) const { return needRewriteQueryWithFinalForStorage(column_names, getNested()); diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h index 0933a2772d9d..c133fee077bf 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h @@ -91,6 +91,8 @@ class StorageMaterializedPostgreSQL final : public IStorage, WithContext bool needRewriteQueryWithFinal(const Names & column_names) const override; + bool hasBucketedMapSerialization() const override; + void read( QueryPlan & query_plan, const Names & column_names, diff --git a/src/Storages/StorageAlias.cpp b/src/Storages/StorageAlias.cpp index eb8bc370f85a..5160352e3432 100644 --- a/src/Storages/StorageAlias.cpp +++ b/src/Storages/StorageAlias.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -15,6 +16,9 @@ #include #include #include +#include +#include +#include namespace DB @@ -31,6 +35,7 @@ namespace ErrorCodes extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int BAD_ARGUMENTS; extern const int SUPPORT_IS_DISABLED; + extern const int NOT_IMPLEMENTED; } StorageAlias::StorageAlias( @@ -171,6 +176,26 @@ SinkToStoragePtr StorageAlias::write( return std::make_shared(*this, local_context, target_metadata); } +void StorageAlias::checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const +{ + /// `InterpreterAlterQuery` checks the export grants (`SELECT` on the table and its row policy) on the name in the query, + /// which is the alias, not the target. The refusal does not need the user, so it also holds on the hosts of `ON CLUSTER`. + for (const auto & command : commands) + { + if (command.type == AlterCommand::MODIFY_SETTING && !StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes).empty()) + { + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Changing the settings that send the data of a table elsewhere through an alias is not supported. " + "Execute the ALTER directly on the target table: {}.{}", + backQuoteIfNeed(target_database), + backQuoteIfNeed(target_table)); + } + } + + getTargetTable()->checkAlterIsPossible(commands, local_context); +} + void StorageAlias::alter( const AlterCommands & params, ContextPtr local_context, diff --git a/src/Storages/StorageAlias.h b/src/Storages/StorageAlias.h index 0753decac7e5..99a9167dd58d 100644 --- a/src/Storages/StorageAlias.h +++ b/src/Storages/StorageAlias.h @@ -55,7 +55,7 @@ class StorageAlias final : public IStorage, WithContext /// Distributed write to target table std::optional distributedWrite(const ASTInsertQuery & query, ContextPtr local_context) override; - void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override { getTargetTable()->checkAlterIsPossible(commands, local_context); } + void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override; /// Alter target table void alter( @@ -143,6 +143,7 @@ class StorageAlias final : public IStorage, WithContext std::optional supportedPrewhereColumns() const override { return getTargetTable()->supportedPrewhereColumns(); } bool canMoveConditionsToPrewhere() const override { return getTargetTable()->canMoveConditionsToPrewhere(); } bool supportsOptimizationToSubcolumns() const override { return getTargetTable()->supportsOptimizationToSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsDeduplication() const override { return getTargetTable()->supportsDeduplication(); } bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageBuffer.cpp b/src/Storages/StorageBuffer.cpp index 090058a95a95..2993357d6658 100644 --- a/src/Storages/StorageBuffer.cpp +++ b/src/Storages/StorageBuffer.cpp @@ -887,6 +887,13 @@ bool StorageBuffer::supportsPrewhere() const return false; } +bool StorageBuffer::hasBucketedMapSerialization() const +{ + if (auto destination = getDestinationTable()) + return destination->hasBucketedMapSerialization(); + return false; +} + bool StorageBuffer::checkThresholds(const Buffer & buffer, bool direct, time_t current_time, size_t additional_rows, size_t additional_bytes) const { time_t time_passed = 0; diff --git a/src/Storages/StorageBuffer.h b/src/Storages/StorageBuffer.h index 481647a89625..8da3169b9b2f 100644 --- a/src/Storages/StorageBuffer.h +++ b/src/Storages/StorageBuffer.h @@ -91,6 +91,7 @@ friend class BufferSink; bool supportsParallelInsert() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } diff --git a/src/Storages/StorageDistributed.cpp b/src/Storages/StorageDistributed.cpp index 478abb8530f7..2bdf34ab918b 100644 --- a/src/Storages/StorageDistributed.cpp +++ b/src/Storages/StorageDistributed.cpp @@ -1,5 +1,10 @@ #include +#include +#include +#include +#include + #include #include @@ -179,6 +184,7 @@ namespace Setting extern const SettingsBool prefer_global_in_and_join; extern const SettingsBool skip_unavailable_shards; extern const SettingsBool enable_global_with_statement; + extern const SettingsMap additional_table_filters; } namespace DistributedSetting @@ -1364,6 +1370,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser auto & select = query.select->as(); StoragePtr src_storage; + bool src_is_table_function = false; /// Distributed write only works in the most trivial case INSERT ... SELECT /// without any unions or joins on the right side @@ -1380,6 +1387,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (joined_tables.tablesCount() == 1) { src_storage = joined_tables.getLeftTableStorage(); + src_is_table_function = joined_tables.isLeftTableFunction(); } } } @@ -1387,6 +1395,19 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (!src_storage) return {}; + /// This is the only place source SELECT access is enforced in this case + /// (table functions have been already checked in ITableFunction::execute) + const auto src_id = src_storage->getStorageID(); + if (!src_is_table_function + && !local_context->getAccess()->isGranted(AccessType::SELECT, src_id.database_name, src_id.table_name)) + return {}; + if (auto row_policy_filter = local_context->getRowPolicyFilter(src_id.database_name, src_id.table_name, RowPolicyFilterType::SELECT_FILTER); + row_policy_filter && !row_policy_filter->isAlwaysTrue()) + return {}; + /// It is not easy to match this table only, analyzer also do not do it + if (!settings[Setting::additional_table_filters].value.empty()) + return {}; + if (auto src_distributed = std::dynamic_pointer_cast(src_storage)) { return distributedWriteBetweenDistributedTables(*src_distributed, query, local_context); diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 0cc905ab1d3c..4ced2fa21aa6 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -1,9 +1,12 @@ #include +#include #include #include #include #include +#include #include +#include #include #include #include @@ -267,4 +270,37 @@ const StorageFactory::StorageFeatures & StorageFactory::getStorageFeatures(const return it->second.features; } +AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & create) const +{ + AccessRightsElements res; + auto add = [&](const ASTStorage & storage) + { + if (!storage.engine || !storage.settings) + return; + auto it = storages.find(storage.engine->name); + if (it != storages.end() && it->second.features.get_export_access_fn) + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + }; + + if (create.storage) + add(*create.storage); + if (create.targets) + { + for (const ASTStorage * inner_engine : create.targets->getInnerEngines()) + add(*inner_engine); + } + return res; +} + +AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const +{ + AccessRightsElements res; + for (const auto & [_, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes)); + } + return res; +} + } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index d3e4ccc969d4..6babf823c358 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -16,6 +16,8 @@ namespace DB class Context; class ASTCreateQuery; class ASTStorage; +class AccessRightsElements; +class SettingsChanges; struct StorageID; struct ConstraintsDescription; @@ -33,6 +35,10 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// Used to validate if table settings belong to the engine or the query before the start of the query interpretation using HasBuiltinSettingFn = bool(std::string_view); + /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. + /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + struct Arguments { const String & engine_name; @@ -76,6 +82,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> std::optional source_access_type = std::nullopt; HasBuiltinSettingFn * has_builtin_setting_fn = nullptr; + GetExportAccessFn * get_export_access_fn = nullptr; }; using CreatorFn = std::function; @@ -111,6 +118,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> .supports_schema_inference = false, .source_access_type = std::nullopt, .has_builtin_setting_fn = nullptr, + .get_export_access_fn = nullptr, }); const Storages & getAllStorages() const @@ -140,6 +148,13 @@ class StorageFactory : private boost::noncopyable, public IHints<> const StorageFeatures & getStorageFeatures(const String & storage_name) const; + /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` + /// table. An unknown engine needs nothing here: creating it fails later. + AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, + /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. + AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; + private: Storages storages; }; diff --git a/src/Storages/StorageInMemoryMetadata.cpp b/src/Storages/StorageInMemoryMetadata.cpp index 7982f7de575a..f99761a93ff7 100644 --- a/src/Storages/StorageInMemoryMetadata.cpp +++ b/src/Storages/StorageInMemoryMetadata.cpp @@ -20,6 +20,8 @@ #include #include +#include + namespace DB { @@ -198,6 +200,47 @@ ContextMutablePtr StorageInMemoryMetadata::getSQLSecurityOverriddenContext(Conte new_context->setUser(getDefinerID(context)); + /// `Context::setUser` only sets the access-control identity (`user_id`); it does not touch the + /// user names in `ClientInfo`. That is harmless when there is an invoker whose names were copied + /// above, but a scheduled refresh of a refreshable materialized view builds its context from the + /// global context, where `current_user`, `initial_user` and `authenticated_user` are empty. + /// `RemoteQueryExecutor` sends the names as-is, and a shard that accepts the interserver + /// `` treats an empty `initial_user` as "interserver mode": it skips authentication + /// (see `TCPHandler::receiveQuery`) and executes the query with full access + /// (see `Context::getAccess`, `full_access = !user_id`). Stamp the definer into the empty fields + /// so the remote leg of the query is bounded by the same identity as the local one. Non-empty + /// fields are left alone so `currentUser` inside an ordinary `DEFINER` view still returns the + /// invoker. `AsynchronousInsertQueue` and `InterpreterExecuteAsQuery` do the same. + { + const auto & new_client_info = new_context->getClientInfo(); + const bool current_user_empty = new_client_info.current_user.empty(); + const bool initial_user_empty = new_client_info.initial_user.empty(); + const bool authenticated_user_empty = new_client_info.authenticated_user.empty(); + + if (current_user_empty || initial_user_empty || authenticated_user_empty) + { + const auto definer_name = new_context->getUserName(); + if (current_user_empty) + new_context->setCurrentUserName(definer_name); + if (initial_user_empty) + { + new_context->setInitialUserName(definer_name); + /// The shard authenticates the definer by `initial_user` and checks `initial_address` + /// against the allowed hosts of that user. Without an invoker, the address is the + /// unspecified `0.0.0.0`, which only matches users with `HOST ANY`. The query is + /// produced by this server itself, so present it as coming from the local host. + if (!new_client_info.initial_address || new_client_info.initial_address->host().isWildcard()) + new_context->setInitialAddress(Poco::Net::SocketAddress(Poco::Net::IPAddress("127.0.0.1"), 0)); + } + if (authenticated_user_empty) + { + ClientInfo client_info_with_definer = new_context->getClientInfo(); + client_info_with_definer.authenticated_user = definer_name; + new_context->setClientInfo(client_info_with_definer); + } + } + } + new_context->clampToSettingsConstraints(changed_settings, SettingSource::QUERY); new_context->applySettingsChanges(changed_settings); new_context->setSetting("allow_ddl", 1); diff --git a/src/Storages/StorageMaterializedView.cpp b/src/Storages/StorageMaterializedView.cpp index cd9b89b12c7b..05223ca73bf7 100644 --- a/src/Storages/StorageMaterializedView.cpp +++ b/src/Storages/StorageMaterializedView.cpp @@ -559,10 +559,19 @@ ContextMutablePtr StorageMaterializedView::createRefreshContext(const String & l { ContextPtr table_context = getContext(); ClientInfo client_info = table_context->getClientInfo(); - client_info.interface = ClientInfo::Interface::BACKGROUND; - client_info.client_name = "refreshable materialized view"; - auto refresh_context = getInMemoryMetadataPtr()->getSQLSecurityOverriddenContext(table_context, &client_info); - refresh_context->setClientInfo(client_info); + auto view_metadata = getInMemoryMetadataPtr(); + auto refresh_context = view_metadata->getSQLSecurityOverriddenContext(table_context, &client_info); + /// For `SQL SECURITY DEFINER`, `getSQLSecurityOverriddenContext` fills the empty user names in + /// the context's `ClientInfo` with the definer. Do not assign the local `client_info` copy to + /// the context: `setClientInfo` replaces the whole struct and would wipe that identity out. + /// Re-read it instead, so that a view without SQL security (which gets a plain copy) also gets + /// these fields. + { + ClientInfo refresh_client_info = refresh_context->getClientInfo(); + refresh_client_info.interface = ClientInfo::Interface::BACKGROUND; + refresh_client_info.client_name = "refreshable materialized view"; + refresh_context->setClientInfo(refresh_client_info); + } refresh_context->setSetting("database_replicated_allow_replicated_engine_arguments", 3); refresh_context->setSetting("log_comment", log_comment); refresh_context->setQueryKind(ClientInfo::QueryKind::INITIAL_QUERY); diff --git a/src/Storages/StorageMaterializedView.h b/src/Storages/StorageMaterializedView.h index 62331b24f329..a4d72e909292 100644 --- a/src/Storages/StorageMaterializedView.h +++ b/src/Storages/StorageMaterializedView.h @@ -36,6 +36,7 @@ class StorageMaterializedView final : public IStorage, WithMutableContext bool supportsFinal() const override { return getTargetTable()->supportsFinal(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsSubcolumns() const override { return getTargetTable()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override; bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageMerge.cpp b/src/Storages/StorageMerge.cpp index 202aae98818e..a70dd5e4659b 100644 --- a/src/Storages/StorageMerge.cpp +++ b/src/Storages/StorageMerge.cpp @@ -318,6 +318,12 @@ bool StorageMerge::supportsPrewhere() const return traverseTablesUntil([](const auto & table) { return !table->supportsPrewhere(); }) == nullptr; } +bool StorageMerge::hasBucketedMapSerialization() const +{ + /// The rewritten query is sent to every underlying table, so all of them must benefit from it. + return traverseTablesUntil([](const auto & table) { return !table->hasBucketedMapSerialization(); }) == nullptr; +} + bool StorageMerge::canMoveConditionsToPrewhere() const { /// NOTE: This check and the above check are used during query analysis as condition for applying diff --git a/src/Storages/StorageMerge.h b/src/Storages/StorageMerge.h index 2c1eafc7f808..948a5f50694f 100644 --- a/src/Storages/StorageMerge.h +++ b/src/Storages/StorageMerge.h @@ -51,6 +51,7 @@ class StorageMerge final : public IStorage, WithContext bool supportsSampling() const override { return true; } bool supportsFinal() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } bool supportsPrewhere() const override; std::optional supportedPrewhereColumns() const override; diff --git a/src/Storages/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index 8419b2aea6c2..cecedf79cca5 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -1114,6 +1114,11 @@ QueryPipeline StorageMergeTree::updateLightweight(const MutationCommands & comma /// Updates currently don't work with parallel replicas. context_copy->setSetting("max_parallel_replicas", Field(1)); + /// A snapshot cached by `enable_shared_storage_snapshot_in_query` before the wait for committing + /// inserts above (e.g. by the validation of `IN` operands in `InterpreterUpdateQuery`) would hide + /// the parts committed during the wait from the update. See `StorageReplicatedMergeTree::updateLightweight`. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); auto sink = std::make_shared(*this, std::move(patch_metadata), std::move(update_holder), context_copy); @@ -2800,25 +2805,24 @@ void StorageMergeTree::replacePartitionFrom(const StoragePtr & source_table, con String partition_id; + /// The merges_blocker must live until the end of the function to prevent background mutations + /// from starting on parts in the target partition between when we stop waiting and when we + /// actually remove old parts via removePartsInRangeFromWorkingSet. Without this, a mutation + /// could "resurrect" old data by completing on an already-removed part and adding a new version + /// of it back to the working set. + ActionLock merges_blocker; if (is_all) { if (replace) throw DB::Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Only support DROP/DETACH/ATTACH PARTITION ALL currently"); + merges_blocker = stopMergesAndWait(); } else { partition_id = getPartitionIDFromQuery(partition, local_context); + merges_blocker = stopMergesAndWaitForPartition(partition_id); } - /// We use the global `stopMergesAndWait` (not the per-partition variant) because the - /// per-partition blocker check in `scheduleDataProcessingJob` happens outside - /// `currently_processing_in_background_mutex`, creating a race window where a mutation - /// can be selected inside the mutex, pass the per-partition check outside the mutex, - /// and get scheduled after the blocker was set but before we call - /// `removePartsInRangeFromWorkingSet`, "resurrecting" old data. - /// The global blocker is checked inside the mutex, eliminating this race. - ActionLock merges_blocker = stopMergesAndWait(); - auto source_metadata_snapshot = source_table->getInMemoryMetadataPtr(); auto my_metadata_snapshot = getInMemoryMetadataPtr(); diff --git a/src/Storages/StorageMongoDB.cpp b/src/Storages/StorageMongoDB.cpp index 6a6fbeca720e..e4dff78729a2 100644 --- a/src/Storages/StorageMongoDB.cpp +++ b/src/Storages/StorageMongoDB.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -36,6 +37,7 @@ #include #include +#include #include using bsoncxx::builder::basic::document; @@ -49,6 +51,7 @@ namespace DB namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int NOT_IMPLEMENTED; @@ -78,6 +81,53 @@ void MongoDBConfiguration::checkCollection() const throw Exception(ErrorCodes::BAD_ARGUMENTS, "MongoDB collection name must be non-empty and must not contain NUL characters"); } +namespace +{ + +void throwIfServerCredentials(const mongocxx::uri & uri, std::string_view remedy) +{ + /// Only these take the credentials from the connection string; `MONGODB-OIDC`, `MONGODB-AWS`, `GSSAPI` and + /// `MONGODB-X509` use the server's. Without a mechanism the driver uses SCRAM or no authentication. Names are case-insensitive. + static constexpr std::string_view allowed_mechanisms[] = {"SCRAM-SHA-1", "SCRAM-SHA-256", "PLAIN"}; + + const String mechanism = uri.auth_mechanism(); + const bool is_allowed_mechanism = mechanism.empty() + || std::ranges::any_of(allowed_mechanisms, [&](std::string_view allowed) { return equalsCaseInsensitive(mechanism, allowed); }); + + if (!is_allowed_mechanism) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB authentication mechanism '{}' is not allowed, because it authenticates with " + "credentials of the server process. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a password " + "in the connection string{}.", + mechanism, remedy); + + /// The driver stores the deprecated `sslClientCertificateKeyFile` under the canonical name, so this covers both. + if (uri.tls_certificate_key_file()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB connection option `tlsCertificateKeyFile` is not allowed, because it makes the server present a " + "client certificate from its own filesystem. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a " + "password in the connection string{}.", + remedy); +} + +} + +void MongoDBConfiguration::checkServerCredentialsForTable(const ContextPtr & context) const +{ + /// In `clickhouse-local` the user is the operator, so the credentials of the process are theirs to use. + if (context->getApplicationType() != Context::ApplicationType::SERVER) + return; + + throwIfServerCredentials(*uri, ""); +} + +void MongoDBConfiguration::checkServerCredentialsForDictionary() const +{ + throwIfServerCredentials(*uri, ", or define the dictionary in the server configuration files"); +} + StorageMongoDB::StorageMongoDB( const StorageID & table_id_, MongoDBConfiguration configuration_, @@ -104,6 +154,9 @@ Pipe StorageMongoDB::read( size_t max_block_size, size_t /*num_streams*/) { + /// Checked per read, with the query's settings: a table created with `mongodb(...)` is built with the global context. + configuration.checkServerCredentialsForTable(context); + storage_snapshot->check(column_names); Block sample_block; diff --git a/src/Storages/StorageMongoDB.h b/src/Storages/StorageMongoDB.h index 5d436a874803..ee514c16762a 100644 --- a/src/Storages/StorageMongoDB.h +++ b/src/Storages/StorageMongoDB.h @@ -53,6 +53,9 @@ struct MongoDBConfiguration void checkHosts(const ContextPtr & context) const; void checkCollection() const; + void checkServerCredentialsForTable(const ContextPtr & context) const; + void checkServerCredentialsForDictionary() const; + bool isOidColumn(const std::string & name) const { return oid_fields.contains(name); diff --git a/src/Storages/StorageProxy.h b/src/Storages/StorageProxy.h index 57c14568e56d..aa24e39addb6 100644 --- a/src/Storages/StorageProxy.h +++ b/src/Storages/StorageProxy.h @@ -38,6 +38,7 @@ class StorageProxy : public IStorage bool noPushingToViewsOnInserts() const override { return getNested()->noPushingToViewsOnInserts(); } bool hasEvenlyDistributedRead() const override { return getNested()->hasEvenlyDistributedRead(); } bool supportsSubcolumns() const override { return getNested()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getNested()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override { return getNested()->supportsColumnsWithDynamicStructure(); } ColumnSizeByName getColumnSizes() const override { return getNested()->getColumnSizes(); } diff --git a/src/Storages/StorageReplicatedMergeTree.cpp b/src/Storages/StorageReplicatedMergeTree.cpp index 853396096da3..9707592466a1 100644 --- a/src/Storages/StorageReplicatedMergeTree.cpp +++ b/src/Storages/StorageReplicatedMergeTree.cpp @@ -249,6 +249,7 @@ namespace FailPoints extern const char rmt_merge_selecting_task_no_free_threads[]; extern const char rmt_merge_selecting_task_max_part_size[]; extern const char rmt_delay_execute_drop_range[]; + extern const char rmt_restore_replica_pause_before_metadata_version_raise[]; } namespace ErrorCodes @@ -7069,6 +7070,7 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( createReplica(metadata_snapshot, zookeeper_retries_info); createNewZooKeeperNodes(zookeeper_retries_info); + FailPointInjection::pauseFailPoint(FailPoints::rmt_restore_replica_pause_before_metadata_version_raise); /// Bump the /metadata ZNode version to match the max parts metadata version. /// The table's in-memory metadata_version is derived from the /metadata ZNode stat.version @@ -7076,12 +7078,41 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( if (max_parts_metadata_version > 0) { auto zookeeper = getZooKeeper(); - String metadata_str = zookeeper->get(zookeeper_path + "/metadata"); - for (int32_t i = 0; i < max_parts_metadata_version; ++i) - zookeeper->set(zookeeper_path + "/metadata", metadata_str); - zookeeper->set(replica_path + "/metadata_version", std::to_string(max_parts_metadata_version)); + /// Each batch logs an ALTER_METADATA entry of the version it reaches, so a replica that cloned an earlier one catches up. + Coordination::Stat metadata_stat; + Coordination::Stat columns_stat; + String metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + String columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + while (metadata_stat.version < max_parts_metadata_version) + { + const auto target = static_cast(std::min( + max_parts_metadata_version, Int64{metadata_stat.version} + static_cast(zkutil::MULTI_BATCH_SIZE))); + + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(zookeeper_path + "/columns", columns_stat.version)); + for (int32_t version = metadata_stat.version; version < target; ++version) + ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/metadata", version + 1 == target ? metadata_str : "", version)); + + ReplicatedMergeTreeLogEntryData entry; + entry.type = LogEntry::ALTER_METADATA; + entry.source_replica = replica_name; + entry.metadata_str = metadata_str; + entry.columns_str = columns_str; + entry.alter_version = target; + entry.create_time = time(nullptr); + entry.have_mutation = false; + ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/log/log-", entry.toString(), zkutil::CreateMode::PersistentSequential)); - LOG_INFO(log, "Bumped metadata version to {} to match parts", max_parts_metadata_version); + Coordination::Responses responses; + const Coordination::Error code = zookeeper->tryMulti(ops, responses); + if (code != Coordination::Error::ZOK && code != Coordination::Error::ZBADVERSION) + zkutil::KeeperMultiException::check(code, ops, responses); + + metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + } + + LOG_INFO(log, "Raised metadata version to {} to match parts", metadata_stat.version); } LOG_INFO(log, "Created ZK nodes for table"); @@ -8433,6 +8464,13 @@ QueryPipeline StorageReplicatedMergeTree::updateLightweight(const MutationComman waitForCommittingOpsToFinish(zookeeper, context_copy->getPartitionIdToMaxBlock(getStorageID().uuid), ops, backoff_ms, sync_timeout); } + /// With `enable_shared_storage_snapshot_in_query` the update reads with the snapshot of this table + /// cached for the whole query. Anything analyzed before this point may have cached one, e.g. the + /// validation of `IN` operands in `InterpreterUpdateQuery`. Such a snapshot predates the wait for committing inserts above, so the + /// parts that arrived during the wait would be invisible to the update and their rows would stay + /// unchanged. Discard it, so that the update and its subqueries share a snapshot taken now. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); diff --git a/src/Storages/System/StorageSystemMutations.cpp b/src/Storages/System/StorageSystemMutations.cpp index 7514ed309af7..b3b65c6003ed 100644 --- a/src/Storages/System/StorageSystemMutations.cpp +++ b/src/Storages/System/StorageSystemMutations.cpp @@ -10,14 +10,67 @@ #include #include #include +#include #include #include #include +#include +#include +#include namespace DB { +namespace Setting +{ + extern const SettingsUInt64 max_parser_depth; + extern const SettingsUInt64 max_parser_backtracks; +} + +namespace ErrorCodes +{ + extern const int SYNTAX_ERROR; + extern const int TOO_DEEP_RECURSION; + extern const int TOO_SLOW_PARSING; +} + +/// The mutation entry keeps the real text of the command, because the mutation is executed from it +/// (on every replica, for replicated tables). Hide the secrets on the way out instead, the way +/// `system.distributed_ddl_queue` does. The command is formatted the same way as the stored text, +/// so only the secrets differ from it. +static String hideSecretsInCommand(const ContextPtr & context, const String & command) +{ + /// Nothing to parse, see `MutationCommand::ast`. + if (command.empty()) + return command; + + const auto & settings = context->getSettingsRef(); + ParserAlterCommandList parser; + ASTPtr ast; + try + { + ast = parseQuery(parser, command, 0, settings[Setting::max_parser_depth], settings[Setting::max_parser_backtracks]); + } + catch (const Exception & e) + { + /// The text may be unparseable on another server version, so hide the whole command instead of failing the table. + if (e.code() != ErrorCodes::SYNTAX_ERROR + && e.code() != ErrorCodes::TOO_DEEP_RECURSION + && e.code() != ErrorCodes::TOO_SLOW_PARSING) + throw; + return "[HIDDEN]"; + } + + return ast->formatWithPossiblyHidingSensitiveData( + /*max_length=*/0, + /*one_line=*/true, + /*show_secrets=*/false, + /*print_pretty_type_names=*/false, + /*identifier_quoting_rule=*/IdentifierQuotingRule::WhenNecessary, + /*identifier_quoting_style=*/IdentifierQuotingStyle::Backticks); +} + ColumnsDescription StorageSystemMutations::getColumnsDescription() { @@ -65,10 +118,11 @@ Block StorageSystemMutations::getFilterSampleBlock() const }; } -void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const +void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const { const auto access = context->getAccess(); const bool check_access_for_databases = !access->isGranted(AccessType::SHOW_TABLES); + const bool show_secrets = canDisplaySecrets(context); /// Collect a set of *MergeTree tables. std::map> merge_tree_tables; @@ -169,25 +223,43 @@ void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr c parts_postpone_reasons_map.emplace_back(std::move(key_value)); } - size_t col_num = 0; - res_columns[col_num++]->insert(database); - res_columns[col_num++]->insert(table); - - res_columns[col_num++]->insert(status.id); - res_columns[col_num++]->insert(status.command); - res_columns[col_num++]->insert(UInt64(status.create_time)); - res_columns[col_num++]->insert(block_partition_ids); - res_columns[col_num++]->insert(block_numbers); - res_columns[col_num++]->insert(parts_in_progress_names); - res_columns[col_num++]->insert(parts_to_do_names); - res_columns[col_num++]->insert(parts_to_do_names.size()); - res_columns[col_num++]->insert(parts_postpone_reasons_map); - res_columns[col_num++]->insert(status.is_done); - res_columns[col_num++]->insert(status.is_killed); - res_columns[col_num++]->insert(status.latest_failed_part); - res_columns[col_num++]->insert(UInt64(status.latest_fail_time)); - res_columns[col_num++]->insert(status.latest_fail_reason); - res_columns[col_num++]->insert(status.latest_fail_error_code_name); + size_t src_index = 0; + size_t res_index = 0; + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(database); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(table); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.id); + /// Parsing the command costs much more than everything else here, so it is done only when the column is queried. + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(show_secrets ? status.command : hideSecretsInCommand(context, status.command)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.create_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_partition_ids); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_numbers); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_in_progress_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names.size()); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_postpone_reasons_map); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_done); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_killed); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_failed_part); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.latest_fail_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_reason); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_error_code_name); } } } diff --git a/src/Storages/System/StorageSystemMutations.h b/src/Storages/System/StorageSystemMutations.h index 5341838a65e3..c3f897491fc7 100644 --- a/src/Storages/System/StorageSystemMutations.h +++ b/src/Storages/System/StorageSystemMutations.h @@ -21,8 +21,9 @@ class StorageSystemMutations final : public IStorageSystemOneBlock protected: using IStorageSystemOneBlock::IStorageSystemOneBlock; - void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const override; + void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const override; Block getFilterSampleBlock() const override; + bool supportsColumnsMask() const override { return true; } }; } diff --git a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp index b573828ddee1..444e3d74a08b 100644 --- a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp +++ b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( const ActionsDAG::Node *, std::vector) const { + const bool display_secrets = canDisplaySecrets(context); auto add_table = [&]( const DatabaseTablesIteratorPtr & it, StorageObjectStorageQueue & storage) { @@ -52,7 +54,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( auto constraints_and_current_profiles = context->getSettingsConstraintsAndCurrentProfiles(); const auto & constraints = constraints_and_current_profiles->constraints; MutableColumnsAndConstraints params(res_columns, constraints); - storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage); + storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage, display_secrets); }; const auto access = context->getAccess(); diff --git a/src/TableFunctions/ITableFunction.cpp b/src/TableFunctions/ITableFunction.cpp index fcd19f5b5408..9624c7464e48 100644 --- a/src/TableFunctions/ITableFunction.cpp +++ b/src/TableFunctions/ITableFunction.cpp @@ -55,11 +55,22 @@ void ITableFunction::checkEngineAccess(ContextPtr context) const context->checkAccess(AccessType::TABLE_ENGINE, engine); } +void ITableFunction::checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const +{ + auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); + if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) + context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); +} + ColumnsDescription ITableFunction::getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const { /// Resolving table structure is always a read operation. checkSourceAccess(context, /*is_insert_query*/ false); checkEngineAccess(context); + /// Resolving the structure may access the source (e.g. schema inference fetches a URL), so it must be + /// gated in the same way as `execute`: otherwise `DESCRIBE TABLE url(...)` would let a user who cannot + /// run the table function (e.g. under `readonly = 1`) make the server request an endpoint. + checkCreateTemporaryTableAccess(context, /*is_insert_query*/ false); return getActualTableStructure(context, is_insert_query); } @@ -73,9 +84,7 @@ StoragePtr ITableFunction::execute(const ASTPtr & ast_function, ContextPtr conte /// Deliberately not under `check_source_access`: no caller takes over the engine check. checkEngineAccess(context); - auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); - if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) - context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); + checkCreateTemporaryTableAccess(context, is_insert_query); auto context_to_use = use_global_context ? context->getGlobalContext() : context; diff --git a/src/TableFunctions/ITableFunction.h b/src/TableFunctions/ITableFunction.h index 0aeb1d497e1a..6579ff2ce25a 100644 --- a/src/TableFunctions/ITableFunction.h +++ b/src/TableFunctions/ITableFunction.h @@ -88,8 +88,9 @@ class ITableFunction : public std::enable_shared_from_this StoragePtr execute(const ASTPtr & ast_function, ContextPtr context, const std::string & table_name, ColumnsDescription cached_columns_ = {}, bool use_global_context = false, bool is_insert_query = false) const; - /// Returns actual table structure after enforcing source access checks. - /// Use this instead of getActualTableStructure() from outside execute(). + /// Returns actual table structure after enforcing the same access checks as `execute`: source, engine, + /// and `CREATE TEMPORARY TABLE` (for table functions not allowed in readonly mode). + /// Use this instead of `getActualTableStructure` from outside `execute`. ColumnsDescription getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const; /// Check that the user has the required source access (e.g. READ ON MYSQL, WRITE ON S3). @@ -98,6 +99,10 @@ class ITableFunction : public std::enable_shared_from_this /// Check the `TABLE ENGINE` grant, for engines that opt in via `requiresTableEngineGrant`. void checkEngineAccess(ContextPtr context) const; + /// Check the `CREATE TEMPORARY TABLE` grant, required to use a table function unless it is allowed + /// in readonly mode and the query is not an insert. + void checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const; + virtual ~ITableFunction() = default; protected: diff --git a/src/configure_config.cmake b/src/configure_config.cmake index 39b16eeebbe7..0d3a4da3abaa 100644 --- a/src/configure_config.cmake +++ b/src/configure_config.cmake @@ -150,6 +150,9 @@ endif() if (TARGET ch_contrib::parquet) set(USE_PARQUET 1) set(USE_ARROW 1) +endif() +# The ORC reader and writer are implemented in ClickHouse and need only the compression libraries. +if (TARGET ch_contrib::snappy) set(USE_ORC 1) endif() if (TARGET ch_contrib::liburing) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 26adc0ca8970..08f04e9081b2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -59,8 +59,38 @@ def tune_local_port_range(): ) +def is_xdist_replacement_worker(): + """True when this worker was spawned to replace one that died mid-run. + + `pytest-xdist` numbers a replacement past the size of the original pool, so `gw8` in a pool of + eight (`gw0`..`gw7`) is a replacement. A replacement starts a fresh pytest *session*, which + re-runs every session-scoped fixture - and `cleanup_environment` kills every container on the + host, including the ones the workers that are still running own. One worker dying, from an OOM + kill for instance, would otherwise take the containers of the whole job with it. + """ + worker = os.environ.get("PYTEST_XDIST_WORKER", "") + count = os.environ.get("PYTEST_XDIST_WORKER_COUNT", "") + if not worker.startswith("gw") or not count.isdigit(): + return False + + index = worker.removeprefix("gw") + if not index.isdigit(): + return False + + return int(index) >= int(count) + + @pytest.fixture(autouse=True, scope="session") def cleanup_environment(): + if is_xdist_replacement_worker(): + logging.info( + "Worker %s replaces a worker that died, so the containers of the workers which are " + "still running are not ours to clean up. Skipping the environment cleanup.", + os.environ["PYTEST_XDIST_WORKER"], + ) + yield + return + try: result = run_and_check(["docker ps | wc -l"], shell=True) if int(result) > 1: diff --git a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml index d4ac4986c22d..ad199feefc1e 100644 --- a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml +++ b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml @@ -2,6 +2,7 @@ host:80 ^[a-z]*\.ru$ + .*\.allowed\.example diff --git a/tests/integration/test_allowed_url_from_config/test.py b/tests/integration/test_allowed_url_from_config/test.py index 78ff4b22d321..b43422300bba 100644 --- a/tests/integration/test_allowed_url_from_config/test.py +++ b/tests/integration/test_allowed_url_from_config/test.py @@ -72,6 +72,43 @@ def test_azure_host_filter_before_client_creation(start_cluster, query): assert node5.query(container_requests) == before +def test_object_storage_queue_move_destination_host_filter(start_cluster): + # The source is on an allowed host (`host:80`), so only the move destination can be rejected. `node1` has no + # Keeper, so a rejection with "not allowed" must come from the settings validation, which runs before any + # Keeper access. + s3_queue = ( + "CREATE TABLE s3queue_move_host (x UInt8) " + "ENGINE = S3Queue('http://host:80/bucket/data/', 'key', 'secret', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_uri = '{}', " + "after_processing_move_access_key_id = 'key', after_processing_move_secret_access_key = 'secret'" + ) + azure_queue = ( + "CREATE TABLE azurequeue_move_host (x UInt8) " + "ENGINE = AzureQueue('http://host:80', 'container', '*', 'account', 'YQ==', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_connection_string = " + "'DefaultEndpointsProtocol=http;AccountName=account;AccountKey=YQ==;BlobEndpoint=http://host:123/account;', " + "after_processing_move_container = 'dst'" + ) + + try: + error = node1.query_and_get_error(s3_queue.format("http://host:123/bucket/")) + assert "not allowed" in error, error + + error = node1.query_and_get_error( + azure_queue, settings={"azure_sdk_max_retries": 0} + ) + assert "not allowed" in error, error + + # Control: an allowed destination passes the host check and only fails later, on the missing Keeper. + error = node1.query_and_get_error(s3_queue.format("http://host:80/bucket/")) + assert "not allowed" not in error, error + finally: + node1.query("DROP TABLE IF EXISTS s3queue_move_host SYNC") + node1.query("DROP TABLE IF EXISTS azurequeue_move_host SYNC") + + def test_config_with_only_primary_hosts(start_cluster): assert ( node2.query( @@ -217,6 +254,34 @@ def test_mysql_dictionary_host_filter(start_cluster): node5.query("DROP DICTIONARY IF EXISTS default.test_mysql_host_filter") +def test_mysql_database_host_filter(start_cluster): + # node5 denies all hosts; the check runs before any connection attempt. + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('10.0.0.1:3306', 'db', 'u', 'p')" + ) + node5.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nc AS " + "host = '10.0.0.1', port = 3306, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nc)" + ) + node5.query("DROP NAMED COLLECTION test_mysql_db_filter_nc") + + # node1's suffix rule would match the whole string, but the connector stops at the NUL; reject it. + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('127.0.0.1\\0.allowed.example:1', 'db', 'u', 'p')" + ) + node1.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nul_nc AS " + "host = '127.0.0.1\\0.allowed.example', port = 1, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nul_nc)" + ) + node1.query("DROP NAMED COLLECTION test_mysql_db_filter_nul_nc") + + def test_mysql_dictionary_replica_host_filter(start_cluster): """MySQL dictionary source with REPLICA(...) syntax should respect RemoteHostFilter.""" # Covers the replica branch: if (config.has(settings_config_prefix + ".replica")) @@ -335,3 +400,58 @@ def test_table_function_remote(start_cluster): "SELECT * FROM remote('localhost:800', system, metrics)" ) ) + + +# The catalog is built lazily on first use, so a query on a table connects to the metastore. +def hive_catalog_error(node, database, url): + node.query( + f"CREATE DATABASE {database} ENGINE = DataLakeCatalog('{url}') " + "SETTINGS catalog_type = 'hive', warehouse = 'test_warehouse'", + settings={"allow_experimental_database_hms_catalog": 1}, + ) + return node.query_and_get_error(f"SELECT * FROM {database}.`ns.tbl`") + + +def test_hive_catalog_host_filter(start_cluster): + url = "thrift://localhost:1" + try: + # Control first: `node4` declares no `remote_url_allow_hosts` at all, so its filter stays + # uninitialized and allows everything - the same statement gets past the check and fails at + # the network instead. Without this arm, a filter that rejected everything would also pass. + error = hive_catalog_error(node4, "test_hive_host_filter", url) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + + # `node5` declares an empty `remote_url_allow_hosts`, which allows nothing. + error = hive_catalog_error(node5, "test_hive_host_filter", url) + assert "UNACCEPTABLE_URL" in error, error + # The check must run before the connect, so the refusal carries no connection error. + assert "Connection refused" not in error, error + finally: + node4.query("DROP DATABASE IF EXISTS test_hive_host_filter") + node5.query("DROP DATABASE IF EXISTS test_hive_host_filter") + + +def test_hive_catalog_host_filter_rejects_nul(start_cluster): + try: + # Control: the suffix rule in `config_with_hosts.xml` admits this host, so it gets past the + # filter and fails at name resolution instead. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://hms.allowed.example:1" + ) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + node1.query("DROP DATABASE test_hive_host_filter_nul") + + # The same rule matches the whole string including the NUL, but `getaddrinfo` would stop at the + # NUL and connect to 127.0.0.1. The host must be refused before any connection attempt. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://127.0.0.1\\0.allowed.example:1" + ) + assert "BAD_ARGUMENTS" in error, error + assert "Unexpected character" in error, error + assert "Connection refused" not in error, error + finally: + node1.query("DROP DATABASE IF EXISTS test_hive_host_filter_nul") diff --git a/tests/integration/test_arrowflight_interface/test.py b/tests/integration/test_arrowflight_interface/test.py index 634ade912d13..4a1c124f986e 100644 --- a/tests/integration/test_arrowflight_interface/test.py +++ b/tests/integration/test_arrowflight_interface/test.py @@ -519,6 +519,43 @@ def test_doget_multiple_chunks(): assert actual[1].column("name").equals(pa.chunked_array([pa.array(["cde"], type=pa.string())])) +# A result is split across several Arrow arrays only when it exceeds the 32-bit offsets of the +# String/Binary/List buffers, so a small one must arrive as a single chunk per column for every type. +def test_doget_single_chunk_per_column(): + node.query( + """ + CREATE TABLE mytable ( + id Int64, + s String, + ns Nullable(String), + lc LowCardinality(String), + arr Array(String), + m Map(String, String), + t Tuple(String, String), + fs FixedString(3) + ) ORDER BY id + """ + ) + node.query( + """ + INSERT INTO mytable SELECT + number, toString(number), if(number % 2, NULL, toString(number)), toString(number % 2), + [toString(number)], map('k', toString(number)), (toString(number), 'x'), toFixedString('abc', 3) + FROM numbers(4) + """ + ) + + client, options = get_client() + + descriptor = flight.FlightDescriptor.for_command("SELECT * FROM mytable ORDER BY id") + flight_info = client.get_flight_info(descriptor, options) + table = client.do_get(flight_info.endpoints[0].ticket, options).read_all() + + assert table.num_rows == 4 + for name, column in zip(table.schema.names, table.columns): + assert column.num_chunks == 1, f"column {name} was split into {column.num_chunks} chunks" + + # We don't support any formats different from "Arrow". def test_doget_cmd_select_invalid_format(): node.query("CREATE TABLE mytable (id Int64, name String) ORDER BY id") diff --git a/tests/integration/test_backup_restore_new/test.py b/tests/integration/test_backup_restore_new/test.py index d317a99a0b49..0df792a10ecc 100644 --- a/tests/integration/test_backup_restore_new/test.py +++ b/tests/integration/test_backup_restore_new/test.py @@ -1474,6 +1474,131 @@ def test_system_users_required_privileges(): instance.query("DROP USER u2") +# Access backups include every entity of a type, so these checks need this module's isolated server. +def test_restore_row_policy_replace_requires_scoped_drop(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROW POLICY ON test.table TO u2") + instance.query( + "CREATE ROW POLICY rowpol1 ON test.table AS RESTRICTIVE USING 1 TO ALL" + ) + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.row_policies TO {backup_name}") + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + + restore = f"RESTORE TABLE system.row_policies FROM {backup_name}" + select_filter = "SELECT select_filter FROM system.row_policies WHERE short_name = 'rowpol1' AND database = 'test' AND table = 'table'" + instance.query(f"{restore} SETTINGS create_access='if-not-exists'", user="u2") + assert instance.query(select_filter) == "owner = 1\n" + + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("GRANT DROP ROW POLICY ON test.another_table TO u2") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("DROP ROW POLICY rowpol1 ON test.table") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "" + + instance.query(f"{restore} SETTINGS create_access='create'", user="u2") + assert instance.query(select_filter) == "1\n" + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + instance.query("GRANT DROP ROW POLICY ON test.table TO u2") + instance.query(f"{restore} SETTINGS create_access='replace'", user="u2") + assert instance.query(select_filter) == "1\n" + + +@pytest.mark.parametrize( + "kind,system_table,target", [("USER", "users", "u1"), ("ROLE", "roles", "r1")] +) +def test_restore_access_partial_revoke_cannot_cancel_drop(kind, system_table, target): + instance.query(f"CREATE {kind} {target} SETTINGS max_threads = 1") + instance.query(f"GRANT DROP {kind} ON * TO {target}") + instance.query(f"REVOKE DROP {kind} ON {target} FROM {target}") + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.{system_table} TO {backup_name}") + instance.query(f"ALTER {kind} {target} SETTINGS max_threads = 2") + + # Create the actor after the backup so its grants cannot mask the target's partial revoke. + instance.query("CREATE USER u2") + instance.query(f"GRANT CREATE {kind} ON {target} TO u2") + instance.query(f"GRANT DROP {kind} ON * TO u2 WITH GRANT OPTION") + instance.query(f"REVOKE DROP {kind} ON {target} FROM u2") + restore = f"RESTORE TABLE system.{system_table} FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert f"DROP {kind}" in error + assert "max_threads = 2" in instance.query(f"SHOW CREATE {kind} {target}") + + # Ordinary `DROP` is sufficient; the target's grants exclude `DROP` on itself. + instance.query(f"GRANT DROP {kind} ON {target} TO u2") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query(f"SHOW CREATE {kind} {target}") + + +def test_restore_access_partial_revokes_preserve_grant_and_table_requirements(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("INSERT INTO test.table VALUES (1)") + instance.query("CREATE ROLE r1 SETTINGS max_threads = 1") + instance.query("GRANT SELECT, INSERT ON test.* TO r1 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM r1") + instance.query("REVOKE INSERT ON test.table FROM r1") + backup_name = new_backup_name() + backup_tables = "TABLE system.roles, TABLE test.table" + instance.query(f"BACKUP {backup_tables} TO {backup_name}") + instance.query("ALTER ROLE r1 SETTINGS max_threads = 2") + + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROLE, DROP ROLE ON r1 TO u2") + instance.query("GRANT CREATE TABLE ON test.table TO u2") + instance.query("GRANT SELECT, INSERT ON test.* TO u2 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM u2") + restore = f"RESTORE TABLE system.roles FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert "SELECT" in error + assert "WITH GRANT OPTION" in error + assert "max_threads = 2" in instance.query("SHOW CREATE ROLE r1") + + instance.query("GRANT SELECT ON test.table TO u2 WITH GRANT OPTION") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query("SHOW CREATE ROLE r1") + + instance.query("TRUNCATE TABLE test.table") + instance.query("REVOKE INSERT ON test.table FROM u2") + restore_with_table = ( + f"RESTORE {backup_tables} FROM {backup_name} SETTINGS create_access='replace'" + ) + error = instance.query_and_get_error(restore_with_table, user="u2") + assert "ACCESS_DENIED" in error + assert "INSERT" in error + assert instance.query("SELECT count() FROM test.table") == "0\n" + + instance.query("GRANT INSERT ON test.table TO u2") + instance.query(restore_with_table, user="u2") + assert instance.query("SELECT * FROM test.table") == "1\n" + + def test_system_users_async(): instance.query("CREATE USER u1 IDENTIFIED BY 'qwe123' SETTINGS custom_c = 3") diff --git a/tests/integration/test_crash_log/test.py b/tests/integration/test_crash_log/test.py index 3c11c28add8e..9990917c913c 100644 --- a/tests/integration/test_crash_log/test.py +++ b/tests/integration/test_crash_log/test.py @@ -55,9 +55,14 @@ def test_crash_log_synchronous(started_node): wait_for_clickhouse_stop(started_node) started_node.restart_clickhouse() crashes_count += 1 + # Report the rows that are there. Without them a lost row leaves only `'1' == '2'` behind, + # which says nothing about which of the two crashes failed to record itself. assert ( started_node.query("SELECT COUNT(*) FROM system.crash_log") == f"{crashes_count}\n" + ), started_node.query( + "SELECT event_time_microseconds, signal, signal_description, query " + "FROM system.crash_log ORDER BY event_time_microseconds FORMAT Vertical" ) diff --git a/tests/integration/test_database_glue/test.py b/tests/integration/test_database_glue/test.py index 585fe2899b5c..eac84dd81389 100644 --- a/tests/integration/test_database_glue/test.py +++ b/tests/integration/test_database_glue/test.py @@ -588,6 +588,62 @@ def test_timestamps(started_cluster): assert node.query(f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}`") == "2024-01-01 12:00:00.000000\t2024-01-01 12:00:00.000000\n" +def test_timestamp_types_cache_does_not_keep_metadata(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_ts_cache_{uuid.uuid4().hex}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + database_name = f"db_{test_ref}" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + schema = Schema( + NestedField(field_id=1, name="timestamp", field_type=TimestampType(), required=False), + NestedField(field_id=2, name="timestamptz", field_type=TimestamptzType(), required=False), + ) + table = create_table(catalog, root_namespace, table_name, schema, dir=test_ref) + + create_clickhouse_glue_database(started_cluster, node, database_name) + + def cache_metrics(): + return [ + int(value) + for value in node.query( + "SELECT value FROM system.metrics " + "WHERE metric IN ('GlueCatalogSchemaCacheBytes', 'GlueCatalogSchemaCacheEntries') ORDER BY metric" + ).split() + ] + + bytes_before, entries_before = cache_metrics() + + row = pa.Table.from_pylist( + [{"timestamp": datetime(2024, 1, 1, 12), "timestamptz": datetime(2024, 1, 1, 12, tzinfo=pytz.UTC)}] + ) + versions = 30 + for _ in range(versions): + table.append(row) + description = node.query(f"DESCRIBE TABLE {database_name}.`{root_namespace}.{table_name}`") + assert [line.split("\t")[1] for line in description.splitlines()] == [ + "Nullable(DateTime64(6))", + "Nullable(DateTime64(6, \\'UTC\\'))", + ] + + bytes_after, entries_after = cache_metrics() + assert entries_after - entries_before == versions + + metadata_size = int( + node.query( + f"SELECT max(_size) FROM s3('http://minio1:9001/warehouse-glue/{test_ref}/metadata/*.metadata.json', " + f"'{minio_access_key}', '{minio_secret_key}', 'One')" + ) + ) + assert bytes_after - bytes_before < metadata_size + + node.query(f"DROP DATABASE {database_name}") + + def test_insert(started_cluster): node = started_cluster.instances["node1"] diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index e979a99c18b8..fcdcf17d2989 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -806,3 +806,500 @@ def test_invalid_auth_header_format(started_cluster): """ ) assert "Invalid auth header format" in str(err.value) + + +def test_writes_mutate_update(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_update_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String, y Int32)") + + node.query(f"INSERT INTO {table_ref} VALUES ('123', 1);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456', 2);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('999', 3);", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\t1\n456\t2\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = '777' WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n777\t1\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'goshan dr' WHERE x = '777';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n999\t3\ngoshan dr\t1\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'pudge1000-7' WHERE y = 2;", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "999\t3\ngoshan dr\t1\npudge1000-7\t2\n" + + +def test_writes_mutate_delete(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_delete_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String)") + + # DELETE on empty table is a no-op. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "" + + node.query(f"INSERT INTO {table_ref} VALUES ('123');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('789'), ('890'), ('999');", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + # No-match DELETE keeps the table intact. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '789';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n890\n999\n" + + # Lightweight DELETE syntax should work identically against catalog tables. + node.query(f"DELETE FROM {table_ref} WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '999';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n" + + +def test_iceberg_file_progress_callback(started_cluster): + """ + Regression test for the `IcebergIterator::next` file-progress callback wiring (PR #105413). + + `IcebergIterator` stored a `FileProgressCallback` but never invoked it, so the + per-query `Progress.total_bytes_to_read` stayed at zero for Iceberg scans and + the progress bar showed no estimate. The fix invokes the callback with the data + file size for every object info returned. The assertion below uses the + `FileProgressCallbackInvocations` ProfileEvent, which is incremented inside the + callback lambda installed by `TCPHandler::setFileProgressCallback`, so removing + the `callback(...)` call in `IcebergIterator::next` makes this event stay at + zero for the test query. + """ + node = started_cluster.instances["node1"] + + test_ref = f"test_progress_callback_{uuid.uuid4().hex[:8]}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + table = create_table( + catalog, + root_namespace, + table_name, + DEFAULT_SCHEMA, + PartitionSpec(), + DEFAULT_SORT_ORDER, + ) + + # Append a small but non-empty batch so the iterator returns a data-file entry. + num_rows = 50 + data = [generate_record() for _ in range(num_rows)] + df = pa.Table.from_pylist(data) + table.append(df) + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + # `node.query` uses native TCP, the only protocol path where + # `setFileProgressCallback` is currently wired. `SELECT *` with `FORMAT Null` + # forces a full scan: the metadata-only `SELECT count()` path resolves the row + # count from manifest statistics and bypasses the data-file iterator. + query_id = f"iceberg_progress_callback_{uuid.uuid4().hex}" + node.query( + f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}` FORMAT Null", + query_id=query_id, + ) + + node.query("SYSTEM FLUSH LOGS") + + # `FileProgressCallbackInvocations` is incremented inside the lambda installed + # by `TCPHandler::setFileProgressCallback`. For an Iceberg-table scan it can + # only fire from `IcebergIterator::next` (the generic + # `StorageObjectStorageSource::KeysIterator` path is replaced by + # `IcebergIterator` for Iceberg storage), so a non-zero value proves the + # iterator's `callback(FileProgress(...))` invocation was executed. + profile_event_value = node.query( + f""" + SELECT ProfileEvents['FileProgressCallbackInvocations'] + FROM system.query_log + WHERE query_id = '{query_id}' AND type = 'QueryFinish' + ORDER BY event_time_microseconds DESC + LIMIT 1 + """ + ).strip() + assert profile_event_value, ( + f"`system.query_log` has no `QueryFinish` row for query_id={query_id}." + ) + file_progress_callback_invocations = int(profile_event_value) + assert file_progress_callback_invocations > 0, ( + f"Expected `FileProgressCallbackInvocations` > 0 from the Iceberg scan, " + f"got {file_progress_callback_invocations}. " + f"`IcebergIterator::next` did not invoke the file-progress callback " + f"(regression of PR #105413 wiring)." + ) + + +def test_alter_database_settings_not_supported(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"iceberg_alter_settings_{uuid.uuid4().hex}" + create_clickhouse_iceberg_database(started_cluster, node, db_name) + + fake_token = f"fake_secret_token_{uuid.uuid4().hex}" + + qid_alter = uuid.uuid4().hex + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = '{fake_token}'", + query_id=qid_alter, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING no_such_setting = 1" + ) + assert "BAD_ARGUMENTS" in error or "UNKNOWN_SETTING" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "other_warehouse" not in show_result + assert "onelake_bearer_token" not in show_result + node.query( + f"SELECT name FROM system.tables WHERE database = '{db_name}' SETTINGS show_data_lake_catalogs_in_system_tables = true" + ) + + node.query("SYSTEM FLUSH LOGS system.query_log") + logged_query = node.query( + f"SELECT arrayStringConcat(groupArray(query), '\\n') FROM system.query_log WHERE query_id = '{qid_alter}'" + ) + assert fake_token not in logged_query + assert "[HIDDEN]" in logged_query + + node.query(f"DROP DATABASE {db_name}") + + glue_db_name = f"glue_alter_settings_{uuid.uuid4().hex}" + node.query( + f""" + ATTACH DATABASE {glue_db_name} ENGINE = DataLakeCatalog('http://fake-glue:1') + SETTINGS catalog_type = 'glue', region = 'us-east-1', storage_endpoint = 'http://fake-glue:1/x' + """ + ) + error = node.query_and_get_error( + f"ALTER DATABASE {glue_db_name} MODIFY SETTING region = 'eu-west-1'" + ) + assert "NOT_IMPLEMENTED" in error + node.query(f"DROP DATABASE {glue_db_name}") + + +def test_alter_database_settings_rest_auth_header(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"rest_alter_auth_header_{uuid.uuid4().hex}" + old_header = f"Authorization: Bearer old_{uuid.uuid4().hex}" + new_header = f"Authorization: Bearer new_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-rest:1/api') + SETTINGS catalog_type = 'rest', warehouse = 'wh', auth_header = '{old_header}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING auth_header = '{new_header}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING catalog_credential = 'id:secret'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_header not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_header in engine_full_with_secrets + assert old_header not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_persistence(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_alter_persist_{uuid.uuid4().hex}" + old_token = f"secret_token_{uuid.uuid4().hex}" + new_token = f"secret_token_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-0', onelake_tenant_id = 'tenant-1', onelake_bearer_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_tenant_id = 'tenant-2', onelake_bearer_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_client_id = 'client-1'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = ''" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert new_token not in show_result + assert old_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert "tenant-2" in engine_full_with_secrets + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.restart_clickhouse() + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert "tenant-0" not in show_result + assert "tenant-1" not in show_result + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert "tenant-2" in engine_full + assert "tenant-0" not in engine_full + assert "tenant-1" not in engine_full + assert new_token not in engine_full + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_refresh_token(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_refresh_token_{uuid.uuid4().hex}" + old_token = f"refresh_token_{uuid.uuid4().hex}" + new_token = f"refresh_token_{uuid.uuid4().hex}" + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_refresh_token = '{old_token}' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', oauth_server_use_request_body = 0 + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "oauth_server_use_request_body" in error + + # In refresh-token mode the catalog access token is reused for Azure storage, + # so a non-storage auth_scope is rejected at CREATE time. + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', auth_scope = 'api://my-catalog/.default' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "auth_scope" in error + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_refresh_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = 'token'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert new_token not in engine_full + + node.query(f"DROP DATABASE {db_name}") + + +def test_catalog_listing_error_surfaces_in_system_tables(started_cluster): + """ + Regression test: an error from the catalog while listing tables (e.g. expired + catalog credentials) must not be silently turned into an empty listing when the + user explicitly opted into showing datalake catalogs in system tables with + show_data_lake_catalogs_in_system_tables=1. Without the opt-in the old tolerant + behaviour is kept (system tables must not fail because of one broken catalog). + """ + node = started_cluster.instances["node1"] + + root_namespace = f"clickhouse_{uuid.uuid4()}" + namespace = f"{root_namespace}_test_listing_error" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(namespace) + create_table(catalog, namespace, "table_x") + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + node.query("SYSTEM ENABLE FAILPOINT datalake_get_tables_throw") + try: + assert ( + node.query( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}'" + ).strip() + == "0" + ) + + error = node.query_and_get_error( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name, engine FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + finally: + node.query("SYSTEM DISABLE FAILPOINT datalake_get_tables_throw") + + result = node.query( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "table_x" in result + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") + + +def test_catalog_commit_conflict_reaches_caller_at_once(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_catalog_commit_conflict_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node, root_namespace, table_name, "(x UInt64)" + ) + + # Every sink reads the branch tip in its constructor, and all `max_insert_threads` sinks are + # constructed before the pipeline starts, so all but one of them commit against a stale parent + # and are refused with `409`. That makes the conflict a property of the plan rather than a race. + num_writers = 4 + query_id = uuid.uuid4().hex + node.query( + f"INSERT INTO {table_ref} SELECT number FROM numbers_mt(4000000)", + query_id=query_id, + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + "max_insert_threads": num_writers, + "max_threads": num_writers, + }, + ) + + node.query("SYSTEM FLUSH LOGS system.text_log") + + conflicts, http_requests = map( + int, + node.query( + f""" + SELECT + countIf(logger_name LIKE 'RestCatalog%' AND message LIKE '%updateMetadata conflict%'), + countIf(logger_name = 'ReadWriteBufferFromHTTP') + FROM system.text_log + WHERE query_id = '{query_id}' AND message LIKE '%409%' + """ + ).split(), + ) + + assert conflicts, ( + "no writer was refused, so nothing about conflict handling was exercised" + ) + assert http_requests == conflicts, ( + f"{conflicts} refused commit(s) cost {http_requests} catalog requests, so a conflict is " + f"resent with backoff instead of being handed back to the sink at once" + ) + + assert int(node.query(f"SELECT count() FROM {table_ref}")) == 4000000 + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") diff --git a/tests/integration/test_dotnet_client/test.py b/tests/integration/test_dotnet_client/test.py index 76778a84edbd..80fea52d791a 100644 --- a/tests/integration/test_dotnet_client/test.py +++ b/tests/integration/test_dotnet_client/test.py @@ -54,11 +54,14 @@ def test_dotnet_client(started_cluster, dotnet_container): reference = fp.read() code, (stdout, stderr) = dotnet_container.exec_run( - "dotnet run --host {host} --port {port} --user default --password 123 --database default".format( + "dotnet /client/out/clickhouse.test.dll --host {host} --port {port} --user default --password 123 --database default".format( host=started_cluster.get_instance_ip("node"), port=8123 ), demux=True, ) - assert code == 0 - assert stdout == reference + # These two streams exist nowhere else: the client runs in its own container and nothing in the + # job collects its output. Reporting them here is what makes a client that died on a signal + # diagnosable at all, instead of leaving a bare exit code behind. + assert code == 0, f"stdout:\n{stdout!r}\nstderr:\n{stderr!r}" + assert stdout == reference, f"stderr:\n{stderr!r}" diff --git a/tests/integration/test_git_import/test.py b/tests/integration/test_git_import/test.py index 13c76498e0a5..e1c6fc623d29 100644 --- a/tests/integration/test_git_import/test.py +++ b/tests/integration/test_git_import/test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import logging +import re import time import pytest @@ -40,8 +41,24 @@ def clone_git_repository(repo, dir, commit=None): time.sleep(1) +# `ClickHouseCluster` gives the whole container the running server's profraw merge pool +# (`LLVM_PROFILE_FILE=/debug/it-%c%4m.profraw`), which every `docker exec`-ed process inherits. +# A second writer cannot merge into a continuous-mode profile - it records its own writer's counter +# bias - so in a coverage build the profiling runtime writes +# `LLVM Profile Warning: Unable to merge profile data: source profile file is not compatible.` and +# two `File exists` errors to stderr. Give this one-shot process a file of its own: its coverage is +# still collected and it no longer touches the server's pool. +GIT_IMPORT_PROFILE_FILE = "/debug/git-import-%p.profraw" + +# One progress line per processed commit, which `git-import` writes to stderr. +COMMIT_PROGRESS_RE = re.compile(r"^\d+% \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [0-9a-f]{40} ") + + def run_git_import(dir): - command = f"cd {dir} && /usr/bin/clickhouse git-import 2>&1" + command = ( + f"cd {dir} && LLVM_PROFILE_FILE={GIT_IMPORT_PROFILE_FILE} " + "/usr/bin/clickhouse git-import 2>&1" + ) return node.exec_in_container(["bash", "-c", command]) @@ -176,7 +193,15 @@ def test_git_import(): create_tables() insert_into_tables(dir) - assert output.count("\n") == 26 + # `git-import` prints the `git log` command it runs and the commit count to stdout, and one + # progress line per commit to stderr, which the `2>&1` above merges into the same stream. Match + # those shapes instead of counting every newline, so that a line written by anything other than + # `git-import` - a profiling or sanitizer runtime, a loader warning - fails the thing it + # actually broke rather than this count. + lines = output.splitlines() + assert "git log --reverse --no-merges --pretty=%H" in lines, output + assert "Total 24 commits to process." in lines, output + assert sum(1 for line in lines if COMMIT_PROGRESS_RE.match(line)) == 24, output assert node.query("SELECT count() FROM commits") == "24\n" assert node.query("SELECT count() FROM file_changes") == "35\n" assert node.query("SELECT count(), round(avg(indent), 1) FROM line_changes") == TSV( diff --git a/tests/integration/test_keeper_remove_rejoin_leader/test.py b/tests/integration/test_keeper_remove_rejoin_leader/test.py index 8cb03c599d26..e51bbbdc7041 100644 --- a/tests/integration/test_keeper_remove_rejoin_leader/test.py +++ b/tests/integration/test_keeper_remove_rejoin_leader/test.py @@ -28,6 +28,7 @@ import json import os +import re import time import uuid from typing import NamedTuple @@ -132,6 +133,46 @@ def started_cluster(): pass +def _relax_timeouts_for_sanitizer(config_path): + """Rewrite a keeper config with relaxed Raft timeouts for sanitizer builds. + + Under sanitizers (ASan, MSan, TSan) CPU overhead can delay Raft + heartbeats enough to trigger spurious leader elections. This bumps + the heartbeat interval and election timeout so the cluster stays + stable even with 3-5x slowdown. + """ + with open(config_path) as f: + content = f.read() + + content = re.sub( + r"\d+", + "2000", + content, + ) + content = re.sub( + r"\d+", + "5000", + content, + ) + content = re.sub( + r"\d+", + "10000", + content, + ) + # Configs for nodes 1/2/3 omit election timeouts — add them. + if "" not in content: + content = re.sub( + r"([ \t]*)", + r"\g<1> 5000\n" + r"\g<1> 10000\n" + r"\g<1>", + content, + ) + + with open(config_path, "w") as f: + f.write(content) + + def send_rcfg(cluster, node, command, timeout_sec=60): result_str = keeper_utils.send_4lw_cmd( cluster, @@ -183,6 +224,30 @@ def test_leader_election_after_rolling_membership_change(started_cluster): for n in [node1, node2, node3]: keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Under sanitizers, Raft heartbeats can be delayed enough to trigger + # spurious leader elections. Detect and relax timeouts if needed. + if node1.is_built_with_sanitizer(): + # Patch all 6 config files on disk. Nodes 4/5/6 will pick them + # up later when start_keeper copies them into the container. + for i in range(1, 7): + _relax_timeouts_for_sanitizer( + os.path.join(CONFIG_DIR, _get_generated_cfg(node_names, i)) + ) + + # Rolling-restart nodes 1/2/3 so they pick up the relaxed + # timeouts. Only one node is down at a time, so quorum is kept. + for node_obj in [node1, node2, node3]: + cfg_name = _get_generated_cfg(node_names, node_id(node_obj)) + node_obj.stop_clickhouse() + node_obj.copy_file_to_container( + os.path.join(CONFIG_DIR, cfg_name), + "/etc/clickhouse-server/config.d/" + cfg_name, + ) + node_obj.start_clickhouse() + + for n in [node1, node2, node3]: + keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Identify the current leader and the two followers dynamically so the # test does not depend on which node wins the initial election. leader = keeper_utils.get_leader(cluster, [node1, node2, node3]) diff --git a/tests/integration/test_mask_sensitive_info/test.py b/tests/integration/test_mask_sensitive_info/test.py index 83dd82d92c8b..7f17c145e335 100644 --- a/tests/integration/test_mask_sensitive_info/test.py +++ b/tests/integration/test_mask_sensitive_info/test.py @@ -725,13 +725,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"icebergAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] # DeltaLake table functions are not available under Memory Sanitizer (Rust code is not instrumented) @@ -742,9 +742,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: @@ -764,13 +764,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"icebergAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_delta_lake: @@ -780,9 +780,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..362c39c90ed8 --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,11 @@ + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py new file mode 100644 index 000000000000..3996927d149f --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py @@ -0,0 +1,102 @@ +import pytest + +from helpers.cluster import ClickHouseCluster, QueryRuntimeException + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) + +TENANT = {"user": "tenant", "password": "tpass"} + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def test_scheduled_refresh_of_definer_view_carries_definer_to_remote_shard( + started_cluster, +): + # Protected data lives only on node2. The tenant exists on both nodes but has no grant on it. + node2.query( + """ + CREATE DATABASE lab; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + CREATE TABLE lab.secrets (id UInt64, payload String) ENGINE = MergeTree ORDER BY id; + INSERT INTO lab.secrets VALUES (1, 'a'), (2, 'b'), (3, 'c'); + """ + ) + # With `table_engines_require_grant = false`, `TABLE ENGINE ON Distributed` is revoked unless the + # user also has `READ` and `WRITE` on the `REMOTE` source. + node1.query( + """ + CREATE DATABASE tenant_db; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT CREATE TABLE, SELECT, INSERT ON tenant_db.* TO tenant; + GRANT TABLE ENGINE ON Distributed TO tenant; + GRANT READ, WRITE ON REMOTE TO tenant; + """ + ) + + node1.query( + """ + CREATE TABLE tenant_db.dist (id UInt64, payload String) + ENGINE = Distributed('secure', 'lab', 'secrets', rand()); + CREATE TABLE tenant_db.target + (id UInt64, payload String, current_user String, authenticated_user String) + ENGINE = MergeTree ORDER BY id; + """, + **TENANT, + ) + + # A direct read through the Distributed table is denied on the remote shard. + assert "ACCESS_DENIED" in node1.query_and_get_error( + "SELECT * FROM tenant_db.dist", **TENANT + ) + + # The shard also checks the allowed hosts of the definer against `initial_address`. A scheduled + # refresh has no client, so it must present itself as coming from the local host of the + # initiator rather than from the unspecified address, which only `HOST ANY` users accept. + node2.query("ALTER USER tenant HOST LOCAL") + + # The refresh runs under the definer's identity and must be denied on the remote shard too. + # Before the fix, the refresh query was sent with an empty `initial_user`, which the remote + # shard treated as interserver mode and executed without any access checks. + node1.query( + """ + CREATE MATERIALIZED VIEW tenant_db.rmv REFRESH EVERY 1 YEAR APPEND TO tenant_db.target + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT id, payload, currentUser() AS current_user, authenticatedUser() AS authenticated_user + FROM tenant_db.dist; + """, + **TENANT, + ) + + with pytest.raises(QueryRuntimeException, match="ACCESS_DENIED"): + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT count() FROM tenant_db.target") == "0\n" + assert "ACCESS_DENIED" in node1.query( + "SELECT exception FROM system.view_refreshes WHERE database = 'tenant_db' AND view = 'rmv'" + ) + + # Once the definer is granted access on the remote shard, the refresh succeeds and the remote + # shard sees the definer as the current and authenticated user. + node2.query("GRANT SELECT ON lab.secrets TO tenant") + node1.query("SYSTEM REFRESH VIEW tenant_db.rmv") + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT * FROM tenant_db.target ORDER BY id", **TENANT) == ( + "1\ta\ttenant\ttenant\n2\tb\ttenant\ttenant\n3\tc\ttenant\ttenant\n" + ) diff --git a/tests/integration/test_restore_replica_metadata_version/test.py b/tests/integration/test_restore_replica_metadata_version/test.py index b35af4075c11..4fc23ce116ae 100644 --- a/tests/integration/test_restore_replica_metadata_version/test.py +++ b/tests/integration/test_restore_replica_metadata_version/test.py @@ -36,6 +36,79 @@ def start_cluster(): cluster.shutdown() +def test_alter_after_concurrent_restore(start_cluster): + zk = cluster.get_kazoo_client("zoo1") + table = "test_concurrent_restore" + zk_path = f"/clickhouse/tables/{table}" + failpoint = "rmt_restore_replica_pause_before_metadata_version_raise" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + for node in [node_1, node_2]: + node.query( + f"CREATE TABLE {table} (n UInt32) " + f"ENGINE = ReplicatedMergeTree('{zk_path}/', '{node.name}') ORDER BY n" + ) + + # Two ALTERs bring the metadata version of the table, and of the part inserted after them, to 2 + for column in ["a", "b"]: + node_1.query( + f"ALTER TABLE {table} ADD COLUMN {column} UInt32", + settings={"alter_sync": 2}, + ) + node_1.query(f"INSERT INTO {table} VALUES (1, 1, 1)") + node_2.query(f"SYSTEM SYNC REPLICA {table}") + for node in [node_1, node_2]: + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + zk_rmr_with_retries(zk, zk_path) + for node in [node_1, node_2]: + node.query(f"SYSTEM RESTART REPLICA {table}") + + # Restore both replicas at the same time, as ON CLUSTER does: node_1 stops after it has + # restored the table in Keeper, before it raises the metadata version to the one of its part, + # and node_2 restores in the meantime by copying node_1 + node_1.query(f"SYSTEM ENABLE FAILPOINT {failpoint}") + restore = node_1.get_query_request(f"SYSTEM RESTORE REPLICA {table}") + node_1.query(f"SYSTEM WAIT FAILPOINT {failpoint} PAUSE") + node_2.query(f"SYSTEM RESTORE REPLICA {table}") + assert ( + node_2.query(f"SELECT is_readonly FROM system.replicas WHERE table = '{table}'") + == "0\n" + ) + node_1.query(f"SYSTEM DISABLE FAILPOINT {failpoint}") + restore.get_answer() + + for node in [node_1, node_2]: + node.query(f"SYSTEM SYNC REPLICA {table}") + + _, stat = zk.get(f"{zk_path}/metadata") + assert stat.version == 2 + for node in [node_1, node_2]: + version, _ = zk.get(f"{zk_path}/replicas/{node.name}/metadata_version") + assert version == b"2" + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + # A replica left below the metadata version of the table rejects every ALTER with CANNOT_ASSIGN_ALTER + node_2.query(f"ALTER TABLE {table} ADD COLUMN c UInt32", settings={"alter_sync": 2}) + node_1.query(f"ALTER TABLE {table} ADD COLUMN d UInt32", settings={"alter_sync": 2}) + for node in [node_1, node_2]: + assert node.query(f"SELECT n, a, b, c, d FROM {table}") == "1\t1\t1\t0\t0\n" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + + def test_fix_metadata_version_on_attach_part_after_restore(start_cluster): zk = cluster.get_kazoo_client("zoo1") diff --git a/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py new file mode 100644 index 000000000000..d90720f797bd --- /dev/null +++ b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py @@ -0,0 +1,99 @@ +""" +An Iceberg manifest-list entry may declare any `manifest_length`. Reading such a table must not +depend on that number: it used to become the metadata cache cell weight and terminate the server. +""" +import os +import shutil +import tempfile + +from helpers.iceberg_utils import get_uuid_str +from test_storage_iceberg_no_spark.test_local_path_traversal import ( + _download_table_from_container, + _get_manifest_paths_from_chain, + _modify_avro_file, +) + +NOCACHE = { + "use_iceberg_metadata_files_cache": False, + "use_parquet_metadata_cache": False, +} +CACHE = {"use_iceberg_metadata_files_cache": True} +HUGE_MANIFEST_LENGTH = 2**62 + + +def _make_table_with_manifest_length(instance, table_name, table_path, new_length): + """Build a well-formed IcebergLocal table with the cache off, then rewrite every + manifest-list entry's `manifest_length`. new_length=None rewrites the file without + changing the value. Returns the manifest files' real total size on disk.""" + instance.query( + f"CREATE TABLE {table_name} (c0 Int) ENGINE = IcebergLocal('{table_path}/', 'Parquet');", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + instance.query( + f"INSERT INTO {table_name} VALUES (1), (2), (3)", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + assert instance.query(f"SELECT count() FROM {table_name}", settings=NOCACHE).strip() == "3" + instance.query(f"DROP TABLE {table_name}") + + temp_dir = tempfile.mkdtemp() + try: + host_path = os.path.join(temp_dir, table_name) + os.makedirs(host_path, exist_ok=True) + _download_table_from_container(instance, table_path, host_path) + manifest_list_rel, manifest_rels = _get_manifest_paths_from_chain(host_path, table_path) + local_manifest_list = os.path.join(host_path, manifest_list_rel) + _modify_avro_file( + local_manifest_list, + ["manifest_length"], + (lambda v: v) if new_length is None else (lambda _: new_length), + ) + instance.copy_file_to_container(local_manifest_list, f"{table_path}/{manifest_list_rel}") + return sum(os.path.getsize(os.path.join(host_path, rel)) for rel in manifest_rels) + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + + +def _read_back(instance, table_path): + """Read with the metadata cache ON, from a cold cache: the cache-miss path is the only + one that builds the cell whose weight the declared length used to set. Returns the + query results plus the cache weight those reads produced.""" + instance.query("SYSTEM DROP ICEBERG METADATA CACHE") + count = instance.query(f"SELECT count() FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + total = instance.query(f"SELECT sum(c0) FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + weight = instance.query( + "SELECT value FROM system.metrics WHERE metric = 'IcebergMetadataFilesCacheBytes'" + ).strip() + return count, total, int(weight) + + +def _assert_weighed_by_real_size(weight, manifest_bytes): + """A manifest is charged three times its size on storage, so the total must clear that + bound. Reading the size from the file rather than hardcoding it keeps this stable while + still failing if the weight ever comes from something other than the real size.""" + assert weight >= 3 * manifest_bytes, f"weight {weight} < 3 * {manifest_bytes}" + + +def test_iceberg_rewritten_manifest_list_is_readable(started_cluster_iceberg_no_spark): + """Control for the test below: the same Avro round-trip with the declared length + untouched. It runs first so that a regression of the fix, which aborts the server and + makes every later query in the package fail to connect, cannot mask this result.""" + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_manifest_list_roundtrip" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length(instance, table_name, table_path, None) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) + + +def test_iceberg_huge_manifest_length_is_readable(started_cluster_iceberg_no_spark): + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_huge_manifest_length" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length( + instance, table_name, table_path, HUGE_MANIFEST_LENGTH + ) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) diff --git a/tests/integration/test_storage_s3/test.py b/tests/integration/test_storage_s3/test.py index eb975f052251..be913f27a387 100644 --- a/tests/integration/test_storage_s3/test.py +++ b/tests/integration/test_storage_s3/test.py @@ -2683,6 +2683,41 @@ def test_page_cache(started_cluster): assert 0 < int(gets) +def test_cache_key_includes_storage(started_cluster): + # The same key with the same content, so the same ETag, in another bucket or behind another endpoint: + # the filesystem cache and the page cache must not serve it the entry filled by the first object. + instance = started_cluster.instances["dummy"] + table_name = f"test_cache_key_includes_storage-{uuid.uuid4()}" + host = f"{started_cluster.minio_host}:{started_cluster.minio_port}" + ip = f"{started_cluster.minio_ip}:{started_cluster.minio_port}" + + for bucket in [started_cluster.minio_bucket, started_cluster.minio_bucket_2]: + instance.query( + f"insert into function s3('http://{host}/{bucket}/{table_name}.tsv', auto, 'x UInt64') select number from numbers(100) SETTINGS s3_truncate_on_insert=1" + ) + + urls = [ + f"http://{host}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{ip}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{host}/{started_cluster.minio_bucket_2}/{table_name}.tsv", + ] + for settings in ["filesystem_cache_name = 'cache1', enable_filesystem_cache=1", "use_page_cache_for_object_storage=1"]: + for url in urls: + query_id = f"{table_name}-{uuid.uuid4()}" + assert "100\n" == instance.query( + f"select sum(ignore(*) + 1) from s3('{url}', 'TSV', 'x UInt64') SETTINGS {settings}", + query_id=query_id, + ) + + instance.query("SYSTEM FLUSH LOGS") + + assert 0 < int( + instance.query( + f"SELECT ProfileEvents['S3GetObject'] FROM system.query_log WHERE query_id = '{query_id}' AND type = 'QueryFinish'" + ) + ) + + def test_archive(started_cluster): id = uuid.uuid4() bucket = started_cluster.minio_bucket diff --git a/tests/integration/test_storage_url/test.py b/tests/integration/test_storage_url/test.py index 8c7bc908f932..fa68686b1f67 100644 --- a/tests/integration/test_storage_url/test.py +++ b/tests/integration/test_storage_url/test.py @@ -115,7 +115,8 @@ def test_table_function_url_access_rights(): f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1" ) - node1.query("GRANT READ ON URL TO u1") + # Like `SELECT`, `DESCRIBE` of a table function also needs `CREATE TEMPORARY TABLE`. + node1.query("GRANT READ ON URL, CREATE TEMPORARY TABLE ON *.* TO u1") assert node1.query( f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1", diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py b/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml new file mode 100644 index 000000000000..0b5411455b46 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml @@ -0,0 +1,6 @@ + + + root + clickhouse + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..af0b7ad21cab --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,14 @@ + + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml new file mode 100644 index 000000000000..ae00b3b543f9 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + ::/0 + + default + default + 1 + + + + + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/test.py b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py new file mode 100644 index 000000000000..f14f501904b5 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py @@ -0,0 +1,299 @@ +# pylint: disable=unused-argument +# pylint: disable=redefined-outer-name +# pylint: disable=line-too-long + +""" +Pushes from streaming engines into a `Distributed` table must reach the shard under the definer. + +`Kafka`, `RabbitMQ` and the other streaming engines never write anywhere themselves: a consumed +batch is pushed only into the dependent materialized views, from a copy of the global context that +has no user. A view with `SQL SECURITY DEFINER` switches that push to the definer. When the view's +target is a `Distributed` table over a cluster with an interserver ``, the definer's name +must travel with the query: before the fix `Context::setUser` left the `ClientInfo` user names +empty, the shard received an empty `initial_user`, treated the query as interserver mode and +executed it with full access. A tenant that could create tables only in its own database could +chain `Kafka -> MATERIALIZED VIEW -> Distributed('secure', default, secret_data)` and write into +a table on the shard it had no `INSERT` grant on. + +The `secure` cluster consists of `node2` only, so a table on `node1` can reach `default.secret_data` +solely over the interserver connection. Every pipeline is built twice with the same statements: by +`tenant`, who has no grants on `node2` and whose rows must be rejected there, and by `writer`, who +has `INSERT` on the target and whose rows must arrive. In both cases the shard must see the +definer's name in `system.query_log`. + +The push is also checked with `distributed_foreground_insert = 0`, where the rows go through the +background directory queue of the `Distributed` table: the persisted insert must keep the definer's +name, although the streaming context has `query_kind = NO_QUERY`. +""" + +import json +import time + +import pika +import pytest + +import helpers.kafka.common as k +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml", "configs/rabbitmq.xml"], + user_configs=["configs/users.xml"], + with_kafka=True, + with_rabbitmq=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + user_configs=["configs/users.xml"], +) + +WRITER = "writer" +TENANT = "tenant" +CREDENTIALS = { + WRITER: {"user": WRITER, "password": "wpass"}, + TENANT: {"user": TENANT, "password": "tpass"}, +} +ROWS_PER_PIPELINE = 2 + +# How long a streaming engine gets to consume the messages and push them to the shard. Consumer +# group setup in Kafka alone can take several seconds. +DELIVERY_WAIT_SECONDS = 60 + +users = pytest.mark.parametrize("user", [WRITER, TENANT]) + + +def database(user): + return f"{user}_db" + + +def query_as(user, sql): + return node1.query(sql, **CREDENTIALS[user]) + + +def remote_rows(): + return int(node2.query("SELECT count() FROM default.secret_data")) + + +def shard_inserts(user, condition): + """Number of `INSERT` queries into the protected table that the shard executed under `user`.""" + node2.query("SYSTEM FLUSH LOGS") + return int( + node2.query( + f""" + SELECT count() FROM system.query_log + WHERE user = '{user}' AND query LIKE 'INSERT INTO default.secret_data%' AND {condition} + """ + ) + ) + + +def shard_finished_inserts(user): + return shard_inserts(user, "type = 'QueryFinish'") + + +def shard_denied_inserts(user): + # The access check happens before the pipeline starts, so the shard logs the denial as + # `ExceptionBeforeStart`. + return shard_inserts( + user, + "type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing') AND exception_code = 497", + ) + + +def wait_until(condition, timeout=DELIVERY_WAIT_SECONDS): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(1) + return False + + +@pytest.fixture(scope="module", autouse=True) +def started_cluster(): + try: + cluster.start() + + # The protected table lives on the shard only. Both users exist on both nodes, but on + # the shard only `writer` may insert into it. + node2.query( + """ + CREATE TABLE default.secret_data (key Int) ENGINE = MergeTree ORDER BY key; + CREATE USER writer IDENTIFIED WITH plaintext_password BY 'wpass'; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT INSERT ON default.secret_data TO writer; + """ + ) + for user in (WRITER, TENANT): + db = database(user) + # Send to the shard synchronously by default, so that a push either delivers the rows + # or fails right away, without a background directory queue in between. + # With `table_engines_require_grant = false`, `TABLE ENGINE` on a source engine is + # revoked unless the user also has `READ` and `WRITE` on its source. + node1.query( + f""" + CREATE USER {user} IDENTIFIED WITH plaintext_password BY '{CREDENTIALS[user]["password"]}' + SETTINGS distributed_foreground_insert = 1; + CREATE DATABASE {db}; + GRANT ALL ON {db}.* TO {user}; + GRANT TABLE ENGINE ON Distributed, TABLE ENGINE ON Kafka, TABLE ENGINE ON RabbitMQ TO {user}; + GRANT READ, WRITE ON REMOTE, READ, WRITE ON KAFKA, READ, WRITE ON RABBITMQ TO {user}; + """ + ) + query_as( + user, + f"CREATE TABLE {db}.dist (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + + yield cluster + finally: + cluster.shutdown() + + +@pytest.fixture(autouse=True) +def clean_remote_table(): + node2.query("TRUNCATE TABLE default.secret_data") + yield + + +def drop_pipeline(user, source): + """Stop the streaming table, so that a rejected push is not retried into the next test.""" + db = database(user) + query_as(user, f"DROP TABLE {db}.{source}_to_dist") + query_as(user, f"DROP TABLE {db}.{source} SYNC") + + +def create_definer_view(user, source, target="dist"): + """A view owned by `user` that pushes the source rows into the user's `Distributed` table.""" + db = database(user) + query_as( + user, + f""" + CREATE MATERIALIZED VIEW {db}.{source}_to_dist TO {db}.{target} + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT key FROM {db}.{source} + """, + ) + + +def check_delivery(user, finished_before, denied_before): + """The shard must have executed the push under the user's name, with the outcome the user's + grants dictate: the rows arrive for `writer` and are rejected for `tenant`.""" + if user == WRITER: + assert wait_until(lambda: remote_rows() == ROWS_PER_PIPELINE) + assert shard_finished_inserts(WRITER) > finished_before + else: + assert wait_until( + lambda: shard_denied_inserts(TENANT) > denied_before or remote_rows() > 0 + ) + assert remote_rows() == 0 + assert shard_denied_inserts(TENANT) > denied_before + + +def check_direct_insert(user): + """The control case: a direct `INSERT` carries the user's name to the shard, where it is checked. + + It passes without the fix as well, so it is not a separate test: bugfix validation requires every + new test to fail on the unfixed binary. It runs before a streaming pipeline instead.""" + db = database(user) + if user == WRITER: + query_as(WRITER, f"INSERT INTO {db}.dist VALUES (1)") + assert remote_rows() == 1 + else: + error = node1.query_and_get_error( + f"INSERT INTO {db}.dist VALUES (1)", **CREDENTIALS[TENANT] + ) + assert "ACCESS_DENIED" in error + assert remote_rows() == 0 + node2.query("TRUNCATE TABLE default.secret_data") + + +@users +@pytest.mark.parametrize("foreground", [1, 0]) +def test_kafka(user, foreground): + db = database(user) + topic = f"definer_interserver_{user}_{foreground}" + k.kafka_create_topic(k.get_admin_client(cluster), topic) + + query_as( + user, + f""" + CREATE TABLE {db}.kafka (key Int) ENGINE = Kafka + SETTINGS kafka_broker_list = 'kafka1:19092', + kafka_topic_list = '{topic}', + kafka_group_name = '{topic}', + kafka_format = 'JSONEachRow', + kafka_flush_interval_ms = 1000 + """, + ) + # A separate `Distributed` table per mode, so that a rejected file left in the background queue + # is dropped together with the table and is not retried into the next test. + target = f"dist_{foreground}" + query_as( + user, + f"CREATE TABLE {db}.{target} (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + # The definer's settings apply to the push. It is not set in the server's profile, because the + # settings of the context the push starts from would override the definer's ones. + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = {foreground}") + create_definer_view(user, "kafka", target) + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + k.kafka_produce( + cluster, topic, [json.dumps({"key": i}) for i in range(ROWS_PER_PIPELINE)] + ) + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "kafka") + query_as(user, f"DROP TABLE {db}.{target} SYNC") + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = 1") + + +@users +def test_rabbitmq(user): + check_direct_insert(user) + db = database(user) + exchange = f"definer_interserver_{user}" + + query_as( + user, + f""" + CREATE TABLE {db}.rabbitmq (key Int) ENGINE = RabbitMQ + SETTINGS rabbitmq_host_port = 'rabbitmq1:5672', + rabbitmq_exchange_name = '{exchange}', + rabbitmq_format = 'JSONEachRow', + rabbitmq_flush_interval_ms = 1000, + rabbitmq_max_block_size = 100 + """, + ) + create_definer_view(user, "rabbitmq") + + # The exchange and the queue are declared by the table in the background; messages + # published before that are dropped by RabbitMQ. + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: RabbitMQ setup completed") + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: Queue .* is declared") + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + + credentials = pika.PlainCredentials("root", "clickhouse") + parameters = pika.ConnectionParameters( + cluster.rabbitmq_ip, cluster.rabbitmq_port, "/", credentials + ) + connection = pika.BlockingConnection(parameters) + channel = connection.channel() + for i in range(ROWS_PER_PIPELINE): + channel.basic_publish( + exchange=exchange, routing_key="", body=json.dumps({"key": i}) + ) + connection.close() + + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "rabbitmq") diff --git a/tests/integration/test_totp_auth/test_totp.py b/tests/integration/test_totp_auth/test_totp.py index d682ecf94848..7aa30c96a53c 100644 --- a/tests/integration/test_totp_auth/test_totp.py +++ b/tests/integration/test_totp_auth/test_totp.py @@ -98,9 +98,37 @@ def test_one_time_password(started_cluster): query_text, user="totuser", password=f"aa+bb+{old_password}" ) - assert "REQUIRED_SECOND_FACTOR" in node.query_and_get_error( - query_text, user="totuser", password=f"aa+bb" + # Without a code the response does not depend on the password, so the error REQUIRED_SECOND_FACTOR + # does not confirm a guessed password: a wrong or an empty password gets exactly the same error + error_without_code = node.query_and_get_error( + query_text, user="totuser", password="aa+bb" ) + assert "REQUIRED_SECOND_FACTOR" in error_without_code + for password in ["wrongpwd", ""]: + assert error_without_code == node.query_and_get_error( + query_text, user="totuser", password=password + ) + + http_responses = [ + node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": password}, + ) + for password in ["aa+bb", "wrongpwd"] + ] + for response in http_responses: + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "767" + assert http_responses[0].text == http_responses[1].text + + response = node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": "aa+bb+000000000"}, + ) + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "516" assert "totuser42\n" == node.query( query_text, user="totuser", password=f"aa+bb+{get_otp('totuser')}" @@ -196,13 +224,17 @@ def test_interactive_totp_authentication(started_cluster): # Then enter wrong TOTP when prompted c.expect("TOTP.*:") - c.send(f"000000", eol="\r") + c.send("000000000", eol="\r") c.expect(expected_error) - with client(command=f"{client_command(user0)} --password aa+bb+000000") as c: + # A wrong code of the configured length (9 digits); a suffix of another length counts as no code + with client(command=f"{client_command(user0)} --password aa+bb+000000000") as c: c.expect(expected_error) + # A wrong password without a code is asked for the code like a right one, and fails only after that with client(command=f"{client_command(user0)} --password wrongpwd") as c: + c.expect("TOTP.*:") + c.send(get_otp(user0), eol="\r") c.expect(expected_error) with client( @@ -370,7 +402,10 @@ def test_one_time_only_no_password(started_cluster): assert f"{user0}42\n" == node.query(query_text, user=user0, password=get_otp(user0)) + # The client cannot know that the account has no password: it asks for the password first with client(command=f"{client_command(user0)}") as c: + c.expect("Password.*:") + c.send("", eol="\r") c.expect("TOTP.*:") c.send(get_otp(user0, offset_steps=1), eol="\r") c.expect(prompt) diff --git a/tests/performance/map_bucketed_serialization.xml b/tests/performance/map_bucketed_serialization.xml index d86c681a4f3b..e5016ad60d46 100644 --- a/tests/performance/map_bucketed_serialization.xml +++ b/tests/performance/map_bucketed_serialization.xml @@ -1,6 +1,6 @@ @@ -107,7 +107,7 @@ CREATE TABLE map_subcol_pw_mixed (id UInt64, tags Map(String, String), value UInt32) @@ -126,7 +126,7 @@ OPTIMIZE TABLE map_subcol_pw_mixed FINAL SETTINGS mutations_sync=1 - diff --git a/tests/performance/prewhere_subcolumn_read_steps.xml b/tests/performance/prewhere_subcolumn_read_steps.xml new file mode 100644 index 000000000000..04cb68d9dd07 --- /dev/null +++ b/tests/performance/prewhere_subcolumn_read_steps.xml @@ -0,0 +1,19 @@ + + + 0 + + + CREATE TABLE t_prewhere_json (id UInt64, j JSON(max_dynamic_paths = 0)) ENGINE = MergeTree ORDER BY id + CREATE TABLE t_prewhere_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0 + + INSERT INTO t_prewhere_json SELECT number, concat('{{"kind":"a","n":', toString(number), ',"payload":"', repeat('x', 2000), '"}}') FROM numbers_mt(3000000) + INSERT INTO t_prewhere_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> repeat('v', 60), range(16))) FROM numbers_mt(10000000) + + + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j)) > 10 + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 + SELECT count() FROM t_prewhere_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 + + DROP TABLE IF EXISTS t_prewhere_json + DROP TABLE IF EXISTS t_prewhere_map + diff --git a/tests/queries/0_stateless/00900_long_parquet_load_2.sh b/tests/queries/0_stateless/00900_long_parquet_load_2.sh index dc8d68888463..b58b54143176 100755 --- a/tests/queries/0_stateless/00900_long_parquet_load_2.sh +++ b/tests/queries/0_stateless/00900_long_parquet_load_2.sh @@ -47,6 +47,10 @@ EXCLUDE=( # malformed on purpose, so loading it here would print an exception. 05035_delta_byte_array_zero_values.parquet 05035_delta_byte_array_decimal.parquet + # `INT96` timestamps outside the `DateTime64(9)` range (throws with the default `date_time_overflow_behavior`), tested by 05443. + 05443_int96_out_of_range.parquet + # `INT96` timestamp on the lower boundary day of the `DateTime64(9)` range, tested by 05444. + 05444_int96_lower_boundary.parquet ) for NAME in $(find "$DATA_DIR" -type f \( -iname '*.parquet' -o -iname '*.parquet.gz' \) -print0 | xargs -0 -n 1 basename | LC_ALL=C sort | grep -vFf <(printf '%s\n' "${EXCLUDE[@]}")); do diff --git a/tests/queries/0_stateless/01035_avg.reference b/tests/queries/0_stateless/01035_avg.reference index 1f47b3a8b7ea..192bceec0560 100644 --- a/tests/queries/0_stateless/01035_avg.reference +++ b/tests/queries/0_stateless/01035_avg.reference @@ -1,6 +1,6 @@ nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan --0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.493856 32355.57552 499999.5 499999.5 499999.5 499999.5 499999.5 499999.5 -0.000500002 0.49999949943727 -0.000005 -0.000004999999999999992 --2767.546272 -999999 --0.50000449943727 +-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.467744 31470.715104 124999.5 124999.5 124999.5 124999.5 124999.5 124999.5 -0.0005000056 0.12499949943764 -0.000005000000000000001 -0.0000050000000000000334 +-3182.944672 +249999 +-0.12500449943764 1 1 \N \N 1 1 diff --git a/tests/queries/0_stateless/01035_avg.sql b/tests/queries/0_stateless/01035_avg.sql index 0f7baddaec57..a8aae4480e66 100644 --- a/tests/queries/0_stateless/01035_avg.sql +++ b/tests/queries/0_stateless/01035_avg.sql @@ -27,7 +27,7 @@ SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(f32), avg(f64), avg(d32), avg(d64), avg(d128), avg(d256) FROM test_01035_avg; -INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 1000000; +INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 250000; SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(u8), avg(u16), avg(u32), avg(u64), avg(u128), avg(u256), diff --git a/tests/queries/0_stateless/01252_weird_time_zone.reference b/tests/queries/0_stateless/01252_weird_time_zone.reference index 90f5bf0e30dd..a93b19a6dd70 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.reference +++ b/tests/queries/0_stateless/01252_weird_time_zone.reference @@ -5,3 +5,41 @@ Pacific/Kwajalein 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Apia 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Enderbury 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Fakaofo 2020-01-02 03:04:05 2020-01-02 00:00:00 3 +--- offset of zones that crossed the international date line +Pacific/Kiritimati 50400 +Pacific/Apia 46800 +Pacific/Fakaofo 46800 +Pacific/Enderbury 46800 +Pacific/Kanton 46800 +Pacific/Kwajalein 43200 +Kwajalein 43200 +--- the same zones before their jump, and a +13:45 zone, must not move +Pacific/Apia -39600 +Pacific/Fakaofo -39600 +Pacific/Chatham 49500 +Pacific/Chatham 45900 +--- negative offsets before the epoch +Africa/Abidjan -968 +Africa/Accra -52 +Africa/Addis_Ababa 9320 +Europe/Moscow 9017 +--- parseDateTime agrees with toDateTime on an affected zone +1 +1 +1 +1 +1 +1 +--- other consumers of the offset ++1400 +2025-06-14 22:00:00 2025-06-16 02:00:00 +2025-06-14 22:00:00.500 2025-06-16 02:00:00.500 +--- consumers that reduce the offset modulo a day must be unaffected +12:00:00 12:00:00.500 +1970-01-02 12:00:00 2025-06-15 00:00:00 12 2025-06-15 +--- daylight saving transitions keep their sub-day offset +-18000 -14400 -18000 +--- inside and outside the lookup table window report the same offset +1 +--- every zone agrees with rendering the instant as local text and reading it back as UTC +0 diff --git a/tests/queries/0_stateless/01252_weird_time_zone.sql b/tests/queries/0_stateless/01252_weird_time_zone.sql index c4919ca4fe01..729eea83216d 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.sql +++ b/tests/queries/0_stateless/01252_weird_time_zone.sql @@ -13,3 +13,56 @@ SELECT 'Pacific/Kwajalein', rand() as r, toHour(toDateTime(r, 'Pacific/Kwajalein SELECT 'Pacific/Apia', rand() as r, toHour(toDateTime(r, 'Pacific/Apia') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Enderbury', rand() as r, toHour(toDateTime(r, 'Pacific/Enderbury') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Fakaofo', rand() as r, toHour(toDateTime(r, 'Pacific/Fakaofo') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; + +-- timezoneOffset must report the true UTC offset, including its whole-day component (issue #115281). +SELECT '--- offset of zones that crossed the international date line'; +SELECT 'Pacific/Kiritimati', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Enderbury', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Enderbury')); +SELECT 'Pacific/Kanton', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kanton')); +SELECT 'Pacific/Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kwajalein')); +SELECT 'Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Kwajalein')); + +SELECT '--- the same zones before their jump, and a +13:45 zone, must not move'; +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Chatham')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Chatham')); + +SELECT '--- negative offsets before the epoch'; +SELECT 'Africa/Abidjan', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Abidjan')); +SELECT 'Africa/Accra', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Accra')); +SELECT 'Africa/Addis_Ababa', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Addis_Ababa')); +SELECT 'Europe/Moscow', timeZoneOffset(toDateTime64(-1900000000, 0, 'Europe/Moscow')); + +SELECT '--- parseDateTime agrees with toDateTime on an affected zone'; +SELECT toUnixTimestamp(parseDateTime('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeOrNull('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTime64('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00', 'yyyy-MM-dd HH:mm:ss', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeBestEffort('2025-06-15 12:00:00', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00 Pacific/Kiritimati', 'yyyy-MM-dd HH:mm:ss z')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- other consumers of the offset'; +SELECT formatDateTime(toDateTime64(1750000000, 0, 'UTC'), '%z', 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'); + +SELECT '--- consumers that reduce the offset modulo a day must be unaffected'; +SELECT CAST(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati') AS Time), CAST(toDateTime64('2025-06-15 12:00:00.5', 3, 'Pacific/Kiritimati') AS Time64(3)); +SELECT toTime(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toStartOfDay(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toHour(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toDate(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- daylight saving transitions keep their sub-day offset'; +SELECT timeZoneOffset(toDateTime('2025-03-09 01:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-03-09 03:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-11-02 03:00:00', 'America/New_York')); + +SELECT '--- inside and outside the lookup table window report the same offset'; +SELECT timeZoneOffset(toDateTime64(1750000000, 0, 'Pacific/Kiritimati')) = timeZoneOffset(toDateTime64(90000000000, 0, 'Pacific/Kiritimati')); + +SELECT '--- every zone agrees with rendering the instant as local text and reading it back as UTC'; +WITH + arrayJoin([toDateTime64(1262347200, 0, 'UTC'), toDateTime64(1750000000, 0, 'UTC'), toDateTime64(2000000000, 0, 'UTC')]) AS ts, + formatDateTime(ts, '%z', time_zone) AS z, + (toInt64(substring(z, 2, 2)) * 3600 + toInt64(substring(z, 4, 2)) * 60) * multiIf(substring(z, 1, 1) = '-', -1, 1) AS reported, + toInt64(toDateTime(formatDateTime(ts, '%Y-%m-%d %H:%i:%S', time_zone), 'UTC')) - toInt64(ts) AS expected +SELECT count() FROM system.time_zones WHERE reported != expected; diff --git a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference index d771371b2644..0eb78aef3648 100644 --- a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference +++ b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference @@ -1 +1 @@ -0bedc9eaf0b07ce14f59ffd25e1a6df6 - +75b5b0cbd2734c37f4f02bd726c4ea60 - diff --git a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh index a44ae6f1e95a..960f2f03174f 100755 --- a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh +++ b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash -# Tags: distributed +# Tags: distributed, no-llvm-coverage +# no-llvm-coverage: the test needs the shard accumulating `repeat('a', 100000)` per row to hit +# `max_memory_usage=1G` and emit `Query memory limit exceeded` before the other shard cancels. +# LLVM source-based coverage instrumentation perturbs this memory-tracking cadence, so the +# expected exception sometimes does not surface on `127.3` before cancellation, leaving an empty +# `grep` match and a flaky FAIL. CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -9,7 +14,11 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # 1 on 127.2 # 2 on 127.3 # max_block_size to fail faster -# max_memory_usage/_shard_num/repeat() will allow failure on the first shard earlier. +# `groupArrayIf` on `_shard_num` makes `127.3` the only shard that can run out of memory: on +# `127.2` the condition is false for every row, so its aggregate states never grow and it just +# streams `system.numbers` until the initiator cancels it. Before this, `127.2` accumulated +# one-byte strings and reached the same `max_memory_usage` only about 20% later than `127.3`, so +# which shard failed first was a race. opts=( "--max_memory_usage=1G" "--max_block_size=50" @@ -17,9 +26,30 @@ opts=( "--max_distributed_connections=2" "--max_bytes_before_external_group_by=0" "--max_bytes_ratio_before_external_group_by=0" + # The query reads `system.numbers` until a shard runs out of memory, so `max_memory_usage` + # has to be the only limit that can stop it. The test profile of the CI configuration + # (tests/config/users.d/limits.yaml) sets `max_rows_to_read = 20000000`, which `127.2` and + # the initiator reach at about the same time as `127.3` reaches `max_memory_usage`; the query + # then fails with `TOO_MANY_ROWS` instead of `MEMORY_LIMIT_EXCEEDED` and the `grep` below + # finds nothing. + "--max_rows_to_read=0" + # `127.2` now never fails on its own, so if the cancellation this test is about ever breaks, + # the query would stream forever and the test would be killed by the runner's timeout with no + # output. Fail it with `TIMEOUT_EXCEEDED` instead, far above the ~1s the expected exception + # needs. + "--max_execution_time=100" ) -${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArray(repeat('a', if(_shard_num == 2, 100000, 1))), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" |& { - # the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. - grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" - # while if this will not correctly then it will got the exception from the 127.2:9000 and fail -} +LOG="$CLICKHOUSE_TMP/err-$CLICKHOUSE_DATABASE" +trap 'rm -f "$LOG"' EXIT + +${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArrayIf(repeat('a', 100000), _shard_num == 2), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" > "$LOG" 2>&1 +CODE=$? + +# the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. +# while if this will not correctly then it will got the exception from the 127.2:9000 and fail +if ! grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" "$LOG"; then + # stderr only on the failing path: a test that writes there and exits 0 is a FAIL for the runner. + echo "Fail, Code: $CODE, client output:" >&2 + cat "$LOG" >&2 + exit 1 +fi diff --git a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 index 2b1dc6c1c781..89f267e614a3 100644 --- a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 +++ b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 @@ -1,4 +1,8 @@ --- Tags: long +-- Tags: long, no-msan +-- no-msan: 5 join algorithms x ~78 statements, several of them deliberately spilling, average +-- ~183s under MSan against ~4s in a release build; the p99 is 73% of the 600s per-test budget, so +-- a run that gets killed on the timeout is an ordinary tail event. Join implicit-cast semantics +-- get no MSan-specific coverage, and the test still runs under ASan, UBSan and TSan. SET enable_analyzer = 1; DROP TABLE IF EXISTS t1; diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference index 9942759a9480..2d3bd2d2ebfd 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference @@ -1,3 +1,5 @@ 1 10 42 53 1 10 42 53 1 10 42 53 +1 +1 0 0 0 diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql index c49bf392895b..31bf6c5e6524 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql @@ -6,3 +6,13 @@ insert into function file(currentDatabase() || '_data_02302.orc') select 1 as x, select * from file(currentDatabase() || '_data_02302.orc', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_orc_allow_missing_columns=1; insert into function file(currentDatabase() || '_data_02302.arrow') select 1 as x, null::Nullable(UInt8) as xx settings engine_file_truncate_on_insert=1; select * from file(currentDatabase() || '_data_02302.arrow', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_arrow_allow_missing_columns=1; + +-- The next two queries test the native Parquet reader, so they pin it (some release branches still randomize it off). +-- A count-only read reads just the single smallest declared column, so `d` must stay strictly +-- narrower than every other column for this to exercise a defaulted one. The count cache would +-- answer before a reader exists, and the two count-only optimizations are randomized off in some runs, so all three are pinned. +-- Missing columns are rejected so that a read which is not count-only fails here instead of +-- synthesizing `d` into a correctly sized mask and returning the same count with no guard in place. +select count() from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt64, d UInt8 default 10') settings use_cache_for_count_from_files = 0, optimize_count_from_files = 1, optimize_trivial_count_query = 1, input_format_parquet_allow_missing_columns = 0, input_format_parquet_use_native_reader_v3 = 1; +-- With the setting off no `default` expression is applied, so the columns keep their type defaults. +select * from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_parquet_allow_missing_columns=1, input_format_defaults_for_omitted_fields=0, input_format_parquet_use_native_reader_v3=1; diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference new file mode 100644 index 000000000000..0f9d2713f87d --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference @@ -0,0 +1 @@ +idx text diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql new file mode 100644 index 000000000000..a629b362ee8e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql @@ -0,0 +1,24 @@ +-- An `ALTER` that adds an index is authorized against the schema the whole statement produces. +-- That must not skip the validation of its other commands and run into an exception. + +SET enable_full_text_index = 1; + +DROP TABLE IF EXISTS tab; +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab + RENAME COLUMN missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 1; -- { serverError NOT_FOUND_COLUMN_IN_BLOCK } + +ALTER TABLE tab + RENAME COLUMN val TO a, + RENAME COLUMN a TO b, + ADD INDEX idx(id) TYPE minmax GRANULARITY 1; -- { serverError NOT_IMPLEMENTED } + +ALTER TABLE tab + RENAME COLUMN IF EXISTS missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1; + +SELECT name, type FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab'; + +DROP TABLE tab; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.reference b/tests/queries/0_stateless/02346_text_index_transform_access.reference new file mode 100644 index 000000000000..1c382f1ae6da --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.reference @@ -0,0 +1,19 @@ +1. Direct call denied. +2. Denied in a preprocessor. +3. Denied when nested under a String result. +4. Denied via ALTER ADD INDEX. +5. Unprivileged expression unaffected. +1 +6. Accepted with the privilege, so not a blocklist. +1 +7. Existing index stays readable without the privilege. +1 +8. Unrelated ALTER does not re-authorize. +1 +9. Neither does DETACH/ATTACH. +1 +10. Redeclaring with a privileged function is denied. +11. The transform preflight does not reject what a plain ALTER accepts. +idx_pre +12. A statement without a transform is not analyzed at all. +idx_minmax diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.sql b/tests/queries/0_stateless/02346_text_index_transform_access.sql new file mode 100644 index 000000000000..62903e79d44b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.sql @@ -0,0 +1,124 @@ +-- Text index `preprocessor` expressions must only use functions the user declaring +-- the index is permitted to run. +-- +-- The test needs a function the current user may not run. Introspection functions fit: they are +-- refused both without the grant and, as here, with `allow_introspection_functions = 0`. Using the +-- setting keeps the test in plain SQL, with no second user to create. + +DROP TABLE IF EXISTS tab; + +-- The test configuration sets this to 1. +SET allow_introspection_functions = 0; + +SELECT '1. Direct call denied.'; + +SELECT demangle('_ZNK2DB7Context9getAccessEv'); -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. Denied in a preprocessor.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Denied when nested under a String result.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, demangle(val))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '4. Denied via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)); -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '5. Unprivileged expression unaffected.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'Hello World'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; + +SELECT '6. Accepted with the privilege, so not a blocklist.'; + +SET allow_introspection_functions = 1; + +-- `demangle` returns a non-mangled argument unchanged. +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'hello world'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '7. Existing index stays readable without the privilege.'; + +SET allow_introspection_functions = 0; + +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '8. Unrelated ALTER does not re-authorize.'; + +ALTER TABLE tab ADD COLUMN extra UInt8 DEFAULT 0; +ALTER TABLE tab RENAME COLUMN val TO val2; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '9. Neither does DETACH/ATTACH.'; + +DETACH TABLE tab; +ATTACH TABLE tab; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '10. Redeclaring with a privileged function is denied.'; + +ALTER TABLE tab DROP INDEX idx, + ADD INDEX idx(val2) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val2)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '11. The transform preflight does not reject what a plain ALTER accepts.'; + +CREATE TABLE tab_preflight (id UInt64, val String, num UInt64) +ENGINE = MergeTree ORDER BY id SETTINGS auto_statistics_types = 'minmax'; + +-- The preflight must drop implicit statistics too, or `ADD STATISTICS` looks like a duplicate. +ALTER TABLE tab_preflight ADD INDEX idx_pre(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1, + ADD STATISTICS num TYPE minmax; + +SELECT name FROM system.data_skipping_indices +WHERE database = currentDatabase() AND table = 'tab_preflight' ORDER BY name; + +DROP TABLE tab_preflight; + +SELECT '12. A statement without a transform is not analyzed at all.'; + +SET allow_statistics = 1; +CREATE TABLE tab_plain (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS auto_statistics_types = 'minmax'; + +ALTER TABLE tab_plain ADD INDEX idx_minmax(x) TYPE minmax GRANULARITY 1, ADD STATISTICS x TYPE minmax; + +SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab_plain'; + +DROP TABLE tab_plain; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference new file mode 100644 index 000000000000..8a97bd9c341e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference @@ -0,0 +1,3 @@ +1. ALTER ADD INDEX is denied. +2. CREATE TABLE is denied. +3. Accepted with the privilege. diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql new file mode 100644 index 000000000000..67ca0d15dcdc --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql @@ -0,0 +1,40 @@ +-- Tags: zookeeper, no-replicated-database +-- no-replicated-database: the test creates its own Replicated database + +-- A Replicated database hands the DDL to replicas that apply it without the submitting user, so the +-- permission check happens on the node it was submitted to. See 02346_text_index_transform_access +-- for the checks themselves, and 02346_text_index_transform_on_cluster for `ON CLUSTER`. + +SET allow_introspection_functions = 0; + +-- {CLICKHOUSE_DATABASE_1} may be left over from a previous run, hence the DROP. +DROP DATABASE IF EXISTS {CLICKHOUSE_DATABASE_1:Identifier}; +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} +ENGINE = Replicated('/clickhouse/02346_text_index_transform_access/{database}', 'shard1', 'replica1') FORMAT Null; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab (id UInt64, val String) +ENGINE = MergeTree ORDER BY id FORMAT Null; + +SELECT '1. ALTER ADD INDEX is denied.'; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. CREATE TABLE is denied.'; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab_denied +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Accepted with the privilege.'; + +SET allow_introspection_functions = 1; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1 FORMAT Null; + +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} FORMAT Null; diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.reference b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference new file mode 100644 index 000000000000..3954d852fafa --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference @@ -0,0 +1,6 @@ +1. A set from a table. +2. A subquery. +3. A dictionary lookup. +4. The same via ALTER ADD INDEX. +5. A literal set is still accepted. +1 diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.sql b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql new file mode 100644 index 000000000000..9d785850ee83 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql @@ -0,0 +1,68 @@ +-- Text index transforms are analysed under the global context, so anything that reads a table or a +-- dictionary while being analysed would do it with full access, and constant folding could reveal +-- what it read. A transform must be a pure function of the indexed value, so these are rejected +-- before any analysis. See 02346_text_index_transform_access for the function permission checks. + +DROP TABLE IF EXISTS tab; +DROP TABLE IF EXISTS set_source; +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dict_source; + +CREATE TABLE set_source (x String) ENGINE = Set; +INSERT INTO set_source VALUES ('secret'); + +CREATE TABLE dict_source (id UInt64, value String) ENGINE = MergeTree ORDER BY id; +INSERT INTO dict_source VALUES (1, 'secret'); +CREATE DICTIONARY dict (id UInt64, value String) PRIMARY KEY id +SOURCE(CLICKHOUSE(TABLE 'dict_source')) LAYOUT(FLAT()) LIFETIME(0); + +SELECT '1. A set from a table.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '2. A subquery.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, (SELECT any(value) FROM dict_source))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '3. A dictionary lookup.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '4. The same via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN (SELECT x FROM set_source), val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))); -- { serverError INCORRECT_QUERY } + +SELECT '5. A literal set is still accepted.'; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN ('hello', 'world'), val, val)); +INSERT INTO tab VALUES (1, 'hello there'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; +DROP DICTIONARY dict; +DROP TABLE dict_source; +DROP TABLE set_source; diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference new file mode 100644 index 000000000000..91fa6db49214 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference @@ -0,0 +1,14 @@ +1. ALTER ADD INDEX with a transform is refused. +1 +2. CREATE with a transform is refused. +1 +3. Refused on the legacy entry-format path too, which normalizes on the host. +1 +4. Indices inherited by CREATE AS on the legacy path are refused. +1 +5. An index without a transform is unaffected. +idx_plain +6. CREATE AS with an explicit engine and no privilege on the source. +SHOW COLUMNS ON default.tab +7. The same for a source that does not exist. +SHOW COLUMNS ON default.missing diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh new file mode 100755 index 000000000000..15b49c8bf03b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database +# no-replicated-database: ON CLUSTER is not allowed for a Replicated database + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The hosts of an `ON CLUSTER` query resolve a text index transform against their own schema and +# without the submitting user, so it is refused unless they run as that user. + +USER="user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER IF EXISTS $USER; + CREATE TABLE tab (id UInt64, val String, lowered String ALIAS lower(val)) ENGINE = MergeTree ORDER BY id; +" + +echo '1. ALTER ADD INDEX with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lowered) +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '2. CREATE with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_transform ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '3. Refused on the legacy entry-format path too, which normalizes on the host.' +$CLICKHOUSE_CLIENT --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_legacy ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '4. Indices inherited by CREATE AS on the legacy path are refused.' +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.src_transform (id UInt64, val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val))) ENGINE = MergeTree ORDER BY id" +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_inherited ON CLUSTER test_shard_localhost + AS ${CLICKHOUSE_DATABASE}.src_transform ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '5. An index without a transform is unaffected.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx_plain(val) TYPE text(tokenizer = 'splitByNonAlpha') +" +$CLICKHOUSE_CLIENT -q "SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab' ORDER BY name" + +# With an explicit engine `setEngine` does not look at `AS src`, and the inherited indices are inspected +# on the initiator, so describing the source has to be authorized first. +$CLICKHOUSE_CLIENT -n -q " + CREATE USER $USER; + GRANT CREATE TABLE ON ${CLICKHOUSE_DATABASE}.dst TO $USER; + GRANT TABLE ENGINE ON MergeTree TO $USER; +" + +echo '6. CREATE AS with an explicit engine and no privilege on the source.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.tab ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.tab" + +echo '7. The same for a source that does not exist.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.missing ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.missing" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER $USER; + DROP TABLE tab; + DROP TABLE src_transform; +" diff --git a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 index 45c6b5fe5f3f..d05007d356e4 100644 --- a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 +++ b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 @@ -1,4 +1,4 @@ --- Tags: long +-- Tags: long, no-msan SET enable_analyzer = 1; SET single_join_prefer_left_table = 0; diff --git a/tests/queries/0_stateless/02426_orc_bug.reference b/tests/queries/0_stateless/02426_orc_bug.reference index 4f76072e70d1..d5f93b43aa8d 100644 --- a/tests/queries/0_stateless/02426_orc_bug.reference +++ b/tests/queries/0_stateless/02426_orc_bug.reference @@ -1 +1 @@ -64a50db9526e0e3aa8c969939922658d - +f8d66b83061a9b0ce960c0b9ce32a64c - diff --git a/tests/queries/0_stateless/02884_authentication_quota.reference b/tests/queries/0_stateless/02884_authentication_quota.reference index d8ed6d97b505..c41269381185 100644 --- a/tests/queries/0_stateless/02884_authentication_quota.reference +++ b/tests/queries/0_stateless/02884_authentication_quota.reference @@ -6,7 +6,7 @@ > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -18,9 +18,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login @@ -32,7 +32,7 @@ QUOTA_EXCEEDED > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -44,9 +44,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login diff --git a/tests/queries/0_stateless/02884_authentication_quota.sh b/tests/queries/0_stateless/02884_authentication_quota.sh index bca24bf6cc27..b092e0b35359 100755 --- a/tests/queries/0_stateless/02884_authentication_quota.sh +++ b/tests/queries/0_stateless/02884_authentication_quota.sh @@ -18,7 +18,7 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Quota is exceeded 1 >= 1. Login with correct password should fail." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" @@ -37,10 +37,10 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' - ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Also try to login with correct password. Quota should stay exceeded." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference new file mode 100644 index 000000000000..8c21354a38e1 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference @@ -0,0 +1,6 @@ +1 +0 +0 +1 +0 +0 diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh new file mode 100755 index 000000000000..bc088b046271 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel, no-replicated-database, no-shared-merge-tree +# no-parallel: uses a global failpoint and two replicas with stopped replication queues. +# no-fasttest: a test that arms a global failpoint must run alone, and such tests are kept out of the fast test. +# no-replicated-database: the test controls replication queues of individual tables. +# no-shared-merge-tree: the failpoint is in the `ReplicatedMergeTree` block allocation path. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -e + +function cleanup_tables() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R2" 2>/dev/null || true + wait || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R2 SYNC" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R1 SYNC" 2>/dev/null || true +} + +function cleanup() +{ + cleanup_tables +} +trap cleanup EXIT + +# Runs a lightweight update of partition 2 whose rows arrive from the other replica while the update +# waits for committing inserts, and checks that the update has patched all of them. +function run_case() +{ + local name=$1 + local assignment=$2 + R1=t_lwu_prune_empty_03100_58_${name}_r1 + R2=t_lwu_prune_empty_03100_58_${name}_r2 + + $CLICKHOUSE_CLIENT --query " + SET insert_keeper_fault_injection_probability = 0.0; + + DROP TABLE IF EXISTS $R2 SYNC; + DROP TABLE IF EXISTS $R1 SYNC; + + CREATE TABLE $R1 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r1') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + CREATE TABLE $R2 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r2') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + INSERT INTO $R1 SELECT 1, number, 1 FROM numbers(50); + INSERT INTO $R1 SELECT 2, number, 1 FROM numbers(50); + SYSTEM SYNC REPLICA $R2; + + ALTER TABLE $R1 DELETE WHERE p = 2 SETTINGS mutations_sync = 2; + + SYSTEM STOP REPLICATION QUEUES $R1; + + SELECT count() FROM system.parts + WHERE database = currentDatabase() AND table = '$R1' AND partition_id = '2' AND active AND rows = 0; + " + + $CLICKHOUSE_CLIENT --query "INSERT INTO $R2 SELECT 2, 1000000 + number, 1 FROM numbers(30)" + + block_numbers_path="/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name/block_numbers/2" + block_count_before=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + + $CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" + + $CLICKHOUSE_CLIENT --query "UPDATE $R1 SET v = $assignment WHERE p = 2 SETTINGS enable_lightweight_update = 1, enable_shared_storage_snapshot_in_query = 1" & + + for _ in {0..300}; do + sleep 0.3 + block_count_after=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + if [[ "$block_count_after" -gt "$block_count_before" ]]; then + break + fi + done + + if [[ "$block_count_after" -le "$block_count_before" ]]; then + echo "Failed to observe a new block allocation for lightweight update at $block_numbers_path" >&2 + exit 2 + fi + + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" + + wait + + + result=$($CLICKHOUSE_CLIENT --query " + SYSTEM SYNC REPLICA $R1; + SYSTEM SYNC REPLICA $R2; + + SELECT count() FROM $R1 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1; + SELECT count() FROM $R2 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1") + + if [[ "$result" != $'0\n0' ]]; then + echo "Unexpected unpatched-row counts in case $name:" >&2 + echo "$result" >&2 + $CLICKHOUSE_CLIENT --query " + SELECT 'patch parts', name, rows FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND startsWith(name, 'patch') + ORDER BY table, name; + SELECT 'partition 2 parts', table, name, rows, min_block_number, max_block_number FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND partition_id = '2' + ORDER BY table, name; + SELECT 'frozen mutation version', table, mutation_id, block_numbers.partition_id, block_numbers.number + FROM system.mutations + WHERE database = currentDatabase() AND table = '$R1' + ORDER BY create_time DESC;" >&2 + exit 1 + fi + + echo "$result" + + cleanup_tables +} + +run_case plain 999 +# The `IN` operand names the updated table, so validating it in `InterpreterUpdateQuery` takes a storage +# snapshot of the table before the update waits for committing inserts. +run_case in_assignment "if((p, x, v) IN t_lwu_prune_empty_03100_58_in_assignment_r1, 999, 998)" diff --git a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh index 6819deea1fc1..35498f567da2 100755 --- a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh +++ b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh @@ -15,7 +15,7 @@ ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} SYNC" ${CLICKHOUSE_CLIENT} --query "CREATE TABLE ${TABLE_NAME} (c0 Int) ENGINE = File(ORC, '${USER_FILES_PATH}/${TEST_FILE}')" ${CLICKHOUSE_CLIENT} --query "INSERT INTO TABLE ${TABLE_NAME} (c0) VALUES (1),(2),(3),(5.4)" -${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx SETTINGS input_format_orc_use_fast_decoder = 0" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} sync" diff --git a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference index 2217316a750e..8f35989d78b9 100644 --- a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference +++ b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference @@ -10,6 +10,8 @@ Expression Name: v Description: set GRANULARITY 1 Condition: true - Parts: 0/1 - Granules: 0/1 - Ranges: 0 + Parts: 1/1 + Granules: 1/1 + Ranges: 1 +1 +1 diff --git a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql index c799670ca5db..d3a92f2e129a 100644 --- a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql +++ b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql @@ -13,3 +13,8 @@ ORDER BY (ts); INSERT INTO test (v) FORMAT Values ('VALUE1'); EXPLAIN indexes = 1, description=0 SELECT CAST(NULL, 'Nullable(String)') AS source, v AS v FROM test WHERE (source = 'VALUE1') OR (v ILIKE 'VALUE1'); + +-- The row matches via the second disjunct, so the granule must not be pruned: the set +-- index must return the same rows as a scan with skip indexes disabled. +SELECT count() FROM test WHERE (CAST(NULL, 'Nullable(String)') = 'VALUE1') OR (v ILIKE 'VALUE1'); +SELECT count() FROM test WHERE (CAST(NULL, 'Nullable(String)') = 'VALUE1') OR (v ILIKE 'VALUE1') SETTINGS use_skip_indexes = 0; diff --git a/tests/queries/0_stateless/03784_bad_base_backup.sh b/tests/queries/0_stateless/03784_bad_base_backup.sh index ef0cdd18a110..6ac1401f2fea 100755 --- a/tests/queries/0_stateless/03784_bad_base_backup.sh +++ b/tests/queries/0_stateless/03784_bad_base_backup.sh @@ -48,3 +48,15 @@ thread & thread & wait + +# The databases are created outside of the test database, so they must be dropped here: +# leftover `Replicated` databases break tests that enumerate all `Replicated` databases of the server, +# such as `05061_system_drop_database_replica_access`. Wait for the `ASYNC` backups to finish first. +for _ in $(seq 1 600) +do + [[ $($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.backups WHERE status = 'CREATING_BACKUP' AND name LIKE '%${CLICKHOUSE_DATABASE}%'") == 0 ]] && break + sleep 0.1 +done + +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d1_$CLICKHOUSE_DATABASE SYNC" +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d2_$CLICKHOUSE_DATABASE SYNC" diff --git a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh index 6db574849a79..6548e86729d7 100755 --- a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh +++ b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh @@ -16,7 +16,7 @@ EOF (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; -${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user"; +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE, CREATE TEMPORARY TABLE ON *.* TO $user"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "FILE_DOESNT_EXIST") >= 1 )) && echo "FILE_DOESNT_EXIST" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "CANNOT_STAT") >= 1 )) && echo "CANNOT_STAT" || echo "UNEXPECTED"; diff --git a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh index 3e4c623ee8e6..8caf9b22b41b 100755 --- a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh +++ b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh @@ -30,7 +30,7 @@ $CLICKHOUSE_CLIENT --allow_experimental_kafka_offsets_storage_in_keeper 1 -q " kafka_format = 'JSONEachRow', kafka_max_block_size = 100, kafka_keeper_path = '$KEEPER_PATH', - kafka_replica_name = 'r1'; + kafka_replica_name = '{replica}'; " # Create destination table diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference index 491b7765b057..7d4cda3c2395 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference @@ -16,7 +16,7 @@ 1 1 1 --- Optimization also works with basic (non-bucketed) serialization +-- No optimization with basic (non-bucketed) serialization 1 -- Correctness: results with optimization 7 7 70 diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql index c9eaddb60218..e161a47a3cfa 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql @@ -150,20 +150,19 @@ SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHE -- ========================================== -- Section 8: basic serialization (not with_buckets) --- The optimization still applies because DataTypeMap exposes dynamic subcolumns --- regardless of serialization version. With basic serialization, the whole map is --- read and the key is extracted; with_buckets reads only the relevant bucket. +-- The rewrite is not applied: with basic serialization the key subcolumn reads the whole map anyway. -- ========================================== DROP TABLE t_map_subcolumns; CREATE TABLE t_map_subcolumns (id UInt64, m Map(String, UInt64)) -ENGINE = MergeTree ORDER BY id; +ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; INSERT INTO t_map_subcolumns SELECT number, map('key1', number) FROM numbers(10); -SELECT '-- Optimization also works with basic (non-bucketed) serialization'; -SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; +SELECT '-- No optimization with basic (non-bucketed) serialization'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; -- ========================================== -- Section 9: Correctness - verify actual query results after optimization diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference index 89024e17dd7f..a108bf0eea76 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference @@ -54,7 +54,7 @@ 98 98 2 99 99 1 -- Section 4: PREWHERE with basic serialization --- Optimization still rewrites to subcolumn +-- No rewrite to subcolumn 1 -- Correctness: PREWHERE with basic serialization 96 96 960 diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql index a3594aff2a1b..db0474ce8c2a 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql @@ -133,7 +133,7 @@ DROP TABLE t_map_prewhere; -- ========================================== -- Section 4: PREWHERE with basic serialization (non-bucketed) --- Optimization still applies, but reads the whole map internally. +-- No rewrite to the key subcolumn, it would read the whole map anyway. -- ========================================== DROP TABLE IF EXISTS t_map_prewhere; @@ -141,14 +141,15 @@ CREATE TABLE t_map_prewhere (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'basic', + map_serialization_version_for_zero_level_parts = 'basic', min_bytes_for_wide_part = 1, min_rows_for_wide_part = 1; INSERT INTO t_map_prewhere SELECT number, map('key1', number, 'key2', number * 10) FROM numbers(100); SELECT '-- Section 4: PREWHERE with basic serialization'; -SELECT '-- Optimization still rewrites to subcolumn'; -SELECT count() > 0 FROM ( +SELECT '-- No rewrite to subcolumn'; +SELECT count() = 0 FROM ( EXPLAIN actions = 1 SELECT id, m FROM t_map_prewhere PREWHERE m['key1'] > 95 ) WHERE explain LIKE '%m.key_key1%'; diff --git a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql index 05fe94c220e0..d0a35aacb003 100644 --- a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql +++ b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql @@ -1,7 +1,7 @@ -- Tags: no-random-settings -- Tests that text indexes built on mapValues(m) work correctly when the analyzer --- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form. +-- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form, which it does only for bucketed Maps. SET enable_analyzer = 1; @@ -16,7 +16,8 @@ CREATE TABLE tab ) ENGINE = MergeTree ORDER BY id -SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0; +SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; INSERT INTO tab VALUES (0, {'service':'web-api'}), (1, {'service':'backend'}), (2, {'service':'frontend'}); diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference new file mode 100644 index 000000000000..e99e8dbc05e4 --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference @@ -0,0 +1,8 @@ +1 +0 +1 +0 +1 +0 +1 +0 diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql new file mode 100644 index 000000000000..0965065b3bbe --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql @@ -0,0 +1,9 @@ +SELECT hasSubsequenceUTF8('', ''); +SELECT hasSubsequenceUTF8('', 'a'); +SELECT hasSubsequenceCaseInsensitiveUTF8('', ''); +SELECT hasSubsequenceCaseInsensitiveUTF8('', 'A'); + +SELECT hasSubsequenceUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceUTF8(materialize(''), materialize('a')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('A')); diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference new file mode 100644 index 000000000000..382c328e0874 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference @@ -0,0 +1,3 @@ +2 20 +2 20 +2099-01-01 00:00:00 20 diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql new file mode 100644 index 000000000000..06a0cd88ef07 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql @@ -0,0 +1,34 @@ +SET mutations_sync = 1; + +-- Test that TTL expressions referencing subcolumns work correctly. +-- Previously, executeExpressionAndGetColumn used getByName which failed +-- for subcolumns not present as top-level columns in the block. +-- We test both INSERT (updateTTL in MergeTreeDataWriter) and merge +-- (TTL algorithms in the merge pipeline) paths. + +-- Case 1: Tuple subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol; +CREATE TABLE t_ttl_subcol (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL t.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol VALUES ((1, '2000-01-01'), 10); +INSERT INTO t_ttl_subcol VALUES ((2, '2099-01-01'), 20); +OPTIMIZE TABLE t_ttl_subcol FINAL; +SELECT t.a, val FROM t_ttl_subcol ORDER BY val; +DROP TABLE t_ttl_subcol; + +-- Case 2: Tuple subcolumn with function in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol_func; +CREATE TABLE t_ttl_subcol_func (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL toDate(t.d) + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol_func VALUES ((1, '2000-01-01 12:00:00'), 10); +INSERT INTO t_ttl_subcol_func VALUES ((2, '2099-01-01 12:00:00'), 20); +OPTIMIZE TABLE t_ttl_subcol_func FINAL; +SELECT t.a, val FROM t_ttl_subcol_func ORDER BY val; +DROP TABLE t_ttl_subcol_func; + +-- Case 3: JSON subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_json_subcol; +CREATE TABLE t_ttl_json_subcol (json JSON(d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL json.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2000-01-01"}', 10); +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2099-01-01"}', 20); +OPTIMIZE TABLE t_ttl_json_subcol FINAL; +SELECT json.d, val FROM t_ttl_json_subcol ORDER BY val; +DROP TABLE t_ttl_json_subcol; diff --git a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh index 6dfb8038211b..1639da5845ab 100755 --- a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh +++ b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh @@ -7,10 +7,9 @@ # grind (and could overflow the native stack), uncancellable. It must now be rejected as # TOO_DEEP_RECURSION once the nesting exceeds max_parser_depth. # -# 2. The Apache ORC C++ library (convertType) builds its own orc::Type tree by recursing over the -# file footer before any ClickHouse code runs. A pathologically deep file used to overflow the -# native stack there (crashing the process / triggering the OOM killer). The library now bounds -# the nesting depth and rejects such a file instead of crashing. +# 2. The ORC reader builds its type tree by recursing over the file footer before the schema +# inference runs. A pathologically deep file must not overflow the native stack there: the +# reader bounds the nesting depth and rejects such a file. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -55,18 +54,24 @@ orc.write_table(pa.table({'x': pa.array([], type=t)}), '$2') " } -# (1) A moderate file (200 levels) that the ORC library builds fine, with max_parser_depth lowered +# (1) A moderate file (200 levels) that the ORC reader builds fine, with max_parser_depth lowered # below the nesting so parseORCType rejects it deterministically and build-independently. gen_orc 200 "${TMP_DIR}/moderate.orc" $CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/moderate.orc', ORC) SETTINGS max_parser_depth = 100" 2>&1 \ | expect_contains parser_depth_limit TOO_DEEP_RECURSION -# (2) A file nested past the ORC library's own limit. Even with max_parser_depth raised so high that -# parseORCType would accept it, the library must reject it (without crashing). The library throws +# (2) A file nested past the ORC reader's own limit. Even with max_parser_depth raised so high that +# parseORCType would accept it, the reader must reject it (without crashing). The reader throws # before recursing past its limit, so this is safe to run. gen_orc 3000 "${TMP_DIR}/deep.orc" -$CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1 \ - | expect_contains orc_library_depth_limit "nesting depth exceeds the limit" +# Under TSan the stack size check allows only 5% of the stack, so it can reject the file before the depth limit. +out=$($CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1) +if printf '%s\n' "$out" | grep -qF -e "nesting depth exceeds the limit" -e "TOO_DEEP_RECURSION"; then + echo "orc_library_depth_limit: nesting depth exceeds the limit" +else + echo "orc_library_depth_limit: expected 'nesting depth exceeds the limit', got:" + printf '%s\n' "$out" | head -3 +fi # (3) max_parser_depth=0 means unlimited (matching the SQL parser), so a moderately nested file must # still be inferred normally rather than rejected by the explicit limit. diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.reference b/tests/queries/0_stateless/04338_async_insert_current_user.reference new file mode 100644 index 000000000000..161fe963e5bf --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.reference @@ -0,0 +1,6 @@ +1 1 1 +2 1 1 +1 1 1 +2 1 1 +10 1 1 +20 1 1 diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.sql b/tests/queries/0_stateless/04338_async_insert_current_user.sql new file mode 100644 index 000000000000..5a04881f9670 --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.sql @@ -0,0 +1,43 @@ +-- Regression test for issue #107530: context-dependent functions such as currentUser() +-- must evaluate to the inserting user (not an empty string) on the async_insert flush path, +-- both in DEFAULT/MATERIALIZED column expressions and in materialized views. + +DROP TABLE IF EXISTS t_async_user; +DROP TABLE IF EXISTS t_async_user_src; +DROP TABLE IF EXISTS t_async_user_dst; +DROP VIEW IF EXISTS t_async_user_mv; + +-- DEFAULT / MATERIALIZED column expressions calling currentUser(). +CREATE TABLE t_async_user +( + x Int32, + u_default String DEFAULT currentUser(), + u_materialized String MATERIALIZED currentUser() +) +ENGINE = MergeTree ORDER BY x; + +INSERT INTO t_async_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1); +INSERT INTO t_async_user (x) SETTINGS async_insert = 0 VALUES (2); + +-- The async row (x=1) and the sync row (x=2) must both record the inserting user. +-- Before the fix the async row recorded an empty string. +SELECT x, u_default = currentUser() AS default_matches, length(u_default) > 0 AS default_non_empty +FROM t_async_user ORDER BY x; +SELECT x, u_materialized = currentUser() AS materialized_matches, length(u_materialized) > 0 AS materialized_non_empty +FROM t_async_user ORDER BY x; + +-- Materialized view selecting currentUser(). +CREATE TABLE t_async_user_src (x Int32) ENGINE = MergeTree ORDER BY x; +CREATE TABLE t_async_user_dst (x Int32, u String) ENGINE = MergeTree ORDER BY x; +CREATE MATERIALIZED VIEW t_async_user_mv TO t_async_user_dst AS SELECT x, currentUser() AS u FROM t_async_user_src; + +INSERT INTO t_async_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10); +INSERT INTO t_async_user_src SETTINGS async_insert = 0 VALUES (20); + +SELECT x, u = currentUser() AS mv_matches, length(u) > 0 AS mv_non_empty +FROM t_async_user_dst ORDER BY x; + +DROP VIEW t_async_user_mv; +DROP TABLE t_async_user_dst; +DROP TABLE t_async_user_src; +DROP TABLE t_async_user; diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference new file mode 100644 index 000000000000..697f9b3fa30a --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference @@ -0,0 +1,3 @@ +1 1 1 1 +2 1 1 1 +10 1 1 1 diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh new file mode 100755 index 000000000000..b457807b3384 --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Regression test for issue #107530: authenticatedUser() must evaluate to the +# originally authenticated user (not an empty string, and not currentUser()) on the +# async_insert flush path. Uses EXECUTE AS so currentUser() and authenticatedUser() +# diverge: the test then fails if setAuthenticatedUserName is removed (au becomes empty) +# or wired to the wrong value (au becomes the impersonated user). + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +AUTH_USER="auth_user_${CLICKHOUSE_DATABASE}" +APP_USER="app_user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${APP_USER}" +$CLICKHOUSE_CLIENT --query "CREATE USER ${AUTH_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "CREATE USER ${APP_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "GRANT IMPERSONATE ON ${APP_USER} TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${APP_USER}" + +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP VIEW IF EXISTS t_auth_user_mv" + +# DEFAULT columns: currentUser() = impersonated user, authenticatedUser() = original user. +$CLICKHOUSE_CLIENT --query " +CREATE TABLE t_auth_user +( + x Int32, + cu String DEFAULT currentUser(), + au String DEFAULT authenticatedUser() +) +ENGINE = MergeTree ORDER BY x" + +# Async insert (x=1) and sync insert (x=2), both under EXECUTE AS the impersonated user. +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1)" +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 0 VALUES (2)" + +# The async row (x=1) and the sync row (x=2) must both record currentUser()=impersonated +# and authenticatedUser()=originally authenticated. Before the fix the async row recorded +# an empty authenticatedUser(). cu_ne_au proves the two ClientInfo fields are restored +# independently (it would be false if authenticatedUser were mis-wired to currentUser). +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user ORDER BY x" + +# Materialized view selecting authenticatedUser() under EXECUTE AS on the async path. +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_src (x Int32) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_dst (x Int32, cu String, au String) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE MATERIALIZED VIEW t_auth_user_mv TO t_auth_user_dst AS SELECT x, currentUser() AS cu, authenticatedUser() AS au FROM t_auth_user_src" + +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10)" + +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user_dst ORDER BY x" + +$CLICKHOUSE_CLIENT --query "DROP VIEW t_auth_user_mv" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP USER ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER ${APP_USER}" diff --git a/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference new file mode 100644 index 000000000000..add40c4db3ca --- /dev/null +++ b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference @@ -0,0 +1,14 @@ +50 +50 +50 +50 +50 +50 +50 +50 +50 +33 +50 +50 +1 +1 diff --git a/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql new file mode 100644 index 000000000000..c653a112c5f6 --- /dev/null +++ b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql @@ -0,0 +1,50 @@ +-- Regression test for https://github.com/ClickHouse/ClickHouse/issues/103103 +-- A NULL-valued atom (e.g. toInt64OrNull('x')) reaching the set skip index was bit-wrapped by +-- __bitWrapperFunc and propagated NULL instead of the UNKNOWN mask, so the granule check wrongly +-- pruned matching granules and the query returned fewer rows than with skip indexes disabled. + +DROP TABLE IF EXISTS t_null_const_set_index; + +CREATE TABLE t_null_const_set_index (v Int64, lc LowCardinality(String), INDEX i lc TYPE set(64) GRANULARITY 1) +ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 32; + +INSERT INTO t_null_const_set_index SELECT number, toString(number % 3) FROM numbers(100); + +-- Disable the query condition cache so every query below is analyzed by the index, not served +-- from a cached verdict, and both granule-filtering paths are exercised deterministically: +-- secondary_indices_enable_bulk_filtering = 1 -> getPossibleGranules, 0 -> mayBeTrueOnGranule. +SET use_query_condition_cache = 0; + +-- All of the following match 50 rows via the second disjunct and must not be pruned. +-- Before the fix they returned 0 with the index. Run each under both granule paths. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 1; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 0; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND nullIf(1, 1)) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 1; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND nullIf(1, 1)) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 0; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND CAST(NULL AS Nullable(Int64))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toUInt8OrNull('x')) OR v < 50; +-- The NULL value may be hidden behind a function that suppresses constant folding, so the atom +-- is not a folded ColumnConst; identity() and materialize() must be handled the same way. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND identity(toInt64OrNull('x'))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND materialize(toInt64OrNull('x'))) OR v < 50; +-- NULL value next to a predicate on the indexed column itself, and under NOT. +SELECT count() FROM t_null_const_set_index WHERE (lc = '1' AND toInt64OrNull('x')) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE NOT ((lc = '1' AND toInt64OrNull('x')) OR v >= 50); +-- Non-integer typed NULL and bare NULL route to UNKNOWN already; must stay 50. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND CAST(NULL AS Nullable(Float64))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND NULL) OR v < 50; + +-- The NULL atom must not disable pruning: the index still prunes a granule it can legitimately +-- exclude. `lc = '999'` matches nothing, so every granule is skipped (`Granules: 0/`, +-- asserted format-agnostically since the total depends on the randomized part type). +SELECT count() > 0 AS prunes_nonmatching_granules +FROM (EXPLAIN indexes = 1 SELECT count() FROM t_null_const_set_index WHERE lc = '999') +WHERE explain ILIKE '%Granules: 0/%'; + +-- With the NULL atom present, a matching disjunct must still keep its granules: the index is +-- analyzed (the UNKNOWN atom does not disable it) and does not prune to zero. +SELECT count() = 0 AS null_atom_keeps_matching_granules +FROM (EXPLAIN indexes = 1 SELECT count() FROM t_null_const_set_index WHERE (lc = '1' AND toInt64OrNull('x')) OR lc = '2') +WHERE explain ILIKE '%Granules: 0/%'; + +DROP TABLE t_null_const_set_index; diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference new file mode 100644 index 000000000000..f693c2c0ae49 --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference @@ -0,0 +1,9 @@ +345 +11400 +168 5800 +[0,1,2,3,4,5,6,7,8,9,10,11,12] +3 3 +10 10 +17 4 +24 11 +1152 71944 diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql new file mode 100644 index 000000000000..4ce81b48033e --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql @@ -0,0 +1,23 @@ +-- Multi-step PREWHERE must keep columns needed to evaluate `DEFAULT`s of columns missing in the part. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default; + +CREATE TABLE t_multistep_prewhere_default (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple(); +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default ADD COLUMN v Int64 DEFAULT k % 13; +ALTER TABLE t_multistep_prewhere_default ADD COLUMN w Int64 DEFAULT k + length(s); + +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +SELECT sum(v) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3' AND k % 2 = 1; +SELECT arraySort(groupUniqArray(v)) FROM (SELECT DISTINCT v FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'); +SELECT k, v FROM t_multistep_prewhere_default WHERE k <= 30 AND s = '3' ORDER BY k; + +-- Parts written after the ALTER store v and w physically. +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7), 42, 43 FROM numbers(1000, 100); +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 1050 AND s = '3'; + +DROP TABLE t_multistep_prewhere_default; diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference new file mode 100644 index 000000000000..22b6a5ac9c04 --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference @@ -0,0 +1,6 @@ +350 +350 +4 4 +11 11 +18 5 +25 12 diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql new file mode 100644 index 000000000000..46e95b8cd3dd --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql @@ -0,0 +1,25 @@ +-- Multi-step PREWHERE must see patched values of the columns it carries over to evaluate `DEFAULT`s. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default_patch; + +SET enable_lightweight_update = 1, apply_patch_parts = 1; +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +CREATE TABLE t_multistep_prewhere_default_patch (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple() +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1; + +SYSTEM STOP MERGES t_multistep_prewhere_default_patch; + +INSERT INTO t_multistep_prewhere_default_patch SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default_patch ADD COLUMN v Int64 DEFAULT k % 13; + +UPDATE t_multistep_prewhere_default_patch SET k = k + 1 WHERE 1; + +-- Both queries must agree: `v` is missing in the part, so it is evaluated from the patched `k`. +SELECT sum((k % 13)::Int64) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; +SELECT sum(v) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; + +SELECT k, v FROM t_multistep_prewhere_default_patch WHERE k <= 30 AND s = '3' ORDER BY k; + +DROP TABLE t_multistep_prewhere_default_patch; diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference new file mode 100644 index 000000000000..7bed391e68f3 --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference @@ -0,0 +1,4 @@ +INCORRECT_DATA +0 0 +1 1 +2 2 diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh new file mode 100755 index 000000000000..57a8727696be --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The stripe footer of this blob is truncated, so reading it must fail with a regular +# INCORRECT_DATA exception. +BLOB='4f52431100000a061204080150005500000a280a06000000000000121e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc1550000f0000780039604d293e0b00006e0007dda36300f00a0608061000180b0a0608061001182d0a0608011001180a0a060805100118081204080010001204080210001a03474d545100000a260a04080150000a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc155000b500000803107e1a0a08031038181220342801220f080c1201011a0263302000280030002208080920002800300030013a04080150003a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc15500040904e48016200085d1005188080102202000c282b300682f403034f524317' + +# The fixture must stay pure even-length lowercase hex: unhex's result for a non-hex character is +# implementation-defined, so one invalid character makes the corrupt footer decoder-dependent and +# this test silently stops asserting anything. +if [[ ! $BLOB =~ ^[0-9a-f]+$ ]] || (( ${#BLOB} % 2 )); then + echo "BLOB must be an even-length string of [0-9a-f]" >&2 + exit 1 +fi + +$CLICKHOUSE_LOCAL -q "SELECT c0 FROM format(ORC, 'c0 DateTime64(3)', unhex('$BLOB'));" 2>&1 \ + | grep -oE "INCORRECT_DATA" \ + | sort -u + +# Well-formed ORC must still read back unchanged. +DATA_FILE="$CLICKHOUSE_TMP/04856_orc_control_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_LOCAL -q "SELECT number AS a, toString(number) AS b FROM numbers(3) FORMAT ORC" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT a, b FROM file('$DATA_FILE', ORC) ORDER BY a" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference new file mode 100644 index 000000000000..1f714f4b2082 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference @@ -0,0 +1,14 @@ +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +1 +2 diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh new file mode 100755 index 000000000000..dd54288e64f9 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Truncating this fixture to 289 bytes leaves byte 6 in the postscript's compression field. Codec 6 +# is BROTLI, which the ORC format declares but this reader does not implement. The reader rejects it +# with a NOT_IMPLEMENTED exception; it must never be a logical error, which aborts in debug and +# sanitizer builds. +DATA_FILE="$CLICKHOUSE_TMP/05036_orc_codec6_${CLICKHOUSE_DATABASE}.orc" +head -c 289 "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$DATA_FILE" + +# Both the schema-inference path and the explicit-structure path reach the reader, so both are +# asserted here. Match on the error text, never on the exit status: ClickHouse exits with the error +# code truncated to a byte, so 636 and 124 are the same outcome. +for query in \ + "SELECT * FROM file('$DATA_FILE', ORC) FORMAT Null" \ + "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" \ + "SELECT count() FROM file('$DATA_FILE', ORC, 'x Int32')" \ + "DESCRIBE file('$DATA_FILE', ORC)" \ + "SELECT * FROM format(ORC, 'x Int32', (SELECT * FROM file('$DATA_FILE', RawBLOB))) FORMAT Null" +do + # An abort prints nothing at all, so classify explicitly rather than letting the arm go silent: + # a missing line is much harder to read in a diff than a named verdict. + OUT=$($CLICKHOUSE_LOCAL --query "$query" 2>&1) + if [ -z "$OUT" ]; then + echo "no output at all" + else + echo "$OUT" | grep -o -m1 'BROTLI compression in ORC files is not supported\|Logical error' || echo "unexpected: $OUT" + fi +done + +# The message must name the codec, and must not call the file corrupt: a well-formed +# Brotli-compressed ORC file takes this same path. +$CLICKHOUSE_LOCAL --query "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" 2>&1 \ + | grep -o -m1 'BROTLI compression in ORC files is not supported\|CORRUPTED\|INCORRECT_DATA' + +# Neighbouring truncations are genuinely corrupt and must keep reporting corruption rather than the +# codec gap. Schema inference wraps every non-retryable cause in one outer code, so that arm alone +# cannot tell the two apart; the explicit-structure arm bypasses the wrapper and surfaces the inner +# classification, and counting the codec error there pins them apart. +for length in 200 400 +do + NEIGHBOUR="$CLICKHOUSE_TMP/05036_orc_${length}_${CLICKHOUSE_DATABASE}.orc" + head -c $length "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$NEIGHBOUR" + $CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC) FORMAT Null" 2>&1 \ + | grep -o -m1 'CANNOT_EXTRACT_TABLE_STRUCTURE\|Logical error' + EXPLICIT=$($CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC, 'x Int32') FORMAT Null" 2>&1) + echo "$EXPLICIT" | grep -o -m1 'INCORRECT_DATA\|Logical error' || echo "unexpected: $EXPLICIT" + echo "$EXPLICIT" | grep -c 'BROTLI compression' + rm "$NEIGHBOUR" +done + +# Well-formed ORC must still read back unchanged. +$CLICKHOUSE_LOCAL --query "SELECT i FROM file('$CUR_DIR/data_orc/orc_union_type.orc', ORC) ORDER BY i" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference new file mode 100644 index 000000000000..98fb6a686563 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference @@ -0,0 +1,4 @@ +1 +1 +1 +1 diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh new file mode 100755 index 000000000000..0e451abc8151 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: zookeeper, replica, no-shared-merge-tree, no-replicated-database +# no-shared-merge-tree: the setting bounds the ReplicatedMergeTree log, which SharedMergeTree does not have +# no-replicated-database: the ZooKeeper path and the replica name are literal, so they collide between the hosts of the database + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# The oldest kept log record names the threshold that log pointers of inactive replicas are compared +# with, so a window that keeps no records at all has no meaning. +ERR="A setting's value has to be greater than 0" + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs_zero (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# An ATTACH that carries a full definition is user input too, and reaches the same check. +uuid=$($CLICKHOUSE_CLIENT --query "SELECT generateUUIDv4()") +$CLICKHOUSE_CLIENT --query " + ATTACH TABLE max_logs_zero UUID '$uuid' (x UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r2', '1') ORDER BY x; +" +$CLICKHOUSE_CLIENT --query " + ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# A positive value is still accepted and stored. +$CLICKHOUSE_CLIENT --query "ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 1;" +$CLICKHOUSE_CLIENT --query " + SELECT count() FROM system.tables + WHERE database = currentDatabase() AND name = 'max_logs' + AND engine_full LIKE '%max_replicated_logs_to_keep = 1%'; +" + +$CLICKHOUSE_CLIENT --query "DROP TABLE max_logs SYNC" diff --git a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference index ec35dc29b3b4..6be1fa0c53ad 100644 --- a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference +++ b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference @@ -1,5 +1,9 @@ SASL mechanism longer than the message: error response password without a terminator: error response +password message at the Int32 maximum: error response +password message above the limit: error response +SASL initial response at the Int32 maximum: error response +SASL final response at the Int32 maximum: error response well-formed exchange: query result received query with a smuggled tail: error response query shorter than declared: error response diff --git a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh index e5fd34c2db3f..b5d3e9b7acef 100755 --- a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh +++ b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh @@ -32,6 +32,32 @@ def connect(): return sock +def connect_short(): + """A connection whose client timeout is well below the server's `handshake_timeout_milliseconds` (30 + seconds by default), so a message the server waits for shows up as a client timeout. With a timeout + at or above the handshake timeout the server would answer the same error response on its own, and a + regression that only makes the server wait would not be noticed.""" + sock = socket.create_connection(("127.0.0.1", port), timeout=5) + sock.settimeout(5) + return sock + + +def read_message(sock): + """Reads one backend message: a type byte, a length that counts itself, and the body.""" + def recv_exactly(size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise AssertionError("the connection closed before a complete message") + data += chunk + return data + + message_type = recv_exactly(1) + (length,) = struct.unpack(">i", recv_exactly(4)) + return message_type, recv_exactly(length - 4) + + def startup(sock, user): payload = ("user\x00" + user + "\x00\x00").encode() sock.sendall(struct.pack(">ii", 8 + len(payload), 196608) + payload) @@ -93,6 +119,46 @@ except (BrokenPipeError, ConnectionResetError, socket.timeout): print("password without a terminator:", outcome(sock)) sock.close() +# The declared length of a message that is parsed before authentication is bounded by the server, because +# the client that declares it is not trusted yet. Otherwise the client declares the Int32 maximum and the +# server buffers up to 2 GiB of payload that never completes. +sock = connect_short() +startup(sock, user_plain) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("password message at the Int32 maximum:", outcome(sock)) +sock.close() + +# The same for a length just above the limit, which pins the boundary itself. +sock = connect_short() +startup(sock, user_plain) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 10001)) +print("password message above the limit:", outcome(sock)) +sock.close() + +# The same for a `SASLInitialResponse`. +sock = connect_short() +startup(sock, user_scram) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("SASL initial response at the Int32 maximum:", outcome(sock)) +sock.close() + +# The same for a `SASLResponse`, the second SCRAM message. A well-formed client-first message is needed +# to get there, and its own declared lengths stay small. +sock = connect_short() +startup(sock, user_scram) +read_message(sock) +client_first = b"n,,n=,r=abcdefghijklmnopqrstuvwx" +body = b"SCRAM-SHA-256\x00" + struct.pack(">i", len(client_first)) + client_first +sock.sendall(b"p" + struct.pack(">i", 4 + len(body)) + body) +message_type, body = read_message(sock) +assert message_type == b"R" and struct.unpack(">i", body[:4])[0] == 11, body +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("SASL final response at the Int32 maximum:", outcome(sock)) +sock.close() + # A well-formed exchange still works: authenticate and run a query. def read_until_ready(sock): data = b"" diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference new file mode 100644 index 000000000000..743f61f80a90 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference @@ -0,0 +1,9 @@ +String: batches>1=1 64 2016 1 +Nullable(String): batches>1=1 64 2016 1 +LowCardinality: batches>1=1 64 2016 4 +Array(String): batches>1=1 64 2016 1 +Map: batches>1=1 64 2016 1 +Tuple: batches>1=1 64 2016 1 +FixedString: batches>1=1 64 2016 1 +FixedString fixed-width: batches>1=0 64 2016 1 +UInt64: batches>1=0 64 2016 64 diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh new file mode 100755 index 000000000000..695c740a9cd8 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Arrow offsets its String/Binary/List buffers with 32-bit integers, so a block holding more than that has +# to be written as several record batches. `output_format_arrow_max_record_batch_size_bytes` lowers the +# bound, which exercises the same splitting with kilobytes instead of the 2 GiB a real overflow needs. +# +# Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_split.arrows" +trap 'rm -f "$FILE"' EXIT + +batches() { + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY +} + +run() { + local label="$1" expr="$2" limit="$3" extra="${4:-}" + $CLICKHOUSE_LOCAL --allow_suspicious_fixed_string_types 1 --query " + SELECT number AS n, ${expr} AS v + FROM numbers(64) + SETTINGS max_block_size = 64, + output_format_arrow_compression_method = 'none', + output_format_arrow_max_record_batch_size_bytes = ${limit}${extra} + FORMAT ArrowStream + " > "$FILE" + echo -n "${label}: batches>1=$([ "$(batches)" -gt 1 ] && echo 1 || echo 0) " + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(n), uniqExact(v) FROM file('$FILE', ArrowStream)" +} + +# One block of 64 rows against a small bound, so each shape must split. +run "String" "repeat('x', 64)" 512 +run "Nullable(String)" "if(number % 3 = 0, NULL, repeat('y', 64))::Nullable(String)" 512 +run "LowCardinality" "toLowCardinality(repeat(toString(number % 4), 64))" 512 +run "Array(String)" "[repeat('z', 64)]" 512 +run "Map" "map('k', repeat('m', 64))" 512 +run "Tuple" "(repeat('p', 64), repeat('q', 64))" 512 +# Only the offsets mode gives `FixedString` a buffer the bound applies to; the default maps it to a +# fixed-width Arrow type instead. +run "FixedString" "toFixedString(repeat('f', 64), 64)" 512 ", output_format_arrow_fixed_string_as_fixed_byte_array = 0" + +# A fixed-width column has no offsets buffer to overflow, so the bound leaves it in one batch. +run "FixedString fixed-width" "toFixedString(repeat('f', 64), 64)" 512 +run "UInt64" "number" 64 diff --git a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh index ff237fd5db5b..20fc7c819b31 100755 --- a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh +++ b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh @@ -14,7 +14,7 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) BG_MESSAGE="M_bg_${CLICKHOUSE_DATABASE}" FG_MESSAGE="M_fg_${CLICKHOUSE_DATABASE}" -START=$(${CLICKHOUSE_CLIENT} --query "SELECT toString(now64(6))") +START=$(${CLICKHOUSE_CLIENT} --query "SELECT toUnixTimestamp64Micro(now64(6))") ${CLICKHOUSE_CLIENT} --query " CREATE TABLE dest_bg (s String) ENGINE = File(ProtobufSingle) @@ -33,10 +33,11 @@ do ${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS text_log" # The logger is checked too because this query is itself written to the text log, so otherwise # an iteration would match the previous one instead of the background exception. + # `event_date` is in the server time zone, and the session one is randomized. refused=$(${CLICKHOUSE_CLIENT} --query " SELECT count() > 0 FROM system.text_log - WHERE event_date >= toDate('${START}') - AND event_time_microseconds >= toDateTime64('${START}', 6) + WHERE event_date >= yesterday() + AND event_time_microseconds >= fromUnixTimestamp64Micro(${START}) AND logger_name LIKE '%StorageBuffer%' AND message LIKE '%can only be executed on behalf of a user%'") [ "$refused" = "1" ] && break diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference new file mode 100644 index 000000000000..5567708ffa73 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference @@ -0,0 +1,2 @@ +HTTP status code: 409 +requests: 1 diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh new file mode 100755 index 000000000000..1a260ca3f719 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +# `409 Conflict` reports a state mismatch on the server, so resending the same bytes cannot succeed. +# Retrying it only postpones the error the caller has to act on: an Iceberg REST catalog commit +# refused with `409` was resent `http_max_tries` times with backoff, adding ~32 seconds per conflict. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HTTP_PORT=$(python3 -c " +import socket +s = socket.socket() +s.bind(('127.0.0.1', 0)) +print(s.getsockname()[1]) +s.close() +") + +python3 -c " +import threading +from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + +requests = 0 +lock = threading.Lock() + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + global requests + if self.path == '/requests': + with lock: + body = str(requests).encode() + self.send_response(200) + else: + with lock: + requests += 1 + body = b'{\"error\": \"conflict\"}' + self.send_response(409) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + +ThreadingHTTPServer(('127.0.0.1', $HTTP_PORT), Handler).serve_forever() +" & +HTTP_PID=$! + +trap 'kill $HTTP_PID 2>/dev/null' EXIT + +for _ in {1..100}; do + if [ "$(${CLICKHOUSE_CURL} -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${HTTP_PORT}/requests")" = "200" ]; then + break + fi + sleep 0.1 +done + +${CLICKHOUSE_CLIENT} --query "SELECT * FROM url('http://127.0.0.1:${HTTP_PORT}/data', JSONEachRow, 'x Int32')" 2>&1 | grep -o "HTTP status code: 409" | head -n 1 + +echo "requests: $(${CLICKHOUSE_CURL} -s "http://127.0.0.1:${HTTP_PORT}/requests")" diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference new file mode 100644 index 000000000000..fe1489a7d47e --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference @@ -0,0 +1,4 @@ +low_cardinality_as_dictionary=0 record batches for 3 blocks: 3 +6 15 +low_cardinality_as_dictionary=1 record batches for 3 blocks: 3 +6 15 diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh new file mode 100755 index 000000000000..bff3fc53e4fa --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The writer splits a chunk across record batches only when it exceeds the 32-bit offsets of the Arrow +# buffers, so a small result must give exactly one batch per block for every type shape. A wrong row +# count from the split logic shows up only here: the data reads back correctly either way. +# +# `FORMAT ArrowStream` into a file rather than `INSERT INTO FUNCTION file`, whose path squashes the +# blocks into one. Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +GEN="SELECT + toString(number) AS s, + if(number % 3 = 0, NULL, toString(number))::Nullable(String) AS ns, + toLowCardinality(toString(number % 2)) AS lc, + arrayMap(x -> toString(x), range(number % 3)) AS arr, + arrayMap(y -> arrayMap(x -> toString(x), range(y)), range(number % 3)) AS arr2, + map(toString(number), toString(number % 2)) AS m, + (toString(number), toString(number % 2)) AS t, + toFixedString(toString(number), 3) AS fs, + number AS u +FROM numbers(6)" + +for lc_as_dict in 0 1; do + $CLICKHOUSE_LOCAL --query "${GEN} SETTINGS + max_block_size = 2, + output_format_arrow_compression_method = 'none', + output_format_arrow_fixed_string_as_fixed_byte_array = 0, + output_format_arrow_low_cardinality_as_dictionary = ${lc_as_dict} + FORMAT ArrowStream" > "$FILE" + + echo -n "low_cardinality_as_dictionary=${lc_as_dict} record batches for 3 blocks: " + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY + + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(u) FROM file('$FILE', ArrowStream)" +done diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference new file mode 100644 index 000000000000..15e7d3a0e939 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference @@ -0,0 +1,22 @@ +-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs +3 +-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs +3 +-- a nested unknown setting still throws +1 +-- a nested value the setting cannot take still throws +1 +-- a nested clause forwarded to the shards carries the clamped value +1 +-- the same query for an unconstrained user reads both shards +6 +-- a view with an invalid nested setting in its stored body fails on a direct read +1 +-- and on a remote shard through Distributed +1 +-- a parameterized view with an invalid nested setting fails on a direct read +1 +-- and on a remote shard +1 +-- the session settings are untouched +false diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh new file mode 100755 index 000000000000..f05616c8d829 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer +# (the clamp is analyzer-path behaviour; the legacy interpreter throws on such a nested clause) +# A nested `SETTINGS` clause is clamped to the session's settings constraints, and the clamped clause is +# what the query node keeps. So a shard receives the clamped clause, and an +# unknown name or an uncastable value in a nested clause throws, as it does in a top-level clause - also +# when the clause sits in a view's stored body and the view is read on a remote shard. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Users and settings profiles are server-global, so their names carry the test database to keep this +# test safe against a concurrent copy of itself - which is how the flaky check runs it. +SUFFIX="05141_${CLICKHOUSE_DATABASE}" +CONST_USER="user_const_${SUFFIX}" +CONST_PROFILE="profile_const_${SUFFIX}" +RO_USER="user_ro_${SUFFIX}" +RO_PROFILE="profile_ro_${SUFFIX}" +FREE_USER="user_free_${SUFFIX}" +DIST_USER="user_dist_${SUFFIX}" +DIST_PROFILE="profile_dist_${SUFFIX}" +TABLE="t_05141" +DIST_TABLE="dist_05141" +VIEW="v_05141" +DIST_VIEW="dist_v_05141" +PARAM_VIEW="pv_05141" + +${CLICKHOUSE_CLIENT} --query " +DROP USER IF EXISTS ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE IF EXISTS ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; + +CREATE TABLE ${CLICKHOUSE_DATABASE}.${TABLE} (id UInt32, s String) ENGINE = MergeTree ORDER BY id; +INSERT INTO ${CLICKHOUSE_DATABASE}.${TABLE} VALUES (1, 'a'), (2, 'b'), (3, 'c'); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE} AS ${CLICKHOUSE_DATABASE}.${TABLE} + ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${TABLE}); + +CREATE SETTINGS PROFILE ${CONST_PROFILE} SETTINGS use_query_cache = 0 CONST; +CREATE SETTINGS PROFILE ${RO_PROFILE} SETTINGS readonly = 1 CONST; +CREATE SETTINGS PROFILE ${DIST_PROFILE} SETTINGS max_rows_to_read MAX 2; +CREATE USER ${CONST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${CONST_PROFILE}; +CREATE USER ${RO_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${RO_PROFILE}; +CREATE USER ${FREE_USER} IDENTIFIED WITH no_password; +CREATE USER ${DIST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${DIST_PROFILE}; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.* TO ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +" + +# `CREATE` does not analyze the body of a view with an explicit column list nor of a parameterized view, so +# such definitions can carry an invalid nested setting. +${CLICKHOUSE_CLIENT} --query " +CREATE VIEW ${CLICKHOUSE_DATABASE}.${VIEW} (x UInt8) AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW} (x UInt8) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${VIEW}); +CREATE VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW} AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1) WHERE x = {p:UInt8}; +" + +# The bare binary, not ${CLICKHOUSE_CLIENT}: the harness's randomized settings would be rejected for the readonly user. +RESTRICTED_CLIENT="${CLICKHOUSE_CLIENT_BINARY} --host=${CLICKHOUSE_HOST} --port=${CLICKHOUSE_PORT_TCP} --database=${CLICKHOUSE_DATABASE}" +CONST="${RESTRICTED_CLIENT} --user=${CONST_USER}" +RO="${RESTRICTED_CLIENT} --user=${RO_USER}" +FREE="${RESTRICTED_CLIENT} --user=${FREE_USER}" +DIST="${RESTRICTED_CLIENT} --user=${DIST_USER}" + +echo "-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs" +${RO} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- a nested unknown setting still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threds = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a nested value the setting cannot take still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threads = 'abc')" 2>&1 | grep -c -F "CANNOT_PARSE_INPUT_ASSERTION_FAILED" + +# The IN subquery runs on the shards, whose user has no constraints. It must arrive with the value the +# initiator clamped (2, so reading 3 rows fails there), not with the value as written. +echo "-- a nested clause forwarded to the shards carries the clamped value" +${DIST} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" 2>&1 | grep -c -F "TOO_MANY_ROWS" + +echo "-- the same query for an unconstrained user reads both shards" +${FREE} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" + +# The bare binary again: `${CLICKHOUSE_CLIENT}` adds `--send_logs_level`, so the server's error log line would +# be printed too and `grep -c` would count two lines. +echo "-- a view with an invalid nested setting in its stored body fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${VIEW}" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# `prefer_localhost_replica = 0` is explicit: the local shard is analyzed under the initiator's query kind +# and already throws, so only the remote path exercises the fix, and the harness randomizes this setting. +echo "-- and on a remote shard through Distributed" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${DIST_VIEW} SETTINGS prefer_localhost_replica = 0" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a parameterized view with an invalid nested setting fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${PARAM_VIEW}(p = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# 127.0.0.2 is the non-local shard of `test_cluster_two_shards`; the port is explicit so the test runs on +# a non-default port; the database is qualified because the remote session does not inherit the test database. +echo "-- and on a remote shard" +${RESTRICTED_CLIENT} --query "SELECT * FROM remote('127.0.0.2:${CLICKHOUSE_PORT_TCP}', view(SELECT * FROM ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}(p = 1)))" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- the session settings are untouched" +${CONST} --query "SELECT getSetting('use_query_cache')" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; +DROP USER ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +" diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference new file mode 100644 index 000000000000..6ee89cf48413 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference @@ -0,0 +1,18 @@ +-- control: the setting is not changed in the session +0 1 +-- control: compatibility = '26.1' in a nested clause moves the setting to its old default +1 0 +-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level +1 1 +-- and stays on the query node +1 +-- same clause: an equal assignment before compatibility keeps the current value +1 1 +-- same clause: an equal assignment before a profile that carries compatibility keeps the current value +1 1 +-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one +1 +-- child scope: the same with a profile that carries compatibility in the inner one +1 +-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery +1 diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh new file mode 100755 index 000000000000..03ce5a1eebc0 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer + +# A nested `SETTINGS` change equal to the current value is applied and marks the setting as changed +# in the subquery's context, as at the top level. That flag is what `compatibility` respects +# ("changed manually" settings are left alone), also when `compatibility` sits in a profile or in +# a nested query, so the flag must not be dropped as a "no-op". + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Settings profiles are server-global, so the name carries the test database. +PROFILE="p_compat_05175_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE IF EXISTS ${PROFILE}" +${CLICKHOUSE_CLIENT} --query "CREATE SETTINGS PROFILE ${PROFILE} SETTINGS compatibility = '26.1'" + +Q="SELECT changed, value FROM system.settings WHERE name = 'ignore_format_null_for_explain'" + +echo "-- control: the setting is not changed in the session" +${CLICKHOUSE_CLIENT} --query "${Q}" + +echo "-- control: compatibility = '26.1' in a nested clause moves the setting to its old default" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS compatibility = '26.1')" + +echo "-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- and stays on the query node" +${CLICKHOUSE_CLIENT} --query "EXPLAIN QUERY TREE SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" | grep -c "SETTINGS ignore_format_null_for_explain=" + +echo "-- same clause: an equal assignment before compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, compatibility = '26.1')" + +echo "-- same clause: an equal assignment before a profile that carries compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, profile = '${PROFILE}')" + +echo "-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- child scope: the same with a profile that carries compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS profile = '${PROFILE}') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery" +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "SELECT value FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE ${PROFILE}" diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference new file mode 100644 index 000000000000..06604339ef49 --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference @@ -0,0 +1,7 @@ +ACCESS_DENIED: necessary to have the grant READ, WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +ACCESS_DENIED: Missing permissions: WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +424242 diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh new file mode 100755 index 000000000000..1fa58284b9aa --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Tags: no-object-storage, no-replicated-database +# no-object-storage: the query attaches a directory on the local disk, and there the table data lives on +# object storage. +# no-replicated-database: a Replicated database enqueues the query before the path is resolved against +# `user_files`, and the DDL worker then rejects the path as outside of `user_files`. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the data of the new table and moves it to +# the data path of the table, so it needs `READ ON FILE` like the `file` function and `WRITE ON FILE` like +# renaming files after processing. Without that check `CREATE TABLE` on a table of their own is enough for a +# user to read and consume data that somebody else staged in `user_files`. + +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +staged_root="${CLICKHOUSE_TEST_UNIQUE_NAME}_staged" +staged_table_dir="${staged_root}/data/staging/protected" + +# Stage a MergeTree table directory in `user_files` with clickhouse-local, as an admin or a migration +# workflow would do. An Ordinary database keeps the table directory at a known place. +${CLICKHOUSE_LOCAL} --path "${USER_FILES_PATH}/${staged_root}" --allow_deprecated_database_ordinary=1 --query " + CREATE DATABASE staging ENGINE = Ordinary; + CREATE TABLE staging.protected (id UInt64, secret UInt64) ENGINE = MergeTree ORDER BY id; + INSERT INTO staging.protected VALUES (1, 424242); +" + +${CLICKHOUSE_CLIENT} <&1 | grep -qF "$1"; then + echo "ACCESS_DENIED: $1" + else + echo "UNEXPECTED: the attach was not denied with: $1" + fi + ${CLICKHOUSE_CLIENT} --query "SELECT 'tables named stolen:', count() FROM system.tables WHERE database = currentDatabase() AND name = 'stolen'" + if [ -d "${USER_FILES_PATH}/${staged_table_dir}" ]; then + echo "staged directory is still in place" + else + echo "UNEXPECTED: the staged directory is gone" + fi +} +check_denied_and_untouched "necessary to have the grant READ, WRITE ON FILE" +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user" +check_denied_and_untouched "Missing permissions: WRITE ON FILE" + +# With both grants the same query attaches the data. +${CLICKHOUSE_CLIENT} --query "GRANT WRITE ON FILE TO $user" +${CLICKHOUSE_CLIENT} --user "$user" --query "$attach_query" +${CLICKHOUSE_CLIENT} --user "$user" --query "SELECT secret FROM stolen" + +${CLICKHOUSE_CLIENT} <&1 \ + | tr '\t' ' ' | grep -oE "QUOTA_REQUIRES_CLIENT_KEY|^[[:alnum:]_]+ [[:digit:]]+$" +} + +echo "1. warm two cached quota contexts of the same user, without and with a quota key" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "2. a tightening that keeps the key type reaches the warm context" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} FOR INTERVAL 100 YEAR MAX queries = 900" +usage --user "${user}" + +echo "3. switching the key type to client_key must reach both warm contexts" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY client_key FOR INTERVAL 100 YEAR MAX queries = 800" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "4. a user whose context was never cached is rejected the same way" +usage --user "${control_user}" + +echo "5. reverting the key type lets the never-detached context resume" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY user_name FOR INTERVAL 100 YEAR MAX queries = 700" +usage --user "${user}" + +${CLICKHOUSE_CLIENT} -q "DROP QUOTA ${quota}" +${CLICKHOUSE_CLIENT} -q "DROP USER ${user}, ${control_user}" diff --git a/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference new file mode 100644 index 000000000000..08c55835830b --- /dev/null +++ b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference @@ -0,0 +1,43 @@ +the reported oracle mismatch: count(p) + count(not p) + count(p is null) = count(*) +1 +predicate, row-level truth, answer over the partitioned table +assumeNotNull(c0) = 0 3 3 +assumeNotNull(c0) < 3 4 4 +NOT (assumeNotNull(c0) > 0) 3 3 +assumeNotNull(c0) >= 0 5 5 +assumeNotNull(c0) IN (0) 3 3 +isNull and isNotNull compared with a constant +(c0 IS NULL) >= true 2 2 +(c0 IS NOT NULL) < true 2 2 +not(1 < (c0 IS NULL)) 5 5 +the partition step is the sole pruner here, and it now keeps the NULL partition +MinMax +Condition: true +Parts: 4/4 +Partition +Condition: (isNull(c0) in [1, +Inf)) +Parts: 1/4 +ifNull and coalesce reach the same chain once the rewrite that usually hides them is off +ifNull(c0, 0) = 0 3 3 +coalesce(c0, 0) = 0 3 3 +NOT (ifNull(c0, 0) >= 7) 5 5 +NOT (coalesce(nullIf(c0, 5), 0) = 1) 4 4 +MinMax +Parts: 4/4 +Partition +Parts: 3/4 +reverse key 3 3 +LowCardinality(Nullable) key 3 3 +SummingMergeTree, the query the fuzzer reported +1 +control: with no NULL row the partition step is the only pruner and still prunes +isZeroOrNull(c0) >= true 1 +MinMax +Parts: 3/3 +Partition +Parts: 1/3 +control: the primary-key path already rejected the chain and is unchanged +assumeNotNull(c0) = 0 3 3 +control: a NULL-preserving wrapper maps the NULL row to NULL and still answers correctly +c0 + 1 = 1 1 1 +round(c0) = 0 1 1 diff --git a/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql new file mode 100644 index 000000000000..58bcbf7cc70d --- /dev/null +++ b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql @@ -0,0 +1,112 @@ +-- Tags: no-replicated-database, no-parallel-replicas +-- no-replicated-database: EXPLAIN output differs for replicated database. +-- no-parallel-replicas: EXPLAIN output differs for parallel replicas. +-- Test for https://github.com/ClickHouse/ClickHouse/issues/121133, https://github.com/ClickHouse/ClickHouse/issues/126369 and https://github.com/ClickHouse/ClickHouse/issues/127755 + +-- Randomized to 0 or 1, and the value changes the plan the EXPLAIN blocks below print. +SET parallel_replicas_local_plan = 1; +-- Statistics are a part-pruning source of their own; pinning it off keeps the Min-Max and +-- Partition steps the only pruners the EXPLAIN blocks below can attribute a Parts: count to. +SET use_statistics = 0; + +DROP TABLE IF EXISTS t_part; +DROP TABLE IF EXISTS t_flat; + +-- `t_flat` holds the same rows behind an unprunable key, so its answer is the row-level truth +-- that every other table below must reproduce. +CREATE TABLE t_part (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +CREATE TABLE t_flat (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY tuple() ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_part VALUES (NULL), (0), (1), (5), (NULL); +INSERT INTO t_flat VALUES (NULL), (0), (1), (5), (NULL); + +SELECT 'the reported oracle mismatch: count(p) + count(not p) + count(p is null) = count(*)'; +SELECT (SELECT count() FROM t_part WHERE assumeNotNull(c0) = 0) + + (SELECT count() FROM t_part WHERE NOT (assumeNotNull(c0) = 0)) + + (SELECT count() FROM t_part WHERE (assumeNotNull(c0) = 0) IS NULL) + = (SELECT count() FROM t_part) AS tlp_identity_holds; + +SELECT 'predicate, row-level truth, answer over the partitioned table'; +SELECT 'assumeNotNull(c0) = 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_part WHERE assumeNotNull(c0) = 0); +SELECT 'assumeNotNull(c0) < 3', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) < 3), (SELECT count() FROM t_part WHERE assumeNotNull(c0) < 3); +SELECT 'NOT (assumeNotNull(c0) > 0)', (SELECT count() FROM t_flat WHERE NOT (assumeNotNull(c0) > 0)), (SELECT count() FROM t_part WHERE NOT (assumeNotNull(c0) > 0)); +SELECT 'assumeNotNull(c0) >= 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) >= 0), (SELECT count() FROM t_part WHERE assumeNotNull(c0) >= 0); +-- A set atom carries its own copy of the chain and is applied by MergeTreeSetIndex, not by KeyCondition. +SELECT 'assumeNotNull(c0) IN (0)', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) IN (0)), (SELECT count() FROM t_part WHERE assumeNotNull(c0) IN (0)); + +SELECT 'isNull and isNotNull compared with a constant'; +SELECT '(c0 IS NULL) >= true', (SELECT count() FROM t_flat WHERE (c0 IS NULL) >= true), (SELECT count() FROM t_part WHERE (c0 IS NULL) >= true); +SELECT '(c0 IS NOT NULL) < true', (SELECT count() FROM t_flat WHERE (c0 IS NOT NULL) < true), (SELECT count() FROM t_part WHERE (c0 IS NOT NULL) < true); +SELECT 'not(1 < (c0 IS NULL))', (SELECT count() FROM t_flat WHERE not(1 < (c0 IS NULL))), (SELECT count() FROM t_part WHERE not(1 < (c0 IS NULL))); + +-- `isNull` reports no monotonicity, so only the single-point Partition step can use it: it is the sole +-- pruner and its Parts: denominator is the table's part count. +SELECT 'the partition step is the sole pruner here, and it now keeps the NULL partition'; +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_part WHERE (c0 IS NULL) >= true + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0 +) WHERE explain LIKE '%Condition%' OR explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +SELECT 'ifNull and coalesce reach the same chain once the rewrite that usually hides them is off'; +SELECT 'ifNull(c0, 0) = 0', (SELECT count() FROM t_flat WHERE ifNull(c0, 0) = 0), (SELECT count() FROM t_part WHERE ifNull(c0, 0) = 0); +SELECT 'coalesce(c0, 0) = 0', (SELECT count() FROM t_flat WHERE coalesce(c0, 0) = 0), (SELECT count() FROM t_part WHERE coalesce(c0, 0) = 0); +-- The rewrite applies only to a non-negated condition, so a negated one reaches the chain with the rewrite on. +SELECT 'NOT (ifNull(c0, 0) >= 7)', (SELECT count() FROM t_flat WHERE NOT (ifNull(c0, 0) >= 7)), (SELECT count() FROM t_part WHERE NOT (ifNull(c0, 0) >= 7)); + +-- An inner link can also produce a real NULL: `nullIf` maps the exact point 5 to one, and the chain +-- leaves it untransformed just like an infinity bound. Such a bound compares as both inside and +-- outside every range, so the negated atom is the form that can wrongly prune it; keep it negated. +SELECT 'NOT (coalesce(nullIf(c0, 5), 0) = 1)', (SELECT count() FROM t_flat WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1)), (SELECT count() FROM t_part WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1)); +-- Partition 1 is still pruned, so such a bound costs its own partition and no other. +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_part WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1) + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0, use_skip_indexes = 0 +) WHERE explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +DROP TABLE IF EXISTS t_rev; +CREATE TABLE t_rev (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY (c0 DESC) +SETTINGS allow_nullable_key = 1, allow_experimental_reverse_key = 1; +INSERT INTO t_rev VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'reverse key', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_rev WHERE assumeNotNull(c0) = 0); + +DROP TABLE IF EXISTS t_lc; +SET allow_suspicious_low_cardinality_types = 1; +CREATE TABLE t_lc (c0 LowCardinality(Nullable(Int))) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_lc VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'LowCardinality(Nullable) key', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_lc WHERE assumeNotNull(c0) = 0); + +DROP TABLE IF EXISTS t_smt; +CREATE TABLE t_smt (c0 Nullable(Int)) ENGINE = SummingMergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_smt VALUES (NULL), (0), (1), (NULL); +SELECT 'SummingMergeTree, the query the fuzzer reported'; +SELECT (SELECT count() FROM t_smt WHERE assumeNotNull(t_smt.c0) = false) + + (SELECT count() FROM t_smt WHERE NOT (assumeNotNull(t_smt.c0) = false)) + + (SELECT count() FROM t_smt WHERE (assumeNotNull(t_smt.c0) = false) IS NULL) + = (SELECT count() FROM t_smt) AS tlp_identity_holds; + +SELECT 'control: with no NULL row the partition step is the only pruner and still prunes'; +DROP TABLE IF EXISTS t_nonull; +CREATE TABLE t_nonull (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_nonull VALUES (0), (1), (5); +SELECT 'isZeroOrNull(c0) >= true', count() FROM t_nonull WHERE isZeroOrNull(c0) >= true; +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_nonull WHERE isZeroOrNull(c0) >= true + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0 +) WHERE explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +SELECT 'control: the primary-key path already rejected the chain and is unchanged'; +DROP TABLE IF EXISTS t_pk; +CREATE TABLE t_pk (c0 Nullable(Int)) ENGINE = MergeTree ORDER BY c0 SETTINGS allow_nullable_key = 1, index_granularity = 1; +INSERT INTO t_pk VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'assumeNotNull(c0) = 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_pk WHERE assumeNotNull(c0) = 0); + +SELECT 'control: a NULL-preserving wrapper maps the NULL row to NULL and still answers correctly'; +SELECT 'c0 + 1 = 1', (SELECT count() FROM t_flat WHERE c0 + 1 = 1), (SELECT count() FROM t_part WHERE c0 + 1 = 1); +SELECT 'round(c0) = 0', (SELECT count() FROM t_flat WHERE round(c0) = 0), (SELECT count() FROM t_part WHERE round(c0) = 0); + +DROP TABLE t_part; +DROP TABLE t_flat; +DROP TABLE t_rev; +DROP TABLE t_lc; +DROP TABLE t_smt; +DROP TABLE t_nonull; +DROP TABLE t_pk; diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference new file mode 100644 index 000000000000..c9a233584ace --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference @@ -0,0 +1,5 @@ +t_05291 (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE v = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE _row_exists = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291_replicated (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +0 diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql new file mode 100644 index 000000000000..58aa5021b160 --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql @@ -0,0 +1,47 @@ +-- Tags: no-fasttest +-- no-fasttest: the `s3` table function is not in the fast test build. + +-- A mutation entry keeps the real text of its commands, because the mutation is executed from it (on every +-- replica, for replicated tables). `system.mutations.command` must still hide the credentials of the table +-- functions in the mutation subqueries, the way the query log does. + +SET mutations_sync = 0; +SET lightweight_deletes_sync = 0; +SET allow_nondeterministic_mutations = 1; + +DROP TABLE IF EXISTS t_05291; +DROP TABLE IF EXISTS t_05291_replicated; + +CREATE TABLE t_05291 (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id; +CREATE TABLE t_05291_replicated (id UInt64, v UInt64) +ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/t_05291_replicated', 'r1') ORDER BY id; + +INSERT INTO t_05291 SELECT number, number FROM numbers(10); +INSERT INTO t_05291_replicated SELECT number, number FROM numbers(10); + +-- Keep the mutations pending, so that they stay in `system.mutations`. +SYSTEM STOP MERGES t_05291; +SYSTEM STOP MERGES t_05291_replicated; + +ALTER TABLE t_05291 DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291DELETE', 'CSV', 'c1 String')); +ALTER TABLE t_05291 UPDATE v = 0 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291UPDATE', 'CSV', 'c1 String')); +DELETE FROM t_05291 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291LIGHTWEIGHT', 'CSV', 'c1 String')); +ALTER TABLE t_05291_replicated DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291REPLICATED', 'CSV', 'c1 String')); + +-- The replica loads the mutations from ZooKeeper asynchronously; `PULL` fetches them synchronously. +SYSTEM SYNC REPLICA t_05291_replicated PULL; + +SELECT table, command FROM system.mutations WHERE database = currentDatabase() ORDER BY table, mutation_id; + +-- A secret cannot be probed with a filter on the column either. +SELECT count() FROM system.mutations WHERE database = currentDatabase() AND position(command, 'SECRET05291') > 0; + +-- `KILL MUTATION` parses the command that it reads from `system.mutations` to check the access rights. +KILL MUTATION WHERE database = currentDatabase() AND table = 't_05291' FORMAT Null; + +DROP TABLE t_05291; +DROP TABLE t_05291_replicated; diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference new file mode 100644 index 000000000000..a685fc6d0653 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference @@ -0,0 +1,6 @@ +-- baseline: the policy confines the user to its single tenant (1) +1 +-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards) +8 +-- and the shards consumed it through an explicit __getScalar reference (1) +1 diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh new file mode 100755 index 000000000000..add1062cda49 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# A row policy whose USING expression contains a scalar subquery (here `has((SELECT [2]), tenant_id)`) +# is resolved through the analyzer's scalar-subquery cache, which lives in the same `Context::scalars` +# map that a client can write to with a `Scalar` packet (the `clickhouse-client --external ... --scalar` +# feature). A restricted user could therefore name a client scalar with the policy subquery's query-tree +# hash and forge its result, replacing `(SELECT [2])` with an attacker-chosen array and reading every +# tenant's rows. On 26.3 `clickhouse-client` cannot send scalars (no `--external ... --scalar`), so the +# forged-scalar cases are left out and this test only pins the policy baseline and that scalars shipped +# to shards in distributed queries still resolve. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# User and policy names are server-global, so suffix them with the (unique) test database. +user="u_scalar_rlp_${CLICKHOUSE_DATABASE}" +policy="rp_scalar_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE IF EXISTS docs; +CREATE TABLE docs (id UInt64, tenant_id UInt8, secret String) ENGINE = MergeTree ORDER BY id; +INSERT INTO docs SELECT number, number, 'secret-' || toString(number) FROM numbers(1, 8); + +CREATE USER ${user} NOT IDENTIFIED; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.docs TO ${user}; +-- The policy confines ${user} to tenant 2 only, via a scalar subquery. +CREATE ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING has((SELECT [2]), tenant_id) TO ${user}; +-- Once a table has any policy, \`throw_on_unmatched_row_policies\` (on in the test config) rejects +-- reads by users no policy matches, so the default user needs a permissive one of its own. +CREATE ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING 1 TO ALL EXCEPT ${user}; +" + +echo "-- baseline: the policy confines the user to its single tenant (1)" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SELECT count() FROM ${CLICKHOUSE_DATABASE}.docs SETTINGS enable_scalar_subquery_optimization = 1" + +# Marking wire scalars as client-supplied must not disturb distributed queries: the initiator computes +# an array-returning scalar subquery once and ships the result to the shards in the same `Scalar` packet, +# where it arrives through `addClientScalar`. The shard consumes it through the explicit `__getScalar` +# reader, which still reads client-supplied entries, rather than through the narrowed subquery cache. +log_comment="scalar_rlp_dist_${CLICKHOUSE_DATABASE}" + +echo "-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards)" +${CLICKHOUSE_CLIENT} --log_comment "${log_comment}" --query " +SELECT count() FROM cluster('test_cluster_two_shards', '${CLICKHOUSE_DATABASE}', docs) +WHERE has((SELECT [2, 3, 4, 5]), tenant_id) +SETTINGS prefer_localhost_replica = 0, enable_scalar_subquery_optimization = 1" + +echo "-- and the shards consumed it through an explicit __getScalar reference (1)" +# The secondary queries log `current_database = 'default'` rather than the test database, so they are +# selected by the id of the initial query, which does carry it. +${CLICKHOUSE_CLIENT} --query " +SYSTEM FLUSH LOGS query_log; +SELECT count() > 0 FROM system.query_log +WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 0 + AND query LIKE '%__getScalar%' + AND initial_query_id IN ( + SELECT query_id FROM system.query_log + WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 1 + AND current_database = currentDatabase() AND log_comment = '${log_comment}')" + +${CLICKHOUSE_CLIENT} --query " +DROP ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs; +DROP ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs; +DROP TABLE docs; +" +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference new file mode 100644 index 000000000000..88b9566a6b12 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference @@ -0,0 +1,3 @@ +column 20 is out of range, the file has 5 columns +column 20 is out of range, the file has 5 columns +100 4950 diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh new file mode 100755 index 000000000000..27b41467be72 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: Depends on S3 + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A 569-byte ORC file (id Int64, name String, v Float64, part Int32) with one row, whose stripe footer declares a +# row index stream for column 20, but the file has 5 columns. Two readers indexed the selected-column mask with +# that id and aborted the server; both must report a malformed file instead: +# - remote reads prebuffer stripes (`ORC::Reader::preBuffer`), so the file is read through s3; +# - predicate pushdown loads the row indexes (`ORC::RowReader::loadStripeIndex`), also for local files. The +# predicate must keep the stripe (`id >= 0`; the row has id 1), or the stripe statistics skip it first. +ORC_B64=$(tr -d '\n' <<'B64' +T1JDEQAACgYSBAgBUAArAAAKEwoDAAAAEgwIARIGCAIQAhgCUAAzAAAKFwoFAAAAAAASDggBIggKAWESAWEYAlAAUwAACicKAgAA +EiEIARobCQAAAAAAAPg/EQAAAAAAAPg/GQAAAAAAAPg/UAArAAAKEwoDAAAAEgwIARIGCAAQABgAUAAHAABCAIADAABhBwAAQACA +EQAAAAAAAAAA+D8HAABAAACuAAAotS/9IGR1AgCEAwoGCAYQABgLCgYIBhABGBgCGBwDGCwUARABGAYCGAQKBggCEAIDARAEGAYS +AggAEgIIAgASAggCCAB7/hAam+nkirydJ0AbQIZdZQm6AAAotS/9IF+lAgBEBApdCgQIAVAACg4IARIGCAIQAhgCUABYBgoQCAEi +CAoBYRIBYQoKIwgBGhsJAPg/EQD4PxkA+D9QAFgLABAAGABQAFgGBQBKyAIaAUJwd1jtfAJ4AQAotS/9IOydBQBCyiYskLc5//// +///w6acgxiIELbemIDUZs4IjVzcRUBwT/pE0KZF9o02pZZNSphSQJ3okw0BbBghYiEDLlRuOvFiuU8aKKePElHHiyPYGVW7/bcVn +e6TQcm1Ni83htzOUa/ujDT2c/5Sg/4wO/hPqp6rnKrCqiyUKQ5//PDC42JMILQmsez1JVU0+1/o9wp3ZDoEFo2mF6HyRLSE6DwgA +SsgCGgFCcHdas32g06DT47p5Bgi/ARAFGICAECICAAwoYDAJgvQDA09SQxg= +B64 +) +FILE="05317_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$FILE', format='RawBLOB') SELECT base64Decode('$ORC_B64')" + +# Stripes are prebuffered only with `remote_filesystem_read_prefetch`, which CI randomizes. +$CLICKHOUSE_CLIENT --remote_filesystem_read_prefetch 1 \ + --query "SELECT * FROM s3(s3_conn, filename='$FILE', format='ORC') FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' + +# Predicate pushdown (on by default) on a local file, which is never prebuffered. +LOCAL_FILE="05317_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --engine_file_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION file('$LOCAL_FILE', 'RawBLOB') SELECT base64Decode('$ORC_B64')" +$CLICKHOUSE_CLIENT --input_format_orc_filter_push_down 1 \ + --query "SELECT * FROM file('$LOCAL_FILE', 'ORC') WHERE id >= 0 FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' +rm -f "${USER_FILES_PATH:?}/$LOCAL_FILE" + +# The server is still alive, and a valid ORC file is still read through the same path. +VALID="05317_valid_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$VALID', format='ORC') SELECT number AS id, toString(number) AS s FROM numbers(100)" +$CLICKHOUSE_CLIENT --query "SELECT count(), sum(id) FROM s3(s3_conn, filename='$VALID', format='ORC')" diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference new file mode 100644 index 000000000000..21113e5c614b --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference @@ -0,0 +1,18 @@ +-- Q-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded LF +contains CR, LF or NUL +400 +-- B-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded NUL +contains CR, LF or NUL +400 +-- Encoded word in the middle of the value +contains CR, LF or NUL +400 +-- Other encoded words are still decoded +café au lait +café diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh new file mode 100755 index 000000000000..ef96f960e4b3 --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# An RFC 2047 encoded word must not decode into CR, LF or NUL inside a header value: +# such a value could split the header when it is forwarded (e.g. to an HTTP authentication server). + +function check_rejected() +{ + local header="$1" + ${CLICKHOUSE_CURL} -sS -H "$header" -w '%{http_code}\n' "${CLICKHOUSE_URL}&query=SELECT+1" | grep -o -F -e 'contains CR, LF or NUL' -e '400' +} + +echo "-- Q-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?Q?x=0D=0AInjected:_1?=' +echo "-- Q-encoded LF" +check_rejected 'X-Test: =?UTF-8?Q?x=0AInjected:_1?=' +echo "-- B-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?B?eA0KSW5qZWN0ZWQ6IDE=?=' +echo "-- Q-encoded NUL" +check_rejected 'X-Test: =?UTF-8?Q?x=00y?=' +echo "-- Encoded word in the middle of the value" +check_rejected 'X-Test: prefix =?UTF-8?Q?=0D=0A?= suffix' + +echo "-- Other encoded words are still decoded" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?Q?caf=C3=A9_au_lait?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?B?Y2Fmw6k=?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference new file mode 100644 index 000000000000..7a770acba3a2 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference @@ -0,0 +1,7 @@ +json_whole 1 +json_whole_prewhere 1 +json_other_path 1 +tuple_whole 1 +map_size_and_key 1 +maps_other_map 1 +map_key_and_whole 1 diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql new file mode 100644 index 000000000000..a87623566a81 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql @@ -0,0 +1,79 @@ +-- Tags: no-parallel-replicas +-- no-parallel-replicas: read_bytes in the initiator's query_log does not include the replicas' reads. + +-- A condition on a cheap subcolumn gets its own PREWHERE read step, so the column it is combined with is read +-- only for the rows it keeps. No row passes the first condition, so a case reads about the bytes of that one alone. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; +SET optimize_move_to_prewhere = 1; +SET query_plan_optimize_prewhere = 1; +SET move_all_conditions_to_prewhere = 1; +SET enable_multiple_prewhere_read_steps = 1; +SET use_query_condition_cache = 0; + +DROP TABLE IF EXISTS t_json; +DROP TABLE IF EXISTS t_tuple; +DROP TABLE IF EXISTS t_map; +DROP TABLE IF EXISTS t_maps; + +CREATE TABLE t_json (id UInt64, j JSON) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_tuple (id UInt64, t Tuple(kind String, payload String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +-- Bucketed, with as many buckets as keys, so that `m['k1']` reads one bucket and not the whole Map. +CREATE TABLE t_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', + map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0; +CREATE TABLE t_maps (id UInt64, c Tuple(left Map(String, String), right Map(String, String))) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +-- Random values, so that the size of a column on disk, by which the conditions are ordered, reflects the cost of reading it. +INSERT INTO t_json SELECT number, concat('{"kind":"a","payload":"', hex(randomString(500)), '"}') FROM numbers(20000); +INSERT INTO t_tuple SELECT number, tuple('a', hex(randomString(500))) FROM numbers(20000); +INSERT INTO t_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> hex(randomString(30)), range(16))) FROM numbers(20000); +INSERT INTO t_maps SELECT number, tuple(map('k', 'a'), map('k', hex(randomString(500)))) FROM numbers(20000); + +SELECT count() FROM t_json WHERE j.kind = 'b' FORMAT Null SETTINGS log_comment = 'json_cheap'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' FORMAT Null SETTINGS log_comment = 'tuple_cheap'; +SELECT count() FROM t_map WHERE length(m) = 3 FORMAT Null SETTINGS log_comment = 'map_cheap'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' FORMAT Null SETTINGS log_comment = 'map_key_cheap'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' FORMAT Null SETTINGS log_comment = 'maps_cheap'; + +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole'; +SELECT count() FROM t_json PREWHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole_prewhere'; +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 FORMAT Null SETTINGS log_comment = 'json_other_path'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' AND length(toString(t)) > 10 FORMAT Null SETTINGS log_comment = 'tuple_whole'; +-- PREWHERE keeps the written order, which the WHERE optimizer may change based on the column sizes. +SELECT count() FROM t_map PREWHERE length(m) = 3 AND m['k1'] != '' FORMAT Null SETTINGS log_comment = 'map_size_and_key'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' AND c.right['k'] != '' FORMAT Null SETTINGS log_comment = 'maps_other_map'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 FORMAT Null SETTINGS log_comment = 'map_key_and_whole'; + +SYSTEM FLUSH LOGS query_log; + +SELECT c.case_name, q.bytes < 2 * base.bytes +FROM VALUES('idx UInt8, case_name String, base_name String', + (1, 'json_whole', 'json_cheap'), + (2, 'json_whole_prewhere', 'json_cheap'), + (3, 'json_other_path', 'json_cheap'), + (4, 'tuple_whole', 'tuple_cheap'), + (5, 'map_size_and_key', 'map_cheap'), + (6, 'maps_other_map', 'maps_cheap'), + (7, 'map_key_and_whole', 'map_key_cheap')) AS c +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS q ON q.log_comment = c.case_name +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS base ON base.log_comment = c.base_name +ORDER BY c.idx; + +DROP TABLE t_json; +DROP TABLE t_tuple; +DROP TABLE t_map; +DROP TABLE t_maps; diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference new file mode 100644 index 000000000000..fcc2c16d9ebd --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference @@ -0,0 +1,30 @@ +bucketed MergeTree +1 +MergeTree with bucketed zero-level parts +1 +basic MergeTree +1 +Memory +1 +explicit key subcolumn of a basic Map +8 8 +9 9 +results +8 8 +9 9 +8 8 +9 9 +8 8 +9 9 +Merge over a bucketed table +1 +MaterializedView with a bucketed target +1 +Buffer with a bucketed destination +1 +Merge over a bucketed and a basic table +1 +8 8 +8 8 +9 9 +9 9 diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql new file mode 100644 index 000000000000..cd62f633bf69 --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql @@ -0,0 +1,75 @@ +-- `m['key']` is rewritten to the Map key subcolumn `m.key_` only when the table serializes Maps +-- with buckets, because only then can a single key be read without the whole Map. +-- Both serialization settings are named in every table, clickhouse-test randomizes them. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; + +DROP TABLE IF EXISTS t_map_buffer; +DROP TABLE IF EXISTS t_map_mv; +DROP TABLE IF EXISTS t_map_merge; +DROP TABLE IF EXISTS t_map_memory; +DROP TABLE IF EXISTS t_map_basic; +DROP TABLE IF EXISTS t_map_zero_level_bucketed; +DROP TABLE IF EXISTS t_map_bucketed; + +CREATE TABLE t_map_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_zero_level_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_basic (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; +CREATE TABLE t_map_memory (id UInt64, m Map(String, UInt64)) ENGINE = Memory; + +INSERT INTO t_map_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_zero_level_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_basic SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_memory SELECT number, map('k', number) FROM numbers(10); + +SELECT 'bucketed MergeTree'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MergeTree with bucketed zero-level parts'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_zero_level_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'basic MergeTree'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_basic WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Memory'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_memory WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +SELECT 'explicit key subcolumn of a basic Map'; +SELECT id, m.key_k FROM t_map_basic WHERE m.key_k > 7 ORDER BY id; + +SELECT 'results'; +SELECT id, m['k'] FROM t_map_bucketed WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_basic WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_memory WHERE m['k'] > 7 ORDER BY id; + +-- Engines that pass the analyzed query to other tables answer for those tables. +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_bucketed$'); +CREATE MATERIALIZED VIEW t_map_mv (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets' +AS SELECT id, m FROM t_map_bucketed; +CREATE TABLE t_map_buffer (id UInt64, m Map(String, UInt64)) +ENGINE = Buffer(currentDatabase(), t_map_bucketed, 1, 10, 100, 10000, 1000000, 10000000, 100000000); + +SELECT 'Merge over a bucketed table'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MaterializedView with a bucketed target'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_mv WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Buffer with a bucketed destination'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_buffer WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +-- The query is sent to every table of a Merge, so all of them must be bucketed. +DROP TABLE t_map_merge; +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_(bucketed|basic)$'); + +SELECT 'Merge over a bucketed and a basic table'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT id, m['k'] FROM t_map_merge WHERE m['k'] > 7 ORDER BY id; + +DROP TABLE t_map_buffer; +DROP TABLE t_map_mv; +DROP TABLE t_map_merge; +DROP TABLE t_map_memory; +DROP TABLE t_map_basic; +DROP TABLE t_map_zero_level_bucketed; +DROP TABLE t_map_bucketed; diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference new file mode 100644 index 000000000000..dfd940ddad71 --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference @@ -0,0 +1,3 @@ +3000 30 +3000 4501500 +1000 499500 diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh new file mode 100755 index 000000000000..f36ec224287c --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires `IcebergLocal` (USE_AVRO build option) + +# Each finished Iceberg data file used to keep its Parquet encoder threads until the commit, so writing +# 30 partitions with `max_threads = 16` needed 480 threads of the 300-thread global pool. +# https://github.com/ClickHouse/ClickHouse/issues/126508 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 16); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 16); do printf ', number * %d' "$i"; done) +SETTINGS="SET allow_insert_into_iceberg = 1, max_insert_threads = 1, max_threads = 16, output_format_parquet_parallel_encoding = 1" + +# INSERT, then ALTER TABLE ... UPDATE, which writes one position delete file and one data file per partition. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32 ${COLS}) ENGINE = IcebergLocal('${TABLE_DIR}/update/') PARTITION BY p; + INSERT INTO t SELECT number % 30 ${EXPRS} FROM numbers(3000); + SELECT count(), uniqExact(_path) FROM t; + ALTER TABLE t UPDATE c1 = c1 + 1 WHERE 1; + SELECT count(), sum(c1) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 + +# ALTER TABLE ... DELETE writes two-column position delete files, so it needs more partitions to fill the pool. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32, x Int64) ENGINE = IcebergLocal('${TABLE_DIR}/delete/') PARTITION BY p; + INSERT INTO t SELECT number % 80, number FROM numbers(2000); + ALTER TABLE t DELETE WHERE x >= 1000; + SELECT count(), sum(x) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference new file mode 100644 index 000000000000..636bda45df5e --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference @@ -0,0 +1,4 @@ +[[[[NULL]]],[[[NULL]]]] +[NULL,NULL] +4 2 +server is alive diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh new file mode 100755 index 000000000000..81d6382e1910 --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# The fast-test build is unoptimized and re-runs a new test several times under a 60s cap, while +# materializing a deeply nested Dynamic value whose operation does not trip the recursion guard takes +# superlinear time. The optimized stateless configurations run it within budget. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Each repetition of 1E2B0801 is a value of type Array(Dynamic(max_types=8)) with one element, so the +# nesting depth of the Dynamic value comes from the data, not from the declared type. The second row is NULL. +nested_value() { echo "format(RowBinary, 'd Dynamic', unhex(concat(repeat('1E2B0801', $1), '0000')))"; } + +$CLICKHOUSE_CLIENT -q "SELECT arraySort([d, d]) FROM $(nested_value 3)" + +# Depending on the build and the stack size, a deep value is either processed or rejected with +# TOO_DEEP_RECURSION, but it must never crash the server or use memory quadratic in the depth. +# Parsing a value takes time quadratic in its depth (every level has a longer type name), so the deepest value, +# which exhausts the stack in the release build, is only used for the operations that recurse into the nested +# columns: `index`, `compareAt`, and `filter`. +check_query() { + out=$($CLICKHOUSE_CLIENT -q "$1 FORMAT Null" 2>&1) + [[ -z "$out" || "$out" == *TOO_DEEP_RECURSION* ]] || echo "$1: $out" +} +table=$(nested_value 1000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d, arrayJoin([1, 2]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done +table=$(nested_value 9000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done + +# Writing a part and merging parts go through the dynamic structure helpers of the column. +# Writing a part takes time quadratic in the nesting depth (every level adds substreams with longer names), +# so a depth that exhausts the stack takes tens of seconds; use a small depth that checks the normal path +# and stays far from the stack limit in sanitizer builds, where depth 300 already hits it. +# The substream names of a deep value exceed the file name length limit of the filesystem in a wide part, +# so they must be replaced with hashes regardless of the randomized MergeTree settings. +$CLICKHOUSE_CLIENT -q "CREATE TABLE deep_dynamic (d Dynamic) ENGINE = MergeTree ORDER BY tuple() SETTINGS replace_long_file_name_to_hash = 1, max_file_name_length = 127" +table=$(nested_value 64) +for query in "INSERT INTO deep_dynamic SELECT d FROM $table" "INSERT INTO deep_dynamic SELECT d FROM $table" "OPTIMIZE TABLE deep_dynamic FINAL"; do + out=$($CLICKHOUSE_CLIENT -q "$query" 2>&1) + [[ -z "$out" ]] || echo "$query: $out" +done +$CLICKHOUSE_CLIENT -q "SELECT count(), countIf(d IS NULL) FROM deep_dynamic" +$CLICKHOUSE_CLIENT -q "DROP TABLE deep_dynamic" + +$CLICKHOUSE_CLIENT -q "SELECT 'server is alive'" diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference new file mode 100644 index 000000000000..fcc653eab3e4 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference @@ -0,0 +1,5 @@ +writer: time zone is rejected +reader: time zone is rejected +reader file: time zone is rejected +--- stateless server is still alive --- +1 diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh new file mode 100755 index 000000000000..f8e04add8d56 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e + +# A malformed ORC timezone name used to reach an empty TZif file outside TZDIR and abort +# inside libc++. The time zones are now resolved only from the embedded time zone database, +# so such a name must be rejected without touching the file system. Keep each attempt in a child clickhouse-local process and disable core dumps. +ulimit -c 0 + +WORK_DIR="${CLICKHOUSE_TMP}/orc_timezone_traversal_${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${WORK_DIR}" +mkdir -p "${WORK_DIR}" +trap 'rm -rf "${WORK_DIR}"' EXIT + +regression_status=0 +python3 - "${WORK_DIR}" <<'PY' || regression_status=$? +import os +import pathlib +import shlex +import shutil +import subprocess +import sys + +work_dir = pathlib.Path(sys.argv[1]) +tz_dir = work_dir / "zoneinfo" / "a" / "b" +tz_dir.mkdir(parents=True) + +# Use real, minimal zone files so the valid setup and the ORC fixture can be loaded while +# TZDIR points at this private directory. The traversal resolves to this test's empty file. +system_zoneinfo = pathlib.Path("/usr/share/zoneinfo") +for zone in ("UTC", "America/Vancouver"): + source = system_zoneinfo / zone + if not source.is_file(): + raise SystemExit(f"required time zone file not found: {source}") + target = tz_dir / zone + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + +(work_dir / "outside").write_bytes(b"") +if (tz_dir / "../../../outside").resolve() != (work_dir / "outside").resolve(): + raise SystemExit("private timezone traversal fixture is misconfigured") +(work_dir / "dev").mkdir() +(work_dir / "dev" / "null").write_bytes(b"") +if (tz_dir / "../../../dev/null").resolve() != (work_dir / "dev" / "null").resolve(): + raise SystemExit("private ORC metadata traversal fixture is misconfigured") + +env = os.environ.copy() +env["TZDIR"] = str(tz_dir) +env["TZ"] = "UTC" +local_command = shlex.split(env["CLICKHOUSE_LOCAL"]) + + +def run_local(path, *args, query=None, input_data=None): + path.mkdir(parents=True, exist_ok=True) + command = local_command + ["--path", str(path), *args] + if query is not None: + command += ["--query", query] + return subprocess.run( + command, + input=input_data, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + + +safe_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='America/Vancouver', " + "output_format_orc_compression_method='none'" +) +fixture = run_local(work_dir / "safe", query=safe_query) +if fixture.returncode != 0 or not fixture.stdout.startswith(b"ORC"): + diagnostic = (fixture.stderr + fixture.stdout).decode(errors="replace") + raise SystemExit(f"could not create valid ORC fixture: {diagnostic[:1000]}") + +# Preserve the ORC file's byte lengths while replacing its writer timezone metadata +# with the path from the customer reproducer. This exercises a file supplied by a +# reader, without requiring a malicious query setting. +safe_name = b"America/Vancouver" +unsafe_name = b"../../../dev/null" +if len(safe_name) != len(unsafe_name) or fixture.stdout.count(safe_name) != 1: + raise SystemExit("valid ORC fixture has unexpected timezone metadata") +malicious_file = fixture.stdout.replace(safe_name, unsafe_name, 1) + +malicious_writer_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='../../../outside', " + "output_format_orc_compression_method='none'" +) +writer = run_local(work_dir / "writer", query=malicious_writer_query) +reader = run_local( + work_dir / "reader", + "--input-format=ORC", + "--input_format_orc_reader_time_zone_name=../../../outside", + query="SELECT * FROM table", + input_data=fixture.stdout, +) +reader_file = run_local( + work_dir / "reader_file", + "--input-format=ORC", + query="SELECT * FROM table", + input_data=malicious_file, +) + +failed = False +for label, result in (("writer", writer), ("reader", reader), ("reader file", reader_file)): + if result.returncode < 0: + print(f"{label}: terminated by signal {-result.returncode}") + failed = True + elif result.returncode == 0: + print(f"{label}: malformed timezone unexpectedly succeeded") + failed = True + elif any( + message in result.stdout + result.stderr + for message in (b"is not supported. Use a name from `system.time_zones`", b"Cannot load time zone ../../../") + ): + print(f"{label}: time zone is rejected") + else: + diagnostic = (result.stderr + result.stdout).decode(errors="replace") + first_line = next((line for line in diagnostic.splitlines() if line), "no diagnostic") + print(f"{label}: unexpected error: {first_line[:300]}") + failed = True + +if failed: + raise SystemExit(1) +PY + +echo '--- stateless server is still alive ---' +${CLICKHOUSE_CLIENT} --query "SELECT 1" +exit "${regression_status}" diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference b/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql new file mode 100644 index 000000000000..329dfc62bcda --- /dev/null +++ b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql @@ -0,0 +1,9 @@ +-- Tags: no-fasttest +-- no-fasttest: needs Azure Blob Storage support, which is not built in the fast test. + +-- The (url, sas_token) form of the Azure table functions parses a URL that ends right after the host like the same URL +-- with a trailing slash (both then fail at format detection), and rejects a malformed abfss URL with BAD_ARGUMENTS. +SELECT * FROM azureBlobStorage('https://acc.blob.core.windows.net', 'sv=2022'); -- { serverError CANNOT_DETECT_FORMAT } +SELECT * FROM azureBlobStorage('abfss://foo.net', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://foo.net/c/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://c.x@acc.dfs.core.windows.net/p/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference new file mode 100644 index 000000000000..e838531bffe0 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference @@ -0,0 +1,51 @@ +LIKE `t0` +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(KEY `k` (`x`)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +LIKE `t0` +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(KEY `k` (`x`)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(`x` int, `y` varchar(10)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh new file mode 100755 index 000000000000..ab7e6079e829 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `CREATE TABLE` in a MySQL dump without column definitions (`CREATE TABLE ... LIKE`, or only indexes or constraints) +# gives no structure, so the structure is inferred from the data of the `INSERT`. + +function dump() +{ + printf 'CREATE TABLE `t1` %s;\n/*!40101 SET character_set_client = @saved_cs_client */;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB'; do + echo "$create" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "DESCRIBE TABLE table" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" +done + +# The `INSERT` immediately following the `CREATE TABLE` must not be skipped. + +function dump_single_insert() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +function dump_multiple_inserts() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"');\nINSERT INTO `t1` VALUES (2,'"'"'b'"'"');\nINSERT INTO `t1` VALUES (3,'"'"'c'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB' '(`x` int, `y` varchar(10)) ENGINE=InnoDB'; do + echo "$create" + dump_single_insert "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --structure 'x UInt32, y String' --query "SELECT * FROM table" +done diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference new file mode 100644 index 000000000000..5453565c8dd8 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference @@ -0,0 +1,3 @@ +BAD_ARGUMENTS +x UInt32 +supported_values Map(String, UInt32) diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh new file mode 100755 index 000000000000..e551cdbc6837 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `map` whose value type is unsupported is skipped in schema inference with +# `input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1`. + +SCHEMADIR="$CUR_DIR/format_schemas" +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 0" 2>&1 | grep -o -m1 -F 'BAD_ARGUMENTS' +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1" diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference new file mode 100644 index 000000000000..739d1f2b1342 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference @@ -0,0 +1,4 @@ +Map(Int64, Nullable(Int64)) {1:1} +Map(Int64, Nullable(Int64)) {0:1} +Map(Int64, Nullable(Int64)) {2:3} +Map(Int64, Int64) {0:1} diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql new file mode 100644 index 000000000000..fb99be351299 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest +-- no-fasttest: MsgPack format is not available in the fasttest environment + +-- A MsgPack map whose first key has no inferable type (nil, empty array, empty map, nested map with a nil key) +-- must be reported as "cannot determine type", not dereferenced. + +SET input_format_msgpack_number_of_columns = 1; + +-- {1: 1} +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\x01\x01'); + +-- {nil: 1}, {[]: 1}, {{}: 1}, {{nil: 1}: 1} +DESC format(MsgPack, '\x81\xc0\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x90\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x80\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x81\xc0\x01\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- {nil: 1}, {2: 3}: the type is taken from the second row. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01\x81\x02\x03'); + +-- {nil: 1} with schema_inference_hints, which the error message suggests. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01') SETTINGS schema_inference_hints = 'c1 Map(Int64, Int64)'; diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference new file mode 100644 index 000000000000..98c80be8e58b --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference @@ -0,0 +1,5 @@ +0300000000000000 +c9b15b7fd5143f1d8f677be3dc4daab9 - +c9b15b7fd5143f1d8f677be3dc4daab9 - +9038957ba26f89fe09ee1964aad98576 - +9038957ba26f89fe09ee1964aad98576 - diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh new file mode 100755 index 000000000000..d6493c3c6808 --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# `RawBLOB` must write the serialized state of an aggregate function, the same as its conversion to `String`, +# not the pointer to the state in memory. + +$CLICKHOUSE_CLIENT -q "SELECT sumState(number) FROM numbers(3) FORMAT RawBLOB" | od -An -tx1 | tr -d ' \n' +echo + +$CLICKHOUSE_CLIENT -q "SELECT quantileState(number) FROM numbers(100000) FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(quantileState(number) AS String) FROM numbers(100000) FORMAT RawBLOB" | md5sum + +$CLICKHOUSE_CLIENT -q "SELECT uniqExactState(number) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(uniqExactState(number) AS String) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference new file mode 100644 index 000000000000..e5046dab0a10 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -0,0 +1,35 @@ +table created +-- ALTER with only ALTER SETTINGS +settings that are not a destination: allowed +-- ALTER with SELECT on the table, but no WRITE on S3 +-- ALTER ON CLUSTER is rejected by the initiator +-- ALTER ON CLUSTER of a table that does not exist on the initiator +-- ALTER with WRITE on S3 limited by a URL filter +-- ALTER with WRITE on S3 +destination with WRITE on S3: allowed +empty destination without WRITE on S3: allowed +-- ALTER with WRITE on S3, restricted by a row policy +empty destination with a row policy: allowed +-- ALTER through an Alias +settings that are not a destination through an alias: allowed +-- CREATE without WRITE on S3 or AZURE +table without a destination: created +-- CREATE AS with a destination, without WRITE on S3 +-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3 +-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3 +-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3 +-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3 +-- ATTACH with a full definition and a destination, without WRITE on S3 +-- RESTORE of a queue with a destination, without WRITE on S3 +0 +0 +0 +-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 +CREATE AS with WRITE on S3: created +materialized view with WRITE on S3: created +RESTORE with WRITE on S3: restored +RESTORE ON CLUSTER with WRITE on S3: restored +CREATE ON CLUSTER with WRITE on S3: created +CREATE AS ON CLUSTER with WRITE on S3: created +ATTACH with WRITE on S3: attached +RESTORE TEMPORARY with WRITE on S3: restored 1 diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh new file mode 100755 index 000000000000..5699f7262195 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -0,0 +1,377 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, zookeeper, no-replicated-database +# Tag no-fasttest: the `S3Queue` and `AzureQueue` engines are not built into the fast test build. +# Tag zookeeper: `S3Queue` keeps its state in Keeper, and `ON CLUSTER` queries use the distributed DDL queue. +# Tag no-replicated-database: with `access_control_improvements.enable_read_write_grants` disabled (the default), +# a replicated access storage round-trips the user through serialized SQL, which rewrites `WRITE ON S3('')` +# into the old-style whole-source `S3` grant without the filter. + +# The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +# `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads the processed files with its +# own credentials and writes them to the destination. So setting `after_processing_move_uri`, +# `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) +# source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. +# `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +db="${CLICKHOUSE_DATABASE}" +user_alter="s3queue_move_alter_${db}" +user_create="s3queue_move_create_${db}" +keeper_path="/s3queue_move_destination_access_${db}" +src="http://localhost:11111/test/${db}_move_src/" +dst="http://localhost:11111/test/${db}_move_dst/" +backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" +backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" +attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") +azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}', after_processing = 'keep' +" +echo "table created" + +$CLICKHOUSE_CLIENT -q " + CREATE USER ${user_alter}; + GRANT ALTER SETTINGS ON ${db}.t TO ${user_alter}; + CREATE USER ${user_create}; + GRANT CREATE TABLE ON ${db}.* TO ${user_create}; + GRANT TABLE ENGINE ON S3Queue TO ${user_create}; + GRANT TABLE ENGINE ON AzureQueue TO ${user_create}; +" + +echo "-- ALTER with only ALTER SETTINGS" + +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container redirects the move to another container of the same account. +# The check reads only the query, so it fails before the storage is involved, although `t` is an `S3Queue`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# Settings that do not choose a destination need only ALTER SETTINGS. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING polling_max_timeout_ms = 20000, after_processing_move_prefix = 'prefix_${db}' +" && echo "settings that are not a destination: allowed" + +echo "-- ALTER with SELECT on the table, but no WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${db}.t TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container is a destination change that needs `WRITE` on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER is rejected by the initiator" + +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" + +# The grants come from the settings in the query, not from the table, so the initiator checks them without the table. +# With the grant, the query reaches the host and fails there. +$CLICKHOUSE_CLIENT -q "GRANT ALTER SETTINGS, SELECT ON ${db}.t_missing TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError UNKNOWN_TABLE } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3 limited by a URL filter" + +# The move writes keys built from the prefix and the source keys, so a URL filter cannot authorize them. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3('${dst}.*') TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3('${dst}.*') FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} +" && echo "destination with WRITE on S3: allowed" + +# Resetting the destination disables the move, so it needs no grant for a destination. +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination without WRITE on S3: allowed" + +echo "-- ALTER with WRITE on S3, restricted by a row policy" + +# The move copies whole files, so a user whose row policy hides rows of the table cannot set a destination. +$CLICKHOUSE_CLIENT -q " + GRANT WRITE ON S3 TO ${user_alter}; + CREATE ROW POLICY p_${db} ON ${db}.t USING x = 1 TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +# Turning the move off needs no check. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination with a row policy: allowed" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY p_${db} ON ${db}.t; + REVOKE WRITE ON S3 FROM ${user_alter}; +" + +echo "-- ALTER through an Alias" + +# The export checks see only the name in the query, which is the alias, so the change is refused for every user. +$CLICKHOUSE_CLIENT --allow_experimental_alias_table_engine 1 -q "CREATE TABLE ${db}.t_alias ENGINE = Alias('${db}', 't')" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError NOT_IMPLEMENTED } +" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 +" && echo "settings that are not a destination through an alias: allowed" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_alias SYNC" + +echo "-- CREATE without WRITE on S3 or AZURE" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# The same CREATE without a destination, or with an empty one, needs no grant for it. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'keep', + after_processing_move_uri = '' +" && echo "table without a destination: created" + +echo "-- CREATE AS with a destination, without WRITE on S3" + +# The engine and the settings of `AS` are inherited after the query is parsed, so the check has to see the final definition. +# `AS` inherits the definition only when the query has no storage clause (with `SETTINGS`, the engine is +# `default_table_engine`), so the destination comes from the source table. +# The source has no `keeper_path`, so each copy gets its own default path from its `UUID`. +# `SELECT` is required because the definition of the source has secret parts. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_as_src (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', after_processing = 'move', after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "GRANT SHOW COLUMNS, SELECT ON ${db}.t_as_src TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3" + +# The engine is an inner engine of the view, and the inner table is created as an internal query, which checks nothing. +$CLICKHOUSE_CLIENT -q "GRANT CREATE VIEW ON ${db}.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3" + +# This format ships the query as written and the workers resolve `AS` with no user. +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_entry_format_version 2 -q " + CREATE TABLE ${db}.t_as_cluster ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3" + +# This format builds the definition on the initiator. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ATTACH with a full definition and a destination, without WRITE on S3" + +# A full definition in `ATTACH` is a new definition, like `CREATE`. An `Atomic` database needs a `UUID` for it. +# The server warns that a full definition in `ATTACH` is not recommended, so only errors are sent to the client. +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- RESTORE of a queue with a destination, without WRITE on S3" + +# The restored definition comes from the backup, and the table is created by an internal query, +# so the restore has to authorize the destination before it creates anything. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "BACKUP TABLE ${db}.t_backup TO ${backup} FORMAT Null" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_backup SYNC" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup'" + +# The hosts create the tables with no user, so the initiator must authorize the destination. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup_cluster'" + +# A temporary table keeps its engine, even with `restore_replace_external_engines_to_null`, so the same check applies. +# Temporary tables live in a session, so the table is created and backed up in one client. +$CLICKHOUSE_CLIENT -m -q " + CREATE TEMPORARY TABLE t_tmp_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_tmp_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys}; + BACKUP TEMPORARY TABLE t_tmp_backup TO ${backup_tmp} FORMAT Null; +" +$CLICKHOUSE_CLIENT -q "GRANT CREATE TEMPORARY TABLE ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} + SETTINGS structure_only = 1, restore_replace_external_engines_to_null = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" + +# The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src +" && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x +" && echo "materialized view with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE ON CLUSTER with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "CREATE ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src +" && echo "CREATE AS ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "ATTACH with WRITE on S3: attached" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; + SELECT 'RESTORE TEMPORARY with WRITE on S3: restored', count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference new file mode 100644 index 000000000000..1ee31d8b5520 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference @@ -0,0 +1,3 @@ +src 0 1 +src 1 2 +tgt 0 1 diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql new file mode 100644 index 000000000000..71c125e9ef63 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql @@ -0,0 +1,39 @@ +-- Two async inserts with the same `insert_deduplication_token` but different data are coalesced +-- into one batch. In the materialized view target, the rows of the two tokens land in different +-- partitions. For the partition of the second (duplicate) token, self-deduplication removes all +-- rows, and the recalculated block for that partition is empty. The empty block used to reach +-- `MergeTreeDataWriter::mergeBlock` and trigger the "Required source after the first merge is +-- not 0" logical error with `optimize_on_insert` enabled and a `ReplacingMergeTree` target. + +DROP TABLE IF EXISTS mv_dedup_empty; +DROP TABLE IF EXISTS tgt_dedup_empty; +DROP TABLE IF EXISTS src_dedup_empty; + +CREATE TABLE src_dedup_empty (p UInt64, v UInt64) ENGINE = MergeTree ORDER BY v; +CREATE TABLE tgt_dedup_empty (p UInt64, v UInt64) ENGINE = ReplacingMergeTree PARTITION BY p ORDER BY v + SETTINGS non_replicated_deduplication_window = 100; +CREATE MATERIALIZED VIEW mv_dedup_empty TO tgt_dedup_empty AS SELECT p, v FROM src_dedup_empty; + +SET async_insert = 1; +SET wait_for_async_insert = 0; +SET async_insert_deduplicate = 1; +SET deduplicate_blocks_in_dependent_materialized_views = 1; +SET optimize_on_insert = 1; +-- Prevent an automatic flush between the two inserts; the flush below is explicit. +SET async_insert_busy_timeout_min_ms = 600000; +SET async_insert_busy_timeout_max_ms = 600000; +SET async_insert_use_adaptive_busy_timeout = 0; + +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (0, 1); +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (1, 2); + +SYSTEM FLUSH ASYNC INSERT QUEUE src_dedup_empty; + +-- The source table has no deduplication window, so it keeps both rows. In the target table the +-- second insert is a duplicate of the first by token, so only the first row survives. +SELECT 'src', p, v FROM src_dedup_empty ORDER BY v; +SELECT 'tgt', p, v FROM tgt_dedup_empty ORDER BY v; + +DROP TABLE mv_dedup_empty; +DROP TABLE tgt_dedup_empty; +DROP TABLE src_dedup_empty; diff --git a/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference new file mode 100644 index 000000000000..be1f63edcc4c --- /dev/null +++ b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference @@ -0,0 +1,12 @@ +a1 x1 x1 x Nullable(String) +a3 x1 x1 x Nullable(String) +a1 x1 x1 x +a3 x1 x1 x +a1 x1 x1 x Nullable(String) +a3 x1 x1 x Nullable(String) +a1 x1 x1 x +a3 x1 x1 x +a1 x1 x1 x +a3 x1 x1 x +a1 x1 x1 x +a3 x1 x1 x diff --git a/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql new file mode 100644 index 000000000000..1ad38d850bb4 --- /dev/null +++ b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql @@ -0,0 +1,71 @@ +-- https://github.com/ClickHouse/ClickHouse/issues/127331: with join_use_nulls = 1, an outer join converted to INNER and +-- reordered so that its null-supplying side is joined first failed with "Cannot fold actions for projection". + +DROP TABLE IF EXISTS a; +DROP TABLE IF EXISTS b; +DROP TABLE IF EXISTS c; +DROP TABLE IF EXISTS d; + +CREATE TABLE a (k String, t String, v String) ENGINE = MergeTree ORDER BY k; +CREATE TABLE b (k String, t String, x String) ENGINE = MergeTree ORDER BY k; +CREATE TABLE c (x String, t String, v String) ENGINE = MergeTree ORDER BY x; +INSERT INTO a VALUES ('k1', 't1', 'a1'), ('k2', 't1', 'a2'), ('k3', 't2', 'a3'); +INSERT INTO b VALUES ('k1', 't1', 'x1'), ('k2', 't1', 'x2'), ('k3', 't2', 'x1'); +INSERT INTO c VALUES ('x1', 't1', 'x'), ('x2', 't1', 'y'), ('x1', 't2', 'x'); + +SELECT a.v, b.x, c.x, c.v, toTypeName(c.x) +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND b.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'greedy'; + +SELECT a.v, b.x, c.x, c.v +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND b.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'dpsize'; + +-- There are no transitive predicates in this version, so `a.t = c.t` is written explicitly to let `c` be joined with `a` before `b`. +SELECT a.v, b.x, c.x, c.v, toTypeName(c.x) +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND a.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'greedy'; + +SELECT a.v, b.x, c.x, c.v +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND a.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'dpsize'; + +SELECT ab.v, ab.x, c.x, c.v +FROM c RIGHT JOIN (SELECT a.v AS v, a.t AS t, b.x AS x FROM a JOIN b ON a.k = b.k AND a.t = b.t) AS ab ON ab.x = c.x AND ab.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'greedy'; + +DROP TABLE a; +DROP TABLE c; +CREATE TABLE a (k String, t String, v String) ENGINE = MergeTree ORDER BY k; +CREATE TABLE c (x String, t String, v String) ENGINE = MergeTree ORDER BY x; +CREATE TABLE d (w String) ENGINE = MergeTree ORDER BY w; +INSERT INTO a VALUES ('x1', 't1', 'a1'), ('x2', 't1', 'a2'), ('x1', 't2', 'a3'); +INSERT INTO c VALUES ('x1', 't1', 'x'), ('x2', 't1', 'y'); +INSERT INTO d VALUES ('x1'), ('x2'); + +SELECT a.v, b.x, c.x, c.v +FROM a JOIN d ON a.k = d.w JOIN b ON d.w = b.x AND a.t = b.t LEFT JOIN c ON b.x = c.x +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'dpsize'; + +DROP TABLE a; +DROP TABLE b; +DROP TABLE c; +DROP TABLE d; diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference new file mode 100644 index 000000000000..f7068f2917b6 --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference @@ -0,0 +1,7 @@ +parallel_distributed_insert_select=0 ACCESS_DENIED +parallel_distributed_insert_select=1 ACCESS_DENIED +parallel_distributed_insert_select=2 ACCESS_DENIED +0 +1 +row policy on source FALLBACK +additional_table_filters 0 diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh new file mode 100755 index 000000000000..1c39f64182cf --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="user_$CLICKHOUSE_DATABASE" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE secret_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + CREATE TABLE copy_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + INSERT INTO secret_local VALUES (1, 'secret'); + + CREATE TABLE src_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), secret_local, id); + CREATE TABLE dst_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), copy_local, id); + + DROP USER IF EXISTS $user; + CREATE USER $user IDENTIFIED WITH no_password; + GRANT SELECT, INSERT ON $CLICKHOUSE_DATABASE.dst_dist TO $user; +" + +# The cluster has no interserver secret, so the shard runs the forwarded query under the credentials +# from the cluster configuration rather than as the caller. +client=($CLICKHOUSE_CLIENT --user "$user" --prefer_localhost_replica 0) + +for setting in 0 1 2; do + echo -n "parallel_distributed_insert_select=$setting " + "${client[@]}" --parallel_distributed_insert_select "$setting" -q "INSERT INTO dst_dist SELECT * FROM src_dist" |& + grep -o -m1 'ACCESS_DENIED' || echo 'NOT DENIED' +done + +# Read the destination directly: resolving `dst_dist` also authorizes `copy_local` once the shard +# query is planned on the initiator, which depends on the distributed plan settings. +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# With the grant in place the optimized path must still work. +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON $CLICKHOUSE_DATABASE.src_dist TO $user" +"${client[@]}" --parallel_distributed_insert_select 2 -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# A row policy on the source table cannot be applied by the optimized rewrite (it ships the query +# to the shards, where the policy on the Distributed table never applies), so it must fall back to +# the regular path. The regular path reads `src_dist` with a `SELECT` sent to the shard, while the +# optimized rewrite sends only an `INSERT ... SELECT` there, so the fallback is detected by the +# kind of the secondary queries in `system.query_log`. (The regular path of this branch does not +# enforce a row policy on a Distributed table, so the result of the copy itself is not checked.) +# +# The two fallback cases below pin serialize_query_plan = 0: with plan serialization the initiator +# plans the read of the underlying table itself and requires the caller's own SELECT on it, which +# these cases do not grant. +$CLICKHOUSE_CLIENT -q "CREATE ROW POLICY policy_05443 ON src_dist USING id != 1 TO $user" +query_id="05443_row_policy_${CLICKHOUSE_DATABASE}_$RANDOM" +"${client[@]}" --parallel_distributed_insert_select 2 --enable_analyzer 1 --enable_parallel_replicas 0 \ + --serialize_query_plan 0 --query_id "$query_id" \ + -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY policy_05443 ON src_dist; + SYSTEM FLUSH DISTRIBUTED dst_dist; + TRUNCATE TABLE copy_local; + SYSTEM FLUSH LOGS query_log; + SELECT + 'row policy on source', + if(countIf(query_kind = 'Select') > 0 AND countIf(query_kind = 'Insert' AND query ILIKE '%SELECT%') = 0, + 'FALLBACK', 'OPTIMIZED') + FROM system.query_log + WHERE event_date >= yesterday() AND initial_query_id = '$query_id' AND NOT is_initial_query AND type = 'QueryFinish' +" + +# additional_table_filters is keyed by the source table name, which the optimized rewrite would +# drop, so it must fall back to the regular path, which applies the filter: the only row has +# id = 1, nothing is copied and the destination stays empty. +echo -n "additional_table_filters " +"${client[@]}" --parallel_distributed_insert_select 2 --enable_parallel_replicas 0 --serialize_query_plan 0 \ + --additional_table_filters "{'src_dist' : 'id != 1'}" -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH DISTRIBUTED dst_dist; SELECT count() FROM copy_local" + +$CLICKHOUSE_CLIENT -q "DROP USER $user" diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference new file mode 100644 index 000000000000..aca8188dbcd7 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference @@ -0,0 +1,13 @@ +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +0 1900-01-01 00:00:00.145224192 Nullable(DateTime64(9, \'UTC\')) +1 1900-01-01 00:00:00.000000000 Nullable(DateTime64(9, \'UTC\')) +2 2020-05-17 10:20:30.123456000 Nullable(DateTime64(9, \'UTC\')) +3 2262-04-11 23:47:16.854775807 Nullable(DateTime64(9, \'UTC\')) +4 \N Nullable(DateTime64(9, \'UTC\')) +0 1900-01-01 00:00:00.145225 Nullable(DateTime64(6, \'UTC\')) +1 1900-01-01 00:00:00.000000 Nullable(DateTime64(6, \'UTC\')) +2 2020-05-17 10:20:30.123456 Nullable(DateTime64(6, \'UTC\')) +3 2262-04-11 23:47:16.854775 Nullable(DateTime64(6, \'UTC\')) +4 \N Nullable(DateTime64(6, \'UTC\')) +2 diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh new file mode 100755 index 000000000000..184859b09430 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# INT96 timestamps 0001-01-01, 1800-01-01 12:30, 2020-05-17 10:20:30.123456, 9999-12-31 23:59:59 and NULL, written by +# pyarrow with `use_deprecated_int96_timestamps=True`. The first and the fourth do not fit into Int64 nanoseconds. +DATA_FILE="${CUR_DIR}/data_parquet/05443_int96_out_of_range.parquet" + +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'throw'" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet, 'id Int32, ts Nullable(DateTime64(6, \'UTC\'))') ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT count() FROM file('${DATA_FILE}', Parquet) WHERE ts > '2000-01-01' SETTINGS date_time_overflow_behavior = 'saturate';" diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference new file mode 100644 index 000000000000..0b775a99cb4f --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference @@ -0,0 +1,2 @@ +0 1900-01-01 00:00:00.000000000 -9223329600000000000 +0 1900-01-01 00:00:00.000000000 -9223329600000000000 diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh new file mode 100755 index 000000000000..39e02424f38a --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A single INT96 timestamp 1677-09-21 12:00:00 (julian day 2333836, time of day 43200000000000 ns), written by pyarrow +# with `use_deprecated_int96_timestamps=True`. Midnight of that day does not fit into Int64 nanoseconds, but the full value +# -9223329600000000000 does, so it must be read exactly instead of being saturated to the Int64 minimum or rejected. +DATA_FILE="${CUR_DIR}/data_parquet/05444_int96_lower_boundary.parquet" + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'throw';" diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference new file mode 100644 index 000000000000..aa20b4a60886 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference @@ -0,0 +1 @@ +ACCESS_DENIED diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh new file mode 100755 index 000000000000..71282f1c8437 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tags: distributed, no-fasttest +# Tag no-fasttest: the interserver `` requires SSL, which the fast test build does not have. + +# Queued `Distributed` inserts of different users must not be sent in one batch: the batch is sent with +# the `ClientInfo` of its first file, and over a cluster with an interserver `` the shard +# authenticates the whole batch as that file's `initial_user`. Before the fix, rows of a user without +# the remote `INSERT` grant were delivered under the identity of a user that had it. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Flushing the rejected file (also when the table is dropped) logs the error on the server. +CLICKHOUSE_CLIENT=$(echo "$CLICKHOUSE_CLIENT" | sed "s/--send_logs_level=${CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL:-none}/--send_logs_level=none/g") + +WRITER="writer_${CLICKHOUSE_DATABASE}" +TENANT="tenant_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${WRITER}, ${TENANT}; + CREATE TABLE target (key Int) ENGINE = MergeTree ORDER BY key; + CREATE TABLE dist (key Int) ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), target, 0) + SETTINGS background_insert_batch = 1; + SYSTEM STOP DISTRIBUTED SENDS dist; + CREATE USER ${WRITER} IDENTIFIED WITH no_password; + CREATE USER ${TENANT} IDENTIFIED WITH no_password; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.dist TO ${WRITER}, ${TENANT}; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.target TO ${WRITER}; +" + +${CLICKHOUSE_CLIENT} --user "${WRITER}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (1)" +${CLICKHOUSE_CLIENT} --user "${TENANT}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (2)" + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH DISTRIBUTED dist" 2>&1 | grep -o -m1 "ACCESS_DENIED" +${CLICKHOUSE_CLIENT} -q "SELECT key FROM target WHERE key = 2" + +${CLICKHOUSE_CLIENT} -m -q " + DROP TABLE dist; + DROP USER ${WRITER}, ${TENANT}; +" diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference new file mode 100644 index 000000000000..65bc13dc12ac --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference @@ -0,0 +1,13 @@ +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', '[HIDDEN]', 'container', 'blob') +SELECT * FROM icebergAzure('[HIDDEN]', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = '[HIDDEN]', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +HIDDEN +0 1 +0 1 diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh new file mode 100755 index 000000000000..8ef143807a79 --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no `azureBlobStorage` table function + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A storage account url carrying a credential of its own (a SAS `?sig=...`, `user:key@`), or a value that is +# not a plain string literal, is hidden whole in the Azure table functions, positional or as a named-collection +# override, as the `AzureBlobStorage` engine and the backup destination already do. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('https://user:plain_password@account.blob.core.windows.net', 'container', 'blob') +SELECT * FROM azureBlobStorage(concat('https://account.blob.core.windows.net/?sig=', 'plain_sas_signature'), 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +EOF + +# `SELECT` on a view implies `SHOW COLUMNS`, so a user granted only that sees the view definition through +# `SHOW CREATE TABLE` and `system.tables`, but not the SAS in it. +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +$CLICKHOUSE_CLIENT -q "DROP USER IF EXISTS ${user}" +$CLICKHOUSE_CLIENT -q "CREATE VIEW ${CLICKHOUSE_DATABASE}.v_sas AS SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'file.csv', 'CSV', 'none', 'id UInt8')" +$CLICKHOUSE_CLIENT -q "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'hello'" +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.v_sas TO ${user}" + +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SHOW CREATE TABLE ${CLICKHOUSE_DATABASE}.v_sas" | grep -o -e 'plain_sas_signature' -e 'HIDDEN' +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SELECT countIf(create_table_query LIKE '%plain_sas_signature%'), countIf(create_table_query LIKE '%[HIDDEN]%') FROM system.tables WHERE database = '${CLICKHOUSE_DATABASE}' AND name = 'v_sas'" + +# `EXPLAIN AST optimize = 1` expands the view, which executes the table function and needs more than `SELECT` +# on the view, so it is run as the default user, who sees no secrets either without +# `format_display_secrets_in_show_and_select`. +$CLICKHOUSE_CLIENT --format_display_secrets_in_show_and_select 0 -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN AST optimize = 1 SELECT * FROM ${CLICKHOUSE_DATABASE}.v_sas)" + +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.reference b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference new file mode 100644 index 000000000000..a46fd0469968 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference @@ -0,0 +1,14 @@ +1900-06-01 00:01:41.000007000 -2195942298999993 +1900-06-01 00:01:41.000000000 -2195942299000000 +1960-06-01 00:01:41.000007000 -302486298999993 +2000-06-01 00:01:41.000007000 959817701000007 +none 25000 609103159500350648 +zstd 25000 609103159500350648 +lz4 25000 609103159500350648 +snappy 25000 609103159500350648 +zlib 25000 609103159500350648 +expected 25000 609103159500350648 +1001 4500 5500 +1923 +['a','b','a','b'] +['a','b','a','b'] Array(LowCardinality(String)) diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.sh b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh new file mode 100755 index 000000000000..bee99fd05840 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The Arrow ORC adapter stores negative nanoseconds for the timestamps before the epoch, +# and the reader must decode them as the reference implementation does. +$CLICKHOUSE_LOCAL -q "SELECT t, toUnixTimestamp64Micro(t) FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_arrow.orc', ORC) SETTINGS session_timezone = 'UTC'" + +DATA_FILE="$CLICKHOUSE_TMP/05447_${CLICKHOUSE_DATABASE}.orc" + +# Dictionary encoding of strings (with the row index and several row groups), a non-GMT writer time +# zone, and the values that need all integer encodings: repeats, deltas, outliers. +QUERY="SELECT number AS n, + toString(number % 13) AS low_cardinality, + if(number % 5 = 0, NULL, concat('value_', toString(number))) AS high_cardinality, + toDateTime64(1700000000 + number * 37, 3, 'UTC') AS ts, + if(number % 1000 = 0, 1000000000000, number % 7) AS outliers, + intDiv(number, 100) AS runs, + toDecimal128(number, 10) * -3 AS dec +FROM numbers(25000)" + +for compression in none zstd lz4 snappy zlib +do + $CLICKHOUSE_LOCAL -q "$QUERY FORMAT ORC SETTINGS output_format_orc_compression_method = '$compression', + output_format_orc_dictionary_key_size_threshold = 0.5, output_format_orc_row_index_stride = 1000, + output_format_orc_writer_time_zone_name = 'America/Los_Angeles'" > "$DATA_FILE" + $CLICKHOUSE_LOCAL -q "SELECT '$compression', count(), sum(cityHash64(*)) FROM file('$DATA_FILE', ORC, + 'n UInt64, low_cardinality String, high_cardinality Nullable(String), ts DateTime64(3, \'UTC\'), outliers UInt64, runs UInt64, dec Decimal(38, 10)') + SETTINGS input_format_orc_reader_time_zone_name = 'America/Los_Angeles'" +done +$CLICKHOUSE_LOCAL -q "SELECT 'expected', count(), sum(cityHash64(*)) FROM ($QUERY)" + +# Filter pushdown skips the row groups by the statistics in the row index. +$CLICKHOUSE_LOCAL -q "SELECT count(), min(n), max(n) FROM file('$DATA_FILE', ORC) WHERE n BETWEEN 4500 AND 5500 SETTINGS input_format_orc_filter_push_down = 1" +$CLICKHOUSE_LOCAL -q "SELECT count() FROM file('$DATA_FILE', ORC) WHERE low_cardinality = '12' SETTINGS input_format_orc_filter_push_down = 1" + +# The dictionary of a string column nested in an array can have more entries than the stripe has rows. +$CLICKHOUSE_LOCAL -q "SELECT ['a', 'b', 'a', 'b'] AS arr FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 0.5" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT arr FROM file('$DATA_FILE', ORC, 'arr Array(String)')" +$CLICKHOUSE_LOCAL -q "SELECT arr, toTypeName(arr) FROM file('$DATA_FILE', ORC, 'arr Array(LowCardinality(String))')" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.reference b/tests/queries/0_stateless/05448_orc_date_after_2059.reference new file mode 100644 index 000000000000..62cea6b447e4 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.reference @@ -0,0 +1,12 @@ +0 1970-01-01 Nullable(Date32) +1 2059-09-17 Nullable(Date32) +2 2059-09-18 Nullable(Date32) +3 2100-01-01 Nullable(Date32) +4 2149-06-06 Nullable(Date32) +0 1970-01-01 +1 2059-09-17 +2 2059-09-18 +3 2100-01-01 +4 2149-06-06 +3 +4 diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.sh b/tests/queries/0_stateless/05448_orc_date_after_2059.sh new file mode 100755 index 000000000000..8cc480ff4b24 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `Date` is the unsigned number of days, and the dates after 2059-09-18 (more than 32767 days) used +# to be written to ORC as negative numbers, which read back as the dates before 1970. +DATA_FILE="$CLICKHOUSE_TMP/05448_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q "SELECT number AS n, toDate(d) AS d FROM values('number UInt64, d String', (0, '1970-01-01'), (1, '2059-09-17'), (2, '2059-09-18'), (3, '2100-01-01'), (4, '2149-06-06')) FORMAT ORC" > "$DATA_FILE" + +$CLICKHOUSE_LOCAL -q "SELECT n, d, toTypeName(d) FROM file('$DATA_FILE', ORC) ORDER BY n" +$CLICKHOUSE_LOCAL -q "SELECT n, d FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') ORDER BY n" + +# The statistics are correct as well, so the filter pushdown keeps the rows. +$CLICKHOUSE_LOCAL -q "SELECT n FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') WHERE d > '2060-01-01' ORDER BY n SETTINGS input_format_orc_filter_push_down = 1" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference new file mode 100644 index 000000000000..d5d2e9dad4f1 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference @@ -0,0 +1,5 @@ +-- page cache, prefetching read +0 0 +1 10 +2 20 +1 diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh new file mode 100755 index 000000000000..8b52986339b5 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: S3 (MinIO) is not available in the fast test. + +# Parsing a short CSV object through the userspace page cache with a prefetching read must not read past the end of the +# page cache cell that holds it. A sanitizer build aborts on such a read. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}/data.csv" + +CONFIG_FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_page_cache.yaml" +echo "page_cache_max_size: 134217728" > "${CONFIG_FILE}" + +# A 14-byte object: "0,0\n1,10\n2,20\n". +${CLICKHOUSE_CLIENT} --query " + INSERT INTO FUNCTION s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a UInt32, b UInt32') + SELECT number, number * 10 FROM numbers(3) SETTINGS s3_truncate_on_insert = 1" + +echo "-- page cache, prefetching read" +${CLICKHOUSE_LOCAL} --config-file "${CONFIG_FILE}" --query " + SELECT * FROM s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a String, b UInt32') ORDER BY b + SETTINGS input_format_parallel_parsing = 0, use_page_cache_for_object_storage = 1, + remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1; + SELECT value > 0 FROM system.metrics WHERE metric = 'PageCacheBytes'" + +rm "${CONFIG_FILE}" diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference new file mode 100644 index 000000000000..a4a9c43f01b2 --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference @@ -0,0 +1,8 @@ +1.6.0 0 18000000000 Mike +1.6.0 0 1 +1.6.0 1 18000000000 Mike +1.6.0 1 1 +1.6.11 0 18000000000 Mike +1.6.11 0 1 +1.6.11 1 18000000000 Mike +1.6.11 1 1 diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh new file mode 100755 index 000000000000..30badff1fa0d --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# The bloom filters written by the C++ writer of ORC 1.6.0 - 1.6.11 and 1.7.0 use incorrect hashing (ORC-1024) +# and must be ignored, otherwise the filter pushdown skips the matching rows. +for version in 1.6.0 1.6.11 +do + for push_down in 0 1 + do + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, id, name + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id = 18000000000 + SETTINGS input_format_orc_filter_push_down = $push_down" + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, count() + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id IN (18000000000, 18000000001) + SETTINGS input_format_orc_filter_push_down = $push_down" + done +done diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference new file mode 100644 index 000000000000..cf669808c66d --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference @@ -0,0 +1,39 @@ +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +SELECT * FROM azureBlobStorage('[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('[HIDDEN]', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=[HIDDEN]', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = '[HIDDEN]', storage_account_url = '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', connection_string = '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('[HIDDEN]', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]' +0 1 +0 1 +0 1 +0 1 +0 1 diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh new file mode 100755 index 000000000000..6246ea1d8cb3 --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Azure table functions and engines, whose arguments it then hides whole + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `clickhouse-format` hides the credentials in the arguments of the Azure table functions and engines and in the +# `SETTINGS` clause of `AzureQueue`, wherever the parser reads them from. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id', tenant_id = 'tid'), 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id'), extra_credentials(tenant_id = 'tid'), 'plain_account_key', 'CSV') +SELECT * FROM azureBlobStorageCluster(extra_credentials(client_id = 'id'), 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')) +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;SharedAccessSignature=sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=https://account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('HTTPS://user:plain_password=x@account.blob.core.windows.net/', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, client_secret = 'plain_client_secret', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = headers('Authorization' = 'plain_header_secret'), blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', storage_account_url = 'AccountName=account;AccountKey=plain_account_key_2') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = concat('AccountName=account;AccountKey=', 'plain_account_key'), connection_string = 'AccountName=account;AccountKey=plain_account_key_2') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage(azure_conf, sas_token = 'plain_sas_signature') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', 'plain_account_key' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'HTTPS://account.blob.core.windows.net/?sig=plain_sas_signature' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'https://user:plain_password=x@account.blob.core.windows.net/' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2' +EOF + +# The query tree hides an argument masked whole, not only the right side of a comparison. +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x'))" +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage(azure_conf, 'sp=r&sig=plain_sas_signature' = 'x'))" + +# Nothing inside an Azure `extra_credentials(...)` is dumped, keys included. +for explain in "AST" "QUERY TREE run_passes = 0"; do + $CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_client_%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN $explain SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')))" +done + +# The statement is logged with the credential hidden. +$CLICKHOUSE_CLIENT -q "EXPLAIN AST SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_logged')" > /dev/null +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS query_log" +$CLICKHOUSE_CLIENT -q "SELECT countIf(query LIKE '%plain_sas_logged%'), countIf(query LIKE '%[HIDDEN]%') FROM system.query_log WHERE current_database = currentDatabase() AND query LIKE 'EXPLAIN AST%azureBlobStorage%' AND type = 'QueryFinish' AND is_initial_query" diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.reference b/tests/queries/0_stateless/05473_orc_footer_content_length.reference new file mode 100644 index 000000000000..ae5399ce4997 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.reference @@ -0,0 +1,2 @@ +1 True True +1 True True diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.sh b/tests/queries/0_stateless/05473_orc_footer_content_length.sh new file mode 100755 index 000000000000..78921273f950 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. +# The `content_length` in the ORC footer covers only the stripes, not the metadata section with the stripe statistics. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +check() +{ + $CLICKHOUSE_LOCAL --query "$1" | python3 -c ' +import sys + +data = sys.stdin.buffer.read() + +def varint(buf, pos): + result = shift = 0 + while True: + byte = buf[pos] + pos += 1 + result |= (byte & 0x7f) << shift + shift += 7 + if byte < 0x80: + return result, pos + +def fields(buf): + pos = 0 + while pos < len(buf): + key, pos = varint(buf, pos) + if key & 7 == 0: + value, pos = varint(buf, pos) + elif key & 7 == 2: + length, pos = varint(buf, pos) + value = buf[pos:pos + length] + pos += length + else: + raise Exception("unexpected wire type") + yield key >> 3, value + +postscript_length = data[-1] +postscript = dict(fields(data[-1 - postscript_length:-1])) +footer_length = postscript[1] +footer = list(fields(data[-1 - postscript_length - footer_length:-1 - postscript_length])) +content_length = next(v for f, v in footer if f == 2) +stripes = [dict(fields(v)) for f, v in footer if f == 3] +stripes_length = sum(s.get(2, 0) + s.get(3, 0) + s.get(4, 0) for s in stripes) +print(len(stripes), content_length == stripes_length, postscript[5] > 0) +' +} + +check "SELECT number FROM numbers(3) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" +check "SELECT number, toString(number) FROM numbers(100000) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.reference b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference new file mode 100644 index 000000000000..754cd5dae768 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference @@ -0,0 +1,20 @@ +a Nullable(Int64) +b Nullable(Decimal(12, 0)) +c Nullable(Decimal(20, 2)) +d Nullable(Decimal(12, 2)) +e Nullable(Decimal(2, 2)) +17292380420 24 36164.16 0.03 0.01 +17292380421 38 63351.7 0.08 0.01 +17292380421 28 42673.96 0.09 0.06 +17292380421 40 76677.6 0.05 0.04 +17292380421 2 2096.48 0.07 0.07 +17292380421 42 45284.82 0.07 0.05 +17292380421 10 18572.9 0.01 0.08 +17292380422 12 14836.8 0.09 0.06 +17292380422 41 82152.52 0.07 0.02 +17292380422 38 47240.84 0.1 0 +38 0.08 +40 0.05 +42 0.07 +41 0.07 +38 0.1 diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.sh b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh new file mode 100755 index 000000000000..94e31bf56154 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `decimal64_v2.orc` from the examples of apache/orc has the format version 1.9999 (`UNSTABLE_PRE_2_0`), +# where the DECIMAL columns with the precision up to 18 are signed RLEv2 integers without the SECONDARY stream. +$CLICKHOUSE_LOCAL -q "DESCRIBE file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT * FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT b, d FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC) WHERE b > 30 SETTINGS input_format_orc_filter_push_down = 1" diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference new file mode 100644 index 000000000000..8588a3ce6bb6 --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference @@ -0,0 +1,4 @@ +400 79800 0 399 +58 11571 +INCORRECT_DATA +1 diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh new file mode 100755 index 000000000000..b0ebdedb176d --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: needs MinIO + +# A source of an object storage reads the Parquet footer of its next file in the background, while it reads the current one. +# One stream (`max_threads = 1`) reads all files, so every file but the first one is read through a prefetched footer. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +DIR="${CLICKHOUSE_TEST_UNIQUE_NAME}" +Q="${CLICKHOUSE_TEST_UNIQUE_NAME}_" + +for i in 0 1 2 3; do + ${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/good/${i}.parquet', format = Parquet) SELECT number + ${i} * 100 AS x FROM numbers(100)" +done +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/0.parquet', format = Parquet) SELECT number AS x FROM numbers(100)" +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/1.parquet', format = RawBLOB) SELECT 'not a parquet file'" + +# The footer is read in advance only by the native Parquet reader, which CI randomizes on this branch. +SETTINGS="--max_threads 1 --use_parquet_metadata_cache 1 --input_format_parquet_use_native_reader_v3 1" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}1" --query "SELECT count(x), sum(x), min(x), max(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet')" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}2" --query "SELECT count(x), sum(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet') WHERE x % 7 = 0" + +# The file that is not Parquet fails the query as it did before the footer was read in advance. +${CLICKHOUSE_CLIENT} $SETTINGS --query "SELECT sum(x) FROM s3(s3_conn, filename = '${DIR}/bad/*.parquet')" 2>&1 | grep -o -m1 "INCORRECT_DATA" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" + +# The second query finds all footers in the Parquet metadata cache. +# With parallel replicas, `s3` is rewritten to `s3Cluster` and the files are read by secondary queries, +# which run with `current_database = 'default'`, so the hits are summed over `initial_query_id`. +${CLICKHOUSE_CLIENT} --query " + SELECT sum(ProfileEvents['ParquetMetadataCacheHits']) >= 4 + FROM system.query_log + WHERE initial_query_id = '${Q}2' AND type = 'QueryFinish' + AND (current_database = currentDatabase() OR NOT is_initial_query) +" diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference new file mode 100644 index 000000000000..f23520f0dbfc --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference @@ -0,0 +1,2 @@ +batches: 4096 row counts: [64] +262144 1000 16777216 diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh new file mode 100755 index 000000000000..e71fb6e12721 --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# ^ pyarrow is not available in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One large block split by a small `output_format_arrow_max_record_batch_size_bytes` into thousands of +# record batches. The `LowCardinality` column never needs a split itself, but measuring it is linear in +# the rows given, so this is the shape where measuring the whole remainder of the block +# for every batch would be quadratic. Every batch is bounded by the `String` column: 64 rows of 64 bytes. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_many_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +$CLICKHOUSE_LOCAL --query " + SELECT + toLowCardinality(toString(number % 1000)) AS lc, + repeat('x', 64) AS s + FROM numbers(262144) + SETTINGS + max_block_size = 262144, + output_format_arrow_max_record_batch_size_bytes = 4096, + output_format_arrow_compression_method = 'none' + FORMAT ArrowStream" > "$FILE" + +python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + batches = list(ipc.open_stream(src)) +print("batches:", len(batches), "row counts:", sorted({batch.num_rows for batch in batches})) +PY + +$CLICKHOUSE_LOCAL --query " + SELECT count(), uniqExact(lc), sum(length(s)) + FROM file('$FILE', ArrowStream)" diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference new file mode 100644 index 000000000000..d00491fd7e5b --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference @@ -0,0 +1 @@ +1 diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh new file mode 100755 index 000000000000..eec443dcca49 --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Tags: zookeeper + +# `SYSTEM RESTORE DATABASE REPLICA` stops and replaces the DDL worker of a `Replicated` database. +# A DDL query that was concurrently waiting in the worker used to keep a raw pointer to it +# and dereference the destroyed worker (segmentation fault). Now such a query either succeeds +# or fails with an exception, and the server stays alive. + +# The racing queries fail with various errors by design; they are not interesting. +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=none + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +TIMEOUT=10 + +function ddl_thread() +{ + local i=0 + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + i=$((i + 1)) + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_${1}_${i} (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS ${DB}.t_${1}_${i} SYNC" >/dev/null 2>&1 + done +} + +function sync_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +function restore_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +ddl_thread 1 & +ddl_thread 2 & +ddl_thread 3 & +sync_thread & +restore_thread & +restore_thread & +wait + +# The server is alive and the database still accepts DDL. +for _ in $(seq 1 60); do + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_final (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 && break + sleep 1 +done +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t_final" + +$CLICKHOUSE_CLIENT --query "DROP DATABASE ${DB} SYNC" diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference new file mode 100644 index 000000000000..587aee15552b --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference @@ -0,0 +1,5 @@ +restore is waiting 1 +create succeeded +restore finished +1 +0 diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh new file mode 100755 index 000000000000..6ef139d50d2d --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# An initial DDL query of a `Replicated` database executes and commits on the submitting thread. +# `SYSTEM RESTORE DATABASE REPLICA` must wait for such a query that was already admitted by the old +# DDL worker before the new worker recovers the replica. Otherwise the query could commit its metadata +# while the recovery compares the Keeper snapshot with the local tables, and the recovery would move +# the just created table to the `_broken_replicated_tables` database. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +# Hold the initial `CREATE TABLE` after the DDL worker has admitted it, before it executes and commits. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = MergeTree ORDER BY x" & +create_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore stops the old DDL worker and then has to wait for the paused `CREATE TABLE`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $create_pid && echo "create succeeded" +# The restore proceeds only after the query has committed. The replica is not lost then (its digest is not empty), +# so the restore may refuse with `REPLICA_ALREADY_EXISTS`; either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +# The table created by the successful query is still there after the recovery of the replica. +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference new file mode 100644 index 000000000000..799f581f2dea --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference @@ -0,0 +1,6 @@ +d_complex LOADED +d_simple LOADED +1 1 +alive +4 +0 diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh new file mode 100755 index 000000000000..aa8ddefa8372 --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-llvm-coverage +# no-fasttest: waits 7 s for the update backoff; no-llvm-coverage: the file size limit below would also cut the coverage profile. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ssd_cache` dictionaries whose cache file cannot grow for the next partition stay usable after the failed update, +# and the next update fails the same way. The file size limit lets the first 64 KiB of each cache file be allocated, +# but not the next 64 KiB, while 100 values of 1.2 KB need more than that. + +dir="${CLICKHOUSE_USER_FILES_UNIQUE:?}" +rm -rf "${dir:?}" +mkdir -p "$dir" +trap 'rm -rf "${dir:?}"' EXIT + +query=" +CREATE TABLE src (k UInt64, v String) ENGINE = Memory; +INSERT INTO src SELECT number, toString(number) || ':' || repeat('x', 1200) FROM numbers(100); + +CREATE DICTIONARY d_simple (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_simple')); + +CREATE DICTIONARY d_complex (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(COMPLEX_KEY_SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_complex')); + +-- Both updates fail, because the cache files cannot grow. +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +-- Wait for the 5-6 s backoff after a failed update, so that the next lookups update the dictionaries again. +SELECT sleep(3) FORMAT Null; +SELECT sleep(3) FORMAT Null; +SELECT sleep(1) FORMAT Null; + +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +SELECT name, status FROM system.dictionaries ORDER BY name; +SELECT dictGet('d_simple', 'v', toUInt64(0)) = '0:' || repeat('x', 1200), dictGet('d_complex', 'v', tuple(toUInt64(0))) = '0:' || repeat('x', 1200); +SELECT 'alive'; +" + +( + cd "$dir" || exit 1 + ulimit -c 0 + trap '' XFSZ + ulimit -f 100 + $CLICKHOUSE_LOCAL --ignore-error --send_logs_level=error --query "$query" 2>"$dir/stderr" +) + +# Each of the four failed updates reports the failed allocation, and none of them was refused by the backoff. +grep -o -F 'Cannot preallocate space' "$dir/stderr" | wc -l +grep -o -F 'nearest update is scheduled' "$dir/stderr" | wc -l diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference new file mode 100644 index 000000000000..350939450c19 --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference @@ -0,0 +1,25 @@ +--- readonly_1 +READONLY +READONLY +READONLY +READONLY +READONLY +OK +--- readonly_2 +OK +OK +OK +OK +OK +--- readonly_0 +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +OK +--- requests to the endpoint +readonly_2_cluster 1 +readonly_2_describe 1 +readonly_2_remote 1 +readonly_2_select 1 diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh new file mode 100755 index 000000000000..621fcc5b8a8b --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Resolving the structure of a table function (`DESCRIBE TABLE url(...)`, or a table function nested in +# `cluster`) must require the same `CREATE TEMPORARY TABLE` grant as reading from it, and must be refused +# before the source is contacted. Otherwise a user who cannot run `url` (e.g. under `readonly = 1`) can make +# the server request an arbitrary endpoint and read the response from the schema inference error. + +USER_READONLY_1="readonly_1_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_2="readonly_2_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_0="readonly_0_${CLICKHOUSE_TEST_UNIQUE_NAME}" +TEMP_CREDENTIALS="unknown" + +# Create users with different readonly settings. +function create_users() { + ${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + CREATE USER ${USER_READONLY_1} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 1; + CREATE USER ${USER_READONLY_2} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 2; + -- \`readonly = 0\`, but without the \`CREATE TEMPORARY TABLE\` grant. + CREATE USER ${USER_READONLY_0} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}'; + GRANT SELECT ON *.*, READ ON URL, READ ON REMOTE TO ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${USER_READONLY_1}, ${USER_READONLY_2}; + " +} + +function drop_users() { + ${CLICKHOUSE_CLIENT} -q "DROP USER ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}" +} + +# Instead of a mock server, use this server's HTTP interface: every request to it is logged in `system.query_log` +# with the marker given as the argument, so `check_endpoint_requests` can tell whether the source was contacted. +# It always responds in `JSONEachRow`, like the JSON metadata service in the original report: the format passed +# to `url` is how the response is parsed, so `Values` fails to parse it and would echo the body in the error. +function endpoint() { + local marker="$1" + echo "${CLICKHOUSE_PORT_HTTP_PROTO}://${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?database=${CLICKHOUSE_DATABASE}&query=SELECT+1+AS+x,+%27marker_${marker}%27+AS+m+FORMAT+JSONEachRow" +} + +# Run a query as the given user and print `READONLY`, `ACCESS_DENIED`, `OK`, or the full unexpected error. +# `CLICKHOUSE_CLIENT` passes randomized settings, which a `readonly = 1` user is not allowed to change. +function run() { + local user="$1" + local query="$2" + local output + output=$(${CLICKHOUSE_CLIENT_BINARY} --host "${CLICKHOUSE_HOST}" --port "${CLICKHOUSE_PORT_TCP}" \ + --user "${user}" --password "${TEMP_CREDENTIALS}" -q "${query}" 2>&1) + if [[ "${output}" =~ \((READONLY|ACCESS_DENIED)\) ]]; then + echo "${BASH_REMATCH[1]}" + elif [[ "${output}" == *Exception* ]]; then + echo "${output}" + else + echo "OK" + fi +} + +# Run all the queries as one user. The user name without the unique suffix (e.g. `readonly_1`) +# labels the output and the endpoint markers. +function check_user() { + local user="$1" + local label="${user%_"${CLICKHOUSE_TEST_UNIQUE_NAME}"}" + echo "--- ${label}" + run "${user}" "SELECT * FROM url('$(endpoint "${label}_select")', 'JSONEachRow')" + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_describe")', 'JSONEachRow')" + # With a format that fails to parse the response, the schema inference error would contain the response body. + # It is skipped for `readonly_2`, which is allowed to read the URL: its error text depends on the server version. + if [[ "${label}" != "readonly_2" ]]; then + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_values")', 'Values')" + fi + + # `remote` is not allowed in readonly mode, so it is refused before the nested `url` is resolved. + run "${user}" "DESCRIBE TABLE remote('127.0.0.1', url('$(endpoint "${label}_remote")', 'JSONEachRow'))" + # `cluster` is allowed in readonly mode, but it resolves the structure of the nested `url` on the local shard. + run "${user}" "DESCRIBE TABLE cluster('test_shard_localhost', url('$(endpoint "${label}_cluster")', 'JSONEachRow'))" + + # Table functions allowed in readonly mode stay available without the grant. + run "${user}" "DESCRIBE TABLE numbers(1)" +} + +# Print the markers of the requests that reached the endpoint, i.e. which queries contacted the source. +# Only the queries of the `readonly = 2` user may appear: a marker without requests has no row. +function check_endpoint_requests() { + echo "--- requests to the endpoint" + ${CLICKHOUSE_CLIENT} -m -q " + SYSTEM FLUSH LOGS query_log; + SELECT extract(query, 'marker_([a-z0-9_]+)') AS marker, count() > 0 + FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE 'SELECT 1 AS x, %marker_%' + GROUP BY marker + ORDER BY marker; + " +} + +create_users +for user in "${USER_READONLY_1}" "${USER_READONLY_2}" "${USER_READONLY_0}"; do + check_user "${user}" +done +check_endpoint_requests +drop_users diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference new file mode 100644 index 000000000000..2e0aea006e63 --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference @@ -0,0 +1,6 @@ +1 +2 +3 +4 +1 [1,2,3] +1 [1,2,3] diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh new file mode 100755 index 000000000000..19aeaf05141f --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: MsgPack format is not available in the fasttest environment + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One async insert batch reuses one MsgPack input format for all its entries. Each case queues an +# invalid entry followed by a valid one: the valid entry must be parsed from a clean state. + +url="${CLICKHOUSE_URL}&async_insert=1&wait_for_async_insert=0&async_insert_use_adaptive_busy_timeout=0&async_insert_busy_timeout_min_ms=100000&async_insert_busy_timeout_max_ms=100000" + +function insert_pair() +{ + local table=$1 bad=$2 good=$3 + printf '%b' "$bad" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + printf '%b' "$good" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + ${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH ASYNC INSERT QUEUE ${table}" + ${CLICKHOUSE_CLIENT} -q "SELECT * FROM ${table} ORDER BY ALL" +} + +${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_scalar (x UInt64) ENGINE = MergeTree ORDER BY x; + CREATE TABLE t_exception (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; + CREATE TABLE t_array (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; +" + +# A uint32 with 1 of its 4 bytes; the valid entry is four rows 1, 2, 3, 4. +insert_pair t_scalar '\xce\x00' '\x01\x02\x03\x04' +# A string inside Array(UInt8) is rejected in the middle of the array. +insert_pair t_exception '\x07\x92\x01\xa1x' '\x01\x93\x01\x02\x03' +# An array of 3 elements with only 1 present. +insert_pair t_array '\x07\x93\x01' '\x01\x93\x01\x02\x03' + +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_scalar; DROP TABLE t_exception; DROP TABLE t_array" diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference new file mode 100644 index 000000000000..60ef3fadf28c --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference @@ -0,0 +1,13 @@ +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string +which the MySQL client library would read as a list of hosts +which the MySQL client library would read as a connection plugin URL +which the MySQL client library would read as the end of the host +connection failed +port 0: rejected +dictionary 127.0.0.1 port 0: rejected +dictionary localhost port 0: unix socket +dictionary localhost port 0: rejected +localhost: tcp +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh new file mode 100755 index 000000000000..bc24f80c9622 --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MySQL client library is not built in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The MySQL client library reinterprets some host strings: a connection string (which can set a socket, a plugin +# directory, TLS files), a connection plugin URL, a list of hosts, or a host cut at a NUL. They must be rejected +# before any connection attempt. + +# Prints how the host was rejected, or "connection failed" for an ordinary connection failure. +function check() +{ + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "$1" 2>&1 | tr -d '\000') + if grep -q -F "which the MySQL client library would read as" <<< "$output"; then + grep -o -m1 "which the MySQL client library would read as [a-zA-Z ]*" <<< "$output" + elif grep -q -F "ALL_CONNECTION_TRIES_FAILED" <<< "$output"; then + echo "connection failed" + else + echo "unexpected output: $output" + fi +} + +check "SELECT * FROM mysql('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('host=localhost;socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1,localhost:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('[replication://127.0.0.1]:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1\\0.example.com:1', 'db', 't', 'u', 'p')" + +# A plain host is passed through and fails to connect as usual. +check "SELECT * FROM mysql('127.0.0.1:1', 'db', 't', 'u', 'p')" + +# Port 0 would be replaced by the client library's default port. +$CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('127.0.0.1:0', 'db', 't', 'u', 'p')" 2>&1 \ + | grep -q -F "MySQL port 0" && echo "port 0: rejected" || echo "port 0: connection failed" + +# A dictionary socket is used only for `localhost`; for another host it is ignored and port 0 is rejected. +function check_dictionary() +{ + $CLICKHOUSE_CLIENT --send_logs_level=fatal -q " + CREATE DICTIONARY ${CLICKHOUSE_DATABASE}.d_mysql (x UInt64, y String) PRIMARY KEY x + SOURCE(MYSQL(HOST '$1' PORT 0 SOCKET '$2' USER 'u' PASSWORD 'p' DB 'db' TABLE 't')) + LAYOUT(FLAT()) LIFETIME(0)" + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM ${CLICKHOUSE_DATABASE}.d_mysql" 2>&1) + if grep -q -E "MySQL port 0|MySQL socket" <<< "$output"; then + echo "dictionary $1 port 0: rejected" + elif grep -q -F "through socket" <<< "$output"; then + echo "dictionary $1 port 0: unix socket" + else + echo "unexpected output: $output" + fi + $CLICKHOUSE_CLIENT -q "DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" +} +check_dictionary "127.0.0.1" "/nonexistent/mysqld.sock" +check_dictionary "localhost" "/nonexistent/mysqld.sock" +# The client library would read a socket starting with NUL as no socket and connect over TCP. +check_dictionary "localhost" "\\0" + +# `localhost` uses TCP to the given port, not the client library's default Unix socket. +output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('localhost:1', 'db', 't', 'u', 'p')" 2>&1) +if grep -q -F "Can't connect to server on 'localhost'" <<< "$output"; then + echo "localhost: tcp" +elif grep -q -F "through socket" <<< "$output"; then + echo "localhost: unix socket" +else + echo "unexpected output: $output" +fi + +# The `MySQL` database engine and table engine use the same connection pool. +check "CREATE DATABASE ${CLICKHOUSE_DATABASE}_mysql ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 'u', 'p')" +check "CREATE TABLE ${CLICKHOUSE_DATABASE}.t_mysql (x UInt32) ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p'); SELECT * FROM ${CLICKHOUSE_DATABASE}.t_mysql" + +$CLICKHOUSE_CLIENT -q "DROP DATABASE IF EXISTS ${CLICKHOUSE_DATABASE}_mysql; DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.t_mysql; DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference new file mode 100644 index 000000000000..6ccddfe23c73 --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference @@ -0,0 +1,4 @@ +after_processing_move_access_key_id key_id_05493 +after_processing_move_connection_string [HIDDEN] +after_processing_move_secret_access_key [HIDDEN] +mode unordered diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql new file mode 100644 index 000000000000..63571197469e --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` engine is not built in the fast test. + +-- `system.s3_queue_settings` hides the secrets that `SHOW CREATE TABLE` hides. + +DROP TABLE IF EXISTS t_secrets; + +CREATE TABLE t_secrets (a String) +ENGINE = S3Queue('http://whatever-we-dont-care:9001/root/t_secrets/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', + after_processing_move_access_key_id = 'key_id_05493', + after_processing_move_secret_access_key = 'SEKRIT_05493_1', + after_processing_move_connection_string = 'DefaultEndpointsProtocol=https;AccountName=a;AccountKey=SEKRIT_05493_2;'; + +SELECT name, value +FROM system.s3_queue_settings +WHERE database = currentDatabase() AND table = 't_secrets' + AND name IN ('after_processing_move_access_key_id', 'after_processing_move_secret_access_key', + 'after_processing_move_connection_string', 'mode') +ORDER BY name; + +DROP TABLE t_secrets; diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference new file mode 100644 index 000000000000..573541ac9702 --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference @@ -0,0 +1 @@ +0 diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql new file mode 100644 index 000000000000..1247bc62fb1f --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql @@ -0,0 +1,31 @@ +-- Tags: no-fasttest +-- no-fasttest: needs S3 support in the build. + +-- An SSE-C key that is not the base64 of a 256-bit key is rejected when the S3 client is created, before any request. + +-- Non-ASCII bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'éAAA'); -- { serverError BAD_ARGUMENTS } + +-- Valid base64 of 3 bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'AAAA'); -- { serverError BAD_ARGUMENTS } + +-- An invalid character in a key of the right length. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAx!jM0NTY3ODkwMTIzNDU2Nzg5MDE='); -- { serverError BAD_ARGUMENTS } + +-- A valid key followed by more characters. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=!'); -- { serverError BAD_ARGUMENTS } + +-- A valid key with surrounding whitespace. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = ' MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE= '); -- { serverError BAD_ARGUMENTS } + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name = 't_sse_c'; diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference new file mode 100644 index 000000000000..573a680fbe86 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference @@ -0,0 +1,16 @@ +nanoseconds local push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=1: (INCORRECT_DATA) +statistics local push_down=0 lazy=0: 3 +statistics local push_down=0 lazy=1: 3 +statistics local push_down=1 lazy=0: 3 +statistics local push_down=1 lazy=1: 3 +statistics remote push_down=0 lazy=0: 3 +statistics remote push_down=0 lazy=1: 3 +statistics remote push_down=1 lazy=0: 3 +statistics remote push_down=1 lazy=1: 3 diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh new file mode 100755 index 000000000000..53eae4b38eb0 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The nanoseconds of a timestamp with the 7 removed trailing zeros overflow `Int64`. +orc_check nanoseconds "$DATA/malformed_timestamp_nanoseconds.orc" 't Nullable(DateTime64(9))' "SELECT count(), max(t) FROM SOURCE" \ + 'Invalid timestamp in ORC column 1: seconds=[0-9]+, encoded nanoseconds=-?[0-9]+' + +# The minimum nanoseconds in the statistics is 0x80000000: such statistics must not be used by the filter pushdown. +orc_check statistics "$DATA/malformed_timestamp_statistics_nanoseconds.orc" 't DateTime64(9)' \ + "SELECT count() FROM SOURCE WHERE t > toDateTime64('2000-01-01 00:00:00', 9, 'UTC')" diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference new file mode 100644 index 000000000000..17ac0b58ed17 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference @@ -0,0 +1,7 @@ +1e308 ['0','1','2','0','1','2','0','1','2','0'] +-1e308 ['0','1','2','0','1','2','0','1','2','0'] +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +9223372036854775807 +-9223372036854775808 diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh new file mode 100755 index 000000000000..6da24b0909d7 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A dictionary threshold that does not fit in `size_t` when multiplied by the number of values. +for threshold in 1e308 -1e308; do + $CLICKHOUSE_LOCAL -q "SELECT toString(number % 3) AS s FROM numbers(10) FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = $threshold" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT '$threshold', groupArray(s) FROM table" +done + +# The extreme `DateTime64` values that cannot be stored in ORC with their statistics in milliseconds. +for value in 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(-9223372036854775808), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(1)'"'"')'; do + $CLICKHOUSE_LOCAL -q "SELECT $value AS t FORMAT ORC" 2>&1 >/dev/null | grep -oE '\(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE\)' | head -n1 | grep . || echo "$value: no error" +done + +# The extreme values with the nanoseconds can be stored. +for value in 9223372036854775807 -9223372036854775808; do + $CLICKHOUSE_LOCAL -q "SELECT reinterpret(toInt64($value), 'DateTime64(9, \'UTC\')') AS t FORMAT ORC" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT reinterpret(t, 'Int64') FROM table" +done diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference new file mode 100644 index 000000000000..2d165fb8a6c0 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference @@ -0,0 +1,16 @@ +empty local push_down=0 lazy=0: (INCORRECT_DATA) +empty local push_down=0 lazy=1: (INCORRECT_DATA) +empty local push_down=1 lazy=0: (INCORRECT_DATA) +empty local push_down=1 lazy=1: (INCORRECT_DATA) +empty remote push_down=0 lazy=0: (INCORRECT_DATA) +empty remote push_down=0 lazy=1: (INCORRECT_DATA) +empty remote push_down=1 lazy=0: (INCORRECT_DATA) +empty remote push_down=1 lazy=1: (INCORRECT_DATA) +nulls local push_down=0 lazy=0: 5 5 +nulls local push_down=0 lazy=1: 5 5 +nulls local push_down=1 lazy=0: 5 5 +nulls local push_down=1 lazy=1: 5 5 +nulls remote push_down=0 lazy=0: 5 5 +nulls remote push_down=0 lazy=1: 5 5 +nulls remote push_down=1 lazy=0: 5 5 +nulls remote push_down=1 lazy=1: 5 5 diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh new file mode 100755 index 000000000000..437d071ce5a5 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# A dictionary without entries referenced by the non-null values. +orc_check empty "$DATA/malformed_dictionary_empty.orc" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" \ + 'ORC dictionary index 0 at row 0 is out of range \[0, 0\)' + +# A valid empty dictionary of a column with only nulls. +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_nulls.orc" +trap 'rm -f "$FILE"' EXIT +$CLICKHOUSE_LOCAL -q "SELECT CAST(NULL, 'Nullable(String)') AS s FROM numbers(5) INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 1" +orc_check nulls "$FILE" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.reference b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference new file mode 100644 index 000000000000..1e94a8329c54 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference @@ -0,0 +1,32 @@ +compression_block local push_down=0 lazy=0: 1 10000 +compression_block local push_down=0 lazy=1: 1 10000 +compression_block local push_down=1 lazy=0: 1 10000 +compression_block local push_down=1 lazy=1: 1 10000 +compression_block remote push_down=0 lazy=0: 1 10000 +compression_block remote push_down=0 lazy=1: 1 10000 +compression_block remote push_down=1 lazy=0: 1 10000 +compression_block remote push_down=1 lazy=1: 1 10000 +dictionary_size local push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.sh b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh new file mode 100755 index 000000000000..bc5685ba3187 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The memory must be allocated by the size of the data, not by the sizes declared in the file. +LIMIT='max_memory_usage = 100000000' + +# The declared compression block size is 1 GiB, the chunks are small. The schema inference reads the compressed footer. +orc_check compression_block "$DATA/malformed_compression_block_1g.orc" '' "SELECT count(), sum(length(s)) FROM SOURCE" '' "$LIMIT" + +# The declared dictionary size is 2^32 - 1, the stream has a few entries. +orc_check dictionary_size "$DATA/malformed_dictionary_size_max.orc" 's Nullable(String)' "SELECT count(), sum(length(s)) FROM SOURCE" \ + 'Unexpected end of ORC stream column 1 kind 2' "$LIMIT" + +# The sizes stored in the snappy and zstd chunks are 1 GiB, the chunks have a few bytes. +orc_check snappy_chunk_size "$DATA/malformed_snappy_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'snappy-compressed chunk of ORC file decompresses to 1073741824 bytes' "$LIMIT" +orc_check zstd_chunk_size "$DATA/malformed_zstd_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'Malformed zstd-compressed data in ORC file' "$LIMIT" diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference new file mode 100644 index 000000000000..3c50f86ded0e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference @@ -0,0 +1,16 @@ +stripe local push_down=0 lazy=0: (INCORRECT_DATA) +stripe local push_down=0 lazy=1: (INCORRECT_DATA) +stripe local push_down=1 lazy=0: (INCORRECT_DATA) +stripe local push_down=1 lazy=1: (INCORRECT_DATA) +stripe remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe remote push_down=1 lazy=1: (INCORRECT_DATA) +stream local push_down=0 lazy=0: (INCORRECT_DATA) +stream local push_down=0 lazy=1: (INCORRECT_DATA) +stream local push_down=1 lazy=0: (INCORRECT_DATA) +stream local push_down=1 lazy=1: (INCORRECT_DATA) +stream remote push_down=0 lazy=0: (INCORRECT_DATA) +stream remote push_down=0 lazy=1: (INCORRECT_DATA) +stream remote push_down=1 lazy=0: (INCORRECT_DATA) +stream remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh new file mode 100755 index 000000000000..2d3b50f7f31e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The sum of the offset and the lengths of the stripe overflows `UInt64`. +orc_check stripe "$DATA/malformed_stripe_offset_overflow.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stripe information at stripe index 0' + +# The length of a stream of a column that is not read is 2^64 - 1, the offsets of the next streams wrap around. +orc_check stream "$DATA/malformed_stream_offset_overflow.orc" 'b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stream.*11.*18446744073709551615' diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference new file mode 100644 index 000000000000..1fafd3d526a4 --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference @@ -0,0 +1,32 @@ +row_groups local push_down=1 lazy=0: (INCORRECT_DATA) +row_groups local push_down=1 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=1: (INCORRECT_DATA) +row_groups local push_down=0 lazy=0: (INCORRECT_DATA) +row_groups local push_down=0 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=0 lazy=0: (INCORRECT_DATA) +patched_base local push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=1 lazy=0: (INCORRECT_DATA) +patched_base local push_down=1 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek local push_down=0 lazy=0: 1 +row_index_seek local push_down=0 lazy=1: 1 +row_index_seek local push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek local push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek remote push_down=0 lazy=0: 1 +row_index_seek remote push_down=0 lazy=1: 1 +row_index_seek remote push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_control local push_down=0 lazy=0: 1 +row_index_control local push_down=0 lazy=1: 1 +row_index_control local push_down=1 lazy=0: 1 +row_index_control local push_down=1 lazy=1: 1 +row_index_control remote push_down=0 lazy=0: 1 +row_index_control remote push_down=0 lazy=1: 1 +row_index_control remote push_down=1 lazy=0: 1 +row_index_control remote push_down=1 lazy=1: 1 diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh new file mode 100755 index 000000000000..163a644dea9f --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The stripe has 2^64 - 1 rows: rounding up the number of row groups overflows. +ORC_PUSH_DOWN_VALUES=1 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'The row index of ORC column 1 has 2 entries, less than the [0-9]+ row groups of stripe 0' +ORC_PUSH_DOWN_VALUES=0 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Unexpected end of ORC stream column 1 kind 1' + +# A PATCHED_BASE run whose last patch is a continuation (gap 255, patch 0). +orc_check patched_base "$DATA/malformed_patched_base_terminal_continuation.orc" 'x Int64' "SELECT count(), sum(x) FROM SOURCE" \ + 'Corrupt PATCHED_BASE encoded data in ORC stream column 1 kind 1 in stripe 0 \(unterminated gap\)' + +# A row index position beyond the end of the stream, and the same file with the valid position. +orc_check row_index_seek "$DATA/malformed_row_index_seek_past_stream.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Seek position 127 is beyond the end of ORC stream column 1 kind 1 in stripe 0 of size 3' +orc_check row_index_control "$DATA/row_index_seek_control.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference new file mode 100644 index 000000000000..bac3e0b9f016 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference @@ -0,0 +1,16 @@ +footer_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh new file mode 100755 index 000000000000..9c0fb713fb91 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The number of the repeated objects in the metadata is limited by the numbers of the columns and the stripes. +orc_check footer_statistics "$DATA/malformed_footer_too_many_statistics.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many column statistics in ORC footer: 13, the file has 3 columns' +orc_check stripe_statistics "$DATA/malformed_metadata_too_many_stripes.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many stripe statistics in ORC metadata, at most 1 expected' diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference new file mode 100644 index 000000000000..7f41d79fbe44 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference @@ -0,0 +1,21 @@ +t < fromUnixTimestamp64Nano(-500000001, 'UTC') +500 +500 0 499 +500 0 499 +t <= fromUnixTimestamp64Nano(-500000001, 'UTC') +600 +501 0 500 +501 0 500 +t = fromUnixTimestamp64Nano(-950000001, 'UTC') +100 +1 50 50 +1 50 50 +t = fromUnixTimestamp64Nano(-999500000, 'UTC') +1 +1 1 1 +1 1 1 +-2000000000 1 +-1 1 +-999500000 1 +-1500000 1 +1000000000 1 diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh new file mode 100755 index 000000000000..21a4b8bb4428 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Prints the number of rows that are not pruned, and the result with and without the filter pushdown. +function check() +{ + local condition=$1 + echo "$condition" + $CLICKHOUSE_LOCAL -q " + SELECT count() FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE indexHint($condition); + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition; + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition + SETTINGS input_format_orc_filter_push_down = 0" +} + +# The timestamps before the epoch with a negative sub-millisecond part, from -1.000000001 to -0.001000001 seconds, +# in row groups of 100 rows. Their statistics must allow the pruning. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano(toInt64(number) * 1000000 - 1000000001, 'UTC') AS t FROM numbers(1000) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 100" +check "t < fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t <= fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t = fromUnixTimestamp64Nano(-950000001, 'UTC')" + +# A timestamp in the millisecond after -1 second, in its own row group: the pruning must keep it. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano([-2000000000, -999500000, -500000000][number + 1], 'UTC') AS t FROM numbers(3) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 1" +check "t = fromUnixTimestamp64Nano(-999500000, 'UTC')" + +# A file from PyArrow (the C++ writer of ORC) with a bloom filter, which rounds the negative milliseconds toward zero, +# and one row in each row group: the bloom filter must keep the matching rows. +for value in -2000000000 -1 -999500000 -1500000 1000000000; do + $CLICKHOUSE_LOCAL -q " + SELECT $value, count() FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc', 'ORC', 't Nullable(DateTime64(9))') + WHERE t = fromUnixTimestamp64Nano($value)" +done diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.reference b/tests/queries/0_stateless/05515_orc_nullable_floats.reference new file mode 100644 index 000000000000..4aae050a32fc --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.reference @@ -0,0 +1,2 @@ +1 +1086 1410 5000 10000 0 diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.sh b/tests/queries/0_stateless/05515_orc_nullable_floats.sh new file mode 100755 index 000000000000..c7eba0810a43 --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Nullable floats with different patterns of nulls, and special values, at the top level and nested. +QUERY=" + SELECT + number, + multiIf(k = 0, NULL, k = 1, nan, k = 2, inf, k = 3, -inf, k = 4, -0., k = 5, toFloat32(1e-42), toFloat32(number) / 7)::Nullable(Float32) AS f32, + multiIf(k2 = 0, NULL, k2 = 1, nan, k2 = 2, -inf, k2 = 3, 5e-324, k2 = 4, -0., number / 3.)::Nullable(Float64) AS f64, + if(intDiv(number, 1000) % 2 = 0, NULL, number / 2.)::Nullable(Float64) AS runs, + NULL::Nullable(Float32) AS all_null, + (number * 1.5)::Nullable(Float64) AS no_null, + arrayMap(x -> if(x % 3 = 0, NULL, toFloat32(x) / 4), range(number % 5))::Array(Nullable(Float32)) AS arr + FROM (SELECT number, cityHash64(number) % 9 AS k, cityHash64(number, 1) % 7 AS k2 FROM numbers(10000))" +STRUCTURE='number UInt64, f32 Nullable(Float32), f64 Nullable(Float64), runs Nullable(Float64), all_null Nullable(Float32), no_null Nullable(Float64), arr Array(Nullable(Float32))' +DIGEST="sum(cityHash64(number, isNull(f32), reinterpretAsUInt32(ifNull(f32, 0)), isNull(f64), reinterpretAsUInt64(ifNull(f64, 0)), + isNull(runs), ifNull(runs, 0), isNull(all_null), no_null, arrayMap(x -> (isNull(x), reinterpretAsUInt32(ifNull(x, 0))), arr)))" + +$CLICKHOUSE_LOCAL -q "$QUERY INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q " + SELECT (SELECT $DIGEST FROM ($QUERY)) = (SELECT $DIGEST FROM file('$FILE', 'ORC', '$STRUCTURE')); + SELECT countIf(f32 IS NULL), countIf(f64 IS NULL), countIf(runs IS NULL), countIf(all_null IS NULL), countIf(no_null IS NULL) FROM file('$FILE', 'ORC', '$STRUCTURE')" diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference new file mode 100644 index 000000000000..36b34a909261 --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference @@ -0,0 +1,6 @@ +restore is waiting 1 +alter succeeded +restore finished +x +y +0 diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh new file mode 100755 index 000000000000..4083ae7715ff --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# `SYSTEM RESTORE DATABASE REPLICA` waits for the initial DDL queries that the DDL worker has already admitted. +# An `ALTER` of a `ReplicatedMergeTree` table with `alter_sync = 1` waits until the table executes its +# `ALTER_METADATA` entry, which requires an active DDL worker of the database (`canExecuteReplicatedMetadataAlter`). +# The restore must not stop the worker before such a query finishes, otherwise both queries wait for each other. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = ReplicatedMergeTree ORDER BY x" + +# Hold the initial `ALTER` after the DDL worker has admitted it, before it executes. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --alter_sync 1 --distributed_ddl_output_mode=none --query "ALTER TABLE ${DB}.t ADD COLUMN y UInt64" & +alter_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore has to wait for the paused `ALTER`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +# The `ALTER` finishes, including the wait for its `ALTER_METADATA` entry, and then the restore proceeds. +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $alter_pid && echo "alter succeeded" +# The replica is not lost (its digest is not empty), so the restore may refuse with `REPLICA_ALREADY_EXISTS`; +# either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "SELECT name FROM system.columns WHERE database = '${DB}' AND table = 't' ORDER BY name" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference new file mode 100644 index 000000000000..4e3dc3cd1a09 --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference @@ -0,0 +1 @@ +4800 552844800 24 diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh new file mode 100755 index 000000000000..b33d61ad599f --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires the Parquet format (USE_PARQUET build option) + +# Every Parquet writer had its own pool of `max_threads` encoder threads, so many open writers with `max_threads = 32` +# did not fit in a 500-thread global pool: the 24 partitions of one stream. +# https://github.com/ClickHouse/ClickHouse/issues/129864 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 48); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 48); do printf ', number * %d' "$i"; done) +SETTINGS="SET max_threads = 32, + output_format_parquet_parallel_encoding = 1, output_format_parquet_row_group_size = 200, + max_block_size = 1000, min_insert_block_size_rows = 1000, min_insert_block_size_bytes = 0" + +# Small row groups make every writer encode while the INSERT runs, not only when its file is finalized. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}, max_insert_threads = 1; + INSERT INTO FUNCTION file('${TABLE_DIR}/file/{_partition_id}.parquet', 'Parquet', 'p UInt8 ${COLS}') PARTITION BY p + SELECT number % 24 ${EXPRS} FROM numbers(4800); + SELECT count(), sum(c48), uniqExact(_path) FROM file('${TABLE_DIR}/file/*.parquet'); +" -- --max_thread_pool_size=500 --thread_pool_queue_size=500 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference new file mode 100644 index 000000000000..ec1c393fef3a --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference @@ -0,0 +1,3 @@ +1 +1 +still alive diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql new file mode 100644 index 000000000000..36af86696314 --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql @@ -0,0 +1,28 @@ +-- A deserialized `groupArraySample` state may carry an arbitrary `total_values` counter. +-- Merging must not wrap it around to zero, which led to a division by zero. + +-- Valid states merge fine. +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')])); +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')])); + +-- total_values = UINT64_MAX, merged with a state with one value. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('010141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +-- Both states have more values than the sample size, and their counters sum to 2^64. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +SELECT 'still alive'; diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.reference b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference new file mode 100644 index 000000000000..d509bf4d85ea --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference @@ -0,0 +1,21 @@ +Mechanisms that take the credentials from the server, and a client certificate file +refused +refused +refused +refused +refused +refused +refused +refused +Credentials in the connection string +connects +connects +connects +A MongoDB table is checked when it is read +refused +refused +So is a table created with CREATE TABLE ... AS mongodb(...) +x UInt8 +refused +And the table function with a named collection +refused diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.sh b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh new file mode 100755 index 000000000000..e563e94de006 --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB table function and table engine need USE_MONGODB + +# A query that reads with the `mongodb` table function or from a `MongoDB` table is refused with `ACCESS_DENIED` if the +# connection string makes the server authenticate with credentials of the server process. Nothing listens on +# 127.0.0.1:1, so a query that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +NC="nc_05567_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +check() +{ + $CLICKHOUSE_CLIENT -q "$1" 2>&1 | classify +} + +read_uri() +{ + check "SELECT count() FROM mongodb('mongodb://${HOST}/db?${TIMEOUTS}&$1', 'c', 'x UInt8')" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP TABLE IF EXISTS t_engine; + DROP TABLE IF EXISTS t_as_function; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Mechanisms that take the credentials from the server, and a client certificate file' +read_uri 'authMechanism=MONGODB-OIDC' +read_uri 'authmechanism=mongodb-oidc&authMechanismProperties=ENVIRONMENT:test' +read_uri 'authMechanism=MONGODB-AWS' +read_uri 'authMechanism=MONGODB-X509' +check "SELECT count() FROM mongodb('mongodb://user@${HOST}/db?${TIMEOUTS}&authMechanism=GSSAPI', 'c', 'x UInt8')" +read_uri 'tls=true&tlsCertificateKeyFile=/nonexistent.pem' +read_uri 'ssl=true&sslClientCertificateKeyFile=/nonexistent.pem' +check "SELECT count() FROM mongodb('${HOST}', 'db', 'c', '', '', 'x UInt8', '${TIMEOUTS}&authMechanism=MONGODB-OIDC')" + +echo 'Credentials in the connection string' +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=plain', 'c', 'x UInt8')" + + +echo 'A MongoDB table is checked when it is read' +$CLICKHOUSE_CLIENT -q "CREATE TABLE t_engine (x UInt8) ENGINE = MongoDB('${OIDC_URI}', 'c')" +check "SELECT count() FROM t_engine" +$CLICKHOUSE_CLIENT -m -q "DETACH TABLE t_engine; ATTACH TABLE t_engine;" +check "SELECT count() FROM t_engine" + +echo 'So is a table created with CREATE TABLE ... AS mongodb(...)' +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE t_as_function AS mongodb('${OIDC_URI}', 'c', 'x UInt8'); + DETACH TABLE t_as_function; + ATTACH TABLE t_as_function; + DESCRIBE t_as_function SETTINGS describe_compact_output = 1; +" +check "SELECT count() FROM t_as_function" + +echo 'And the table function with a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS uri = '${OIDC_URI}', collection = 'c', structure = 'x UInt8'" +check "SELECT count() FROM mongodb(${NC})" diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference new file mode 100644 index 000000000000..f0b81f6f43ed --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference @@ -0,0 +1,12 @@ +Refused +refused +refused +Credentials in the connection string +connects +The options that a dictionary adds to a named collection +refused +A named collection that changes after the dictionary is created +connects +refused +clickhouse-local is not restricted +connects diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh new file mode 100755 index 000000000000..354ecf0acbb7 --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB dictionary source needs USE_MONGODB + +# A MongoDB dictionary created with a DDL query may never make the server authenticate with credentials of the server +# process: the source is built when the server loads the dictionary, also after the named collection it refers to +# has changed. The dictionaries are loaded by `dictGet`. +# Nothing listens on 127.0.0.1:1, so a dictionary that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +SCRAM_URI="mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256" +NC="nc_05568_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +# Runs the queries $1. +check() +{ + $CLICKHOUSE_CLIENT -m -q "$1" 2>&1 | classify +} + +# Creates the dictionary $1 with the source $2 and prints whether reading it is refused. +check_source() +{ + $CLICKHOUSE_CLIENT -q "CREATE DICTIONARY $1 (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB($2 COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" + check "SELECT dictGet('$1', 'v', tuple('k'))" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP DICTIONARY IF EXISTS d_uri; + DROP DICTIONARY IF EXISTS d_options; + DROP DICTIONARY IF EXISTS d_scram; + DROP DICTIONARY IF EXISTS d_named_options; + DROP DICTIONARY IF EXISTS d_named_altered; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Refused' +check_source d_uri "URI '${OIDC_URI}'" +check_source d_options "HOST '127.0.0.1' PORT 1 DB 'db' USER '' PASSWORD '' OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" + +echo 'Credentials in the connection string' +check_source d_scram "URI '${SCRAM_URI}'" + +echo 'The options that a dictionary adds to a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS host = '127.0.0.1', port = '1', db = 'db', user = '', password = ''" +check_source d_named_options "NAME ${NC} OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +$CLICKHOUSE_CLIENT -q "DROP DICTIONARY d_named_options" + +echo 'A named collection that changes after the dictionary is created' +$CLICKHOUSE_CLIENT -q "CREATE DICTIONARY d_named_altered (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB(NAME ${NC} COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" +check "SELECT dictGet('d_named_altered', 'v', tuple('k'))" +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${NC} SET options = '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +check "SYSTEM RELOAD DICTIONARY d_named_altered; SELECT dictGet('d_named_altered', 'v', tuple('k'))" + +echo 'clickhouse-local is not restricted' +$CLICKHOUSE_LOCAL -m -q " + CREATE DICTIONARY d (_id String, v String) PRIMARY KEY _id + SOURCE(MONGODB(URI '${OIDC_URI}' COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT()); + SELECT dictGet('d', 'v', tuple('k')); +" 2>&1 | classify diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference new file mode 100644 index 000000000000..338bce460b79 --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference @@ -0,0 +1,18 @@ +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `l` from type Array(String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `s` from type Tuple(value String) to type Map(String, String) +Code: 53 while converting column `s` from type Tuple(value String) to type Array(String) +Code: 53 while converting column `lm` from type Array(Map(String, String)) to type Array(Tuple(value String)) +Code: 53 while converting column `sl` from type Tuple(a Array(String)) to type Tuple(a Map(String, String)) +2 {\'key\':\'profile\'} +2 [('key','profile')] +2 {'k':'(\'v\')'} +['(\'v\')'] +2 {'key':'profile'} ['profile'] ('profile') {'k':('v')} [{'k':'v'}] (['x']) +('profile',0) +2 +Code: 53 while converting column `m` from type Map(LowCardinality(String), LowCardinality(Nullable(String))) to type Tuple(value Nullable(String)) +Code: 53 while converting column `lm` from type Array(Map(LowCardinality(String), LowCardinality(Nullable(String)))) to type Array(Tuple(value String)) +{\'key\':\'profile\'} +{'key':'profile'} [{'k':'v'}] diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh new file mode 100755 index 000000000000..f503b6d888fa --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +# An ORC list, map or struct requested as a type of another kind is cast to it, not read as default values. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Prints the error code and the conversion of a query that has to fail. +function error() +{ + $CLICKHOUSE_LOCAL -q "$1" 2>&1 | tr '\n' ' ' | grep -o -E 'Code: [0-9]+|while converting column [^:]* to type [^:]*' | head -n 2 | paste -sd ' ' +} + +FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +$CLICKHOUSE_LOCAL -q "SELECT 2::Int64 AS id, map('key', 'profile') AS m, ['profile'] AS l, + CAST(tuple('profile'), 'Tuple(value String)') AS s, map('k', CAST(tuple('v'), 'Tuple(value String)')) AS ms, + [map('k', 'v')] AS lm, CAST(tuple(['x']), 'Tuple(a Array(String))') AS sl FORMAT ORC" > "$FILE" +F="file('$FILE', ORC" + +# Conversions the cast cannot do. +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))') SETTINGS input_format_orc_allow_missing_columns = 0" +error "SELECT * FROM $F, 'id Int64, l Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, s Map(String, String)')" +error "SELECT * FROM $F, 'id Int64, s Array(String)')" +error "SELECT * FROM $F, 'id Int64, lm Array(Tuple(value String))')" +error "SELECT * FROM $F, 'id Int64, sl Tuple(a Map(String, String))')" + +# Conversions the cast does, also of a map value. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m String')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Array(Tuple(String, String))')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, ms Map(String, String)')" +$CLICKHOUSE_LOCAL -q "SELECT ms.values FROM $F, 'id Int64, ms Map(String, String)')" + +# Matching kinds, a Tuple naming only some of the fields, and the other columns of a mismatched structure. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Map(String, String), l Array(String), s Tuple(value String), + ms Map(String, Tuple(value String)), lm Array(Map(String, String)), sl Tuple(a Array(String))')" +$CLICKHOUSE_LOCAL -q "SELECT s FROM $F, 's Tuple(value String, other Int32)')" +$CLICKHOUSE_LOCAL -q "SELECT id FROM $F, 'id Int64, m Tuple(value Nullable(String))')" + +DICT_FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}_dict.orc" +$CLICKHOUSE_LOCAL --output_format_orc_dictionary_key_size_threshold=1 -q "SELECT map('key', 'profile') AS m, [map('k', 'v')] AS lm FORMAT ORC" > "$DICT_FILE" +D="file('$DICT_FILE', ORC" +S="SETTINGS input_format_orc_dictionary_as_low_cardinality = 1" + +# A dictionary-encoded map key. +error "SELECT * FROM $D, 'm Tuple(value Nullable(String))') $S" +error "SELECT * FROM $D, 'lm Array(Tuple(value String))') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm String') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm Map(String, String), lm Array(Map(String, String))') $S" + +rm -f "$FILE" +rm -f "$DICT_FILE" diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference new file mode 100644 index 000000000000..d0fcfd538e17 --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference @@ -0,0 +1,6 @@ +MEMORY_LIMIT_EXCEEDED +PrettyCompactMonoBlock 241 +MEMORY_LIMIT_EXCEEDED +PrettyCompact 241 +MEMORY_LIMIT_EXCEEDED +JSONColumns 241 diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh new file mode 100755 index 000000000000..551f08b3f82c --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Every stored block is larger than the memory limit, so the format that accumulates the result fails to copy it +# when the next block arrives: the query must fail with an error, not crash. +for format in PrettyCompactMonoBlock PrettyCompact JSONColumns; do + $CLICKHOUSE_LOCAL --query " + CREATE TABLE t (x UInt64) ENGINE = Memory; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + SELECT * FROM t FORMAT $format SETTINGS max_threads = 1, max_memory_usage = '20Mi', + output_format_pretty_squash_consecutive_ms = 1000000, output_format_pretty_squash_max_wait_ms = 1000000; + " 2>&1 >/dev/null | grep -o -m1 'MEMORY_LIMIT_EXCEEDED' | head -n1 + echo "$format ${PIPESTATUS[0]}" +done diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference new file mode 100644 index 000000000000..8e054e883dc4 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference @@ -0,0 +1,9 @@ +1900-05-31 16:00:00 +1900-07-06 03:13:13 +1949-12-31 16:00:00 +1900-06-01 08:00:00 +1900-06-01 00:36:45 +1960-01-15 00:00:00 +0 1900-06-01 08:00:00.000000000 +1 1900-06-01 08:00:00.000000000 +1900-06-01 08:00:00.000000000 diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh new file mode 100755 index 000000000000..61cb9f7a7221 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no ORC format + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Before the first transition of a time zone, the wall clock is kept with the oldest standard offset +# (Asia/Shanghai +08:00 until 1901), not with the local mean time, as in other ORC readers. +# `DateTime64` starts at 1900 on this branch. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q " + SELECT arrayJoin([toDateTime64('1900-06-01 00:00:00', 0, 'UTC'), toDateTime64('1900-07-06 11:13:13', 0, 'UTC'), toDateTime64('1950-01-01 00:00:00', 0, 'UTC')]) AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Asia/Shanghai'" + +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# Europe/Lisbon starts with a no-op transition record in 1884 that keeps the local mean time (-00:36:45). +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Europe/Lisbon'" + +# Europe/London had +01:00 in 1970 and +00:00 in 1960, a lower offset before the epoch must not shift the day. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1960-01-15 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Europe/London'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# The timestamp statistics must agree with the values that are read, or the filter pushdown drops the row. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 9, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +for push_down in 0 1; do + $CLICKHOUSE_LOCAL -q " + SELECT $push_down, ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') + WHERE ts = toDateTime64('1900-06-01 08:00:00', 9, 'UTC') SETTINGS input_format_orc_filter_push_down = $push_down" +done + +# A time zone that `DateLUT` loads without an embedded file. +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'libc:UTC'" + +rm -f "$FILE" diff --git a/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference new file mode 100644 index 000000000000..1f7e29a97d9d --- /dev/null +++ b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference @@ -0,0 +1,153 @@ +-- { echo } + +SET engine_file_truncate_on_insert = 1; +SET allow_experimental_nullable_tuple_type = 1; +INSERT INTO FUNCTION file(currentDatabase() || '_05617.orc', 'ORC') SELECT + number AS id, + if(number = 0, [(1, 'a'), (2, 'b')], [])::Array(Tuple(a Int32, b String)) AS l, + if(number = 0, map('k1', (1, 'a'), 'k2', (2, 'b')), map())::Map(String, Tuple(a Int32, b String)) AS m, + map(CAST(tuple(toInt32(number)), 'Tuple(a Int32)'), 'v') AS mk, + CAST((toInt32(number), [(toInt32(number), 'x')]), 'Tuple(a Int32, l Array(Tuple(x Int32, y String)))') AS t, + [[(toInt32(number), 'x'), (1, 'y')]]::Array(Array(Tuple(a Int32, b String))) AS ll, + map('k', [(toInt32(number), 'x')])::Map(String, Array(Tuple(a Int32, b String))) AS ml, + if(number = 0, [(1, 'a'), NULL, (2, 'b')], [])::Array(Nullable(Tuple(a Int32, b String))) AS ln, + [(toInt32(number), 'c')]::Array(Tuple(A Int32, b String)) AS lc, + CAST((toInt32(number), map('k', (1, 'v'))), 'Tuple(a Int32, m Map(String, Tuple(a Int32, b String)))') AS tm, + [(1, tuple(2)), (3, tuple(4))]::Array(Tuple(x Int32, z Tuple(w Int32))) AS n, + [(1, [(1, 'a'), (2, 'b')])]::Array(Tuple(y Int32, x Array(Tuple(a Int32, b String)))) AS lx, + if(number = 0, [tuple(tuple(1)), tuple(NULL)], [tuple(NULL)])::Array(Tuple(b Nullable(Tuple(a Int32)))) AS nb, + map('k', (if(number = 0, tuple(1), NULL), if(number = 0, NULL, tuple('x'))))::Map(String, Tuple(b Nullable(Tuple(a Int32)), c Nullable(Tuple(x String)))) AS mb, + CAST((toInt32(number), [tuple(if(number = 0, tuple(1), NULL))]), 'Tuple(a Int32, l Array(Tuple(b Nullable(Tuple(a Int32)))))') AS tb, + if(number = 0, tuple(1, 'a'), NULL)::Nullable(Tuple(a Int32, b String)) AS ts, + [CAST(tuple(toDateTime64('3000-01-01 00:00:00', 0, 'UTC')), 'Tuple(a DateTime64(0, \'UTC\'))')] AS ld, + CAST([tuple(11, tuple(5))], 'Array(Tuple(w Int32, x Tuple(v Int32)))') AS an +FROM numbers(2); +-- A list element, a map value and a map key, also nested in a struct, a list or a map, and with NULL elements. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [(NULL),(NULL)] +1 [] +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(q Nullable(String)))') ORDER BY id; +0 {'k1':(NULL),'k2':(NULL)} +1 {} +SELECT id, mk FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mk Map(Tuple(z Nullable(Int32)), String)') ORDER BY id; +0 {(NULL):'v'} +1 {(NULL):'v'} +SELECT id, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(a Int32, l Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 (0,[(NULL)]) +1 (1,[(NULL)]) +SELECT id, ll FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ll Array(Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 [[(NULL),(NULL)]] +1 [[(NULL),(NULL)]] +SELECT id, ml FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ml Map(String, Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 {'k':[(NULL)]} +1 {'k':[(NULL)]} +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Array(Nullable(Tuple(q Nullable(Int32))))') ORDER BY id; +0 [(NULL),NULL,(NULL)] +1 [] +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id SETTINGS input_format_orc_row_batch_size = 1; +0 [(NULL),(NULL)] +1 [] +-- The same through a subcolumn of a struct and a subcolumn of a Nested column. +SELECT id, `t.a`, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.a` Int32, `t.l` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 0 [(NULL)] +1 1 [(NULL)] +SELECT id, `tm.m` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tm.m` Map(String, Tuple(q Nullable(String)))') ORDER BY id; +0 {'k':(NULL)} +1 {'k':(NULL)} +SELECT id, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [(NULL),(NULL)] +1 [(NULL),(NULL)] +SELECT id, `n.x`, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.x` Array(Int32), `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [1,3] [(NULL),(NULL)] +1 [1,3] [(NULL),(NULL)] +-- A struct that contains such a list is read with its fields. +SELECT id, lx FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lx Array(Tuple(x Array(Tuple(q Nullable(Int32)))))') ORDER BY id; +0 [([(NULL),(NULL)])] +1 [([(NULL),(NULL)])] +-- A struct read whole by another column keeps its data. optimize_functions_to_subcolumns = 0 keeps `t.l` itself in the read. +SELECT id, t, length(`t.l`) FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t String, `t.l` Array(Tuple(q String, r String))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 (0,[(0,\'x\')]) 1 +1 (1,[(1,\'x\')]) 1 +-- A Tuple naming some of the fields, and case-insensitive matching. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Nullable(Int32)))') ORDER BY id; +0 [(1,NULL),(2,NULL)] +1 [] +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(a Int32, q Nullable(String)))') ORDER BY id; +0 {'k1':(1,NULL),'k2':(2,NULL)} +1 {} +SELECT id, lc FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lc Array(Tuple(a Int32))') ORDER BY id SETTINGS input_format_orc_case_insensitive_column_matching = 1; +0 [(0)] +1 [(1)] +-- A non-nullable Date32 field gets the same default with and without a field that is in the file, an Enum gets its first value. +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Date32, e Enum8(\'x\' = 1, \'y\' = 2))), m Map(String, Tuple(q Date32))') ORDER BY id; +0 [('1970-01-01','x'),('1970-01-01','x')] {'k1':('1970-01-01'),'k2':('1970-01-01')} +1 [] {} +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Date32)), m Map(String, Tuple(a Int32, q Date32))') ORDER BY id; +0 [(1,'1970-01-01'),(2,'1970-01-01')] {'k1':(1,'1970-01-01'),'k2':(2,'1970-01-01')} +1 [] {} +-- A requested struct field of such a struct keeps its presence, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id; +0 [((0)),(NULL)] +1 [(NULL)] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(a Nullable(Int32), q Int32))))') ORDER BY id; +0 [((1,0)),(NULL)] +1 [(NULL)] +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(q Int32)), b Nullable(Tuple(r String))))') ORDER BY id; +0 {'k':(NULL,(''))} +1 {'k':((0),NULL)} +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(x Nullable(String), q Int32)), b Nullable(Tuple(a Nullable(Int32), r String))))') ORDER BY id; +0 {'k':(NULL,(1,''))} +1 {'k':(('x',0),NULL)} +-- A NULL struct requested as non-Nullable is rejected or read as default, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +0 [((0)),((0))] +1 [((0))] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +0 [((1,0)),((NULL,0))] +1 [((NULL,0))] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +-- Two columns reading the same struct with different types get the defaults of their own type. +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(q Nullable(Int32)))), `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) [(NULL,NULL)] +1 ([(NULL)]) [(NULL,NULL)] +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(e Enum8(\'x\' = 1)))), `t.l` Array(Tuple(r Nullable(String)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([('x')]) [(NULL)] +1 ([('x')]) [(NULL)] +SELECT id, `t.l`, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32))), t Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 [(NULL,NULL)] ([(NULL)]) +1 [(NULL,NULL)] ([(NULL)]) +-- Of two columns reading the same struct, one that requests a nested struct of it keeps that struct's presence. +SELECT id, tb, `tb.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.l` Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) [((0))] +1 ([(NULL)]) [(NULL)] +SELECT id, `tb.l`, tb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tb.l` Array(Tuple(b Nullable(Tuple(q Int32)))), tb Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 [((0))] ([(NULL)]) +1 [(NULL)] ([(NULL)]) +SELECT id, tb, `tb.a` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.a` Int32') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) 0 +1 ([(NULL)]) 1 +-- A top-level struct keeps its presence too, also when missing columns are not allowed. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id; +0 (0) +1 \N +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id SETTINGS input_format_orc_allow_missing_columns = 0; +0 (0) +1 \N +-- A field read only for the size of its struct is not converted. +SELECT id, ld FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ld Array(Tuple(q Int32))') ORDER BY id; +0 [(0)] +1 [(0)] +-- An unnamed Tuple is matched by position and must have as many elements as the struct. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +-- The same for a Nested column that is not flattened. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Nested(q Int32)') ORDER BY id SETTINGS flatten_nested = 0; +0 [(0),(0)] +1 [] +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +0 [(NULL),(NULL),(NULL)] +1 [] +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(a Nullable(Int32), q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +0 [(1,NULL),(NULL,NULL),(2,NULL)] +1 [] diff --git a/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql new file mode 100644 index 000000000000..c0092342d918 --- /dev/null +++ b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql @@ -0,0 +1,99 @@ +-- Tags: no-fasttest +-- no-fasttest: ORC is not available in fasttest builds +-- An ORC list or map whose element, key or value struct has none of the fields of the requested Tuple keeps its +-- elements, and each of them is filled with default values. + +-- { echo } + +SET engine_file_truncate_on_insert = 1; +SET allow_experimental_nullable_tuple_type = 1; + +INSERT INTO FUNCTION file(currentDatabase() || '_05617.orc', 'ORC') SELECT + number AS id, + if(number = 0, [(1, 'a'), (2, 'b')], [])::Array(Tuple(a Int32, b String)) AS l, + if(number = 0, map('k1', (1, 'a'), 'k2', (2, 'b')), map())::Map(String, Tuple(a Int32, b String)) AS m, + map(CAST(tuple(toInt32(number)), 'Tuple(a Int32)'), 'v') AS mk, + CAST((toInt32(number), [(toInt32(number), 'x')]), 'Tuple(a Int32, l Array(Tuple(x Int32, y String)))') AS t, + [[(toInt32(number), 'x'), (1, 'y')]]::Array(Array(Tuple(a Int32, b String))) AS ll, + map('k', [(toInt32(number), 'x')])::Map(String, Array(Tuple(a Int32, b String))) AS ml, + if(number = 0, [(1, 'a'), NULL, (2, 'b')], [])::Array(Nullable(Tuple(a Int32, b String))) AS ln, + [(toInt32(number), 'c')]::Array(Tuple(A Int32, b String)) AS lc, + CAST((toInt32(number), map('k', (1, 'v'))), 'Tuple(a Int32, m Map(String, Tuple(a Int32, b String)))') AS tm, + [(1, tuple(2)), (3, tuple(4))]::Array(Tuple(x Int32, z Tuple(w Int32))) AS n, + [(1, [(1, 'a'), (2, 'b')])]::Array(Tuple(y Int32, x Array(Tuple(a Int32, b String)))) AS lx, + if(number = 0, [tuple(tuple(1)), tuple(NULL)], [tuple(NULL)])::Array(Tuple(b Nullable(Tuple(a Int32)))) AS nb, + map('k', (if(number = 0, tuple(1), NULL), if(number = 0, NULL, tuple('x'))))::Map(String, Tuple(b Nullable(Tuple(a Int32)), c Nullable(Tuple(x String)))) AS mb, + CAST((toInt32(number), [tuple(if(number = 0, tuple(1), NULL))]), 'Tuple(a Int32, l Array(Tuple(b Nullable(Tuple(a Int32)))))') AS tb, + if(number = 0, tuple(1, 'a'), NULL)::Nullable(Tuple(a Int32, b String)) AS ts, + [CAST(tuple(toDateTime64('3000-01-01 00:00:00', 0, 'UTC')), 'Tuple(a DateTime64(0, \'UTC\'))')] AS ld, + CAST([tuple(11, tuple(5))], 'Array(Tuple(w Int32, x Tuple(v Int32)))') AS an +FROM numbers(2); + +-- A list element, a map value and a map key, also nested in a struct, a list or a map, and with NULL elements. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(q Nullable(String)))') ORDER BY id; +SELECT id, mk FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mk Map(Tuple(z Nullable(Int32)), String)') ORDER BY id; +SELECT id, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(a Int32, l Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ll FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ll Array(Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ml FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ml Map(String, Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Array(Nullable(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id SETTINGS input_format_orc_row_batch_size = 1; + +-- The same through a subcolumn of a struct and a subcolumn of a Nested column. +SELECT id, `t.a`, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.a` Int32, `t.l` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, `tm.m` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tm.m` Map(String, Tuple(q Nullable(String)))') ORDER BY id; +SELECT id, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, `n.x`, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.x` Array(Int32), `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; + +-- A struct that contains such a list is read with its fields. +SELECT id, lx FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lx Array(Tuple(x Array(Tuple(q Nullable(Int32)))))') ORDER BY id; + +-- A struct read whole by another column keeps its data. optimize_functions_to_subcolumns = 0 keeps `t.l` itself in the read. +SELECT id, t, length(`t.l`) FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t String, `t.l` Array(Tuple(q String, r String))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- A Tuple naming some of the fields, and case-insensitive matching. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Nullable(Int32)))') ORDER BY id; +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(a Int32, q Nullable(String)))') ORDER BY id; +SELECT id, lc FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lc Array(Tuple(a Int32))') ORDER BY id SETTINGS input_format_orc_case_insensitive_column_matching = 1; + +-- A non-nullable Date32 field gets the same default with and without a field that is in the file, an Enum gets its first value. +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Date32, e Enum8(\'x\' = 1, \'y\' = 2))), m Map(String, Tuple(q Date32))') ORDER BY id; +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Date32)), m Map(String, Tuple(a Int32, q Date32))') ORDER BY id; + +-- A requested struct field of such a struct keeps its presence, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(a Nullable(Int32), q Int32))))') ORDER BY id; +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(q Int32)), b Nullable(Tuple(r String))))') ORDER BY id; +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(x Nullable(String), q Int32)), b Nullable(Tuple(a Nullable(Int32), r String))))') ORDER BY id; + +-- A NULL struct requested as non-Nullable is rejected or read as default, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } + +-- Two columns reading the same struct with different types get the defaults of their own type. +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(q Nullable(Int32)))), `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(e Enum8(\'x\' = 1)))), `t.l` Array(Tuple(r Nullable(String)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, `t.l`, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32))), t Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- Of two columns reading the same struct, one that requests a nested struct of it keeps that struct's presence. +SELECT id, tb, `tb.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.l` Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, `tb.l`, tb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tb.l` Array(Tuple(b Nullable(Tuple(q Int32)))), tb Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, tb, `tb.a` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.a` Int32') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- A top-level struct keeps its presence too, also when missing columns are not allowed. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id; +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id SETTINGS input_format_orc_allow_missing_columns = 0; + +-- A field read only for the size of its struct is not converted. +SELECT id, ld FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ld Array(Tuple(q Int32))') ORDER BY id; + +-- An unnamed Tuple is matched by position and must have as many elements as the struct. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } + +-- The same for a Nested column that is not flattened. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Nested(q Int32)') ORDER BY id SETTINGS flatten_nested = 0; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(a Nullable(Int32), q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; diff --git a/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.reference b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.reference new file mode 100644 index 000000000000..67e0669d56c6 --- /dev/null +++ b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.reference @@ -0,0 +1,10 @@ +4 99999 +3 99998 +2 99997 +99999 4 +99998 3 +99997 2 +0 0 0 +1 1 1 +2 2 2 +299995 4999950000 4999950000 diff --git a/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.sh b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.sh new file mode 100755 index 000000000000..4b3b3f2de284 --- /dev/null +++ b/tests/queries/0_stateless/05621_delta_lake_column_mapping_swapped_names_order.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-msan +# Tag no-fasttest: needs Parquet and Delta Lake +# Tag no-msan: delta-kernel-rs (Rust) is not built under MSan, so `deltaLakeLocal` is absent. + +# A Delta Lake table with column mapping where a column is stored under the logical name of another column, read +# with the columns in every order: the renaming of the requested columns to their physical names must not collide +# with a logical name that is not renamed yet (it used to erase the column and read freed memory). + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +DELTA_DIR="${USER_FILES_PATH}/${CLICKHOUSE_DATABASE}_05621" +rm -rf "${DELTA_DIR}" +mkdir -p "${DELTA_DIR}/_delta_log" + +# The data file stores `k` = number % 7, `v` = number and `w` = number: the table's `k_old`, `k` and `w` +# (column mapping enabled on an existing table, then `k` renamed to `k_old` and `v` to `k`). +${CLICKHOUSE_CLIENT} --query " + INSERT INTO FUNCTION file('${DELTA_DIR}/data.parquet', Parquet, 'k Int64, v Int64, w Int64') + SELECT number % 7, number, number FROM numbers(100000)" +DELTA_SCHEMA='{\"type\":\"struct\",\"fields\":[{\"name\":\"k_old\",\"type\":\"long\",\"nullable\":false,\"metadata\":{\"delta.columnMapping.id\":1,\"delta.columnMapping.physicalName\":\"k\"}},{\"name\":\"k\",\"type\":\"long\",\"nullable\":false,\"metadata\":{\"delta.columnMapping.id\":2,\"delta.columnMapping.physicalName\":\"v\"}},{\"name\":\"w\",\"type\":\"long\",\"nullable\":false,\"metadata\":{\"delta.columnMapping.id\":3,\"delta.columnMapping.physicalName\":\"w\"}}]}' +cat > "${DELTA_DIR}/_delta_log/00000000000000000000.json" <`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo mQfoMv*fgJAnSmomfKj5Mfklalfk(r{fUW5ZGqZn?vp4|E0T8hO literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc new file mode 100644 index 0000000000000000000000000000000000000000..fc3ffef8f18c17dc95f532108f94846c6cb9b894 GIT binary patch literal 717 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo vQfoMv*fgI#S!njcc{ArNRAk^N5nz;PXkbxdV&Ks*F<@)@!p!U+JFZE-iyIBTGB(h%cBfX4BGjAJ&?Gn8U6&@(d& zz$y=vGO&;Wsxk>+P+(wKo$%nn**QlR@+j>TaZurBkYr%+<23NG2w({jkqGi}XJ9z6 zYbW!qRlXhHI#@oOiG6Td^2pN_EKS$M7W4_Nc>Rj~#nl5W{0t0koK8+IN-kjSYyv`D ze0)qod?H{j6B7>yAC~|R3qu>wgGrAQgcBw_c*b{mZuY+kFmEzQ>GXvtHD{W zWs;4rS`L~_X0e}<#`Zdy^-@fN9e2o_(5Co~&Su7rnHMtH82$lGnRVvG(L)DC4;)ZE zeNa{9)WwY{H(#^4HOd*NetdLvKd-FANsdH4L0}-t>A5j0stGG=rYRQ(FVL``E)@{c z*M0ZIflEH;k2rN4K6K*36_4{*Ji0C)IdSR0m4Neim{y!?@a9?3$G>FuO^5RVT}K_x zpW#^}ug521v|$3%saXw27$-3@JWde%aZ=^z*@HR-4S|as4*E8Gdp0$@cTAnwIkPpi z%P_FZ(6h@hvdhr5%P_RFv)Q$?x7ok>cmtzPw}gS?Pk~t{8%{Qy?rLq;ZaC;Qt=ZdS z%Hrgco38WrFxe(}Jv!Q5FKyK@N$^mZl1z-7O-v7)laHEP&>6R9%Nzphv`rVRkP+WK zv2p3ld7Z5S?X43RuADe;;?|1sEk78U&P>8TXu+-id_MC9Fa-<` z?lW*QFhnuTafo1Gc%1Y&K{#Q;gJ(<^dxYv@a%6g#dW4FAv=5MebWNDr~+4;VnvT^!awPNw&jholK~7@| z!qQ)f-`+hkxUucGmEX^Ib+-3k9pAk34oO3dhvpw=li&Ht=fd(`*2q-Zz@MuUHur+;QX7&$q76$-W;u-w_ literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc b/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc new file mode 100644 index 0000000000000000000000000000000000000000..27d3a7a5694c836382a434b145463145bc7e4969 GIT binary patch literal 174 zcmeYdaz2pEz)<19(7?sU!6?8e!2+b2fixqKW&+a8LQEVCLL5M`|3JVm#q91I!X?hd z!jTfdz{SszqQuF?SRuq%A#s8+fB~q=Sc(fsGDvVJXltY>ad7YmF)~Uq7ArAvup6XU xfwftoYja@mU`*n2&dE&9_Q)?SPUUb18qm-npv1($qakU)*7Sv$*+0lx8~}Ex9uxoo literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc b/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc new file mode 100644 index 0000000000000000000000000000000000000000..00ab37f164451f7d41fdd9918d3a60e6eb3fb9e1 GIT binary patch literal 353 zcmb7!55@c<-_od@Ma)J`I4HxfN+mPlz%p40|nh@xK=W-?pJwH%K)jX%p}<3F&Fh@rNx z?t8Y(IS+(X;JUy~Nt{KsDqAPB`oye0GaG+COmQR4^X~C!`ttU={aZS&{tbFtXANNv_gqUE3}AonBeEZn8f9rlbM|DkzZPz$`J=lJ`D{5 WN=ytq8jF|>*qXjDGy4ZQO8@|~r#gH9 literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc b/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc new file mode 100644 index 0000000000000000000000000000000000000000..43552b05c31d975806e7b28bf0348ac911b93320 GIT binary patch literal 83 zcmeYda_(bbf5@QqpMi^wgHeD{fZBafx-+D4Gk42F|jIl^(saf&@Ul}_i@Q96kobdi?g;4J`i%|p7O zHQHy4J^a)g0`Qj6YX%1aWcQxocSeo^^{~g%Xx3tINijrGbQqKXl}3-r5QS%EZ#Tnm$hsO_t_nvG%Tof%Rfa2K6BY3f#1KM=U?J&`Kze_YKPs*0 zx=Eu0j}P9!do!~|CB`MJ=O9i9z@@C6VX*Am!Mha&!ECV3S+H<8^mY#W1gIGH9|rxw zXpDOxF>EY&jzr&%B;N@{i#~~@xF<_qJ7Nf;voiJcyp((SJL0nbs+X1h!K@W3q*{Nxeoi)D+c$m>ztpwO3DRD- MFyFsQ%@$SX1Y@lyc>n+a literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc b/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc new file mode 100644 index 0000000000000000000000000000000000000000..ab57ba54f6cb5f35ce2f2225cedead3e3c24d9e6 GIT binary patch literal 238 zcmeYdaz4P>@V{v>Ba?moe+amFYzD)Ut4a(EH!q|}F!G&RDZuEwo9hH)g+~tq6u9SsRejxb{KXpyLT!00RfJK%^8GkYtdsQIOT(QsUs?5n^PNVk}W&;@~vk yvI3i7h1U!R1`oz0F6W%gPb;1ObElwvGVV&dR5V73CA xVnx6dhY5Zjj7eP1Iho1X9{HuksT|=zmo_vAC^0ecXlNL)HGN@b_78Fv2LL-3L?-|M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc b/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc new file mode 100644 index 0000000000000000000000000000000000000000..4f30ed6c7f1acfc4f1587ecd851ca828b38d2f80 GIT binary patch literal 38 scmeYda+Y9V(AcW~cL4(fg99T20|&nVt3(43uxKzeePL$y4{{a;0H`qt$^ZZW literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc b/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..ed3597a70455f3319174fea0ea64f41d446cd797 GIT binary patch literal 666 zcmaix&q~8U5XNU_lXYBHS=Webywo6)Qz;&EDiqX}}d=Fp4 ztKzsxN?H%yzWek=6A!rcN(PZ|1U)2|F+f zWWX+C!3O6Z=i#sQ%pmv^#{76&%5v;*uMLjcUdixCsKY(M%hOn5oHKSQO2pknd z7L|gHsv1oio`%E7btpyAVMwAg?1CC}C6^^LhR zwLh!Q)l7zn1(v%$tsAu28&>Xva+&X5G332>ELE}3))P`rPmei1_n?FU6wIoLEbn+y zx|=2Gzb@vjC2M*Is*1l}t*q0qxQr`v&RGZfszKyT&K0WWt$Db%~yI3Rzfh`{f M`sGWh$!rvU0o^4u?*IS* literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_union_type.orc b/tests/queries/0_stateless/data_orc/orc_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..08c73c83fd428e64b0f74df501b573b0d8eb7b8d GIT binary patch literal 398 zcmeYdau#G@;9?VE;b012kOnfjxtJLk7$AIYAYT~5=iy)!V&e!A2$2X0U@%}{cr5fh zDV2dy(T>kel~3;&m*O!l&Sea23@BQdfLfRYSR~j27}yyY{xL8DNk4`VAnCx+0JNq8 z$Z}&;X<=ZnJ$aD#fB^@y0~3eqm*!uaW)*I7+WlY4H&#<#{+Oh#SHY8X=RnpKi2>>P z+5D?QuKz1<{`|h<^6n{bLhf1XSHJtolmc|qrUyw66Sxu@CfUgJIOWJFGARlvIv655 zae|Z_pV|VQ$qd~r(G1KCFMyg7#4OHf96fqaXM&pI;s>h^E>SshQ2EG_6G}%Tw2sbL zd0@f8gaZqX96qRh@VGj1mnEEJ{oaJQ}73 NY)xO7nf-&D#Q~MRda3{b literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/row_index_seek_control.orc b/tests/queries/0_stateless/data_orc/row_index_seek_control.orc new file mode 100644 index 0000000000000000000000000000000000000000..ede347aa81181c970ec5d83161d8595eef07a424 GIT binary patch literal 213 zcmY+7F$=;#426?iIYPMMI7E+5r66?dD4oO#c9E9SA0Uc@C^(4VSp3cY0MA1Nhvb8o z_g>n*7VQ$o4t{h(0M0Nv&0xVpxP3JIYGlb%2P@1(vknFuiM|L#i(WZm2t%pbYzLW0 z!oe?wDK^G5E4xc2?1fj^yr7)fIK&hmIdM`_6*JXeW{C~%rM{dF=jM999eEv|kE6{A OOffC>^QBbV*RwZ`5EX0y literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc new file mode 100644 index 0000000000000000000000000000000000000000..d6e0144685e7e91cbc4e2f76aba78db27c503b4f GIT binary patch literal 294 zcmeYda^_+aV&Py3VBnJHVqpLRA#n~CFF}d-S0A;$tXG(DYv0WG<_0&-0vIZo8Q1fF zHU<%<3}+*pj2X=Co-wUs{tp7J@2o(YK>&?!#l^uMlK_Jhv%7By$R%JG;c^KFv%n-qDJ~$TDPf^tsKKJd$H61S$SB2FqQIcR zV8Ecn!NCb(8L(J^&9cH}mcs-;55^=`BRwGGhyc2?p@Bt-iGfE$(SWV#3p2BSkh3@d Dw(m#M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc new file mode 100644 index 0000000000000000000000000000000000000000..2afd747824ec0515a92db943df384c0a15d9573e GIT binary patch literal 517 zcmah_F-XHu5WUM!;u%X*Gw3%hG-L`zN_4CaLP4z{m7=SIgM;WMjv~5taS^)MxuUCE zXQx6PTq+J-6>$+1LF@hef*^>uyn8P%clTelR(5R9BwT}kal$cy%S#ikkZk6IWVM&3+yxPgX3uK-?@cBI7ut#aQ69Ap@RG z2HVjWORMWDLb5o9G+8=Y{U{Qd6XB0B)D1Zo%tuz3rj&>1G`*BQ+>fo1s*rPY z<~tIo>C52xd@=P*T`HPO=fa~AC5KX$QO)2}nRh1jyG=~AvjcuNo8b}B*Y_dmqTM+s z%Sgh-{5jA?(yFE`wR{4hIO~K=Wjl7=B}Xf}W{@pajjY)=+iq##pbu_Q=h(2_ti3>u z9J)?2=+GRx-X5s=SumAbf+5?n4%qkartR%4)<&I(Tt*DJ7X=wHr|d<1%^YzzE3xM> z-%7E|JP?a`XAz0(J?42JA3%DAus`Z&$y9Xaij(78A=2Oj@9du!#a=!NEc0aI_oNwy zL6aGK>2?l~?dJ7(AxI8I0lE`VGY3E}E@o%dTVTviD!?e2g#g2kAR) empty_values = 2; + map recursive_values = 3; + map big_enum_values = 4; + map supported_values = 5; +} diff --git a/tests/queries/0_stateless/orc_malformed.lib b/tests/queries/0_stateless/orc_malformed.lib new file mode 100644 index 000000000000..64f884cc4498 --- /dev/null +++ b/tests/queries/0_stateless/orc_malformed.lib @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2154 + +# Helpers to read (possibly malformed) ORC files from the tests: locally with `file` in clickhouse-local, and remotely +# with `s3` in the server, with the filter pushdown and the lazy dictionaries both enabled and disabled. + +ORC_S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}" +# The values of `input_format_orc_filter_push_down` to check. +ORC_PUSH_DOWN_VALUES="0 1" + +# Prints the result in one line, or the name of the error code (with the message if it does not match `expected_error`). +function orc_result() +{ + local output=$1 status=$2 expected_error=$3 + if [ "$status" -eq 0 ]; then + echo "$output" | tr '\n' ' ' | sed 's/ $//' + return + fi + local code + code=$(echo "$output" | grep -oE '\([A-Z_]{3,}\)' | tail -n1) + if [ -z "$code" ]; then + echo "unexpected failure with status $status: $(echo "$output" | head -n3)" + elif [ -z "$expected_error" ] || echo "$output" | grep -qE "$expected_error"; then + echo "$code" + else + echo "$code with an unexpected message: $(echo "$output" | head -n1 | cut -c1-300)" + fi +} + +# orc_check
: one data file holding only `v`, committed in the v0 log. +add_file() { + local table=$1 dir=$2 values=$3 v=$4 + echo "{\"add\":{\"path\":\"${dir}/data.parquet\",\"partitionValues\":${values},\"size\":1,\"modificationTime\":1700000000000,\"dataChange\":true}}" \ + >> "${ROOT}/${table}/_delta_log/00000000000000000000.json" + QUERIES+=" + INSERT INTO FUNCTION file('${ROOT}/${table}/${dir}/data.parquet', Parquet, 'v Int32') VALUES (${v});" +} + +# One data file per partition. Only t and t2 have a NULL partition (`__HIVE_DEFAULT_PARTITION__`, a JSON null). +add_file t 'p=5' '{"p":"5"}' 1 +add_file t 'p=__HIVE_DEFAULT_PARTITION__' '{"p":null}' 2 +add_file t 'p=7' '{"p":"7"}' 3 +add_file t 'p=8' '{"p":"8"}' 4 +add_file n 'p=5' '{"p":"5"}' 1 +add_file n 'p=7' '{"p":"7"}' 3 +add_file n 'p=8' '{"p":"8"}' 4 +add_file t2 'a=__HIVE_DEFAULT_PARTITION__/b=3' '{"a":null,"b":"3"}' 1 +add_file t2 'a=1/b=3' '{"a":"1","b":"3"}' 2 +add_file t2 'a=1/b=5' '{"a":"1","b":"5"}' 3 LABELS=() @@ -65,13 +79,11 @@ arm t "p = 7" "delta_lake_enable_engine_predicate = 0" arm t "p < 6" "delta_lake_enable_engine_predicate = 0" arm t "p IS NOT NULL" "delta_lake_enable_engine_predicate = 0" arm t "has([5, 7], p)" -arm t "ifNull(p, 0) IN (0)" arm n "has([NULL, 5], p)" arm n "NOT has([NULL, 5], p)" arm t2 "has([NULL, 1], a)" -arm s "has([NULL, 'a'], s)" -mapfile -t LINES < <(${CLICKHOUSE_LOCAL} --allow_delta_lake_writes=1 --query "${QUERIES}" < /dev/null) +mapfile -t LINES < <(${CLICKHOUSE_LOCAL} --query "${QUERIES}" < /dev/null) if [[ "${#LINES[@]}" != "$(( 4 * ${#LABELS[@]} ))" ]]; then printf 'Expected %s lines, got %s:\n%s\n' "$(( 4 * ${#LABELS[@]} ))" "${#LINES[@]}" "$(printf '%s\n' "${LINES[@]}")" >&2 exit 1 From f468fb654a7beb44ac31c03042598492d7f0475f Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Sat, 14 Nov 2026 04:52:38 +0000 Subject: [PATCH 015/116] Adapt 05576 to 26.3: `NOT has([NULL, 1]::Array(Nullable(Int64)), p)` prunes no file On 26.3 the Nullable key condition does not prove that this predicate is false for the `NULL` partition, so the partition pruner keeps its file and prunes 0 files instead of 1. The rows are the same; keeping a file is the conservative outcome. Reproduced with the `build_arm_release` binary of this PR (26.3.61.91); the other cases match the reference. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=130717&sha=a3a2d22f6027fc8c95c20735d2a9c17fa472b7a0&name_0=BackportPR&name_1=Stateless%20tests%20%28amd_asan%2C%20distributed%20plan%2C%20parallel%2C%202%2F2%29 PR: https://github.com/ClickHouse/ClickHouse/pull/130717 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 715faa4a5a7167aae62bf03a01874730123ebd16) --- .../05576_delta_lake_partition_pruning_null_in_set.reference | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference b/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference index 7c33f2923fde..e224e8c3e4b8 100644 --- a/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference +++ b/tests/queries/0_stateless/05576_delta_lake_partition_pruning_null_in_set.reference @@ -2,7 +2,7 @@ t: has([NULL, 1], p) [2] [2] 3 t: has([NULL, 5], p) [1,2] [1,2] 2 t: NOT has([NULL, 1], p) [1,3,4] [1,3,4] 0 t: has([NULL, 1]::Array(Nullable(Int64)), p) [2] [2] 3 -t: NOT has([NULL, 1]::Array(Nullable(Int64)), p) [1,3,4] [1,3,4] 1 +t: NOT has([NULL, 1]::Array(Nullable(Int64)), p) [1,3,4] [1,3,4] 0 t: p IN (NULL, 1), transform_null_in = 1 [2] [2] 3 t: p IS NULL, delta_lake_enable_engine_predicate = 0 [2] [2] 3 t: p = 7, delta_lake_enable_engine_predicate = 0 [3] [3] 3 From 10dbb6081e04011225e2b4bf48d54cff8a06f5b8 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sun, 15 Nov 2026 20:50:25 +0000 Subject: [PATCH 016/116] Backport #130997 to 26.3: Keep a delayed task valid when overwriting its deadline fails --- .gitmodules | 3 - .../Foundation/include/Poco/FileChannel.h | 1 + base/poco/Foundation/src/FileChannel.cpp | 40 +- .../include/Poco/Net/DistrustedCertificates.h | 44 + .../src/DistrustedCertificates.cpp | 95 + base/poco/NetSSL_OpenSSL/src/SSLManager.cpp | 15 + base/poco/XML/CMakeLists.txt | 1 + base/poco/XML/include/Poco/XML/expat.h | 5 +- .../XML/include/Poco/XML/expat_external.h | 2 +- base/poco/XML/src/ascii.h | 3 +- base/poco/XML/src/entities.h | 99 + base/poco/XML/src/internal.h | 8 +- base/poco/XML/src/xcs.h | 2 + base/poco/XML/src/xmlparse.cpp | 871 ++++++- base/poco/XML/src/xmltok.h | 4 +- base/poco/XML/src/xmltok_impl.c | 6 +- base/poco/XML/src/xmlxcs.c | 21 + .../integration/dotnet_client/Dockerfile | 11 +- contrib/CMakeLists.txt | 2 +- contrib/arrow-cmake/CMakeLists.txt | 156 +- contrib/arrow-cmake/orc_check.cmake | 14 - contrib/brotli | 2 +- contrib/brotli-cmake/CMakeLists.txt | 51 +- contrib/c-ares | 2 +- contrib/grpc | 2 +- contrib/hive-metastore-cmake/CMakeLists.txt | 14 +- contrib/mongo-c-driver | 2 +- contrib/mongo-c-driver-cmake/CMakeLists.txt | 8 +- contrib/mongo-cxx-driver | 2 +- contrib/orc | 1 - contrib/sqlite-amalgamation | 2 +- .../table-engines/integrations/azure-queue.md | 4 + .../table-engines/integrations/s3queue.md | 2 + docs/en/operations/settings/settings-users.md | 1 + programs/client/Client.cpp | 13 +- src/Access/AccessBackup.cpp | 73 +- src/Access/AccessBackup.h | 8 +- src/Access/AccessControl.cpp | 38 +- src/Access/Authentication.cpp | 77 +- src/Access/ContextAccess.cpp | 4 + src/Access/EnabledQuota.cpp | 13 + src/Access/EnabledQuota.h | 7 + src/Access/HTTPAuthClient.h | 15 +- src/Access/IAccessStorage.cpp | 2 + src/Access/QuotaCache.cpp | 28 +- src/Access/QuotaCache.h | 7 +- src/Access/SettingsConstraints.cpp | 49 +- src/Access/SettingsConstraints.h | 12 +- .../AggregateFunctionGroupArray.cpp | 31 +- .../FunctionSecretArgumentsFinderTreeNode.cpp | 8 +- .../FunctionSecretArgumentsFinderTreeNode.h | 3 +- .../Passes/FunctionToSubcolumnsPass.cpp | 4 + src/Analyzer/QueryTreeBuilder.cpp | 34 +- .../evaluateScalarSubqueryIfNeeded.cpp | 2 +- src/Backups/BackupIO_AzureBlobStorage.cpp | 20 +- src/Backups/BackupMetadataFinder.cpp | 11 + src/Backups/RestorerFromBackup.cpp | 25 +- src/CMakeLists.txt | 13 +- src/Client/ClientBase.cpp | 6 +- src/Client/ClientBaseHelpers.cpp | 10 +- src/Client/ClientBaseHelpers.h | 4 +- src/Client/ReplxxLineReader.cpp | 17 +- src/Client/ReplxxLineReader.h | 19 +- src/Columns/ColumnArray.cpp | 24 +- src/Columns/ColumnDynamic.cpp | 29 + src/Columns/ColumnDynamic.h | 35 +- src/Columns/ColumnLowCardinality.cpp | 10 +- src/Columns/ColumnLowCardinality.h | 1 + src/Columns/ReverseIndex.h | 99 +- .../gtest_reverse_index_exception_safety.cpp | 123 + src/Common/CurrentMetrics.cpp | 2 + src/Common/DateLUTImpl.h | 14 +- src/Common/FailPoint.cpp | 3 + src/Common/RemoteHostFilter.cpp | 4 + src/Common/Scheduler/CPUSlotsAllocation.cpp | 7 +- src/Common/Scheduler/CPUSlotsAllocation.h | 4 + .../tests/gtest_workload_resource_manager.cpp | 38 + src/Common/ThreadStatus.cpp | 5 +- src/Common/ZooKeeper/ZooKeeperConstants.h | 2 + src/Common/ZooKeeper/ZooKeeperIO.cpp | 23 +- src/Common/maskURIPassword.h | 55 + src/Common/mysqlxx/Connection.cpp | 8 + src/Common/mysqlxx/Pool.cpp | 53 + .../tests/gtest_distrusted_certificates.cpp | 137 + .../gtest_file_channel_rotation_failure.cpp | 133 + src/Coordination/Changelog.cpp | 2 + src/Coordination/tests/gtest_coordination.cpp | 63 + .../tests/gtest_coordination_changelog.cpp | 39 + src/Core/BackgroundSchedulePool.cpp | 4 +- src/Core/Field.cpp | 4 + src/Core/FormatFactorySettings.h | 7 + src/Core/PostgreSQLProtocol.h | 28 +- src/Core/Settings.cpp | 4 + src/Core/SettingsChangesHistory.cpp | 1 + .../SerializationLowCardinality.cpp | 7 + .../gtest_low_cardinality_serialization.cpp | 179 ++ src/Databases/DataLake/GlueCatalog.cpp | 47 +- src/Databases/DataLake/GlueCatalog.h | 11 +- src/Databases/DataLake/HiveCatalog.cpp | 18 +- src/Databases/DatabaseReplicated.cpp | 134 +- src/Databases/DatabaseReplicated.h | 22 +- src/Databases/DatabaseReplicatedWorker.cpp | 65 +- src/Databases/DatabaseReplicatedWorker.h | 25 + src/Databases/MySQL/DatabaseMySQL.cpp | 9 + src/Dictionaries/MongoDBDictionarySource.cpp | 7 +- src/Dictionaries/SSDCacheDictionaryStorage.h | 3 +- .../YAMLRegExpTreeDictionarySource.cpp | 2 +- .../AzureBlobStorageCommon.cpp | 30 + .../AzureBlobStorage/AzureBlobStorageCommon.h | 6 + .../AzureBlobStorage/AzureObjectStorage.cpp | 4 +- .../IO/AsynchronousBoundedReadBuffer.cpp | 1 + .../IO/ReadBufferFromAzureBlobStorage.cpp | 2 +- .../gtest_azure_read_buffer_missing_etag.cpp | 106 + src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 8 + src/Formats/ProtobufSerializer.cpp | 3 + src/Functions/HasSubsequenceImpl.h | 2 + src/Functions/URL/protocol.h | 3 + src/IO/CachedInMemoryReadBufferFromFile.cpp | 2 + src/IO/ReadWriteBufferFromHTTP.cpp | 3 +- src/IO/S3/Client.cpp | 21 +- src/IO/S3/Client.h | 2 + src/IO/SharedThreadPools.cpp | 9 + src/IO/SharedThreadPools.h | 2 + src/IO/tests/gtest_brotli_decoder.cpp | 58 + src/Interpreters/AsynchronousInsertQueue.cpp | 38 +- src/Interpreters/AsynchronousInsertQueue.h | 13 +- src/Interpreters/Cache/EvictionCandidates.cpp | 3 +- src/Interpreters/Cache/FileCache.cpp | 10 +- src/Interpreters/Cache/FileSegment.cpp | 18 +- src/Interpreters/Cache/FileSegment.h | 5 + src/Interpreters/Context.cpp | 67 +- src/Interpreters/Context.h | 26 +- .../ExecuteScalarSubqueriesVisitor.cpp | 2 +- src/Interpreters/InterpreterAlterQuery.cpp | 120 + src/Interpreters/InterpreterCreateQuery.cpp | 89 + src/Interpreters/InterpreterCreateQuery.h | 4 + src/Interpreters/JIT/CHJIT.cpp | 9 +- src/Interpreters/JIT/CHJIT.h | 3 +- src/Interpreters/executeDDLQueryOnCluster.cpp | 6 + src/Interpreters/executeDDLQueryOnCluster.h | 8 + .../tests/gtest_async_insert_key.cpp | 54 +- src/Interpreters/tests/gtest_filecache.cpp | 218 ++ src/Parsers/FunctionSecretArgumentsFinder.cpp | 228 +- src/Parsers/FunctionSecretArgumentsFinder.h | 28 + .../FunctionSecretArgumentsFinderAST.h | 2 + src/Parsers/Lexer.cpp | 2 +- src/Parsers/tests/gtest_Parser.cpp | 8 + src/Processors/Chunk.cpp | 12 +- src/Processors/Formats/IInputFormat.h | 2 + .../Formats/Impl/ArrowBatchRowLimit.cpp | 319 +++ .../Formats/Impl/ArrowBatchRowLimit.h | 47 + .../Formats/Impl/ArrowBlockOutputFormat.cpp | 1 + .../Formats/Impl/ArrowBufferedStreams.cpp | 2 +- .../Formats/Impl/ArrowBufferedStreams.h | 2 +- .../Formats/Impl/ArrowColumnToCHColumn.cpp | 2 +- .../Formats/Impl/ArrowColumnToCHColumn.h | 2 +- .../Formats/Impl/CHColumnToArrowColumn.cpp | 105 +- .../Formats/Impl/CHColumnToArrowColumn.h | 3 + .../Formats/Impl/MsgPackRowInputFormat.cpp | 8 +- .../Formats/Impl/MsgPackRowInputFormat.h | 3 +- .../Formats/Impl/MySQLDumpRowInputFormat.cpp | 9 +- .../Impl/NativeORCBlockInputFormat.cpp | 2300 +++++++++++++---- .../Formats/Impl/NativeORCBlockInputFormat.h | 80 +- .../Formats/Impl/ORC/ColumnReader.cpp | 1218 +++++++++ .../Formats/Impl/ORC/ColumnReader.h | 63 + .../Formats/Impl/ORC/Compression.cpp | 437 ++++ src/Processors/Formats/Impl/ORC/Compression.h | 42 + src/Processors/Formats/Impl/ORC/Proto.cpp | 944 +++++++ src/Processors/Formats/Impl/ORC/Proto.h | 343 +++ src/Processors/Formats/Impl/ORC/RLE.cpp | 1129 ++++++++ src/Processors/Formats/Impl/ORC/RLE.h | 151 ++ src/Processors/Formats/Impl/ORC/Reader.cpp | 842 ++++++ src/Processors/Formats/Impl/ORC/Reader.h | 188 ++ .../Formats/Impl/ORC/SearchArgument.cpp | 1075 ++++++++ .../Formats/Impl/ORC/SearchArgument.h | 198 ++ .../Formats/Impl/ORC/Statistics.cpp | 462 ++++ src/Processors/Formats/Impl/ORC/Statistics.h | 71 + src/Processors/Formats/Impl/ORC/Stream.cpp | 248 ++ src/Processors/Formats/Impl/ORC/Stream.h | 140 + src/Processors/Formats/Impl/ORC/Timezone.cpp | 87 + src/Processors/Formats/Impl/ORC/Timezone.h | 25 + src/Processors/Formats/Impl/ORC/Type.cpp | 380 +++ src/Processors/Formats/Impl/ORC/Type.h | 114 + src/Processors/Formats/Impl/ORC/Vector.cpp | 143 + src/Processors/Formats/Impl/ORC/Vector.h | 174 ++ src/Processors/Formats/Impl/ORC/Writer.cpp | 1493 +++++++++++ src/Processors/Formats/Impl/ORC/Writer.h | 78 + .../Formats/Impl/ORCBlockInputFormat.cpp | 276 -- .../Formats/Impl/ORCBlockInputFormat.h | 85 - .../Formats/Impl/ORCBlockOutputFormat.cpp | 551 ++-- .../Formats/Impl/ORCBlockOutputFormat.h | 49 +- .../Formats/Impl/Parquet/Decoding.cpp | 21 +- .../Formats/Impl/Parquet/Decoding.h | 3 + .../Formats/Impl/Parquet/SchemaConverter.cpp | 4 +- .../Formats/Impl/ParquetBlockOutputFormat.cpp | 52 +- .../Formats/Impl/ParquetBlockOutputFormat.h | 12 +- .../Impl/ParquetV3BlockInputFormat.cpp | 32 +- .../Formats/Impl/ParquetV3BlockInputFormat.h | 11 +- .../Formats/Impl/RawBLOBRowOutputFormat.cpp | 20 +- .../Formats/Impl/RawBLOBRowOutputFormat.h | 8 +- .../QueryPlan/Optimizations/optimizeJoin.cpp | 12 +- .../QueryPlan/ReadFromMergeTree.cpp | 13 +- .../Transforms/AddingDefaultsTransform.cpp | 3 +- ...umn_to_arrow_column_record_batch_split.cpp | 127 + src/Server/HTTP/ReadHeaders.cpp | 7 +- src/Server/HTTP/exceptionCodeToHTTPStatus.cpp | 4 +- src/Server/PostgreSQLHandler.cpp | 4 +- src/Server/TCPHandler.cpp | 6 +- src/Storages/AlterCommands.cpp | 38 + src/Storages/AlterCommands.h | 3 + .../DistributedAsyncInsertBatch.cpp | 20 +- .../DistributedAsyncInsertDirectoryQueue.cpp | 6 + .../DistributedAsyncInsertHelpers.cpp | 8 + .../DistributedAsyncInsertHelpers.h | 9 + src/Storages/Distributed/DistributedSink.cpp | 18 +- src/Storages/Hive/HiveFile.cpp | 109 +- src/Storages/Hive/HiveFile.h | 9 +- src/Storages/Hive/StorageHive.cpp | 4 + src/Storages/IStorage.h | 3 + src/Storages/IndicesDescription.cpp | 124 + src/Storages/IndicesDescription.h | 15 + src/Storages/MergeTree/KeyCondition.cpp | 13 +- .../MergeTree/MergeTreeBlockReadUtils.cpp | 3 +- src/Storages/MergeTree/MergeTreeData.cpp | 21 +- src/Storages/MergeTree/MergeTreeData.h | 7 + .../MergeTree/MergeTreeDataWriter.cpp | 5 + .../MergeTree/MergeTreeIndexBloomFilter.cpp | 19 +- src/Storages/MergeTree/MergeTreeIndexSet.cpp | 15 + .../MergeTree/MergeTreeRangeReader.cpp | 8 + .../MergeTree/MergeTreeSelectProcessor.cpp | 11 +- .../MergeTree/MergeTreeSelectProcessor.h | 6 +- src/Storages/MergeTree/MergeTreeSettings.cpp | 2 +- .../MergeTreeSplitPrewhereIntoReadSteps.cpp | 57 +- .../MergeTreeSplitPrewhereIntoReadSteps.h | 5 +- .../MergeTree/MergeTreeWhereOptimizer.cpp | 20 +- .../MergeTree/MergeTreeWhereOptimizer.h | 4 - .../MergeTree/MutateFromLogEntryTask.cpp | 2 +- .../ReplicatedMergeTreeCleanupThread.cpp | 2 +- .../gtest_merge_tree_index_bloom_filter.cpp | 74 + .../ObjectStorage/Azure/Configuration.cpp | 13 +- .../ObjectStorage/Azure/Configuration.h | 2 +- .../Common/AvroForIcebergDeserializer.cpp | 1 + .../Common/AvroForIcebergDeserializer.h | 5 + .../DataLakes/DeltaLake/TableSnapshot.cpp | 36 +- .../DataLakes/DeltaLake/WriteTransaction.cpp | 80 +- .../DataLakes/Iceberg/IcebergIterator.cpp | 3 +- .../Iceberg/IcebergMetadataFilesCache.h | 2 +- .../DataLakes/Iceberg/MultipleFileWriter.cpp | 3 + .../DataLakes/Iceberg/Mutations.cpp | 4 + .../Iceberg/StatelessMetadataFileGetter.cpp | 9 +- .../Iceberg/StatelessMetadataFileGetter.h | 3 +- src/Storages/ObjectStorage/IObjectIterator.h | 1 + .../StorageObjectStorageSource.cpp | 27 +- .../StorageObjectStorageSource.h | 5 +- .../ObjectStorageQueue/AzureQueue_fwd.h | 7 +- ...bjectStorageQueueMoveDestinationAccess.cpp | 119 + .../ObjectStorageQueueMoveDestinationAccess.h | 37 + .../ObjectStorageQueuePostProcessor.cpp | 17 + .../ObjectStorageQueueSettings.cpp | 30 +- .../ObjectStorageQueueSettings.h | 3 +- .../StorageObjectStorageQueue.cpp | 117 +- .../StorageObjectStorageQueue.h | 2 + .../registerQueueStorage.cpp | 3 + .../StorageMaterializedPostgreSQL.cpp | 8 + .../StorageMaterializedPostgreSQL.h | 2 + src/Storages/StorageAlias.cpp | 25 + src/Storages/StorageAlias.h | 3 +- src/Storages/StorageBuffer.cpp | 7 + src/Storages/StorageBuffer.h | 1 + src/Storages/StorageDistributed.cpp | 21 + src/Storages/StorageFactory.cpp | 36 + src/Storages/StorageFactory.h | 15 + src/Storages/StorageInMemoryMetadata.cpp | 43 + src/Storages/StorageMaterializedView.cpp | 17 +- src/Storages/StorageMaterializedView.h | 1 + src/Storages/StorageMerge.cpp | 6 + src/Storages/StorageMerge.h | 1 + src/Storages/StorageMergeTree.cpp | 22 +- src/Storages/StorageMongoDB.cpp | 53 + src/Storages/StorageMongoDB.h | 3 + src/Storages/StorageProxy.h | 1 + src/Storages/StorageReplicatedMergeTree.cpp | 48 +- .../System/StorageSystemMutations.cpp | 112 +- src/Storages/System/StorageSystemMutations.h | 3 +- ...torageSystemObjectStorageQueueSettings.cpp | 4 +- src/TableFunctions/ITableFunction.cpp | 15 +- src/TableFunctions/ITableFunction.h | 9 +- src/configure_config.cmake | 3 + tests/integration/conftest.py | 30 + .../configs/config_with_hosts.xml | 1 + .../test_allowed_url_from_config/test.py | 120 + .../test_arrowflight_interface/test.py | 37 + .../test_backup_restore_new/test.py | 125 + tests/integration/test_crash_log/test.py | 5 + tests/integration/test_database_glue/test.py | 56 + .../integration/test_database_iceberg/test.py | 497 ++++ tests/integration/test_dotnet_client/test.py | 9 +- tests/integration/test_git_import/test.py | 29 +- .../test_keeper_remove_rejoin_leader/test.py | 65 + .../test_mask_sensitive_info/test.py | 24 +- .../__init__.py | 0 .../configs/remote_servers.xml | 11 + .../test.py | 102 + .../test.py | 73 + .../test_manifest_length_cache_weight.py | 99 + tests/integration/test_storage_s3/test.py | 35 + tests/integration/test_storage_url/test.py | 3 +- .../__init__.py | 0 .../configs/rabbitmq.xml | 6 + .../configs/remote_servers.xml | 14 + .../configs/users.xml | 23 + .../test.py | 299 +++ tests/integration/test_totp_auth/test_totp.py | 43 +- .../map_bucketed_serialization.xml | 8 +- tests/performance/map_subcolumns_prewhere.xml | 10 +- .../prewhere_subcolumn_read_steps.xml | 19 + .../0_stateless/00900_long_parquet_load_2.sh | 4 + tests/queries/0_stateless/01035_avg.reference | 8 +- tests/queries/0_stateless/01035_avg.sql | 2 +- .../01252_weird_time_zone.reference | 38 + .../0_stateless/01252_weird_time_zone.sql | 53 + .../01308_orc_output_format_arrays.reference | 2 +- ...01514_distributed_cancel_query_on_error.sh | 44 +- .../01721_join_implicit_cast_long.sql.j2 | 6 +- ...302_defaults_in_columnar_formats.reference | 2 + .../02302_defaults_in_columnar_formats.sql | 10 + ...x_add_with_invalid_alter_command.reference | 1 + ...t_index_add_with_invalid_alter_command.sql | 24 + ...2346_text_index_transform_access.reference | 19 + .../02346_text_index_transform_access.sql | 124 + ...sform_access_replicated_database.reference | 3 + ...x_transform_access_replicated_database.sql | 40 + ...text_index_transform_data_access.reference | 6 + ...02346_text_index_transform_data_access.sql | 68 + ..._text_index_transform_on_cluster.reference | 14 + .../02346_text_index_transform_on_cluster.sh | 77 + .../0_stateless/02372_analyzer_join.sql.j2 | 2 +- .../0_stateless/02426_orc_bug.reference | 2 +- .../02884_authentication_quota.reference | 12 +- .../0_stateless/02884_authentication_quota.sh | 6 +- ...runing_empty_partition_zookeeper.reference | 6 + ...wu_58_pruning_empty_partition_zookeeper.sh | 140 + .../03595_read_orc_file_segfault.sh | 2 +- ...03707_set_index_bad_get_null_bug.reference | 8 +- .../03707_set_index_bad_get_null_bug.sql | 5 + .../0_stateless/03784_bad_base_backup.sh | 12 + .../03822_file_function_read_on_file_grant.sh | 2 +- .../03923_kafka2_keeper_offsets.sh | 2 +- ...subcolumn_function_to_subcolumns.reference | 2 +- ...9_map_subcolumn_function_to_subcolumns.sql | 11 +- .../04000_map_subcolumns_prewhere.reference | 2 +- .../04000_map_subcolumns_prewhere.sql | 7 +- .../04039_text_index_map_values_subcolumn.sql | 5 +- ...3_has_subsequence_empty_haystack.reference | 8 + .../04113_has_subsequence_empty_haystack.sql | 9 + ...66_ttl_with_subcolumn_expression.reference | 3 + .../04266_ttl_with_subcolumn_expression.sql | 34 + ...337_orc_schema_inference_deep_recursion.sh | 23 +- .../04338_async_insert_current_user.reference | 6 + .../04338_async_insert_current_user.sql | 43 + ..._async_insert_authenticated_user.reference | 3 + .../04339_async_insert_authenticated_user.sh | 77 + ...27_set_index_null_const_no_prune.reference | 14 + .../04627_set_index_null_const_no_prune.sql | 50 + ...ultistep_prewhere_default_column.reference | 9 + ...4628_multistep_prewhere_default_column.sql | 23 + ...where_default_column_patch_parts.reference | 6 + ...ep_prewhere_default_column_patch_parts.sql | 25 + .../04856_orc_corrupt_stripe_footer.reference | 4 + .../04856_orc_corrupt_stripe_footer.sh | 29 + ...orc_unimplemented_codec_no_abort.reference | 14 + .../05036_orc_unimplemented_codec_no_abort.sh | 59 + ...replicated_max_logs_to_keep_zero.reference | 4 + .../05053_replicated_max_logs_to_keep_zero.sh | 42 + ...postgresql_protocol_message_size.reference | 4 + .../05054_postgresql_protocol_message_size.sh | 66 + ...5_arrow_split_large_record_batch.reference | 9 + .../05055_arrow_split_large_record_batch.sh | 55 + ...t_schema_source_query_background_access.sh | 7 +- ...055_http_conflict_is_not_retried.reference | 2 + .../05055_http_conflict_is_not_retried.sh | 62 + ...ow_record_batch_split_boundaries.reference | 4 + ...056_arrow_record_batch_split_boundaries.sh | 49 + ...raints_nested_settings_effective.reference | 22 + ...s_constraints_nested_settings_effective.sh | 117 + ...ttings_equal_value_marks_changed.reference | 18 + ...sted_settings_equal_value_marks_changed.sh | 48 + ...ble_from_path_read_on_file_grant.reference | 7 + ...tach_table_from_path_read_on_file_grant.sh | 67 + ...8_quota_client_key_stale_context.reference | 12 + .../05218_quota_client_key_stale_context.sh | 54 + ...l_nullable_partition_key_pruning.reference | 43 + ...ot_null_nullable_partition_key_pruning.sql | 112 + ...91_system_mutations_hide_secrets.reference | 5 + .../05291_system_mutations_hide_secrets.sql | 47 + ...icy_scalar_subquery_cache_bypass.reference | 6 + ...row_policy_scalar_subquery_cache_bypass.sh | 68 + ...rupt_stripe_footer_stream_column.reference | 3 + ...orc_corrupt_stripe_footer_stream_column.sh | 49 + ...9_http_header_rfc2047_line_break.reference | 18 + .../05339_http_header_rfc2047_line_break.sh | 29 + ...39_prewhere_subcolumn_read_steps.reference | 7 + .../05339_prewhere_subcolumn_read_steps.sql | 79 + ...ement_to_subcolumn_bucketed_only.reference | 30 + ...map_element_to_subcolumn_bucketed_only.sql | 75 + ...rite_many_partitions_thread_pool.reference | 3 + ...eberg_write_many_partitions_thread_pool.sh | 40 + ...mic_deep_value_column_operations.reference | 4 + ...07_dynamic_deep_value_column_operations.sh | 50 + ...407_orc_timezone_traversal_abort.reference | 5 + .../05407_orc_timezone_traversal_abort.sh | 137 + .../05427_azure_sas_url_parsing.reference | 0 .../05427_azure_sas_url_parsing.sql | 9 + ...mysqldump_create_without_columns.reference | 51 + .../05428_mysqldump_create_without_columns.sh | 38 + ...tobuf_map_with_unsupported_value.reference | 3 + ...429_protobuf_map_with_unsupported_value.sh | 13 + ...ema_inference_untypeable_map_key.reference | 4 + ...ck_schema_inference_untypeable_map_key.sql | 22 + ...05441_rawblob_aggregate_function.reference | 5 + .../05441_rawblob_aggregate_function.sh | 18 + ..._s3queue_move_destination_access.reference | 35 + .../05441_s3queue_move_destination_access.sh | 377 +++ ...t_mv_dedup_empty_partition_block.reference | 3 + ..._insert_mv_dedup_empty_partition_block.sql | 39 + ...converted_outer_join_type_change.reference | 12 + ...order_converted_outer_join_type_change.sql | 71 + ...uted_insert_select_source_access.reference | 7 + ...distributed_insert_select_source_access.sh | 77 + ...nt96_date_time_overflow_behavior.reference | 13 + ...rquet_int96_date_time_overflow_behavior.sh | 19 + ...444_parquet_int96_lower_boundary.reference | 2 + .../05444_parquet_int96_lower_boundary.sh | 16 + ...uted_async_insert_batch_per_user.reference | 1 + ...distributed_async_insert_batch_per_user.sh | 41 + ...sas_url_hidden_in_table_function.reference | 13 + ..._azure_sas_url_hidden_in_table_function.sh | 43 + .../05447_orc_native_reader_writer.reference | 14 + .../05447_orc_native_reader_writer.sh | 46 + .../05448_orc_date_after_2059.reference | 12 + .../0_stateless/05448_orc_date_after_2059.sh | 20 + ...mats_read_padding_object_storage.reference | 5 + ...ext_formats_read_padding_object_storage.sh | 29 + .../05453_orc_bad_bloom_filter.reference | 8 + .../0_stateless/05453_orc_bad_bloom_filter.sh | 27 + ...entials_hidden_in_logged_queries.reference | 39 + ...re_credentials_hidden_in_logged_queries.sh | 62 + .../05473_orc_footer_content_length.reference | 2 + .../05473_orc_footer_content_length.sh | 53 + .../05474_orc_decimal64_v2.reference | 20 + .../0_stateless/05474_orc_decimal64_v2.sh | 13 + ..._storage_parquet_footer_prefetch.reference | 4 + ..._object_storage_parquet_footer_prefetch.sh | 39 + ..._record_batch_split_many_batches.reference | 2 + ...3_arrow_record_batch_split_many_batches.sh | 40 + ...abase_ddl_during_restore_replica.reference | 1 + ...ted_database_ddl_during_restore_replica.sh | 65 + ..._replica_waits_for_initial_query.reference | 5 + ...restore_replica_waits_for_initial_query.sh | 58 + ...ictionary_cache_file_cannot_grow.reference | 6 + ...cache_dictionary_cache_file_cannot_grow.sh | 57 + ...on_create_temporary_table_access.reference | 25 + ..._function_create_temporary_table_access.sh | 102 + ...async_insert_after_invalid_entry.reference | 6 + ...sgpack_async_insert_after_invalid_entry.sh | 36 + ...5493_mysql_host_connector_syntax.reference | 13 + .../05493_mysql_host_connector_syntax.sh | 77 + ...ttings_system_table_hide_secrets.reference | 4 + ...eue_settings_system_table_hide_secrets.sql | 22 + ...498_s3_disk_sse_c_key_validation.reference | 1 + .../05498_s3_disk_sse_c_key_validation.sql | 31 + .../05507_orc_malformed_timestamps.reference | 16 + .../05507_orc_malformed_timestamps.sh | 19 + ...8_orc_writer_out_of_range_values.reference | 7 + .../05508_orc_writer_out_of_range_values.sh | 26 + ...05509_orc_malformed_dictionaries.reference | 16 + .../05509_orc_malformed_dictionaries.sh | 21 + ...510_orc_allocation_amplification.reference | 32 + .../05510_orc_allocation_amplification.sh | 27 + ...rc_malformed_stripes_and_streams.reference | 16 + ...05511_orc_malformed_stripes_and_streams.sh | 19 + .../05512_orc_malformed_row_groups.reference | 32 + .../05512_orc_malformed_row_groups.sh | 26 + ...c_metadata_repeated_field_limits.reference | 16 + ...5513_orc_metadata_repeated_field_limits.sh | 17 + ...imestamp_statistics_before_epoch.reference | 21 + ...4_orc_timestamp_statistics_before_epoch.sh | 45 + .../05515_orc_nullable_floats.reference | 2 + .../0_stateless/05515_orc_nullable_floats.sh | 30 + ..._replica_waits_for_initial_alter.reference | 6 + ...restore_replica_waits_for_initial_alter.sh | 58 + ...rquet_encoder_shared_thread_pool.reference | 1 + ...5565_parquet_encoder_shared_thread_pool.sh | 31 + ...up_array_sample_counter_overflow.reference | 3 + ...67_group_array_sample_counter_overflow.sql | 28 + ...05567_mongodb_server_credentials.reference | 21 + .../05567_mongodb_server_credentials.sh | 87 + ...db_dictionary_server_credentials.reference | 12 + ...8_mongodb_dictionary_server_credentials.sh | 85 + ...c_requested_type_of_another_kind.reference | 18 + ...5574_orc_requested_type_of_another_kind.sh | 56 + ...ing_result_memory_limit_in_local.reference | 6 + ...cumulating_result_memory_limit_in_local.sh | 18 + ...imestamp_before_first_transition.reference | 9 + ...6_orc_timestamp_before_first_transition.sh | 50 + ..._struct_without_requested_fields.reference | 153 ++ ...nested_struct_without_requested_fields.sql | 99 + .../data_orc/bad_bloom_filter_1.6.0.orc | Bin 0 -> 709 bytes .../data_orc/bad_bloom_filter_1.6.11.orc | Bin 0 -> 717 bytes .../0_stateless/data_orc/decimal64_v2.orc | Bin 0 -> 738 bytes .../malformed_compression_block_1g.orc | Bin 0 -> 414 bytes .../data_orc/malformed_dictionary_empty.orc | Bin 0 -> 170 bytes .../malformed_dictionary_size_max.orc | Bin 0 -> 174 bytes .../malformed_footer_too_many_statistics.orc | Bin 0 -> 353 bytes .../malformed_metadata_too_many_stripes.orc | Bin 0 -> 673 bytes ...med_patched_base_terminal_continuation.orc | Bin 0 -> 83 bytes .../malformed_row_group_count_overflow.orc | Bin 0 -> 237 bytes .../malformed_row_index_seek_past_stream.orc | Bin 0 -> 213 bytes .../data_orc/malformed_snappy_chunk_size.orc | Bin 0 -> 31 bytes .../malformed_stream_offset_overflow.orc | Bin 0 -> 301 bytes .../malformed_stripe_offset_overflow.orc | Bin 0 -> 301 bytes .../malformed_timestamp_nanoseconds.orc | Bin 0 -> 238 bytes ...ormed_timestamp_statistics_nanoseconds.orc | Bin 0 -> 264 bytes .../data_orc/malformed_zstd_chunk_size.orc | Bin 0 -> 38 bytes .../data_orc/orc_nested_union_type.orc | Bin 0 -> 666 bytes .../0_stateless/data_orc/orc_union_type.orc | Bin 0 -> 398 bytes .../data_orc/row_index_seek_control.orc | Bin 0 -> 213 bytes .../timestamps_before_epoch_arrow.orc | Bin 0 -> 294 bytes ...amps_before_epoch_pyarrow_bloom_filter.orc | Bin 0 -> 517 bytes .../05443_int96_out_of_range.parquet | Bin 0 -> 700 bytes .../05444_int96_lower_boundary.parquet | Bin 0 -> 535 bytes ..._protobuf_map_with_unsupported_value.proto | 21 + tests/queries/0_stateless/orc_malformed.lib | 55 + 534 files changed, 25468 insertions(+), 2658 deletions(-) create mode 100644 base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h create mode 100644 base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp create mode 100644 base/poco/XML/src/entities.h delete mode 100644 contrib/arrow-cmake/orc_check.cmake delete mode 160000 contrib/orc create mode 100644 src/Columns/tests/gtest_reverse_index_exception_safety.cpp create mode 100644 src/Common/tests/gtest_distrusted_certificates.cpp create mode 100644 src/Common/tests/gtest_file_channel_rotation_failure.cpp create mode 100644 src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp create mode 100644 src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp create mode 100644 src/IO/tests/gtest_brotli_decoder.cpp create mode 100644 src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp create mode 100644 src/Processors/Formats/Impl/ArrowBatchRowLimit.h create mode 100644 src/Processors/Formats/Impl/ORC/ColumnReader.cpp create mode 100644 src/Processors/Formats/Impl/ORC/ColumnReader.h create mode 100644 src/Processors/Formats/Impl/ORC/Compression.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Compression.h create mode 100644 src/Processors/Formats/Impl/ORC/Proto.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Proto.h create mode 100644 src/Processors/Formats/Impl/ORC/RLE.cpp create mode 100644 src/Processors/Formats/Impl/ORC/RLE.h create mode 100644 src/Processors/Formats/Impl/ORC/Reader.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Reader.h create mode 100644 src/Processors/Formats/Impl/ORC/SearchArgument.cpp create mode 100644 src/Processors/Formats/Impl/ORC/SearchArgument.h create mode 100644 src/Processors/Formats/Impl/ORC/Statistics.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Statistics.h create mode 100644 src/Processors/Formats/Impl/ORC/Stream.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Stream.h create mode 100644 src/Processors/Formats/Impl/ORC/Timezone.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Timezone.h create mode 100644 src/Processors/Formats/Impl/ORC/Type.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Type.h create mode 100644 src/Processors/Formats/Impl/ORC/Vector.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Vector.h create mode 100644 src/Processors/Formats/Impl/ORC/Writer.cpp create mode 100644 src/Processors/Formats/Impl/ORC/Writer.h delete mode 100644 src/Processors/Formats/Impl/ORCBlockInputFormat.cpp delete mode 100644 src/Processors/Formats/Impl/ORCBlockInputFormat.h create mode 100644 src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp create mode 100644 src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp create mode 100644 src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp create mode 100644 src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h create mode 100644 tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py create mode 100644 tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml create mode 100644 tests/integration/test_refreshable_mv_definer_interserver_secret/test.py create mode 100644 tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml create mode 100644 tests/integration/test_streaming_engines_definer_interserver_secret/test.py create mode 100644 tests/performance/prewhere_subcolumn_read_steps.xml create mode 100644 tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference create mode 100644 tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access.reference create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference create mode 100644 tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_data_access.reference create mode 100644 tests/queries/0_stateless/02346_text_index_transform_data_access.sql create mode 100644 tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference create mode 100755 tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh create mode 100644 tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference create mode 100755 tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh create mode 100644 tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference create mode 100644 tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql create mode 100644 tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference create mode 100644 tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql create mode 100644 tests/queries/0_stateless/04338_async_insert_current_user.reference create mode 100644 tests/queries/0_stateless/04338_async_insert_current_user.sql create mode 100644 tests/queries/0_stateless/04339_async_insert_authenticated_user.reference create mode 100755 tests/queries/0_stateless/04339_async_insert_authenticated_user.sh create mode 100644 tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference create mode 100644 tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql create mode 100644 tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference create mode 100644 tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql create mode 100644 tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference create mode 100644 tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql create mode 100644 tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference create mode 100755 tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh create mode 100644 tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference create mode 100755 tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh create mode 100644 tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference create mode 100755 tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh create mode 100644 tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference create mode 100755 tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh create mode 100644 tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference create mode 100755 tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh create mode 100644 tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference create mode 100755 tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh create mode 100644 tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference create mode 100755 tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh create mode 100644 tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference create mode 100755 tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh create mode 100644 tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference create mode 100755 tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh create mode 100644 tests/queries/0_stateless/05218_quota_client_key_stale_context.reference create mode 100755 tests/queries/0_stateless/05218_quota_client_key_stale_context.sh create mode 100644 tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference create mode 100644 tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql create mode 100644 tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference create mode 100644 tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql create mode 100644 tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference create mode 100755 tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh create mode 100644 tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference create mode 100755 tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh create mode 100644 tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference create mode 100755 tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh create mode 100644 tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference create mode 100644 tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql create mode 100644 tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference create mode 100644 tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql create mode 100644 tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference create mode 100755 tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh create mode 100644 tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference create mode 100755 tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh create mode 100644 tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference create mode 100755 tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh create mode 100644 tests/queries/0_stateless/05427_azure_sas_url_parsing.reference create mode 100644 tests/queries/0_stateless/05427_azure_sas_url_parsing.sql create mode 100644 tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference create mode 100755 tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh create mode 100644 tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference create mode 100755 tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh create mode 100644 tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference create mode 100644 tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql create mode 100644 tests/queries/0_stateless/05441_rawblob_aggregate_function.reference create mode 100755 tests/queries/0_stateless/05441_rawblob_aggregate_function.sh create mode 100644 tests/queries/0_stateless/05441_s3queue_move_destination_access.reference create mode 100755 tests/queries/0_stateless/05441_s3queue_move_destination_access.sh create mode 100644 tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference create mode 100644 tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql create mode 100644 tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference create mode 100644 tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql create mode 100644 tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference create mode 100755 tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh create mode 100644 tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference create mode 100755 tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh create mode 100644 tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference create mode 100755 tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh create mode 100644 tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference create mode 100755 tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh create mode 100644 tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference create mode 100755 tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh create mode 100644 tests/queries/0_stateless/05447_orc_native_reader_writer.reference create mode 100755 tests/queries/0_stateless/05447_orc_native_reader_writer.sh create mode 100644 tests/queries/0_stateless/05448_orc_date_after_2059.reference create mode 100755 tests/queries/0_stateless/05448_orc_date_after_2059.sh create mode 100644 tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference create mode 100755 tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh create mode 100644 tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference create mode 100755 tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh create mode 100644 tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference create mode 100755 tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh create mode 100644 tests/queries/0_stateless/05473_orc_footer_content_length.reference create mode 100755 tests/queries/0_stateless/05473_orc_footer_content_length.sh create mode 100644 tests/queries/0_stateless/05474_orc_decimal64_v2.reference create mode 100755 tests/queries/0_stateless/05474_orc_decimal64_v2.sh create mode 100644 tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference create mode 100755 tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh create mode 100644 tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference create mode 100755 tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh create mode 100644 tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference create mode 100755 tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh create mode 100644 tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference create mode 100755 tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh create mode 100644 tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference create mode 100755 tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh create mode 100644 tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference create mode 100755 tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh create mode 100644 tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference create mode 100755 tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh create mode 100644 tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference create mode 100755 tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh create mode 100644 tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference create mode 100644 tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql create mode 100644 tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference create mode 100644 tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql create mode 100644 tests/queries/0_stateless/05507_orc_malformed_timestamps.reference create mode 100755 tests/queries/0_stateless/05507_orc_malformed_timestamps.sh create mode 100644 tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference create mode 100755 tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh create mode 100644 tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference create mode 100755 tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh create mode 100644 tests/queries/0_stateless/05510_orc_allocation_amplification.reference create mode 100755 tests/queries/0_stateless/05510_orc_allocation_amplification.sh create mode 100644 tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference create mode 100755 tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh create mode 100644 tests/queries/0_stateless/05512_orc_malformed_row_groups.reference create mode 100755 tests/queries/0_stateless/05512_orc_malformed_row_groups.sh create mode 100644 tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference create mode 100755 tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh create mode 100644 tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference create mode 100755 tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh create mode 100644 tests/queries/0_stateless/05515_orc_nullable_floats.reference create mode 100755 tests/queries/0_stateless/05515_orc_nullable_floats.sh create mode 100644 tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference create mode 100755 tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh create mode 100644 tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference create mode 100755 tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh create mode 100644 tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference create mode 100644 tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql create mode 100644 tests/queries/0_stateless/05567_mongodb_server_credentials.reference create mode 100755 tests/queries/0_stateless/05567_mongodb_server_credentials.sh create mode 100644 tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference create mode 100755 tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh create mode 100644 tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference create mode 100755 tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh create mode 100644 tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference create mode 100755 tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh create mode 100644 tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference create mode 100755 tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh create mode 100644 tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference create mode 100644 tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql create mode 100644 tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc create mode 100644 tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc create mode 100644 tests/queries/0_stateless/data_orc/decimal64_v2.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_compression_block_1g.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_dictionary_empty.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_metadata_too_many_stripes.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_row_group_count_overflow.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_row_index_seek_past_stream.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_snappy_chunk_size.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_stream_offset_overflow.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_stripe_offset_overflow.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_timestamp_statistics_nanoseconds.orc create mode 100644 tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc create mode 100644 tests/queries/0_stateless/data_orc/orc_nested_union_type.orc create mode 100644 tests/queries/0_stateless/data_orc/orc_union_type.orc create mode 100644 tests/queries/0_stateless/data_orc/row_index_seek_control.orc create mode 100644 tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc create mode 100644 tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc create mode 100644 tests/queries/0_stateless/data_parquet/05443_int96_out_of_range.parquet create mode 100644 tests/queries/0_stateless/data_parquet/05444_int96_lower_boundary.parquet create mode 100644 tests/queries/0_stateless/format_schemas/05429_protobuf_map_with_unsupported_value.proto create mode 100644 tests/queries/0_stateless/orc_malformed.lib diff --git a/.gitmodules b/.gitmodules index 4959a04c45dc..73baf268fde7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -76,9 +76,6 @@ [submodule "contrib/fastops"] path = contrib/fastops url = https://github.com/ClickHouse/fastops -[submodule "contrib/orc"] - path = contrib/orc - url = https://github.com/ClickHouse/orc [submodule "contrib/sparsehash-c11"] path = contrib/sparsehash-c11 url = https://github.com/sparsehash/sparsehash-c11 diff --git a/base/poco/Foundation/include/Poco/FileChannel.h b/base/poco/Foundation/include/Poco/FileChannel.h index 7db27772c0a2..028f1766aaa9 100644 --- a/base/poco/Foundation/include/Poco/FileChannel.h +++ b/base/poco/Foundation/include/Poco/FileChannel.h @@ -246,6 +246,7 @@ class Foundation_API FileChannel : public Channel void unsafeOpen(); private: + void unsafeRotate(); LogFile * newLogFile(); void archiveCorrupted(const std::string & path); bool setNoPurge(const std::string & value); diff --git a/base/poco/Foundation/src/FileChannel.cpp b/base/poco/Foundation/src/FileChannel.cpp index 9f5c10013c2f..4a48894f2fb4 100644 --- a/base/poco/Foundation/src/FileChannel.cpp +++ b/base/poco/Foundation/src/FileChannel.cpp @@ -25,6 +25,7 @@ #include "Poco/Exception.h" #include "Poco/Ascii.h" #include "Poco/CombinedRotateStrategy.h" +#include namespace Poco { @@ -111,15 +112,7 @@ void FileChannel::log(const Message& msg) if (_pRotateStrategy && _pArchiveStrategy && _pRotateStrategy->mustRotate(_pFile)) { - try - { - _pFile = _pArchiveStrategy->archive(_pFile, _streamCompress); - purge(); - } - catch (...) - { - _pFile = newLogFile(); - } + unsafeRotate(); // we must call mustRotate() again to give the // RotateByIntervalStrategy a chance to write its timestamp // to the new file. @@ -340,17 +333,24 @@ void FileChannel::unsafeOpen() { _pFile = newLogFile(); if (_rotateOnOpen && _pFile->size() > 0) - { - try - { - _pFile = _pArchiveStrategy->archive(_pFile, _streamCompress); - purge(); - } - catch (...) - { - _pFile = newLogFile(); - } - } + unsafeRotate(); + } +} + + +void FileChannel::unsafeRotate() +{ + /// `archive` deletes the current file, so `_pFile` must not dangle if opening the new one fails. + /// The raw pointer is intentional: `archive` owns `pFile` and deletes it, so it must not be deleted here. + LogFile * pFile = std::exchange(_pFile, nullptr); + try + { + _pFile = _pArchiveStrategy->archive(pFile, _streamCompress); + purge(); + } + catch (...) + { + _pFile = newLogFile(); } } diff --git a/base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h b/base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h new file mode 100644 index 000000000000..5aca47d6be88 --- /dev/null +++ b/base/poco/NetSSL_OpenSSL/include/Poco/Net/DistrustedCertificates.h @@ -0,0 +1,44 @@ +// +// DistrustedCertificates.h +// +// Library: NetSSL_OpenSSL +// Package: SSLCore +// Module: DistrustedCertificates +// +// Copyright (c) 2026, ClickHouse, Inc. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef NetSSL_DistrustedCertificates_INCLUDED +#define NetSSL_DistrustedCertificates_INCLUDED + + +#include +#include "Poco/Net/NetSSL.h" + + +namespace Poco +{ +namespace Net +{ + + + NetSSL_API int checkDistrustedCertificate(X509 * certificate); + /// Checks the certificate against the list of distrusted public keys built into + /// the binary, and returns `X509_V_OK` if it is not on the list, `X509_V_ERR_CERT_REVOKED` + /// if it is, or another `X509_V_ERR_*` code if the check itself failed. + /// + /// The list contains the keys of CA certificates that must not be trusted even if + /// the trust store of the operating system still contains them, e.g. because their + /// private keys are compromised. A key is identified by the SHA-256 of its DER-encoded + /// `SubjectPublicKeyInfo`, so that every certificate of the same key is rejected, + /// including cross-signed ones. + + +} +} // namespace Poco::Net + + +#endif // NetSSL_DistrustedCertificates_INCLUDED diff --git a/base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp b/base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp new file mode 100644 index 000000000000..448d4f601d9d --- /dev/null +++ b/base/poco/NetSSL_OpenSSL/src/DistrustedCertificates.cpp @@ -0,0 +1,95 @@ +// +// DistrustedCertificates.cpp +// +// Library: NetSSL_OpenSSL +// Package: SSLCore +// Module: DistrustedCertificates +// +// Copyright (c) 2026, ClickHouse, Inc. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/Net/DistrustedCertificates.h" +#include +#include +#include +#include + + +namespace +{ + using SPKIHash = std::array; + + consteval unsigned char hexDigit(char c) + { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + throw "Invalid hex digit"; + } + + consteval SPKIHash fromHex(const char (&hex)[65]) + { + SPKIHash result{}; + for (size_t i = 0; i < result.size(); ++i) + result[i] = static_cast(hexDigit(hex[2 * i]) << 4 | hexDigit(hex[2 * i + 1])); + return result; + } + + /// SHA-256 of the DER-encoded `SubjectPublicKeyInfo` of every distrusted key. + constexpr SPKIHash distrusted_keys[] = + { + /// eMudhra: the private keys of the intermediate CAs below, issued in 2025, can be recovered + /// from their certificates. Each of them is issued by `emSign Root TLS CA - G3` or `emSign Root CS CA - G3` + /// and cross-signed by Sectigo `AAA Certificate Services`; the cross-signed certificates have the same keys. + /// The roots that issued or cross-signed them are distrusted as well. + /// https://emudhra.we-have-a-problem.com/ + fromHex("EBED6475C2C2D80FCB199F3FE8DD6E6B3CE60B77EB15D4E42C3DEC0C6F5B5105"), /// EM DV TLS CA - G3B + fromHex("43BFFA19D6EF651451F6841E019931E96F6F2EAEFF28AB4B6F1CE4576DE2717B"), /// EM OV TLS CA - G3B + fromHex("E0254C7FCDC265E2F0F8A428DABB75AB4AE039B4872D62F5EE57F0877D5A8A41"), /// EM EV TLS CA - G3B + fromHex("49DD353DC2B919A3770645117D0E60C16115E7D1BC259EEFE734B00EA434FE5F"), /// EM DV TLS CA - G3C + fromHex("63ECEFEE431D49523BC1136C4E72D0206A477086CAF606CD5CF025686C109CF8"), /// EM OV TLS CA - G3C + fromHex("5C0660A2B164910D8FF589C18E14552E9E0EC237DCEFE2CB736D41A4811F81A0"), /// EM EV TLS CA - G3C + fromHex("EC4FFA1AD0AC88081314B7AAFFEF6A91F97CD57291BB5BA686C5415F5EB4F6B6"), /// EM OV CS CA - G3B + fromHex("92C063D67E8F14DB71D288E11266FFDAF69CBF115F7BAB14F3BC2F68D25E0E30"), /// EM OV CS CA - G3C + fromHex("C619E4780ED8E0ABEDA24AD732567DE4383A7EA941338F6D1A7D1B49AC792FE9"), /// emSign Root TLS CA - G3 + fromHex("0A6C2B2CA5B364207954171987AC9D2178561569D8205457E77CA90C32EDE282"), /// emSign Root CS CA - G3 + fromHex("8D417DB2DD8BF5E3084D1E3F196D583849D81BDD4C00C70B9D39369E96B8C782"), /// emSign ECC Root CA - G3 + }; +} + + +namespace Poco { +namespace Net { + + +int checkDistrustedCertificate(X509 * certificate) +{ + X509_PUBKEY * key = X509_get_X509_PUBKEY(certificate); + if (key == nullptr) + return X509_V_ERR_UNSPECIFIED; + + /// Not `X509_pubkey_digest`: it hashes only the key bits, without the algorithm identifier. + unsigned char * der = nullptr; + int der_size = i2d_X509_PUBKEY(key, &der); + if (der_size <= 0) + return X509_V_ERR_OUT_OF_MEM; + + SPKIHash hash; + unsigned int hash_size = 0; + int ok = EVP_Digest(der, der_size, hash.data(), &hash_size, EVP_sha256(), nullptr); + OPENSSL_free(der); + if (ok != 1 || hash_size != hash.size()) + return X509_V_ERR_UNSPECIFIED; + + if (std::find(std::begin(distrusted_keys), std::end(distrusted_keys), hash) != std::end(distrusted_keys)) + return X509_V_ERR_CERT_REVOKED; + + return X509_V_OK; +} + + +} } // namespace Poco::Net diff --git a/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp b/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp index 80d85855fe3c..e7764a5ece98 100644 --- a/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp +++ b/base/poco/NetSSL_OpenSSL/src/SSLManager.cpp @@ -14,6 +14,7 @@ #include "Poco/Net/SSLManager.h" #include "Poco/Net/Context.h" +#include "Poco/Net/DistrustedCertificates.h" #include "Poco/Net/Utility.h" #include "Poco/Net/PrivateKeyPassphraseHandler.h" #include "Poco/Net/RejectCertificateHandler.h" @@ -196,6 +197,20 @@ SSLManager::InvalidCertificateHandlerPtr SSLManager::clientCertificateHandler() int SSLManager::verifyCallback(bool server, int ok, X509_STORE_CTX* pStore) { + /// OpenSSL calls this for every certificate of the chain, with `ok` set to 1 if it has + /// no other errors, so this rejects a chain that contains a distrusted certificate at any + /// depth, whichever trust store (the system one, the configured one or the embedded one) + /// it was built from. The rejection is reported like any other verification error. + if (X509 * cert = X509_STORE_CTX_get_current_cert(pStore)) + { + int distrusted = checkDistrustedCertificate(cert); + if (distrusted != X509_V_OK) + { + X509_STORE_CTX_set_error(pStore, distrusted); + ok = 0; + } + } + if (!ok) { int depth = X509_STORE_CTX_get_error_depth(pStore); diff --git a/base/poco/XML/CMakeLists.txt b/base/poco/XML/CMakeLists.txt index 1d3c8d332f1b..d0d9f26fc268 100644 --- a/base/poco/XML/CMakeLists.txt +++ b/base/poco/XML/CMakeLists.txt @@ -9,6 +9,7 @@ add_library (Poco::XML::Expat ALIAS _poco_xml_expat) target_compile_options (_poco_xml_expat PRIVATE -Wno-cast-qual + -Wno-declaration-after-statement -Wno-disabled-macro-expansion -Wno-empty-translation-unit -Wno-extra-semi-stmt diff --git a/base/poco/XML/include/Poco/XML/expat.h b/base/poco/XML/include/Poco/XML/expat.h index 4a57c70fec8d..2d14d53b4e36 100644 --- a/base/poco/XML/include/Poco/XML/expat.h +++ b/base/poco/XML/include/Poco/XML/expat.h @@ -21,6 +21,7 @@ Copyright (c) 2024 Taichi Haradaguchi <20001722@ymail.ne.jp> Copyright (c) 2025 Matthew Fernandez Copyright (c) 2026 Braian Plaku + Copyright (c) 2026 Xisco Fauli Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -1084,7 +1085,7 @@ enum XML_Parser_Property { # if defined(XML_TESTING) XML_PROP_INVALID = 0, # endif -# if XML_GE == 1 +# if defined(XML_GE) && XML_GE == 1 XML_PROP_ALLOC_TRACKER_ACTIVATION_THRESHOLD = 1, // of type `uint64_t` XML_PROP_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION = 2, // of type `double` XML_PROP_BILLION_LAUGHS_ACTIVATION_THRESHOLD = 3, // of type `uint64_t` @@ -1146,7 +1147,7 @@ XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled); See https://semver.org */ # define XML_MAJOR_VERSION 2 -# define XML_MINOR_VERSION 9 +# define XML_MINOR_VERSION 10 # define XML_MICRO_VERSION 0 # ifdef __cplusplus diff --git a/base/poco/XML/include/Poco/XML/expat_external.h b/base/poco/XML/include/Poco/XML/expat_external.h index 9fb80149acd3..f34750afbddc 100644 --- a/base/poco/XML/include/Poco/XML/expat_external.h +++ b/base/poco/XML/include/Poco/XML/expat_external.h @@ -12,7 +12,7 @@ Copyright (c) 2001-2002 Greg Stein Copyright (c) 2002-2006 Karl Waclawek Copyright (c) 2016 Cristian Rodríguez - Copyright (c) 2016-2025 Sebastian Pipping + Copyright (c) 2016-2026 Sebastian Pipping Copyright (c) 2017 Rhodri James Copyright (c) 2018 Yury Gribov Copyright (c) 2026 Matthew Fernandez diff --git a/base/poco/XML/src/ascii.h b/base/poco/XML/src/ascii.h index 56c8807aa574..656c95e28ddb 100644 --- a/base/poco/XML/src/ascii.h +++ b/base/poco/XML/src/ascii.h @@ -10,7 +10,7 @@ Copyright (c) 2000 Clark Cooper Copyright (c) 2002 Fred L. Drake, Jr. Copyright (c) 2007 Karl Waclawek - Copyright (c) 2017 Sebastian Pipping + Copyright (c) 2017-2026 Sebastian Pipping Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -113,6 +113,7 @@ #define ASCII_LT 0x3C #define ASCII_EQUALS 0x3D #define ASCII_GT 0x3E +#define ASCII_QUEST 0x3F #define ASCII_LSQB 0x5B #define ASCII_RSQB 0x5D #define ASCII_UNDERSCORE 0x5F diff --git a/base/poco/XML/src/entities.h b/base/poco/XML/src/entities.h new file mode 100644 index 000000000000..d0cd309c1111 --- /dev/null +++ b/base/poco/XML/src/entities.h @@ -0,0 +1,99 @@ +/* Internal helpers related to entities + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 2026 Sebastian Pipping + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. + + SPDX-License-Identifier: MIT +*/ + +#if ! defined(EXPAT_ENTITIES_H) +# define EXPAT_ENTITIES_H 1 + +# include "expat_config.h" // for XML_GE +# include "Poco/XML/expat_external.h" // for XML_Char +# include "internal.h" // for XML_NONTESTING_STATIC +# include // for size_t +# include // for size_t + +typedef struct { + const XML_Char *name; + const XML_Char *textPtr; + size_t textLen; /* length in XML_Chars */ + size_t processed; /* # of processed bytes - when suspended */ + const XML_Char *systemId; + const XML_Char *base; + const XML_Char *publicId; + const XML_Char *notation; + bool open; + bool hasMore; /* true if entity has not been completely processed */ + /* An entity can be open while being already completely processed (!hasMore). + The reason is the delayed closing of entities until their inner + entities are processed and closed */ + bool is_param; + bool is_internal; /* true if declared in internal subset outside PE */ +# if XML_GE == 1 + /* Indirect accounting bytes charged when this entity is expanded: 1 per text + character, plus each reference's "&name;"/"%name;" token length and its own + expansion. Matches XML_ACCOUNT_ENTITY_EXPANSION, so it is not the + replacement-text size. 0 means "not computed yet" (an empty entity is 0 + too, told apart by textLen == 0). */ + XmlBigCount expandedSize; + bool beingAnalyzed; /* on the resolveEntityClosureExpandedSize depth-first + search stack; used for cycle detection */ + const XML_Char + *scanPtr; /* cursor position into the entity's replacement text; NULL when + `textPtr` is NULL, else a pointer into the entity value, + ranging from `.textPtr` to `.textPtr + .textLen`. */ +# endif /* XML_GE == 1 */ +} ENTITY; + +# if XML_GE == 1 +/* How a scanEntityText call ended. */ +enum EntityScanResult { + ENTITY_SCAN_COMPLETE, /* reached end of text; *expandedSize is final */ + ENTITY_SCAN_BLOCKED, /* stopped at a defined entity whose expanded + size has not been computed yet; *blockerOut + names the entity whose size to compute + first */ + ENTITY_SCAN_OVERFLOW /* the expanded size would exceed XmlBigCount; + callers must abort parsing */ +}; + +XML_NONTESTING_STATIC int isCDataCommentOrPIStart(const XML_Char *pos, + size_t maxLen, + size_t *openTextLen); + +XML_NONTESTING_STATIC int isPredefinedEntityName(const XML_Char *name, + size_t nameLen); + +XML_NONTESTING_STATIC enum EntityScanResult +scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr, + XmlBigCount *expandedSize, ENTITY **blockerOut); +# endif /* XML_GE == 1 */ + +#endif // ! defined(EXPAT_ENTITIES_H) diff --git a/base/poco/XML/src/internal.h b/base/poco/XML/src/internal.h index d0465449a399..58ea8e2b4dc2 100644 --- a/base/poco/XML/src/internal.h +++ b/base/poco/XML/src/internal.h @@ -29,6 +29,7 @@ Copyright (c) 2026 Matthew Wozniczka Copyright (c) 2026 Braian Plaku Copyright (c) 2026 Florian Schmaus + Copyright (c) 2026 Brooks Davis Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -90,11 +91,10 @@ # define EXPAT_FMT_SIZE_T(midpart) "%" midpart "u" # endif # else -# include // PRIdPTR, PRIuPTR # define EXPAT_FMT_LLX(midpart) "%" midpart "llx" # define EXPAT_FMT_ULL(midpart) "%" midpart "llu" -# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart PRIdPTR -# define EXPAT_FMT_SIZE_T(midpart) "%" midpart PRIuPTR +# define EXPAT_FMT_PTRDIFF_T(midpart) "%" midpart "td" +# define EXPAT_FMT_SIZE_T(midpart) "%" midpart "zu" # endif # ifndef UNUSED_P @@ -131,6 +131,8 @@ union expat_align { extern "C" { #endif +typedef unsigned long long XmlBigCount; + void _INTERNAL_trim_to_complete_utf8_characters(const char *from, const char **fromLimRef); diff --git a/base/poco/XML/src/xcs.h b/base/poco/XML/src/xcs.h index 1e63a9b1de2f..2b4268716cce 100644 --- a/base/poco/XML/src/xcs.h +++ b/base/poco/XML/src/xcs.h @@ -44,6 +44,8 @@ extern size_t xcslen(const XML_Char *s); extern int xcscmp(const XML_Char *a, const XML_Char *b); extern int xcsncmp(const XML_Char *a, const XML_Char *b, size_t len); +extern const XML_Char *xcsnstr(const XML_Char *haystack, const XML_Char *needle, + size_t maxLen); #ifdef __cplusplus } diff --git a/base/poco/XML/src/xmlparse.cpp b/base/poco/XML/src/xmlparse.cpp index 001de556c891..56c76bf33034 100644 --- a/base/poco/XML/src/xmlparse.cpp +++ b/base/poco/XML/src/xmlparse.cpp @@ -1,4 +1,4 @@ -/* e3ca845466942140c9af531ac57808c4650116df5d6dbeda3b6546d2548a586e (2.9.0+) +/* d0712c5efef760b5355ed61473a927256c6474aecb853016d2e335e571c64b0c (2.10.0+) __ __ _ ___\ \/ /_ __ __ _| |_ / _ \\ /| '_ \ / _` | __| @@ -58,6 +58,8 @@ Copyright (c) 2026 Braian Plaku Copyright (c) 2026 Filippo Tedeschi Copyright (c) 2026 Junki Lee + Copyright (c) 2026 Shani Yosef + Copyright (c) 2026 Pu Cheng Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining @@ -233,11 +235,13 @@ typedef char ICHAR; /* Do safe (NULL-aware) pointer arithmetic */ #define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0) +#define EXPAT_SAFE_PTR_ADD(p, a) ((p) ? ((p) + (a)) : NULL) #define EXPAT_MIN(a, b) (((a) < (b)) ? (a) : (b)) #include "internal.h" #include "hash_table.h" +#include "entities.h" #include "xmltok.h" #include "xmlrole.h" @@ -315,24 +319,6 @@ typedef struct tag { BINDING *bindings; } TAG; -typedef struct { - const XML_Char *name; - const XML_Char *textPtr; - int textLen; /* length in XML_Chars */ - int processed; /* # of processed bytes - when suspended */ - const XML_Char *systemId; - const XML_Char *base; - const XML_Char *publicId; - const XML_Char *notation; - bool open; - bool hasMore; /* true if entity has not been completely processed */ - /* An entity can be open while being already completely processed (!hasMore). - The reason is the delayed closing of entities until their inner - entities are processed and closed */ - bool is_param; - bool is_internal; /* true if declared in internal subset outside PE */ -} ENTITY; - typedef struct { enum XML_Content_Type type; enum XML_Content_Quant quant; @@ -371,7 +357,7 @@ typedef struct attribute_id { typedef struct { const ATTRIBUTE_ID *id; - XML_Bool isCdata; + bool isCdata; const XML_Char *value; } DEFAULT_ATTRIBUTE; @@ -461,7 +447,6 @@ enum XML_Account { }; #if XML_GE == 1 -typedef unsigned long long XmlBigCount; typedef struct accounting { XmlBigCount countBytesDirect; XmlBigCount countBytesIndirect; @@ -473,6 +458,7 @@ typedef struct accounting { typedef struct MALLOC_TRACKER { size_t bytesAllocated; size_t peakBytesAllocated; // updated live only for debug level >=2 + size_t bytesAllocatedWhenLastReset; unsigned long debugLevel; float maximumAmplificationFactor; // >=1.0 XmlBigCount activationThresholdBytes; @@ -484,6 +470,13 @@ typedef struct entity_stats { unsigned int maximumDepthSeen; unsigned long debugLevel; } ENTITY_STATS; + +/* One pending entity-analysis task on the explicit stack used by + resolveEntityClosureExpandedSize's depth-first search over the entity + reference graph. */ +typedef struct { + ENTITY *entity; /* entity currently being scanned */ +} ENTITY_ANALYSIS_TASK; #endif /* XML_GE == 1 */ typedef enum XML_Error Processor(XML_Parser parser, const char *start, @@ -543,15 +536,15 @@ static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr); static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, - XML_Bool isCdata, XML_Bool isId, - const XML_Char *value, XML_Parser parser); + bool isCdata, bool isId, const XML_Char *value, + XML_Parser parser); static enum XML_Error storeAttributeValue(XML_Parser parser, - const ENCODING *enc, XML_Bool isCdata, + const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account); static enum XML_Error -appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, +appendAttributeValue(XML_Parser parser, const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account, const char **nextPtr); static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc, @@ -566,6 +559,9 @@ static enum XML_Error callStoreEntityValue(XML_Parser parser, const ENCODING *enc, const char *start, const char *end, enum XML_Account account); +static enum XML_Error resolveEntityClosureExpandedSize(XML_Parser parser, + HASH_TABLE *table, + ENTITY *root); #else static enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity); #endif @@ -603,7 +599,7 @@ static const XML_Char *poolCopyString(STRING_POOL *pool, const XML_Char *s); static const XML_Char *poolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s); static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s, - int n); + size_t n); static const XML_Char *poolAppendString(STRING_POOL *pool, const XML_Char *s); static int nextScaffoldPart(XML_Parser parser); @@ -621,12 +617,17 @@ static XML_Parser parserCreate(const XML_Char *encodingName, const XML_Char *nameSep, DTD *dtd, XML_Parser parentParser); -static void parserInit(XML_Parser parser, const XML_Char *encodingName); +static void parserInit(XML_Parser parser, const XML_Char *encodingName, + bool isReset); #if XML_GE == 1 -static float accountingGetCurrentAmplification(XML_Parser rootParser); -static void accountingReportStats(XML_Parser originParser, const char *epilog); -static void accountingOnAbort(XML_Parser originParser); +static float accountingGetCurrentAmplification(XML_Parser rootParser, + XmlBigCount extraIndirectBytes); +static void accountingReportStats(XML_Parser originParser, const char *epilog, + XmlBigCount extraIndirectBytes, + int sourceLine); +static void accountingOnAbort(XML_Parser originParser, + XmlBigCount extraIndirectBytes, int sourceLine); static void accountingReportDiff(XML_Parser rootParser, unsigned int levelsAwayFromRootParser, const char *before, const char *after, @@ -636,6 +637,9 @@ static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok, const char *before, const char *after, int source_line, enum XML_Account account); +static XML_Bool +accountingCurrentAmplificationTolerated(XML_Parser rootParser, + XmlBigCount extraIndirectBytes); static void entityTrackingReportStats(XML_Parser parser, ENTITY *entity, const char *action, int sourceLine); @@ -643,6 +647,10 @@ static void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity, int sourceLine); static void entityTrackingOnClose(XML_Parser parser, ENTITY *entity, int sourceLine); +static void entityTrackingOnScanStart(XML_Parser parser, ENTITY *entity, + int sourceLine); +static void entityTrackingOnScanStop(XML_Parser parser, ENTITY *entity, + int sourceLine); #endif /* XML_GE == 1 */ static XML_Parser getRootParserOf(XML_Parser parser, @@ -798,8 +806,8 @@ struct XML_ParserStruct { const XML_Char *m_declNotationPublicId; ELEMENT_TYPE *m_declElementType; ATTRIBUTE_ID *m_declAttributeId; - XML_Bool m_declAttributeIsCdata; - XML_Bool m_declAttributeIsId; + bool m_declAttributeIsCdata; + bool m_declAttributeIsId; DTD *m_dtd; const XML_Char *m_curBase; TAG *m_tagStack; @@ -871,11 +879,22 @@ expat_heap_increase_tolerable(XML_Parser rootParser, size_t increase, size_t newTotal = 0; bool tolerable = true; + // The idea is to subtract the amount of memory that was already + // allocated the last time that `XML_ParserReset` was called for + // this parser, the memory use of one document could skew the + // memory statso of the next document. + const size_t bytesAllocated + = (rootParser->m_alloc_tracker.bytesAllocatedWhenLastReset + > rootParser->m_alloc_tracker.bytesAllocated) + ? 0 + : (rootParser->m_alloc_tracker.bytesAllocated + - rootParser->m_alloc_tracker.bytesAllocatedWhenLastReset); + // Detect integer overflow - if (SIZE_MAX - rootParser->m_alloc_tracker.bytesAllocated < increase) { + if (SIZE_MAX - bytesAllocated < increase) { tolerable = false; } else { - newTotal = rootParser->m_alloc_tracker.bytesAllocated + increase; + newTotal = bytesAllocated + increase; if (newTotal >= rootParser->m_alloc_tracker.activationThresholdBytes) { assert(newTotal > 0); @@ -1472,7 +1491,7 @@ parserCreate(const XML_Char *encodingName, poolInit(&parser->m_tempPool, parser); poolInit(&parser->m_temp2Pool, parser); - parserInit(parser, encodingName); + parserInit(parser, encodingName, /*isReset=*/false); if (encodingName && ! parser->m_protocolEncodingName) { if (dtd) { @@ -1499,7 +1518,7 @@ parserCreate(const XML_Char *encodingName, } static void -parserInit(XML_Parser parser, const XML_Char *encodingName) { +parserInit(XML_Parser parser, const XML_Char *encodingName, bool isReset) { parser->m_processor = prologInitProcessor; XmlPrologStateInit(&parser->m_prologState); if (encodingName != NULL) { @@ -1547,8 +1566,8 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) { parser->m_declAttributeType = NULL; parser->m_declNotationName = NULL; parser->m_declNotationPublicId = NULL; - parser->m_declAttributeIsCdata = XML_FALSE; - parser->m_declAttributeIsId = XML_FALSE; + parser->m_declAttributeIsCdata = false; + parser->m_declAttributeIsId = false; memset(&parser->m_position, 0, sizeof(POSITION)); parser->m_errorCode = XML_ERROR_NONE; parser->m_eventPtr = NULL; @@ -1567,6 +1586,7 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) { parser->m_unknownEncodingRelease = NULL; parser->m_unknownEncodingData = NULL; parser->m_parsingStatus.parsing = XML_INITIALIZED; + parser->m_parsingStatus.finalBuffer = XML_FALSE; // Reentry can only be triggered inside m_processor calls parser->m_reenter = XML_FALSE; parser->m_handlerCallDepth = 0; @@ -1580,15 +1600,24 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) { parser->m_hash_secret_salt_set = XML_FALSE; #if XML_GE == 1 - memset(&parser->m_accounting, 0, sizeof(ACCOUNTING)); - parser->m_accounting.debugLevel = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u); - parser->m_accounting.maximumAmplificationFactor - = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT; - parser->m_accounting.activationThresholdBytes - = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT; - - memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS)); - parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u); + parser->m_accounting.countBytesDirect = 0; + parser->m_accounting.countBytesIndirect = 0; + if (! isReset) { + parser->m_accounting.debugLevel + = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u); + parser->m_accounting.maximumAmplificationFactor + = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT; + parser->m_accounting.activationThresholdBytes + = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT; + } + + parser->m_entity_stats.countEverOpened = 0; + parser->m_entity_stats.currentDepth = 0; + parser->m_entity_stats.maximumDepthSeen = 0; + if (! isReset) + parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u); +#else + UNUSED_P(isReset); #endif } @@ -1651,8 +1680,16 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) { poolClear(&parser->m_temp2Pool); FREE(parser, (void *)parser->m_protocolEncodingName); parser->m_protocolEncodingName = NULL; - parserInit(parser, encodingName); + parserInit(parser, encodingName, /*isReset=*/true); dtdReset(parser->m_dtd, parser); + +#if XML_GE == 1 + parser->m_alloc_tracker.bytesAllocatedWhenLastReset + = parser->m_alloc_tracker.bytesAllocated; +#endif + + // NOTE: This effectively checks for `copyString` having failed during the + // call to `parserInit` above if (encodingName && ! parser->m_protocolEncodingName) { parser->m_errorCode = XML_ERROR_NO_MEMORY; return XML_FALSE; @@ -2322,13 +2359,12 @@ XML_SetHashSalt16Bytes(XML_Parser parser, const uint8_t entropy[16]) { enum XML_Status XMLCALL XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { - if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) { - if (parser != NULL) - parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; + if (parser == NULL || isCalledFromInsideHandler(parser)) return XML_STATUS_ERROR; - } - if (isCalledFromInsideHandler(parser)) + if ((len < 0) || ((s == NULL) && (len != 0))) { + parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; return XML_STATUS_ERROR; + } switch (parser->m_parsingStatus.parsing) { case XML_SUSPENDED: parser->m_errorCode = XML_ERROR_SUSPENDED; @@ -2348,8 +2384,15 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { #if XML_CONTEXT_BYTES == 0 if (parser->m_bufferPtr == parser->m_bufferEnd) { - const char *end; - int nLeftOver; + // This null-object trick allows us to stop worrying about case `s == NULL` + // within this branch, e.g. with `s + len - end`. + const char *const empty = ""; + if (s == NULL) { + assert(len == 0); + s = empty; + } + const char *end = s + len; + size_t nLeftOver; enum XML_Status result; /* Detect overflow (a+b > MAX <==> b > MAX-a) */ if ((uint64_t)len > UINT64_MAX - parser->m_parseEndByteIndex) { @@ -2366,7 +2409,7 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; parser->m_errorCode - = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end); + = callProcessor(parser, s, parser->m_parseEndPtr = end, &end); if (parser->m_errorCode != XML_ERROR_NONE) { parser->m_eventEndPtr = parser->m_eventPtr; @@ -2396,8 +2439,14 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED // (and XML_ERROR_FINISHED) from XML_GetBuffer. const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing; + if (nLeftOver > INT_MAX) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } parser->m_parsingStatus.parsing = XML_PARSING; - void *const temp = XML_GetBuffer(parser, nLeftOver); + void *const temp = XML_GetBuffer(parser, (int)nLeftOver); parser->m_parsingStatus.parsing = originalStatus; // GetBuffer may have overwritten this, but we want to remember what the // app requested, not how many bytes were left over after parsing. @@ -2415,7 +2464,7 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) { memcpy(parser->m_buffer, end, nLeftOver); } parser->m_bufferPtr = parser->m_buffer; - parser->m_bufferEnd = parser->m_buffer + nLeftOver; + parser->m_bufferEnd = EXPAT_SAFE_PTR_ADD(parser->m_buffer, nLeftOver); parser->m_positionPtr = parser->m_bufferPtr; parser->m_parseEndPtr = parser->m_bufferEnd; parser->m_eventPtr = parser->m_bufferPtr; @@ -3497,7 +3546,7 @@ externalEntityInitProcessor2(XML_Parser parser, const char *start, #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, start, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif /* XML_GE == 1 */ @@ -3527,6 +3576,11 @@ externalEntityInitProcessor2(XML_Parser parser, const char *start, } parser->m_eventPtr = start; return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_NONE: + if (! parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + } + return XML_ERROR_NONE; } parser->m_processor = externalEntityInitProcessor3; return externalEntityInitProcessor3(parser, start, end, endPtr); @@ -3626,7 +3680,7 @@ doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, : next; if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -4058,10 +4112,12 @@ doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, const enum XML_Convert_Result convert_res = XmlConvert( enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd); *eventEndPP = s; - beforeHandler(parser); - charDataHandler(parser->m_handlerArg, parser->m_dataBuf, - (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); - afterHandler(parser); + if (parser->m_characterDataHandler) { + beforeHandler(parser); + charDataHandler(parser->m_handlerArg, parser->m_dataBuf, + (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + afterHandler(parser); + } if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) break; @@ -4158,9 +4214,9 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, TAG_NAME *tagNamePtr, BINDING **bindingsPtr, enum XML_Account account) { DTD *const dtd = parser->m_dtd; /* save one level of indirection */ - int attIndex = 0; + size_t attIndex = 0; XML_Char *uri; - int nPrefixes = 0; + size_t nPrefixes = 0; BINDING *binding; const XML_Char *localPart; @@ -4187,8 +4243,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, return XML_ERROR_NO_MEMORY; /* get the attributes from the tokenizer */ - size_t n = (size_t)XmlGetAttributes(enc, attStr, (int)parser->m_attsSize, - parser->m_atts); + size_t n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts); /* Detect and prevent integer overflow */ if (n > SIZE_MAX - nDefaultAtts) { @@ -4223,11 +4278,22 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, /* Detect and prevent integer overflow. */ if (n > (size_t)INT_MAX) return XML_ERROR_NO_MEMORY; - XmlGetAttributes(enc, attStr, (int)n, parser->m_atts); + XmlGetAttributes(enc, attStr, n, parser->m_atts); } } /* the attribute list for the application */ + // NOTE: `parser->m_atts` is used to read `ATTRIBUTE` elements + // from start to end while at the same time writing `XML_Char *` + // elements from start to end *to the same block of memory*. + // That black magic only works because the first member `.name` in + // `ATTRIBUTE` is no longer being read after `appAtts[attIndex]` + // has been written, which for the first element is the very same + // address in memory. + // And because `attIndex` is increased twice for default attributes + // further down, struct `ATTRIBUTE` must be at least twice the size + // of a pointer, or the allocation size math for `m_attsSize` starts + // to underallocate. const XML_Char **const appAtts = (const XML_Char **)parser->m_atts; for (size_t i = 0; i < n; i++) { ATTRIBUTE *currAtt = &parser->m_atts[i]; @@ -4247,9 +4313,11 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, return XML_ERROR_DUPLICATE_ATTRIBUTE; } (attId->name)[-1] = 1; + // NOTE: The next call overwrites `parser->m_atts`, so we cannot use + // e.g. `parser->m_atts[i].name;` after this line! appAtts[attIndex++] = attId->name; if (! parser->m_atts[i].normalized) { - XML_Bool isCdata = XML_TRUE; + bool isCdata = true; /* figure out whether declared as other than CDATA */ if (attId->maybeTokenized) { @@ -4301,11 +4369,16 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, } /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */ - parser->m_nSpecifiedAtts = attIndex; + // Detect and reject integer overflow + if (attIndex > INT_MAX) + return XML_ERROR_NO_MEMORY; + parser->m_nSpecifiedAtts = (int)attIndex; if (elementType->idAtt && (elementType->idAtt->name)[-1]) { - for (int i = 0; i < attIndex; i += 2) + for (size_t i = 0; i < attIndex; i += 2) if (appAtts[i] == elementType->idAtt->name) { - parser->m_idAttIndex = i; + if (i > INT_MAX) + return XML_ERROR_NO_MEMORY; + parser->m_idAttIndex = (int)i; break; } } else @@ -4338,7 +4411,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr, /* expand prefixed attribute names, check for duplicates, and clear flags that say whether attributes were specified */ - int i = 0; + size_t i = 0; if (nPrefixes) { unsigned int j; /* hash table index */ unsigned long version = parser->m_nsAttsVersion; @@ -4894,7 +4967,7 @@ doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr, int tok = XmlCdataSectionTok(enc, s, end, &next); #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #else @@ -5066,7 +5139,7 @@ doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr, # if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } # endif @@ -5158,7 +5231,7 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s, #if XML_GE == 1 if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -5379,7 +5452,7 @@ entityValueInitProcessor(XML_Parser parser, const char *s, const char *end, # if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } # endif @@ -5432,7 +5505,7 @@ externalParEntProcessor(XML_Parser parser, const char *s, const char *end, else if (tok == XML_TOK_BOM) { if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } @@ -5611,7 +5684,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, break; default: if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } } @@ -5708,7 +5781,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, return XML_ERROR_INVALID_TOKEN; } - if (parser->m_doctypeName) { + if (parser->m_doctypeName && parser->m_startDoctypeDeclHandler) { beforeHandler(parser); parser->m_startDoctypeDeclHandler( parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, @@ -5774,7 +5847,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, handleDefault = XML_FALSE; } break; - case XML_ROLE_INSTANCE_START: + case XML_ROLE_INSTANCE_START: { #ifdef XML_DTD /* if there is no DOCTYPE declaration then now is the last chance to read the foreign DTD @@ -5818,6 +5891,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, #endif /* XML_DTD */ parser->m_processor = contentProcessor; return contentProcessor(parser, s, end, nextPtr); + } case XML_ROLE_ATTLIST_ELEMENT_NAME: parser->m_declElementType = getElementType(parser, enc, s, next); if (! parser->m_declElementType) @@ -5827,16 +5901,16 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, parser->m_declAttributeId = getAttributeId(parser, enc, s, next); if (! parser->m_declAttributeId) return XML_ERROR_NO_MEMORY; - parser->m_declAttributeIsCdata = XML_FALSE; + parser->m_declAttributeIsCdata = false; parser->m_declAttributeType = NULL; - parser->m_declAttributeIsId = XML_FALSE; + parser->m_declAttributeIsId = false; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_CDATA: - parser->m_declAttributeIsCdata = XML_TRUE; + parser->m_declAttributeIsCdata = true; parser->m_declAttributeType = atypeCDATA; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ID: - parser->m_declAttributeIsId = XML_TRUE; + parser->m_declAttributeIsId = true; parser->m_declAttributeType = atypeID; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_IDREF: @@ -5924,7 +5998,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, /* ID attributes aren't allowed to have a default */ if (! defineAttribute( parser->m_declElementType, parser->m_declAttributeId, - parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser)) + parser->m_declAttributeIsCdata, false, attVal, parser)) return XML_ERROR_NO_MEMORY; if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) @@ -5954,17 +6028,23 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, #if XML_GE == 1 // This will store the given replacement text in // parser->m_declEntity->textPtr. - enum XML_Error result = callStoreEntityValue( + const enum XML_Error result = callStoreEntityValue( parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar, XML_ACCOUNT_NONE); + if (result != XML_ERROR_NONE) { + poolDiscard(&dtd->entityValuePool); + return result; + } if (parser->m_declEntity) { /* Detect and prevent signed integer overflow */ if ((size_t)poolLength(&dtd->entityValuePool) > (size_t)INT_MAX) { + poolDiscard(&dtd->entityValuePool); return XML_ERROR_NO_MEMORY; } - parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool); - parser->m_declEntity->textLen - = (int)(poolLength(&dtd->entityValuePool)); + const XML_Char *const valueStart = poolStart(&dtd->entityValuePool); + parser->m_declEntity->textPtr = valueStart; + parser->m_declEntity->textLen = poolLength(&dtd->entityValuePool); + parser->m_declEntity->scanPtr = valueStart; poolFinish(&dtd->entityValuePool); if (parser->m_entityDeclHandler) { *eventEndPP = s; @@ -5972,14 +6052,12 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, parser->m_declEntity->textPtr, - parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); + (int)parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); afterHandler(parser); handleDefault = XML_FALSE; } } else poolDiscard(&dtd->entityValuePool); - if (result != XML_ERROR_NONE) - return result; #else // This will store "&entity123;" in parser->m_declEntity->textPtr // to end up as "&entity123;" in the handler. @@ -5995,7 +6073,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, parser->m_declEntity->textPtr, - parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); + (int)parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); afterHandler(parser); handleDefault = XML_FALSE; } @@ -6114,6 +6192,17 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, } break; case XML_ROLE_GENERAL_ENTITY_NAME: { + // NOTE: XML 1.0 fourth edition demands in section + // "4.6 Predefined Entities" that bad redefinitions of predefined + // general entities must be detected and rejected. Expat has been + // ignoring both conforming and non-conforming redefinitions and + // thus has been failing to reject bad redefinitions, for years. + // As a result, users learned that they can get away with + // `` in practice. We cannot start conforming to + // that part of the spec now, or we risk rejecting many documents + // that parsed fine for years and that may not be fixable now or + // in time. So Expat continues to discard redefinitions of + // predefined entities altogether. if (XmlPredefinedEntityName(enc, s, next)) { parser->m_declEntity = NULL; break; @@ -6640,7 +6729,7 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end, #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, XML_ACCOUNT_DIRECT)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -6707,6 +6796,415 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end, } } +#if XML_GE == 1 +// Checks `name` for being a predefined entity (i.e. one of "amp", "apos", "gt", +// "lt", "quot"). Similar in implementation to function +// `PREFIX(predefinedEntityName)` but operating on an `XML_Char` string with an +// explicit length, instead. Returns +// ASCII_AMP/ASCII_APOS/ASCII_GT/ASCII_LT/ASCII_QUOT for a match or 0 for no +// match. +XML_NONTESTING_STATIC int +isPredefinedEntityName(const XML_Char *name, size_t nameLen) { + switch (nameLen) { + case 2: + // Wanted: "lt" or "gt" + if (name[1] != XML_T(ASCII_t)) + break; + switch (name[0]) { + case XML_T(ASCII_l): + return ASCII_LT; + case XML_T(ASCII_g): + return ASCII_GT; + } + break; + case 3: + // Wanted: "amp" + if (name[0] == XML_T(ASCII_a) && name[1] == XML_T(ASCII_m) + && name[2] == XML_T(ASCII_p)) + return ASCII_AMP; + break; + case 4: + // Wanted: "apos" or "quot" + switch (name[0]) { + case XML_T(ASCII_a): + if (name[1] == XML_T(ASCII_p) && name[2] == XML_T(ASCII_o) + && name[3] == XML_T(ASCII_s)) + return ASCII_APOS; + break; + case XML_T(ASCII_q): + if (name[1] == XML_T(ASCII_u) && name[2] == XML_T(ASCII_o) + && name[3] == XML_T(ASCII_t)) + return ASCII_QUOT; + break; + } + } + return 0; +} + +static const XML_Char cdataOpen[] + = {ASCII_LT, ASCII_EXCL, ASCII_LSQB, ASCII_C, ASCII_D, + ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB, '\0'}; // i.e. "" +static const XML_Char commentOpen[] + = {ASCII_LT, ASCII_EXCL, ASCII_MINUS, ASCII_MINUS, '\0'}; // i.e. "" +static const XML_Char piClose[] = {ASCII_QUEST, ASCII_GT, '\0'}; // i.e. "?>" + +static const size_t cdataOpenLen = sizeof(cdataOpen) / sizeof(cdataOpen[0]) - 1; +static const size_t cdataCloseLen + = sizeof(cdataClose) / sizeof(cdataClose[0]) - 1; +static const size_t commentOpenLen + = sizeof(commentOpen) / sizeof(commentOpen[0]) - 1; +static const size_t commentCloseLen + = sizeof(commentClose) / sizeof(commentClose[0]) - 1; +static const size_t piCloseLen = sizeof(piClose) / sizeof(piClose[0]) - 1; + +// Checks the string starting at `pos` for starting a CDATA section, a comment +// or processing instructions. Returns +// XML_TOK_CDATA_SECT_OPEN/XML_TOK_COMMENT/XML_TOK_PI for a match or +// XML_TOK_INVALID (=0) for no match. Only in the success case, the length +// of the token is written to `*openTextLen`. +XML_NONTESTING_STATIC int +isCDataCommentOrPIStart(const XML_Char *pos, size_t maxLen, + size_t *openTextLen) { + assert(pos != NULL); + assert(openTextLen != NULL); + + if (maxLen < 2) + return XML_TOK_INVALID; + + if (pos[0] != XML_T(ASCII_LT)) + return XML_TOK_INVALID; + + if (pos[1] == XML_T(ASCII_QUEST)) { + *openTextLen = 2; + return XML_TOK_PI; + } + + if (pos[1] != XML_T(ASCII_EXCL)) + return XML_TOK_INVALID; + + if (maxLen >= cdataOpenLen && xcsncmp(pos, cdataOpen, cdataOpenLen) == 0) { + *openTextLen = cdataOpenLen; + return XML_TOK_CDATA_SECT_OPEN; + } + + if (maxLen >= commentOpenLen + && xcsncmp(pos, commentOpen, commentOpenLen) == 0) { + *openTextLen = commentOpenLen; + return XML_TOK_COMMENT; + } + + return XML_TOK_INVALID; +} + +/* Scan `entity`'s body, starting at `*posPtr`, accumulating the expanded + size into `*expandedSize`. + + Return value: how the scan ended, see enum EntityScanResult. + + *blockerOut (out, set only for ENTITY_SCAN_BLOCKED): + The non-empty entity the scan stopped at because its expanded size + has not been computed yet. The caller computes that size first and + calls again with *posPtr unchanged to resume. + The pointer is borrowed from the entity hash table (via lookup), not + a new allocation, so it must not be freed. + + *posPtr (in/out, scan cursor): + Advanced to end-of-text on a complete scan, or parked at the + offending reference otherwise, so a follow-up call resumes from + the same position. Not meaningful after ENTITY_SCAN_OVERFLOW. + + *expandedSize (in/out, expanded-byte accumulator): + The expanded size of this one `entity` (its text plus the expandedSize + of entities it references), not a total across all entities. Not + meaningful after ENTITY_SCAN_OVERFLOW; the overflowing value is never + stored anywhere. */ +XML_NONTESTING_STATIC enum EntityScanResult +scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr, + XmlBigCount *expandedSize, ENTITY **blockerOut) { + if (blockerOut != NULL) + *blockerOut = NULL; + const XML_Char refChar = entity->is_param ? XML_T('%') : XML_T('&'); + HASH_TABLE *const refTable +# ifdef XML_DTD + = entity->is_param ? &parser->m_dtd->paramEntities + : &parser->m_dtd->generalEntities; +# else + = &parser->m_dtd->generalEntities; +# endif + + const XML_Char *pos = *posPtr; + const XML_Char *const end = entity->textPtr + entity->textLen; + + while (pos < end) { + // Detect and skip CDATA/comment/PI sections + // because entities have no effect in these places + if (*pos == XML_T('<')) { + // Detect CDATA/comment/PI section start + size_t openTextLen = 0; + const int tok = isCDataCommentOrPIStart(pos, end - pos, &openTextLen); + if (tok != XML_TOK_INVALID) { + assert(openTextLen != 0); + + // Detect and avoid integer overflow + if (openTextLen > (XmlBigCount)(-1) - *expandedSize) + return ENTITY_SCAN_OVERFLOW; + + *expandedSize += openTextLen; + pos += openTextLen; + + // Detect CDATA/comment/PI section end + const XML_Char *closeText = NULL; + size_t closeLen = 0; + + switch (tok) { + case XML_TOK_CDATA_SECT_OPEN: + closeText = cdataClose; + closeLen = cdataCloseLen; + break; + case XML_TOK_COMMENT: + closeText = commentClose; + closeLen = commentCloseLen; + break; + case XML_TOK_PI: + closeText = piClose; + closeLen = piCloseLen; + break; + default: + assert(0 && "never gets here"); + break; + } + + const size_t remainderLen = end - pos; + const XML_Char *const closeStart + = xcsnstr(pos, closeText, remainderLen); + if (closeStart == NULL) { + // The CDATA/comment/PI section is NOT terminated + if (remainderLen > (XmlBigCount)(-1) - *expandedSize) + return ENTITY_SCAN_OVERFLOW; + *expandedSize += remainderLen; + *posPtr = end; + return ENTITY_SCAN_COMPLETE; + } + + // The CDATA/comment/PI section is NOT terminated + const size_t skippedLen = closeStart + closeLen - pos; + + // Detect and avoid integer overflow + if (skippedLen > (XmlBigCount)(-1) - *expandedSize) + return ENTITY_SCAN_OVERFLOW; + + *expandedSize += skippedLen; + pos += skippedLen; + + continue; + } + } + + // Detect an entity reference + if (*pos != refChar) { + // Detect and avoid integer overflow + if (*expandedSize == (XmlBigCount)(-1)) + return ENTITY_SCAN_OVERFLOW; + (*expandedSize)++; + pos++; + continue; + } + + const XML_Char *nameStart = pos + 1; + const XML_Char *nameEnd = nameStart; + while (nameEnd < end && *nameEnd != XML_T(';')) + nameEnd++; + + if (nameEnd >= end) { + /* Unterminated reference at end of text: treat the trailing + bytes as literal characters. */ + XmlBigCount addend = (XmlBigCount)(end - pos); + // Detect and avoid integer overflow + if (*expandedSize > (XmlBigCount)(-1) - addend) + return ENTITY_SCAN_OVERFLOW; + *expandedSize += addend; + *posPtr = end; + return ENTITY_SCAN_COMPLETE; + } + + const size_t nameLen = (size_t)(nameEnd - nameStart); + + /* At runtime the whole "&name;"/"%name;" token is re-scanned and charged to + the indirect accounting, then its expansion is charged separately; so + every reference below counts this token length plus its expansion. */ + const XmlBigCount refTokenLen + = (XmlBigCount)(/*sigil*/ 1 + nameLen + /*semicolon*/ 1); + + ENTITY *refEntity + = (ENTITY *)lookupWithLength(parser, refTable, nameStart, nameLen, 0); + + XmlBigCount addend = 0; + if (! refEntity) { + /* Predefined entities (amp/lt/gt/quot/apos) are general-only, hence the + `! entity->is_param` guard, and expand to a single character. */ + if (! entity->is_param && isPredefinedEntityName(nameStart, nameLen)) { + addend = refTokenLen + 1; + } else { + /* Undefined entity: expands to nothing, so only the token. */ + addend = refTokenLen; + } + } else if (refEntity->beingAnalyzed) { + /* Cycle: refEntity is already on the depth-first search stack, so its + expandedSize is not final yet; charge just the token. Do not fail the + parse here: per XML 1.0r4, + "A parsed entity MUST NOT contain a recursive reference to + itself, either directly or indirectly", but also "Only parsed + entities that are referenced directly or indirectly within the + document are required to be well-formed" - so a declared-but- + never-expanded cycle must be accepted; if the cycle is actually + expanded, the runtime recursive-ref check reports + XML_ERROR_RECURSIVE_ENTITY_REF. */ + addend = refTokenLen; + } else if (refEntity->textLen > 0 && refEntity->expandedSize == 0) { + /* Non-empty entity whose expanded size has not been computed yet; + report refEntity as a blocker so the caller can compute its size + first. */ + *posPtr = pos; + if (blockerOut != NULL) + *blockerOut = refEntity; + return ENTITY_SCAN_BLOCKED; + } else if (refEntity->expandedSize > 0) { + /* refEntity is fully resolved: expandedSize holds its final expanded + size (a non-zero value is never a partial here - the only entity that + briefly holds a partial is one currently on the resolve stack, which + is caught by the beingAnalyzed branch above). Add the token plus that + expansion. */ + if (refEntity->expandedSize > (XmlBigCount)(-1) - refTokenLen) + return ENTITY_SCAN_OVERFLOW; + addend = refTokenLen + refEntity->expandedSize; + } else { + /* Empty entity (textLen == 0): expands to nothing, so only the token. */ + addend = refTokenLen; + } + + // Detect and avoid integer overflow + if (*expandedSize > (XmlBigCount)(-1) - addend) + return ENTITY_SCAN_OVERFLOW; + *expandedSize += addend; + pos = nameEnd + 1; + } + + /* Loop only exits here with pos == end (a complete scan). */ + assert(pos == end); + *posPtr = end; + return ENTITY_SCAN_COMPLETE; +} + +/* Resolve expandedSize using an iterative depth-first search over the + reference graph. Each entity is scanned at most twice (once on push, + once after its blocker resolves), so the total work is O(N + T) where + N is the number of entities and T is the sum of all entities' textLen. + `entity->beingAnalyzed` marks the entities currently on the stack for + cycle detection; it is cleared again on pop. + Returns XML_ERROR_NO_MEMORY if the stack cannot be allocated, and + XML_ERROR_AMPLIFICATION_LIMIT_BREACH if an entity's expanded size + overflows XmlBigCount. */ +static enum XML_Error +resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table, + ENTITY *root) { + if (root == NULL || root->expandedSize != 0 || root->textPtr == NULL + || root->textLen == 0) + return XML_ERROR_NONE; + + if (table->used == 0) + return XML_ERROR_NONE; + + // Detect and avoid integer overflow + if (table->used > SIZE_MAX / sizeof(ENTITY_ANALYSIS_TASK)) + return XML_ERROR_NO_MEMORY; + + ENTITY_ANALYSIS_TASK *stack + = MALLOC(parser, sizeof(ENTITY_ANALYSIS_TASK) * table->used); + if (stack == NULL) + return XML_ERROR_NO_MEMORY; + + const XML_Parser rootParser = getRootParserOf(parser, NULL); + assert(! rootParser->m_parentParser); + + size_t top = 0; + stack[top].entity = root; + root->beingAnalyzed = XML_TRUE; + top++; + rootParser->m_entity_stats.currentDepth++; + if (rootParser->m_entity_stats.currentDepth + > rootParser->m_entity_stats.maximumDepthSeen) { + rootParser->m_entity_stats.maximumDepthSeen++; + } + + while (top > 0) { + ENTITY_ANALYSIS_TASK *task = &stack[top - 1]; + ENTITY *e = task->entity; + XmlBigCount sizeSoFar = e->expandedSize; + ENTITY *blocker = NULL; + + entityTrackingOnScanStart(parser, e, __LINE__); + + const enum EntityScanResult scanResult + = scanEntityText(parser, e, &e->scanPtr, &sizeSoFar, &blocker); + switch (scanResult) { + case ENTITY_SCAN_COMPLETE: + case ENTITY_SCAN_BLOCKED: + /* Save the size accumulated so far; together with task->pos it is + the state that lets the scan resume once the blocker's size has + been computed. This is the one place where expandedSize briefly + holds neither 0 nor the final size - only while the entity is + on the stack, where the beingAnalyzed check in scanEntityText + keeps every other reader away from the intermediate value. */ + e->expandedSize = sizeSoFar; + break; + default: + break; + } + + entityTrackingOnScanStop(parser, e, __LINE__); + + switch (scanResult) { + case ENTITY_SCAN_OVERFLOW: + /* Abort parsing right away; the beingAnalyzed marks still set on + the stacked entities do not matter once the parse is dead. */ + FREE(parser, stack); + /* expandedSize overflowed; pass SIZE_MAX (unrepresentable size). */ + accountingOnAbort(parser, SIZE_MAX, __LINE__); + return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; + + case ENTITY_SCAN_COMPLETE: + e->beingAnalyzed = XML_FALSE; + top--; + rootParser->m_entity_stats.currentDepth--; + break; + + case ENTITY_SCAN_BLOCKED: + /* Push the blocker. A blocker's expanded size is always still + uncomputed and it is never already on the stack, so each entity + is pushed at most once and top <= table->used. */ + assert(! blocker->beingAnalyzed); + assert(top < table->used); + stack[top].entity = blocker; + blocker->beingAnalyzed = XML_TRUE; + top++; + rootParser->m_entity_stats.currentDepth++; + if (rootParser->m_entity_stats.currentDepth + > rootParser->m_entity_stats.maximumDepthSeen) { + rootParser->m_entity_stats.maximumDepthSeen++; + } + break; + } + } + + FREE(parser, stack); + return XML_ERROR_NONE; +} +#endif /* XML_GE == 1 */ + static enum XML_Error processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl, enum EntityType type) { @@ -6735,6 +7233,37 @@ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl, /* LCOV_EXCL_STOP */ } +#if XML_GE == 1 + // Compute entity size assuming immediate access + if (entity->textLen > 0 && entity->expandedSize == 0) { + HASH_TABLE *const table +# ifdef XML_DTD + = entity->is_param ? &parser->m_dtd->paramEntities + : &parser->m_dtd->generalEntities; +# else + = &parser->m_dtd->generalEntities; +# endif + const enum XML_Error result + = resolveEntityClosureExpandedSize(parser, table, entity); + if (result != XML_ERROR_NONE) + return result; + } + + /* Reject an amplification attack before acquiring openEntity, so a rejected + entity leaks nothing and leaves entity state untouched. */ + if (entity->expandedSize > 0) { + const XML_Parser rootParser = getRootParserOf(parser, NULL); + /* Overflow of expandedSize aborts parsing during resolution + (on first expansion), so the stored value here is always exact. */ + const XmlBigCount expandedBytes = entity->expandedSize; + if (accountingCurrentAmplificationTolerated(rootParser, expandedBytes) + != XML_TRUE) { + accountingOnAbort(rootParser, expandedBytes, __LINE__); + return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; + } + } +#endif /* XML_GE == 1 */ + if (*freeEntityList) { openEntity = *freeEntityList; *freeEntityList = openEntity->next; @@ -6747,7 +7276,7 @@ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl, entity->hasMore = true; #if XML_GE == 1 entityTrackingOnOpen(parser, entity, __LINE__); -#endif +#endif /* XML_GE == 1 */ entity->processed = 0; openEntity->next = *openEntityList; *openEntityList = openEntity; @@ -6809,7 +7338,7 @@ internalEntityProcessor(XML_Parser parser, const char *s, const char *end, && (parser->m_parsingStatus.parsing == XML_SUSPENDED || (parser->m_parsingStatus.parsing == XML_PARSING && parser->m_reenter))) { - entity->processed = (int)(next - (const char *)entity->textPtr); + entity->processed = next - (const char *)entity->textPtr; return result; } @@ -6858,7 +7387,7 @@ errorProcessor(XML_Parser parser, const char *s, const char *end, } static enum XML_Error -storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, +storeAttributeValue(XML_Parser parser, const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account) { const char *next = ptr; @@ -6890,8 +7419,7 @@ storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, // processed. A XML_SUSPENDED check here is not required as // appendAttributeValue will never suspend the parser. if (nextInEntity < textEnd) { - entity->processed - = (int)(nextInEntity - (const char *)entity->textPtr); + entity->processed = nextInEntity - (const char *)entity->textPtr; continue; } assert(nextInEntity == textEnd); @@ -6936,7 +7464,7 @@ storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, } static enum XML_Error -appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, +appendAttributeValue(XML_Parser parser, const ENCODING *enc, bool isCdata, const char *ptr, const char *end, STRING_POOL *pool, enum XML_Account account, const char **nextPtr) { DTD *const dtd = parser->m_dtd; /* save one level of indirection */ @@ -6950,7 +7478,7 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, int tok = XmlAttributeValueTok(enc, ptr, end, &next); #if XML_GE == 1 if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); return XML_ERROR_AMPLIFICATION_LIMIT_BREACH; } #endif @@ -7166,7 +7694,7 @@ storeEntityValue(XML_Parser parser, const ENCODING *enc, if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__, account)) { - accountingOnAbort(parser); + accountingOnAbort(parser, 0, __LINE__); result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH; goto endEntityValue; } @@ -7351,8 +7879,7 @@ callStoreEntityValue(XML_Parser parser, const ENCODING *enc, // processed. A XML_SUSPENDED check here is not required as // appendAttributeValue will never suspend the parser. if (textEnd != nextInEntity) { - entity->processed - = (int)(nextInEntity - (const char *)entity->textPtr); + entity->processed = nextInEntity - (const char *)entity->textPtr; continue; } @@ -7412,8 +7939,9 @@ storeSelfEntityValue(XML_Parser parser, ENTITY *entity) { poolDiscard(pool); return XML_ERROR_NO_MEMORY; } - entity->textPtr = poolStart(pool); - entity->textLen = (int)(poolLength(pool)); + const XML_Char *const valueStart = poolStart(pool); + entity->textPtr = valueStart; + entity->textLen = poolLength(pool); poolFinish(pool); return XML_ERROR_NONE; @@ -7546,8 +8074,8 @@ reportDefault(XML_Parser parser, const ENCODING *enc, const char *s, } static int -defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, - XML_Bool isId, const XML_Char *value, XML_Parser parser) { +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, bool isCdata, + bool isId, const XML_Char *value, XML_Parser parser) { DEFAULT_ATTRIBUTE *att; if (value || isId) { /* The handling of default attributes gets messed up if we have @@ -7708,7 +8236,7 @@ static const XML_Char * getContext(XML_Parser parser) { DTD *const dtd = parser->m_dtd; /* save one level of indirection */ HASH_TABLE_ITER iter; - XML_Bool needSep = XML_FALSE; + bool needSep = false; if (dtd->defaultPrefix.binding) { if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) @@ -7739,7 +8267,7 @@ getContext(XML_Parser parser) { */ return NULL; /* LCOV_EXCL_LINE */ } - needSep = XML_TRUE; + needSep = true; } hashTableIterInit(&iter, &(dtd->prefixes)); @@ -7768,7 +8296,7 @@ getContext(XML_Parser parser) { len--; if (! poolAppendChars(&parser->m_tempPool, prefix->binding->uri, len)) return NULL; - needSep = XML_TRUE; + needSep = true; } hashTableIterInit(&iter, &(dtd->generalEntities)); @@ -7782,7 +8310,7 @@ getContext(XML_Parser parser) { return NULL; if (! poolAppendChars(&parser->m_tempPool, e->name, xcslen(e->name))) return NULL; - needSep = XML_TRUE; + needSep = true; } if (! poolAppendChar(&parser->m_tempPool, XML_T('\0'))) @@ -8190,6 +8718,9 @@ copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable, return 0; newE->textPtr = tem; newE->textLen = oldE->textLen; +#if XML_GE == 1 + newE->scanPtr = tem; +#endif /* XML_GE == 1 */ } if (oldE->notation) { const XML_Char *tem = poolCopyString(newPool, oldE->notation); @@ -8512,7 +9043,7 @@ poolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s) { } static const XML_Char * -poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) { +poolCopyStringN(STRING_POOL *pool, const XML_Char *s, size_t n) { if (! pool->ptr && ! poolGrow(pool)) { /* The following line is unreachable given the current usage of * poolCopyStringN(). Currently it is called from exactly one @@ -8957,25 +9488,27 @@ copyString(const XML_Char *s, XML_Parser parser) { #if XML_GE == 1 static float -accountingGetCurrentAmplification(XML_Parser rootParser) { +accountingGetCurrentAmplification(XML_Parser rootParser, + XmlBigCount extraIndirectBytes) { // 1.........1.........12 => 22 const size_t lenOfShortestInclude = sizeof("") - 1; - const XmlBigCount countBytesOutput - = rootParser->m_accounting.countBytesDirect - + rootParser->m_accounting.countBytesIndirect; + /* Add as floats: u64 counts (max ~1.8e19) are far below FLT_MAX, so the sum + is always finite and cannot wrap the way an unsigned integer add could. */ + const float indirect = (float)rootParser->m_accounting.countBytesIndirect + + (float)extraIndirectBytes; const float amplificationFactor = rootParser->m_accounting.countBytesDirect - ? ((float)countBytesOutput + ? (((float)rootParser->m_accounting.countBytesDirect + indirect) / (float)(rootParser->m_accounting.countBytesDirect)) - : ((float)(lenOfShortestInclude - + rootParser->m_accounting.countBytesIndirect) + : (((float)lenOfShortestInclude + indirect) / (float)lenOfShortestInclude); assert(! rootParser->m_parentParser); return amplificationFactor; } static void -accountingReportStats(XML_Parser originParser, const char *epilog) { +accountingReportStats(XML_Parser originParser, const char *epilog, + XmlBigCount extraIndirectBytes, int sourceLine) { const XML_Parser rootParser = getRootParserOf(originParser, NULL); assert(! rootParser->m_parentParser); @@ -8983,19 +9516,33 @@ accountingReportStats(XML_Parser originParser, const char *epilog) { return; } + /* On an early abort the amplifying bytes have not been charged to the + indirect counter yet; fold extraIndirectBytes in (with overflow detection) + so the reported byte count and amplification reflect what was detected. */ + const XmlBigCount indirect = rootParser->m_accounting.countBytesIndirect; + const XmlBigCount indirectWithExtra + = (extraIndirectBytes > (XmlBigCount)(-1) - indirect) + ? (XmlBigCount)(-1) + : indirect + extraIndirectBytes; const float amplificationFactor - = accountingGetCurrentAmplification(rootParser); + = accountingGetCurrentAmplification(rootParser, extraIndirectBytes); fprintf(stderr, "expat: Accounting(%p): Direct " EXPAT_FMT_ULL( "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s", (void *)rootParser, rootParser->m_accounting.countBytesDirect, - rootParser->m_accounting.countBytesIndirect, - (double)amplificationFactor, epilog); + indirectWithExtra, (double)amplificationFactor, epilog); + /* An abort has no accountingReportDiff before it, so append the originating + source line here to show which rejection site these stats belong to. */ + if (sourceLine > 0) { + fprintf(stderr, " (xmlparse.c:%d)\n", sourceLine); + } } static void -accountingOnAbort(XML_Parser originParser) { - accountingReportStats(originParser, " ABORTING\n"); +accountingOnAbort(XML_Parser originParser, XmlBigCount extraIndirectBytes, + int sourceLine) { + accountingReportStats(originParser, " ABORTING", extraIndirectBytes, + sourceLine); } static void @@ -9035,6 +9582,32 @@ accountingReportDiff(XML_Parser rootParser, fprintf(stderr, "\"\n"); } +static XML_Bool +accountingCurrentAmplificationTolerated(XML_Parser rootParser, + XmlBigCount extraIndirectBytes) { + assert(! rootParser->m_parentParser); + + const XmlBigCount countBytesOutput + = rootParser->m_accounting.countBytesDirect + + rootParser->m_accounting.countBytesIndirect; + /* Overflow check: extraIndirectBytes can be SIZE_MAX, which would otherwise + wrap the unsigned total around to a small value and wrongly report the + output as tolerated. */ + const XmlBigCount countBytesOutputWithExtra + = (extraIndirectBytes > (XmlBigCount)(-1) - countBytesOutput) + ? (XmlBigCount)(-1) + : countBytesOutput + extraIndirectBytes; + const float amplificationFactor + = accountingGetCurrentAmplification(rootParser, extraIndirectBytes); + const XML_Bool tolerated + = (countBytesOutputWithExtra + < rootParser->m_accounting.activationThresholdBytes) + || (amplificationFactor + <= rootParser->m_accounting.maximumAmplificationFactor); + + return tolerated; +} + static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok, const char *before, const char *after, int source_line, @@ -9071,18 +9644,11 @@ accountingDiffTolerated(XML_Parser originParser, int tok, const char *before, return XML_FALSE; *additionTarget += bytesMore; - const XmlBigCount countBytesOutput - = rootParser->m_accounting.countBytesDirect - + rootParser->m_accounting.countBytesIndirect; - const float amplificationFactor - = accountingGetCurrentAmplification(rootParser); const XML_Bool tolerated - = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes) - || (amplificationFactor - <= rootParser->m_accounting.maximumAmplificationFactor); + = accountingCurrentAmplificationTolerated(rootParser, 0); if (rootParser->m_accounting.debugLevel >= 2u) { - accountingReportStats(rootParser, ""); + accountingReportStats(rootParser, "", 0, 0); accountingReportDiff(rootParser, levelsAwayFromRootParser, before, after, bytesMore, source_line, account); } @@ -9128,14 +9694,21 @@ entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity, = limitingNeeded ? (maxLimitedDepth - /* make space for ellipis */ 2) : candidateIndentDepth; + const ptrdiff_t scannedLength + = EXPAT_SAFE_PTR_DIFF(entity->scanPtr, entity->textPtr); + const char *const confidenceMarker + = ((size_t)scannedLength == entity->textLen) ? "!" : "?"; + fprintf( stderr, - "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s length %d (xmlparse.c:%d)\n", + "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s scanned " EXPAT_FMT_PTRDIFF_T( + "") "/" EXPAT_FMT_SIZE_T("") ", expanded " EXPAT_FMT_ULL("") "%s (xmlparse.c:%d)\n", (void *)rootParser, rootParser->m_entity_stats.countEverOpened, rootParser->m_entity_stats.currentDepth, rootParser->m_entity_stats.maximumDepthSeen, indentDepth * 2, "", ellipisOrEmpty, entity->is_param ? "%" : "&", entityName, action, - entity->textLen, sourceLine); + scannedLength, entity->textLen, entity->expandedSize, confidenceMarker, + sourceLine); } static void @@ -9150,6 +9723,7 @@ entityTrackingOnOpen(XML_Parser originParser, ENTITY *entity, int sourceLine) { rootParser->m_entity_stats.maximumDepthSeen++; } + // NOTE: The space at the end of "OPEN " is for length alignment with "CLOSE" entityTrackingReportStats(rootParser, entity, "OPEN ", sourceLine); } @@ -9162,6 +9736,25 @@ entityTrackingOnClose(XML_Parser originParser, ENTITY *entity, int sourceLine) { rootParser->m_entity_stats.currentDepth--; } +static void +entityTrackingOnScanStart(XML_Parser originParser, ENTITY *entity, + int sourceLine) { + const XML_Parser rootParser = getRootParserOf(originParser, NULL); + assert(! rootParser->m_parentParser); + + entityTrackingReportStats(rootParser, entity, "START", sourceLine); +} + +static void +entityTrackingOnScanStop(XML_Parser originParser, ENTITY *entity, + int sourceLine) { + const XML_Parser rootParser = getRootParserOf(originParser, NULL); + assert(! rootParser->m_parentParser); + + // NOTE: The space at the end of "STOP " is for length alignment with "START" + entityTrackingReportStats(rootParser, entity, "STOP ", sourceLine); +} + #endif /* XML_GE == 1 */ static XML_Parser diff --git a/base/poco/XML/src/xmltok.h b/base/poco/XML/src/xmltok.h index 4f6fb3850caf..fb8329e06394 100644 --- a/base/poco/XML/src/xmltok.h +++ b/base/poco/XML/src/xmltok.h @@ -180,8 +180,8 @@ struct encoding { const char *); int (*nameLength)(const ENCODING *, const char *); const char *(*skipS)(const ENCODING *, const char *); - int (*getAtts)(const ENCODING *enc, const char *ptr, int attsMax, - ATTRIBUTE *atts); + size_t (*getAtts)(const ENCODING *enc, const char *ptr, size_t attsMax, + ATTRIBUTE *atts); int (*charRefNumber)(const ENCODING *enc, const char *ptr); int (*predefinedEntityName)(const ENCODING *, const char *, const char *); void (*updatePosition)(const ENCODING *, const char *ptr, const char *end, diff --git a/base/poco/XML/src/xmltok_impl.c b/base/poco/XML/src/xmltok_impl.c index 571af3698af7..67fececb1f61 100644 --- a/base/poco/XML/src/xmltok_impl.c +++ b/base/poco/XML/src/xmltok_impl.c @@ -1505,11 +1505,11 @@ PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end, first attsMax attributes are stored in atts. */ -static int -PREFIX(getAtts)(const ENCODING *enc, const char *ptr, int attsMax, +static size_t +PREFIX(getAtts)(const ENCODING *enc, const char *ptr, size_t attsMax, ATTRIBUTE *atts) { enum { other, inName, inValue } state = inName; - int nAtts = 0; + size_t nAtts = 0; int open = 0; /* defined when state == inValue; initialization just to shut up compilers */ diff --git a/base/poco/XML/src/xmlxcs.c b/base/poco/XML/src/xmlxcs.c index ae5e042d778f..a97647fa9d69 100644 --- a/base/poco/XML/src/xmlxcs.c +++ b/base/poco/XML/src/xmlxcs.c @@ -88,3 +88,24 @@ xcsncmp(const XML_Char *a, const XML_Char *b, size_t len) { return strncmp(a, b, len); #endif } + +// A port of `strnstr(3bsd)` to `XML_Char` +const XML_Char * +xcsnstr(const XML_Char *haystack, const XML_Char *needle, size_t maxLen) { + // NOTE: We are not calling `xcsnlen(haystack, maxLen)` because + // `haystack` could be long and `xcsnlen` could be used in a loop + // and we need to avoid quadratic runtime behavior. + if (! *needle) + return haystack; // i.e. empty needle is always a match + const size_t needleLen = xcslen(needle); + if (needleLen > maxLen) + return NULL; + const size_t maxTries = (maxLen - needleLen) + 1; + for (size_t i = 0; i < maxTries && haystack[i]; i++) { + if (haystack[i] == needle[0] + && xcsncmp(haystack + i, needle, needleLen) == 0) { + return haystack + i; + } + } + return NULL; +} diff --git a/ci/docker/integration/dotnet_client/Dockerfile b/ci/docker/integration/dotnet_client/Dockerfile index 3fe1ba7dafc5..82bf1d686718 100644 --- a/ci/docker/integration/dotnet_client/Dockerfile +++ b/ci/docker/integration/dotnet_client/Dockerfile @@ -1,5 +1,5 @@ # docker build . -# docker run -it --rm --network=host 14f23e59669c dotnet run --host localhost --port 8123 --user default --database default +# docker run -it --rm --network=host 14f23e59669c dotnet /client/out/clickhouse.test.dll --host localhost --port 8123 --user default --database default # Rebuild to enable SBOM/provenance attestations (see #97903, #98511) FROM mcr.microsoft.com/dotnet/sdk:8.0 @@ -9,3 +9,12 @@ COPY *.cs *.csproj /client/ ARG VERSION=4.1.0 RUN dotnet add package ClickHouse.Client -v ${VERSION} + +# Build here, not in the test. `dotnet run` restores, builds and runs, which starts an MSBuild node +# and a Roslyn compiler server alongside the application: three .NET processes where the test needs +# one, and the two extra ones are not what this test covers. They are already a known source of +# noise in this suite - the analyzer crash that +# https://github.com/ClickHouse/ClickHouse/pull/107375 had to work around came from the in-test +# build. Publishing here leaves the test with a single `dotnet ` process. +ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 MSBUILDDISABLENODEREUSE=1 +RUN dotnet publish -c Release -o /client/out && rm -rf /client/obj /client/bin diff --git a/contrib/CMakeLists.txt b/contrib/CMakeLists.txt index 84f8af4c260b..e82c71acc8de 100644 --- a/contrib/CMakeLists.txt +++ b/contrib/CMakeLists.txt @@ -86,7 +86,7 @@ add_contrib (minizip-ng-cmake minizip-ng) add_contrib (snappy-cmake snappy) add_contrib (thrift-cmake thrift) add_contrib (StringZilla-cmake StringZilla) -# parquet/arrow/orc +# parquet/arrow add_contrib (xsimd-cmake xsimd) # required by arrow add_contrib (arrow-cmake arrow) # requires: snappy, thrift, double-conversion, xsimd add_contrib (avro-cmake avro) # requires: snappy diff --git a/contrib/arrow-cmake/CMakeLists.txt b/contrib/arrow-cmake/CMakeLists.txt index 9cd962825e53..1fdf41db8821 100644 --- a/contrib/arrow-cmake/CMakeLists.txt +++ b/contrib/arrow-cmake/CMakeLists.txt @@ -57,18 +57,9 @@ else() endif() -# === orc -set(ORC_SOURCE_DIR "${ClickHouse_SOURCE_DIR}/contrib/orc/c++") -set(ORC_INCLUDE_DIR "${ORC_SOURCE_DIR}/include") -set(ORC_SOURCE_SRC_DIR "${ORC_SOURCE_DIR}/src") -# set(ORC_SOURCE_WRAP_DIR "${ORC_SOURCE_DIR}/wrap") - -set(ORC_BUILD_SRC_DIR "${CMAKE_CURRENT_BINARY_DIR}/../orc/c++/src") -set(ORC_BUILD_INCLUDE_DIR "${CMAKE_CURRENT_BINARY_DIR}/../orc/c++/include") - -set(ORC_ADDITION_SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}) set(ARROW_SRC_DIR "${ClickHouse_SOURCE_DIR}/contrib/arrow/cpp/src") +# Used by `flight.cmake` to generate the Arrow Flight sources. if (NOT CMAKE_HOST_SYSTEM_NAME STREQUAL CMAKE_SYSTEM_NAME OR NOT CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL CMAKE_SYSTEM_PROCESSOR) set(PROTOBUF_EXECUTABLE "${PROJECT_BINARY_DIR}/native/contrib/google-protobuf-cmake/protoc") set(GRPC_EXECUTABLE "${PROJECT_BINARY_DIR}/native/contrib/grpc-cmake/grpc_cpp_plugin") @@ -76,16 +67,6 @@ else () set(PROTOBUF_EXECUTABLE $) set(GRPC_EXECUTABLE $) endif() -set(PROTO_DIR "${ORC_SOURCE_DIR}/../proto") - -add_custom_command(OUTPUT orc_proto.pb.h orc_proto.pb.cc - COMMAND ${PROTOBUF_EXECUTABLE} - -I ${PROTO_DIR} - --cpp_out="${CMAKE_CURRENT_BINARY_DIR}" - "${PROTO_DIR}/orc_proto.proto" - # Without these, the generated sources are not regenerated when the schema or - # `protoc` itself changes, and a stale `orc_proto.pb.h` is compiled instead. - DEPENDS "${PROTO_DIR}/orc_proto.proto" ${PROTOBUF_EXECUTABLE}) # === flatbuffers set(FLATBUFFERS_SRC_DIR "${ClickHouse_SOURCE_DIR}/contrib/flatbuffers") @@ -107,128 +88,6 @@ target_compile_definitions(_flatbuffers PRIVATE -DFLATBUFFERS_LOCALE_INDEPENDENT # NOTE: cannot use ch_contrib::hdfs since it's INCLUDE_DIRECTORIES does not includes trailing "hdfs/" set(HDFS_INCLUDE_DIR "${ClickHouse_SOURCE_DIR}/contrib/libhdfs3/include/hdfs/") -# arrow-cmake cmake file calling orc cmake subroutine which detects certain compiler features. -# Apple Clang compiler failed to compile this code without specifying c++11 standard. -# As result these compiler features detected as absent. In result it failed to compile orc itself. -# In orc makefile there is code that sets flags, but arrow-cmake ignores these flags. -if (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") - set(CXX11_FLAGS "-std=c++0x") -endif () - -set (ORC_CXX_HAS_INITIALIZER_LIST 1) -set (ORC_CXX_HAS_NOEXCEPT 1) -set (ORC_CXX_HAS_NULLPTR 1) -set (ORC_CXX_HAS_OVERRIDE 1) -set (ORC_CXX_HAS_UNIQUE_PTR 1) -set (ORC_CXX_HAS_CSTDINT 1) -set (ORC_CXX_HAS_THREAD_LOCAL 1) - -include(orc_check.cmake) -configure_file("${ORC_SOURCE_SRC_DIR}/Adaptor.hh.in" "${ORC_BUILD_INCLUDE_DIR}/Adaptor.hh") - - -# ARROW_ORC + adapters/orc/CMakefiles -set(ORC_SRCS - "${CMAKE_CURRENT_BINARY_DIR}/orc_proto.pb.h" - "${ORC_ADDITION_SOURCE_DIR}/orc_proto.pb.cc" - "${ORC_SOURCE_SRC_DIR}/Adaptor.cc" - "${ORC_SOURCE_SRC_DIR}/Adaptor.hh.in" - "${ORC_SOURCE_SRC_DIR}/BlockBuffer.cc" - "${ORC_SOURCE_SRC_DIR}/BlockBuffer.hh" - "${ORC_SOURCE_SRC_DIR}/BloomFilter.cc" - "${ORC_SOURCE_SRC_DIR}/BloomFilter.hh" - "${ORC_SOURCE_SRC_DIR}/Bpacking.hh" - "${ORC_SOURCE_SRC_DIR}/BpackingDefault.cc" - "${ORC_SOURCE_SRC_DIR}/BpackingDefault.hh" - "${ORC_SOURCE_SRC_DIR}/ByteRLE.cc" - "${ORC_SOURCE_SRC_DIR}/ByteRLE.hh" - "${ORC_SOURCE_SRC_DIR}/ColumnPrinter.cc" - "${ORC_SOURCE_SRC_DIR}/ColumnReader.cc" - "${ORC_SOURCE_SRC_DIR}/ColumnReader.hh" - "${ORC_SOURCE_SRC_DIR}/ColumnWriter.cc" - "${ORC_SOURCE_SRC_DIR}/ColumnWriter.hh" - "${ORC_SOURCE_SRC_DIR}/Common.cc" - "${ORC_SOURCE_SRC_DIR}/Dictionary.cc" - "${ORC_SOURCE_SRC_DIR}/DictionaryLoader.cc" - "${ORC_SOURCE_SRC_DIR}/Compression.cc" - "${ORC_SOURCE_SRC_DIR}/Compression.hh" - "${ORC_SOURCE_SRC_DIR}/ConvertColumnReader.cc" - "${ORC_SOURCE_SRC_DIR}/ConvertColumnReader.hh" - "${ORC_SOURCE_SRC_DIR}/CpuInfoUtil.cc" - "${ORC_SOURCE_SRC_DIR}/CpuInfoUtil.hh" - "${ORC_SOURCE_SRC_DIR}/Dispatch.hh" - "${ORC_SOURCE_SRC_DIR}/Exceptions.cc" - "${ORC_SOURCE_SRC_DIR}/Geospatial.cc" - "${ORC_SOURCE_SRC_DIR}/Int128.cc" - "${ORC_SOURCE_SRC_DIR}/LzoDecompressor.cc" - "${ORC_SOURCE_SRC_DIR}/LzoDecompressor.hh" - "${ORC_SOURCE_SRC_DIR}/MemoryPool.cc" - "${ORC_SOURCE_SRC_DIR}/Murmur3.cc" - "${ORC_SOURCE_SRC_DIR}/Murmur3.hh" - "${ORC_SOURCE_SRC_DIR}/Options.hh" - "${ORC_SOURCE_SRC_DIR}/OrcFile.cc" - "${ORC_SOURCE_SRC_DIR}/RLE.cc" - "${ORC_SOURCE_SRC_DIR}/RLE.hh" - "${ORC_SOURCE_SRC_DIR}/RLEV2Util.cc" - "${ORC_SOURCE_SRC_DIR}/RLEV2Util.hh" - "${ORC_SOURCE_SRC_DIR}/RLEv1.cc" - "${ORC_SOURCE_SRC_DIR}/RLEv1.hh" - "${ORC_SOURCE_SRC_DIR}/RLEv2.hh" - "${ORC_SOURCE_SRC_DIR}/Reader.cc" - "${ORC_SOURCE_SRC_DIR}/Reader.hh" - "${ORC_SOURCE_SRC_DIR}/RleDecoderV2.cc" - "${ORC_SOURCE_SRC_DIR}/RleEncoderV2.cc" - "${ORC_SOURCE_SRC_DIR}/SchemaEvolution.cc" - "${ORC_SOURCE_SRC_DIR}/SchemaEvolution.hh" - "${ORC_SOURCE_SRC_DIR}/Statistics.cc" - "${ORC_SOURCE_SRC_DIR}/Statistics.hh" - "${ORC_SOURCE_SRC_DIR}/StripeStream.cc" - "${ORC_SOURCE_SRC_DIR}/StripeStream.hh" - "${ORC_SOURCE_SRC_DIR}/Timezone.cc" - "${ORC_SOURCE_SRC_DIR}/Timezone.hh" - "${ORC_SOURCE_SRC_DIR}/TypeImpl.cc" - "${ORC_SOURCE_SRC_DIR}/TypeImpl.hh" - "${ORC_SOURCE_SRC_DIR}/Utils.hh" - "${ORC_SOURCE_SRC_DIR}/Vector.cc" - "${ORC_SOURCE_SRC_DIR}/Writer.cc" - "${ORC_SOURCE_SRC_DIR}/io/InputStream.cc" - "${ORC_SOURCE_SRC_DIR}/io/InputStream.hh" - "${ORC_SOURCE_SRC_DIR}/io/OutputStream.cc" - "${ORC_SOURCE_SRC_DIR}/io/OutputStream.hh" - "${ORC_SOURCE_SRC_DIR}/io/Cache.cc" - "${ORC_SOURCE_SRC_DIR}/io/Cache.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/ExpressionTree.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/ExpressionTree.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/Literal.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/PredicateLeaf.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/PredicateLeaf.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/SargsApplier.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/SargsApplier.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/SearchArgument.cc" - "${ORC_SOURCE_SRC_DIR}/sargs/SearchArgument.hh" - "${ORC_SOURCE_SRC_DIR}/sargs/TruthValue.cc" - ) - -add_library(_orc ${ORC_SRCS}) -target_link_libraries(_orc PRIVATE - ch_contrib::protobuf - ch_contrib::lz4 - ch_contrib::snappy - ch_contrib::zlib - ch_contrib::zstd) -target_include_directories(_orc SYSTEM BEFORE PUBLIC - ${ORC_INCLUDE_DIR} - "${ClickHouse_SOURCE_DIR}/contrib/arrow-cmake/cpp/src/orc/c++/include") -target_compile_options(_orc PRIVATE - -include "${ClickHouse_SOURCE_DIR}/contrib/google-protobuf/src/google/protobuf/stubs/port.h" -) -target_include_directories(_orc SYSTEM BEFORE PUBLIC ${ORC_BUILD_INCLUDE_DIR}) -target_include_directories(_orc SYSTEM PRIVATE - ${ORC_SOURCE_SRC_DIR} - ${ORC_SOURCE_WRAP_DIR} - ${ORC_BUILD_SRC_DIR} - ${ORC_ADDITION_SOURCE_DIR} - ${ARROW_SRC_DIR}) # === arrow @@ -240,11 +99,8 @@ configure_file("${LIBRARY_DIR}/util/config_internal.h.cmake" "${ARROW_GENERATED_ # arrow/cpp/src/arrow/CMakeLists.txt (ARROW_SRCS + ARROW_COMPUTE + ARROW_IPC) # find . \( -iname \*.cc -o -iname \*.cpp -o -iname \*.c \) | sort | awk '{print "\"${LIBRARY_DIR}" substr($1,2) "\"" }' | grep -v 'test.cc' | grep -v 'json' | grep -v 'flight' \| -# grep -v 'csv' | grep -v 'acero' | grep -v 'dataset' | grep -v 'testing' | grep -v 'gpu' | grep -v 'engine' | grep -v 'filesystem' | grep -v 'benchmark.cc' +# grep -v 'csv' | grep -v 'acero' | grep -v 'dataset' | grep -v 'testing' | grep -v 'gpu' | grep -v 'engine' | grep -v 'filesystem' | grep -v 'benchmark.cc' | grep -v 'adapters/orc' set(ARROW_SRCS - "${LIBRARY_DIR}/adapters/orc/adapter.cc" - "${LIBRARY_DIR}/adapters/orc/options.cc" - "${LIBRARY_DIR}/adapters/orc/util.cc" "${LIBRARY_DIR}/array/array_base.cc" "${LIBRARY_DIR}/array/array_binary.cc" "${LIBRARY_DIR}/array/array_decimal.cc" @@ -466,10 +322,6 @@ set(ARROW_SRCS "${LIBRARY_DIR}/vendored/uriparser/UriResolve.c" "${LIBRARY_DIR}/vendored/uriparser/UriShorten.c" "${LIBRARY_DIR}/visitor.cc" - - "${ARROW_SRC_DIR}/arrow/adapters/orc/adapter.cc" - "${ARROW_SRC_DIR}/arrow/adapters/orc/util.cc" - "${ARROW_SRC_DIR}/arrow/adapters/orc/options.cc" ) add_definitions(-DARROW_WITH_BROTLI) @@ -514,10 +366,6 @@ target_link_libraries(_arrow PRIVATE # ARROW_HAVE_* SIMD defines. PUBLIC so the headers are visible to _parquet too (it links _arrow # PUBLIC). target_link_libraries(_arrow PUBLIC ch_contrib::xsimd) -target_link_libraries(_arrow PUBLIC _orc) - -add_dependencies(_arrow protoc) - target_include_directories(_arrow SYSTEM BEFORE PUBLIC ${ARROW_SRC_DIR}) target_include_directories(_arrow SYSTEM BEFORE PUBLIC "${ClickHouse_SOURCE_DIR}/contrib/arrow-cmake/cpp/src") diff --git a/contrib/arrow-cmake/orc_check.cmake b/contrib/arrow-cmake/orc_check.cmake deleted file mode 100644 index 523e1cf1d86b..000000000000 --- a/contrib/arrow-cmake/orc_check.cmake +++ /dev/null @@ -1,14 +0,0 @@ -set (HAS_PREAD 1) -set (HAS_STRPTIME 1) -set (HAS_STOLL 1) -set (INT64_IS_LL 1) -set (HAS_DIAGNOSTIC_PUSH 1) -set (HAS_STD_ISNAN 1) -set (HAS_STD_MUTEX 1) -set (NEEDS_REDUNDANT_MOVE 1) -set (HAS_PRE_1970 1) -set (HAS_POST_2038 1) -set (NEEDS_Z_PREFIX 0) - -set(CMAKE_REQUIRED_INCLUDES) -set(CMAKE_REQUIRED_LIBRARIES) diff --git a/contrib/brotli b/contrib/brotli index d224526f8fa7..2d9c9b61f4e7 160000 --- a/contrib/brotli +++ b/contrib/brotli @@ -1 +1 @@ -Subproject commit d224526f8fa736f24b2339e6f421a142de6586c8 +Subproject commit 2d9c9b61f4e7d3523c9dfb62e48fe91aaf86e812 diff --git a/contrib/brotli-cmake/CMakeLists.txt b/contrib/brotli-cmake/CMakeLists.txt index b89e81ecda19..8c2b41721dc9 100644 --- a/contrib/brotli-cmake/CMakeLists.txt +++ b/contrib/brotli-cmake/CMakeLists.txt @@ -9,35 +9,41 @@ set(BROTLI_SOURCE_DIR "${ClickHouse_SOURCE_DIR}/contrib/brotli/c") set(BROTLI_BINARY_DIR "${ClickHouse_BINARY_DIR}/contrib/brotli/c") set(SRCS - "${BROTLI_SOURCE_DIR}/enc/command.c" - "${BROTLI_SOURCE_DIR}/enc/fast_log.c" + "${BROTLI_SOURCE_DIR}/common/constants.c" + "${BROTLI_SOURCE_DIR}/common/context.c" + "${BROTLI_SOURCE_DIR}/common/dictionary.c" + "${BROTLI_SOURCE_DIR}/common/platform.c" + "${BROTLI_SOURCE_DIR}/common/shared_dictionary.c" + "${BROTLI_SOURCE_DIR}/common/transform.c" "${BROTLI_SOURCE_DIR}/dec/bit_reader.c" - "${BROTLI_SOURCE_DIR}/dec/state.c" - "${BROTLI_SOURCE_DIR}/dec/huffman.c" "${BROTLI_SOURCE_DIR}/dec/decode.c" - "${BROTLI_SOURCE_DIR}/enc/encode.c" - "${BROTLI_SOURCE_DIR}/enc/dictionary_hash.c" + "${BROTLI_SOURCE_DIR}/dec/huffman.c" + "${BROTLI_SOURCE_DIR}/dec/prefix.c" + "${BROTLI_SOURCE_DIR}/dec/state.c" + "${BROTLI_SOURCE_DIR}/dec/static_init.c" + "${BROTLI_SOURCE_DIR}/enc/backward_references.c" + "${BROTLI_SOURCE_DIR}/enc/backward_references_hq.c" + "${BROTLI_SOURCE_DIR}/enc/bit_cost.c" + "${BROTLI_SOURCE_DIR}/enc/block_splitter.c" + "${BROTLI_SOURCE_DIR}/enc/brotli_bit_stream.c" "${BROTLI_SOURCE_DIR}/enc/cluster.c" + "${BROTLI_SOURCE_DIR}/enc/command.c" + "${BROTLI_SOURCE_DIR}/enc/compound_dictionary.c" + "${BROTLI_SOURCE_DIR}/enc/compress_fragment.c" + "${BROTLI_SOURCE_DIR}/enc/compress_fragment_two_pass.c" + "${BROTLI_SOURCE_DIR}/enc/dictionary_hash.c" + "${BROTLI_SOURCE_DIR}/enc/encode.c" + "${BROTLI_SOURCE_DIR}/enc/encoder_dict.c" "${BROTLI_SOURCE_DIR}/enc/entropy_encode.c" + "${BROTLI_SOURCE_DIR}/enc/fast_log.c" + "${BROTLI_SOURCE_DIR}/enc/histogram.c" "${BROTLI_SOURCE_DIR}/enc/literal_cost.c" - "${BROTLI_SOURCE_DIR}/enc/compress_fragment_two_pass.c" + "${BROTLI_SOURCE_DIR}/enc/memory.c" + "${BROTLI_SOURCE_DIR}/enc/metablock.c" "${BROTLI_SOURCE_DIR}/enc/static_dict.c" - "${BROTLI_SOURCE_DIR}/enc/compress_fragment.c" - "${BROTLI_SOURCE_DIR}/enc/block_splitter.c" - "${BROTLI_SOURCE_DIR}/enc/backward_references_hq.c" - "${BROTLI_SOURCE_DIR}/enc/histogram.c" - "${BROTLI_SOURCE_DIR}/enc/brotli_bit_stream.c" + "${BROTLI_SOURCE_DIR}/enc/static_dict_lut.c" + "${BROTLI_SOURCE_DIR}/enc/static_init.c" "${BROTLI_SOURCE_DIR}/enc/utf8_util.c" - "${BROTLI_SOURCE_DIR}/enc/encoder_dict.c" - "${BROTLI_SOURCE_DIR}/enc/backward_references.c" - "${BROTLI_SOURCE_DIR}/enc/bit_cost.c" - "${BROTLI_SOURCE_DIR}/enc/metablock.c" - "${BROTLI_SOURCE_DIR}/enc/memory.c" - "${BROTLI_SOURCE_DIR}/common/dictionary.c" - "${BROTLI_SOURCE_DIR}/common/transform.c" - "${BROTLI_SOURCE_DIR}/common/platform.c" - "${BROTLI_SOURCE_DIR}/common/context.c" - "${BROTLI_SOURCE_DIR}/common/constants.c" ) add_library(_brotli ${SRCS}) @@ -45,4 +51,3 @@ add_library(ch_contrib::brotli ALIAS _brotli) target_include_directories(_brotli SYSTEM BEFORE PUBLIC "${BROTLI_SOURCE_DIR}/include") -target_compile_definitions(_brotli PRIVATE BROTLI_BUILD_PORTABLE=1) diff --git a/contrib/c-ares b/contrib/c-ares index c7a3138dcfe3..bc91829cce98 160000 --- a/contrib/c-ares +++ b/contrib/c-ares @@ -1 +1 @@ -Subproject commit c7a3138dcfe3bb0eaaf10c0c24c36dc66dc790ab +Subproject commit bc91829cce983a35ec01f5dbc05465858a3df469 diff --git a/contrib/grpc b/contrib/grpc index a703d1f9448f..68b2fe0b2b13 160000 --- a/contrib/grpc +++ b/contrib/grpc @@ -1 +1 @@ -Subproject commit a703d1f9448ff77deca3beb36dfc7d337a209d3e +Subproject commit 68b2fe0b2b1318f18aadee9027e86e8ceaa20af2 diff --git a/contrib/hive-metastore-cmake/CMakeLists.txt b/contrib/hive-metastore-cmake/CMakeLists.txt index a5e16c739afb..bf92db62d1b9 100644 --- a/contrib/hive-metastore-cmake/CMakeLists.txt +++ b/contrib/hive-metastore-cmake/CMakeLists.txt @@ -1,7 +1,15 @@ -if (TARGET ch_contrib::hdfs) +if (NOT TARGET ch_contrib::hdfs) + if (ENABLE_HIVE) + message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use Hive without HDFS") + endif() +# `Storages/Hive/HiveFile.h` uses the ORC reader and `parquet/arrow/reader.h` outright, +# so Hive needs both readers, not just the metastore client. The ORC reader needs only snappy. +elseif (NOT TARGET ch_contrib::snappy OR NOT TARGET _parquet) + if (ENABLE_HIVE) + message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use Hive without ORC and Parquet") + endif() +else() option(ENABLE_HIVE "Enable Hive" ${ENABLE_LIBRARIES}) -elseif(ENABLE_HIVE) - message (${RECONFIGURE_MESSAGE_LEVEL} "Cannot use Hive without HDFS") endif() if (NOT ENABLE_HIVE) diff --git a/contrib/mongo-c-driver b/contrib/mongo-c-driver index 70de9e880072..58b4e1f39c6f 160000 --- a/contrib/mongo-c-driver +++ b/contrib/mongo-c-driver @@ -1 +1 @@ -Subproject commit 70de9e880072b120ccbb48c77de334775747d7a9 +Subproject commit 58b4e1f39c6f8bcf4da4204deb84f9b3527388d4 diff --git a/contrib/mongo-c-driver-cmake/CMakeLists.txt b/contrib/mongo-c-driver-cmake/CMakeLists.txt index 7a270790f140..79ad23b40d8d 100644 --- a/contrib/mongo-c-driver-cmake/CMakeLists.txt +++ b/contrib/mongo-c-driver-cmake/CMakeLists.txt @@ -6,12 +6,12 @@ endif() set(libbson_VERSION_MAJOR 2) set(libbson_VERSION_MINOR 5) -set(libbson_VERSION_PATCH 5) -set(libbson_VERSION 2.5.5) +set(libbson_VERSION_PATCH 8) +set(libbson_VERSION 2.5.8) set(libmongoc_VERSION_MAJOR 2) set(libmongoc_VERSION_MINOR 5) -set(libmongoc_VERSION_PATCH 5) -set(libmongoc_VERSION 2.5.5) +set(libmongoc_VERSION_PATCH 8) +set(libmongoc_VERSION 2.5.8) set(LIBBSON_SOURCES_ROOT "${ClickHouse_SOURCE_DIR}/contrib/mongo-c-driver/src") set(LIBBSON_SOURCE_DIR "${LIBBSON_SOURCES_ROOT}/libbson/src") diff --git a/contrib/mongo-cxx-driver b/contrib/mongo-cxx-driver index fa9ee6ed008e..35424a5cc597 160000 --- a/contrib/mongo-cxx-driver +++ b/contrib/mongo-cxx-driver @@ -1 +1 @@ -Subproject commit fa9ee6ed008e84b9562a7a55d70681de8a6bc1c6 +Subproject commit 35424a5cc597391d3737ae5e00f029cd2afc03c4 diff --git a/contrib/orc b/contrib/orc deleted file mode 160000 index 8ca5eeed390f..000000000000 --- a/contrib/orc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 8ca5eeed390f57fe6d1d4f7f8d97da19de6c08cb diff --git a/contrib/sqlite-amalgamation b/contrib/sqlite-amalgamation index 23c7b7692961..f48768e9089b 160000 --- a/contrib/sqlite-amalgamation +++ b/contrib/sqlite-amalgamation @@ -1 +1 @@ -Subproject commit 23c7b76929611997c5f0315b3149372b1bee1d41 +Subproject commit f48768e9089bf66717e8c393dce5dd80c86761f5 diff --git a/docs/en/engines/table-engines/integrations/azure-queue.md b/docs/en/engines/table-engines/integrations/azure-queue.md index 2147a8bbb0e1..bbf5046a163b 100644 --- a/docs/en/engines/table-engines/integrations/azure-queue.md +++ b/docs/en/engines/table-engines/integrations/azure-queue.md @@ -53,6 +53,8 @@ Below are the settings only compatible with AzureQueue and not applicable for S3 Connection string for Azure Blob Storage to move successfully processed files to, if the destination is another Azure container. +Setting it requires the `WRITE` grant on the `AZURE` source. A grant limited by a URL filter is not enough, because a move has no single blob path and writes keys that are built from `after_processing_move_prefix` and the source keys. `ALTER TABLE ... MODIFY SETTING` also requires `SELECT` on the table. The destination must be allowed by `remote_url_allow_hosts`. + Possible values: - String. @@ -63,6 +65,8 @@ Default value: empty string. Container name to move successfully processed files to, if the destination is another Azure container. +Changing it redirects the move to another container of the same account, so it needs the same grants as `after_processing_move_connection_string`: the `WRITE` grant on the `AZURE` source without a URL filter, and `SELECT` on the table for `ALTER TABLE ... MODIFY SETTING`. + Possible values: - String. diff --git a/docs/en/engines/table-engines/integrations/s3queue.md b/docs/en/engines/table-engines/integrations/s3queue.md index 9ee0c93147e4..48d82ab2db78 100644 --- a/docs/en/engines/table-engines/integrations/s3queue.md +++ b/docs/en/engines/table-engines/integrations/s3queue.md @@ -186,6 +186,8 @@ Default value: empty string. URI of S3 bucket to move successfully processed files to, if the destination is another S3 bucket. +Setting it is the same data flow as `INSERT INTO FUNCTION s3('') SELECT * FROM
`, so it requires the `WRITE` grant on the `S3` source. A grant limited by a URL filter is not enough, because the move writes keys that are built from `after_processing_move_prefix` and the source keys, not from the URI. `ALTER TABLE ... MODIFY SETTING` also requires `SELECT` on the table. The destination must be allowed by `remote_url_allow_hosts`. + Possible values: - String. diff --git a/docs/en/operations/settings/settings-users.md b/docs/en/operations/settings/settings-users.md index d7d61ff6ee9c..d029b4cca3ad 100644 --- a/docs/en/operations/settings/settings-users.md +++ b/docs/en/operations/settings/settings-users.md @@ -110,6 +110,7 @@ It's not yet supported in SQL-driven Access Control. To authenticate using TOTP, users must provide a primary password along with a one-time password generated by their TOTP application via the `--one-time-password` command line option or concatenated to main password together with a '+' character. For example if the primary password is `some_password` and the generated TOTP code is `345123`, user may specify `--password some_password+345123` or `--password some_password --one-time-password 345123` when connecting to ClickHouse. If no password specified `clickhouse-client` will prompt for it interactively. +When no code is supplied for an account with TOTP, the server replies with the error `REQUIRED_SECOND_FACTOR` whether or not the password is correct, and `clickhouse-client` prompts for the code; the password is verified only together with the code. Each code is accepted at most once, as required by [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238#section-5.2), so a user can successfully authenticate at most once per `period`. Keep this in mind for clients that authenticate on every request or connection (for example, scripts using the HTTP interface): each authentication needs a fresh code. diff --git a/programs/client/Client.cpp b/programs/client/Client.cpp index d37218c596e4..e7d0ad5281c8 100644 --- a/programs/client/Client.cpp +++ b/programs/client/Client.cpp @@ -408,6 +408,16 @@ try if (should_ask_2fa) { + /// The server asks for the second factor before it checks the password, so the first attempt + /// without any password ends here too. Ask for the password alone first: it may already contain + /// the code (`password+code`); otherwise the server asks again and the code is prompted. + if (!asked_password && !config().has("password") && !config().getBool("ask-password", false)) + { + asked_password = true; + config().setBool("ask-password", true); + continue; + } + asked_2fa = true; if (!connection_parameters.password.empty()) config().setString("password", connection_parameters.password); @@ -567,7 +577,8 @@ void Client::connect() catch (Exception & e) { /// This problem can't be fixed with reconnection so it is not attempted - if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD) + if (e.code() == ErrorCodes::AUTHENTICATION_FAILED || e.code() == ErrorCodes::REQUIRED_PASSWORD + || e.code() == ErrorCodes::REQUIRED_SECOND_FACTOR) throw; if (attempted_address_index == hosts_and_ports.size() - 1) diff --git a/src/Access/AccessBackup.cpp b/src/Access/AccessBackup.cpp index d22edd007e2f..6af476b88b1b 100644 --- a/src/Access/AccessBackup.cpp +++ b/src/Access/AccessBackup.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -176,6 +177,23 @@ namespace } } }; + + AccessRights getRequiredAccessToRestoreGrants(const AccessRights & access) + { + AccessRights required_access; + for (const auto & element : access.getElements()) + { + /// Restoring a grant requires `GRANT OPTION` even if the backed-up entity does not have it. + if (element.is_partial_revoke && element.grant_option) + continue; + + if (element.is_partial_revoke) + required_access.revoke(element); + else + required_access.grantWithGrantOption(element); + } + return required_access; + } } @@ -338,12 +356,14 @@ void AccessRestorerFromBackup::loadFromBackup() } -AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const +AccessRights AccessRestorerFromBackup::getRequiredAccess() const { if (!loaded) throw Exception(ErrorCodes::LOGICAL_ERROR, "Access entities not loaded"); - AccessRightsElements res; + AccessRights res; + /// Like `CREATE ... OR REPLACE`, replacement requires `DROP` even if the entity does not exist. + const bool replace = (creation_mode == RestoreAccessCreationMode::kReplace); for (const auto & [id, entity_info] : entity_infos) { if (!entity_info.restore) @@ -355,57 +375,56 @@ AccessRightsElements AccessRestorerFromBackup::getRequiredAccess() const case User::TYPE: { const auto & user = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_USER, user.getName()); + AccessFlags flags = AccessType::CREATE_USER; + if (replace) + flags |= AccessType::DROP_USER; + res.grant(flags, user.getName()); if (!restore_with_current_grants) - { - auto elements = user.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(user.access)); if (!user.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case Role::TYPE: { const auto & role = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROLE, role.getName()); + AccessFlags flags = AccessType::CREATE_ROLE; + if (replace) + flags |= AccessType::DROP_ROLE; + res.grant(flags, role.getName()); if (!restore_with_current_grants) - { - auto elements = role.access.getElements(); - for (auto & element : elements) - { - if (!element.is_partial_revoke) - element.grant_option = true; - res.emplace_back(element); - } - } + res.makeUnion(getRequiredAccessToRestoreGrants(role.access)); if (!role.granted_roles.isEmpty()) - res.emplace_back(AccessType::ROLE_ADMIN); + res.grant(AccessType::ROLE_ADMIN); break; } case SettingsProfile::TYPE: { - res.emplace_back(AccessType::CREATE_SETTINGS_PROFILE); + AccessFlags flags = AccessType::CREATE_SETTINGS_PROFILE; + if (replace) + flags |= AccessType::DROP_SETTINGS_PROFILE; + res.grant(flags); break; } case RowPolicy::TYPE: { const auto & policy = typeid_cast(*entity); - res.emplace_back(AccessType::CREATE_ROW_POLICY, policy.getDatabase(), policy.getTableName()); + AccessFlags flags = AccessType::CREATE_ROW_POLICY; + if (replace) + flags |= AccessType::DROP_ROW_POLICY; + res.grant(flags, policy.getDatabase(), policy.getTableName()); break; } case Quota::TYPE: { - res.emplace_back(AccessType::CREATE_QUOTA); + AccessFlags flags = AccessType::CREATE_QUOTA; + if (replace) + flags |= AccessType::DROP_QUOTA; + res.grant(flags); break; } diff --git a/src/Access/AccessBackup.h b/src/Access/AccessBackup.h index 8219d1051035..da0f3088a033 100644 --- a/src/Access/AccessBackup.h +++ b/src/Access/AccessBackup.h @@ -11,7 +11,7 @@ class AccessControl; enum class AccessEntityType : uint8_t; struct IAccessEntity; using AccessEntityPtr = std::shared_ptr; -class AccessRightsElements; +class AccessRights; class IAccessStorage; class IBackup; using BackupPtr = std::shared_ptr; @@ -69,9 +69,9 @@ class AccessRestorerFromBackup /// Loads access entities from the backup. void loadFromBackup(); - /// Checks that the current user can do restoring. - /// Function loadFromBackup() must be called before that. - AccessRightsElements getRequiredAccess() const; + /// Returns the access required to restore the loaded entities. + /// `loadFromBackup` must be called first. + AccessRights getRequiredAccess() const; /// Generates random IDs for access entities we're restoring to insert them into an access storage; /// and finds IDs of existing access entities which are used as dependencies. diff --git a/src/Access/AccessControl.cpp b/src/Access/AccessControl.cpp index 03e25e9c513f..92f938920279 100644 --- a/src/Access/AccessControl.cpp +++ b/src/Access/AccessControl.cpp @@ -602,22 +602,25 @@ AuthResult AccessControl::authenticate(const Credentials & credentials, const Po // NOTE: In the case where the user has never been logged in using LDAP, // Then user_id is not generated, and the authentication quota will always be nullptr. auto authentication_quota = getAuthenticationQuota(credentials.getUserName(), address, client_info.getLastForwardedForHost()); - if (authentication_quota) - { - /// Reserve a single try from the quota to check whether we have another authentication try. - /// This is required for correct behavior in this situation: - /// User has 1 login failures quota. - /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. - /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. - /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED - /// and don't let the user authenticate. - /// - /// The authentication failures counter will be reset after successful authentication. - authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); - } try { + if (authentication_quota) + { + /// Reserve a single try from the quota to check whether we have another authentication try. + /// This is required for correct behavior in this situation: + /// User has 1 login failures quota. + /// * At the first login with an invalid password: Increase the quota counter. 1 (used) > 1 (max) is false. + /// Then try to authenticate the user and throw an AUTHENTICATION_FAILED error. + /// * In case of the second try: increase quota counter, 2 (used) > 1 (max), then throw QUOTA_EXCEED + /// and don't let the user authenticate. + /// + /// The authentication failures counter will be reset after successful authentication. + /// Inside the try block, so that an exceeded quota is reported like any other authentication failure + /// and doesn't reveal whether the user exists. + authentication_quota->used(QuotaType::FAILED_SEQUENTIAL_AUTHENTICATIONS, 1); + } + const auto auth_result = MultipleAccessStorage::authenticate(credentials, address, *external_authenticators, client_info, allow_no_password, allow_plaintext_password); if (authentication_quota) @@ -859,7 +862,7 @@ std::shared_ptr AccessControl::getEnabledQuota( const String & forwarded_address, const String & custom_quota_key) const { - return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key, true); + return quota_cache->getEnabledQuota(user_id, user_name, enabled_roles, address, forwarded_address, custom_quota_key); } std::shared_ptr AccessControl::getAuthenticationQuota( @@ -872,18 +875,13 @@ std::shared_ptr AccessControl::getAuthenticationQuota( const auto new_current_roles = user->granted_roles.findGranted(user->default_roles); const auto roles_info = getEnabledRolesInfo(new_current_roles, {}); - // client_key is not received at the moment of authentication during TCP connection - // if key type is set to QuotaKeyType::CLIENT_KEY - // QuotaCache::QuotaInfo::calculateKey will throw exception without throw_if_client_key_empty = false String quota_key; - bool throw_if_client_key_empty = false; return quota_cache->getEnabledQuota(*user_id, user->getName(), roles_info->enabled_roles, std::make_shared(address), forwarded_address, - quota_key, - throw_if_client_key_empty); + quota_key); } return nullptr; } diff --git a/src/Access/Authentication.cpp b/src/Access/Authentication.cpp index 055109dc596b..7745947d0fd2 100644 --- a/src/Access/Authentication.cpp +++ b/src/Access/Authentication.cpp @@ -183,80 +183,60 @@ namespace return {password_with_otp.substr(0, separator_pos), password_with_otp.substr(separator_pos + 1)}; } - Authentication::CredentialsCheckResult checkBasicAuthentication( - const BasicCredentials * basic_credentials, + /// Verifies the primary credential: the password without the one-time password part. + bool checkPrimaryCredential( + std::string_view password, + const BasicCredentials & basic_credentials, const AuthenticationData & authentication_method, const ExternalAuthenticators & external_authenticators, const ClientInfo & client_info, SettingsChanges & settings) { - const auto & provided_password = basic_credentials->getPassword(); - const auto & otp_secret = authentication_method.getOneTimePassword(); - auto [password, one_time_password] = splitOneTimePasswordAndPassword(provided_password, authentication_method); - Authentication::CredentialsCheckResult on_success = Authentication::CredentialsCheckResult::Success; - if (otp_secret) - { - /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after - /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. - if (one_time_password.empty()) - on_success = Authentication::CredentialsCheckResult::NeedSecondFactor; - else if (!checkOneTimePassword(one_time_password, *otp_secret)) - return Authentication::CredentialsCheckResult::Fail; - } - switch (authentication_method.getType()) { case AuthenticationType::NO_PASSWORD: { - return on_success; // N.B. even if the password is not empty! + return true; // N.B. even if the password is not empty! } case AuthenticationType::PLAINTEXT_PASSWORD: { const auto & password_plaintext = authentication_method.getPasswordHashBinary(); - return constantTimeEquals(Util::stringToDigest(password), password_plaintext) ? on_success : Authentication::CredentialsCheckResult::Fail; + return constantTimeEquals(Util::stringToDigest(password), password_plaintext); } case AuthenticationType::SHA256_PASSWORD: { const auto & password_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); String salted_password = String(password).append(salt); - return Util::encodeSHA256(salted_password) == password_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeSHA256(salted_password) == password_sha256; } case AuthenticationType::SCRAM_SHA256_PASSWORD: { const auto & password_scram_sha256 = authentication_method.getPasswordHashBinary(); const auto & salt = authentication_method.getSalt(); auto digest = Util::encodeScramSHA256(password, salt); - return digest == password_scram_sha256 ? on_success : Authentication::CredentialsCheckResult::Fail; + return digest == password_scram_sha256; } case AuthenticationType::DOUBLE_SHA1_PASSWORD: { const auto & password_double_sha1 = authentication_method.getPasswordHashBinary(); - return Util::encodeDoubleSHA1(password) == password_double_sha1 ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::encodeDoubleSHA1(password) == password_double_sha1; } case AuthenticationType::LDAP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; - return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), *basic_credentials) ? - on_success : Authentication::CredentialsCheckResult::Fail; + return external_authenticators.checkLDAPCredentials(authentication_method.getLDAPServerName(), basic_credentials); } case AuthenticationType::BCRYPT_PASSWORD: { const auto & password_bcrypt = authentication_method.getPasswordHashBinary(); - return Util::checkPasswordBcrypt(password, password_bcrypt) ? on_success : Authentication::CredentialsCheckResult::Fail; + return Util::checkPasswordBcrypt(password, password_bcrypt); } case AuthenticationType::HTTP: { - if (otp_secret) - /// One-time password supported only with password-based authentication methods. - return Authentication::CredentialsCheckResult::Fail; if (authentication_method.getHTTPAuthenticationScheme() == HTTPAuthenticationScheme::BASIC) { return external_authenticators.checkHTTPBasicCredentials( - authentication_method.getHTTPAuthenticationServerName(), *basic_credentials, client_info, settings) ? - on_success : Authentication::CredentialsCheckResult::Fail; + authentication_method.getHTTPAuthenticationServerName(), basic_credentials, client_info, settings); } break; } @@ -264,7 +244,38 @@ namespace break; } - return Authentication::CredentialsCheckResult::Fail; + return false; + } + + Authentication::CredentialsCheckResult checkBasicAuthentication( + const BasicCredentials * basic_credentials, + const AuthenticationData & authentication_method, + const ExternalAuthenticators & external_authenticators, + const ClientInfo & client_info, + SettingsChanges & settings) + { + const auto & otp_secret = authentication_method.getOneTimePassword(); + auto [password, one_time_password] = splitOneTimePasswordAndPassword(basic_credentials->getPassword(), authentication_method); + + const auto auth_type = authentication_method.getType(); + if (otp_secret && (auth_type == AuthenticationType::LDAP || auth_type == AuthenticationType::HTTP)) + /// One-time password supported only with password-based authentication methods. + return Authentication::CredentialsCheckResult::Fail; + + /// Decided before the primary credential is looked at, so that the response (and its timing) is the same + /// for a right and a wrong password: otherwise an attacker could confirm a guessed password without the code. + if (otp_secret && one_time_password.empty()) + return Authentication::CredentialsCheckResult::NeedSecondFactor; + + const bool primary_ok = checkPrimaryCredential(password, *basic_credentials, authentication_method, external_authenticators, client_info, settings); + if (!otp_secret) + return primary_ok ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; + + /// Only a pure check here: the code is marked as used by `consumeOneTimePassword` after + /// the whole authentication succeeds, so a failed attempt cannot burn a valid code. + /// Both factors are evaluated unconditionally, so that the timing does not tell which one failed. + const bool otp_ok = checkOneTimePassword(one_time_password, *otp_secret); + return (primary_ok && otp_ok) ? Authentication::CredentialsCheckResult::Success : Authentication::CredentialsCheckResult::Fail; } #if USE_SSL diff --git a/src/Access/ContextAccess.cpp b/src/Access/ContextAccess.cpp index 98cd4af879ed..aedfc9fa08a5 100644 --- a/src/Access/ContextAccess.cpp +++ b/src/Access/ContextAccess.cpp @@ -586,6 +586,10 @@ std::shared_ptr ContextAccess::getQuota() const } } + /// Outside the branch above on purpose: `QuotaCache` refreshes the quota set in place, so an already + /// memoised object has to be re-checked on every call. + enabled_quota->checkClientKeySupplied(); + return enabled_quota; } diff --git a/src/Access/EnabledQuota.cpp b/src/Access/EnabledQuota.cpp index 92518d5506ea..c5333af77e4d 100644 --- a/src/Access/EnabledQuota.cpp +++ b/src/Access/EnabledQuota.cpp @@ -14,6 +14,7 @@ namespace DB namespace ErrorCodes { extern const int QUOTA_EXCEEDED; + extern const int QUOTA_REQUIRES_CLIENT_KEY; } @@ -307,6 +308,18 @@ void EnabledQuota::checkExceeded(QuotaType quota_type) const } +void EnabledQuota::checkClientKeySupplied() const +{ + if (!requires_client_key) + return; + throw Exception( + ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, + "Quota {} (for user {}) requires a client supplied key.", + intervals.load()->quota_name, + getUserName()); +} + + void EnabledQuota::reset(QuotaType quota_type) const { const auto loaded = intervals.load(); diff --git a/src/Access/EnabledQuota.h b/src/Access/EnabledQuota.h index 2513bed9622c..587c97f108f4 100644 --- a/src/Access/EnabledQuota.h +++ b/src/Access/EnabledQuota.h @@ -52,6 +52,10 @@ class EnabledQuota : public boost::noncopyable void checkExceeded() const; void checkExceeded(QuotaType quota_type) const; + /// Throws if a governing quota is keyed by `client_key` and this context supplied none. Authentication + /// is metered before a client key can exist, so only the query path calls this. + void checkClientKeySupplied() const; + void reset(QuotaType quota_type) const; /// Returns the information about quota consumption. @@ -97,6 +101,9 @@ class EnabledQuota : public boost::noncopyable const Params params; boost::atomic_shared_ptr intervals; /// atomically changed by QuotaUsageManager std::atomic empty = false; /// Use a separate flag to avoid loading intervals, which is way more expensive than an atomic bool + /// The chosen quota is keyed by `client_key` and this context supplied none, so it cannot be metered. + /// Refreshed in place by `QuotaCache` together with `intervals`; see `checkClientKeySupplied`. + std::atomic requires_client_key = false; }; } diff --git a/src/Access/HTTPAuthClient.h b/src/Access/HTTPAuthClient.h index 27e0d5dc507b..2768639cb709 100644 --- a/src/Access/HTTPAuthClient.h +++ b/src/Access/HTTPAuthClient.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -12,6 +13,11 @@ namespace DB { +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + struct HTTPAuthClientParams { Poco::URI uri; @@ -95,8 +101,13 @@ class HTTPBasicAuthClient : private HTTPAuthClient for (const auto & k : headers) { - if (this->getForwardHeaders().contains(k.first)) - request.add(k.first, k.second); + if (!this->getForwardHeaders().contains(k.first)) + continue; + /// Poco writes header values verbatim, so a line break would let the value inject extra headers + /// (e.g. an `Authorization` placed before ours) into the request to the authentication server. + if (k.second.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Forwarded HTTP header \"{}\" contains CR, LF or NUL", k.first); + request.add(k.first, k.second); } Poco::Net::HTTPBasicCredentials basic_credentials{user_name, password}; diff --git a/src/Access/IAccessStorage.cpp b/src/Access/IAccessStorage.cpp index 2beb46691b4b..7c2ed52f88e7 100644 --- a/src/Access/IAccessStorage.cpp +++ b/src/Access/IAccessStorage.cpp @@ -598,6 +598,8 @@ std::optional IAccessStorage::authenticateImpl( "check allow_no_password and allow_plaintext_password settings in the server configuration"); } + /// Reported for a missing code before the password is checked (see `checkBasicAuthentication`), + /// so this error does not confirm the password. if (need_second_factor) throw Exception(ErrorCodes::REQUIRED_SECOND_FACTOR, "Authentication requires second factor"); throw Exception(ErrorCodes::WRONG_PASSWORD, "Invalid credentials"); diff --git a/src/Access/QuotaCache.cpp b/src/Access/QuotaCache.cpp index d5a019639a2f..338b09a34e73 100644 --- a/src/Access/QuotaCache.cpp +++ b/src/Access/QuotaCache.cpp @@ -26,7 +26,6 @@ namespace DB { namespace ErrorCodes { - extern const int QUOTA_REQUIRES_CLIENT_KEY; extern const int LOGICAL_ERROR; } @@ -40,7 +39,7 @@ void QuotaCache::QuotaInfo::setQuota(const QuotaPtr & quota_, const UUID & quota } -String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool throw_if_client_key_empty) const +String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled) const { const auto & params = enabled.params; switch (quota->key_type) @@ -65,14 +64,9 @@ String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool th { if (!params.client_key.empty()) return params.client_key; - - if (throw_if_client_key_empty) - throw Exception( - ErrorCodes::QUOTA_REQUIRES_CLIENT_KEY, - "Quota {} (for user {}) requires a client supplied key.", - quota->getName(), - params.user_name); - return ""; // Authentication quota has no client key at time of authentication. + /// An empty key is a legitimate state: at the time of authentication no client key exists yet. + /// The requirement is published as `EnabledQuota::requires_client_key` and enforced on the query path. + return ""; } case QuotaKeyType::CLIENT_KEY_OR_USER_NAME: { @@ -187,8 +181,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( const boost::container::flat_set & enabled_roles, const std::shared_ptr & client_address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty) + const String & client_key) { std::lock_guard lock{mutex}; ensureAllQuotasRead(); @@ -211,7 +204,7 @@ std::shared_ptr QuotaCache::getEnabledQuota( auto res = std::shared_ptr(new EnabledQuota(params)); enabled_quotas.emplace(std::move(params), res); - chooseQuotaToConsumeFor(*res, throw_if_client_key_empty); + chooseQuotaToConsumeFor(*res); return res; } @@ -294,7 +287,7 @@ void QuotaCache::chooseQuotaToConsume() i = enabled_quotas.erase(i); else { - chooseQuotaToConsumeFor(*elem, true); + chooseQuotaToConsumeFor(*elem); ++i; } } @@ -308,16 +301,18 @@ void QuotaCache::chooseQuotaToConsume() LOG_DEBUG(getLogger("QuotaCache"), "Re-chose quotas for {} enabled set(s) over {} quotas in {} ms", enabled_quotas.size(), all_quotas.size(), elapsed_ms); } -void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_client_key_empty) +void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled) { /// `mutex` is already locked. boost::shared_ptr intervals; + bool requires_client_key = false; for (auto & info : all_quotas | boost::adaptors::map_values) { if (info.roles->match(enabled.params.user_id, enabled.params.enabled_roles)) { - String key = info.calculateKey(enabled, throw_if_client_key_empty); + String key = info.calculateKey(enabled); intervals = info.getOrBuildIntervals(key); + requires_client_key = (info.quota->key_type == QuotaKeyType::CLIENT_KEY) && enabled.params.client_key.empty(); break; } } @@ -332,6 +327,7 @@ void QuotaCache::chooseQuotaToConsumeFor(EnabledQuota & enabled, bool throw_if_c enabled.intervals.store(intervals); enabled.empty = false; } + enabled.requires_client_key = requires_client_key; } diff --git a/src/Access/QuotaCache.h b/src/Access/QuotaCache.h index 4c4cd955bac1..29df5ebe50b6 100644 --- a/src/Access/QuotaCache.h +++ b/src/Access/QuotaCache.h @@ -28,8 +28,7 @@ class QuotaCache const boost::container::flat_set & enabled_roles, const std::shared_ptr & address, const String & forwarded_address, - const String & client_key, - bool throw_if_client_key_empty); + const String & client_key); std::vector getAllQuotasUsage() const; @@ -42,7 +41,7 @@ class QuotaCache QuotaInfo(const QuotaPtr & quota_, const UUID & quota_id_) { setQuota(quota_, quota_id_); } void setQuota(const QuotaPtr & quota_, const UUID & quota_id_); - String calculateKey(const EnabledQuota & enabled_quota, bool throw_if_client_key_empty) const; + String calculateKey(const EnabledQuota & enabled_quota) const; boost::shared_ptr getOrBuildIntervals(const String & key); boost::shared_ptr rebuildIntervals(const String & key, std::chrono::system_clock::time_point current_time); void rebuildAllIntervals(); @@ -58,7 +57,7 @@ class QuotaCache void quotaRemoved(const UUID & quota_id); void chooseQuotaToConsume(); void chooseQuotaToConsumeIfNeeded(); - void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota, bool throw_if_client_key_empty); + void chooseQuotaToConsumeFor(EnabledQuota & enabled_quota); const AccessControl & access_control; mutable std::mutex mutex; diff --git a/src/Access/SettingsConstraints.cpp b/src/Access/SettingsConstraints.cpp index bb47d78c603f..dcf8d39879f0 100644 --- a/src/Access/SettingsConstraints.cpp +++ b/src/Access/SettingsConstraints.cpp @@ -287,6 +287,18 @@ void SettingsConstraints::clamp(const Settings & current_settings, SettingsChang }); } +void SettingsConstraints::clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const +{ + /// The surviving list is stored on the query node as the settings set explicitly on that node, + /// so a change equal to the current value must stay in the list. + std::erase_if( + changes, + [&](SettingChange & change) -> bool + { + return !checkImpl(current_settings, change, CLAMP_ON_VIOLATION_THROW_ON_INVALID, source, /*ignore_unchanged_settings=*/ true); + }); +} + /// The value a setting holds now. /// /// `Settings` keeps a `merge_tree_`-prefixed name as a custom setting, under the exact name that wrote it. @@ -321,13 +333,13 @@ Field castValueOfSetting(const String & name, const Field & value) } template -bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool throw_on_failure) +bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & change, Field & new_value, bool ignore_unchanged_settings, bool throw_on_failure) { Field current_value; bool has_current_value = getCurrentValueOfSetting(current_settings, change.name, current_value); /// Setting isn't checked if value has not changed. - if (has_current_value && change.value == current_value) + if (!ignore_unchanged_settings && has_current_value && change.value == current_value) return false; /// Put the value into the type of the setting. This throws when the value does not fit, as @@ -358,7 +370,7 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan /// stores a Bool, the same 1 in a query arrives as a UInt64, and comparing them as they are would /// make a change that keeps the value look like a real one. Field cast_current_value; - if (has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) + if (!ignore_unchanged_settings && has_current_value && cast_value(current_value, cast_current_value) && new_value == cast_current_value) return false; return true; @@ -367,14 +379,18 @@ bool getNewValueToCheck(const SettingsT & current_settings, SettingChange & chan bool SettingsConstraints::checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const + SettingSource source, + bool ignore_unchanged_settings) const { std::string_view setting_name = Settings::resolveName(change.name); if (setting_name == "profile") return true; - if (reaction == THROW_ON_VIOLATION) + /// Invalid changes (an unknown or disallowed name, an uncastable value) throw in every mode but `CLAMP_ON_VIOLATION`. + const bool throw_on_invalid_change = reaction != CLAMP_ON_VIOLATION; + + if (throw_on_invalid_change) { try { @@ -396,7 +412,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, return false; Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, ignore_unchanged_settings, /*throw_on_failure=*/ throw_on_invalid_change)) return false; return getChecker(current_settings, setting_name).check(change, new_value, reaction, source); @@ -405,7 +421,7 @@ bool SettingsConstraints::checkImpl(const Settings & current_settings, bool SettingsConstraints::checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const { Field new_value; - if (!getNewValueToCheck(current_settings, change, new_value, reaction == THROW_ON_VIOLATION)) + if (!getNewValueToCheck(current_settings, change, new_value, /*ignore_unchanged_settings=*/ false, reaction == THROW_ON_VIOLATION)) return false; if (isAnyTierRestricted()) @@ -422,9 +438,12 @@ bool SettingsConstraints::Checker::check(SettingChange & change, ReactionOnViolation reaction, SettingSource source) const { + /// Every reaction other than `THROW_ON_VIOLATION` clamps or drops a violating change. + const bool throw_on_violation = reaction == THROW_ON_VIOLATION; + if (!explain.text.empty()) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(explain, code); return false; } @@ -433,7 +452,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto less_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateLess(left, right); try { @@ -447,7 +466,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, auto equals_or_cannot_compare = [=](const Field & left, const Field & right) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) return accurateEquals(left, right); try { @@ -462,7 +481,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (constraint.writability == SettingConstraintWritability::CONST) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} should not be changed", setting_name); return false; } @@ -473,7 +492,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && !max_value.isNull() && less_or_cannot_compare(max_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception( ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "The maximum ({}) value is less than the minimum ({}) value for setting {}", @@ -485,7 +504,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!min_value.isNull() && less_or_cannot_compare(new_value, min_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be less than {}", setting_name, applyVisitor(FieldVisitorToString(), min_value)); @@ -495,7 +514,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!max_value.isNull() && less_or_cannot_compare(max_value, new_value)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) { throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be greater than {}", setting_name, applyVisitor(FieldVisitorToString(), max_value)); @@ -513,7 +532,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, if (!getSettingSourceRestrictions(setting_name).isSourceAllowed(source)) { - if (reaction == THROW_ON_VIOLATION) + if (throw_on_violation) throw Exception(ErrorCodes::READONLY, "Setting {} is not allowed to be set by {}", setting_name, toString(source)); return false; } diff --git a/src/Access/SettingsConstraints.h b/src/Access/SettingsConstraints.h index dc87368a62e2..2231cda9cfd6 100644 --- a/src/Access/SettingsConstraints.h +++ b/src/Access/SettingsConstraints.h @@ -95,8 +95,13 @@ class SettingsConstraints void check(const MergeTreeSettings & current_settings, const SettingsChanges & changes) const; /// Checks whether `change` violates these and clamps the `change` if so. + /// A change equal to the current value is dropped from `changes`. void clamp(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + /// Same as `clamp`, but an unknown or disallowed setting name and an uncastable value throw, as in `check`, + /// and a change equal to the current value is kept in `changes`. + void clampRejectingInvalidChanges(const Settings & current_settings, SettingsChanges & changes, SettingSource source) const; + friend bool operator ==(const SettingsConstraints & left, const SettingsConstraints & right); friend bool operator !=(const SettingsConstraints & left, const SettingsConstraints & right) { return !(left == right); } @@ -104,8 +109,12 @@ class SettingsConstraints private: enum ReactionOnViolation { + /// Any violation, an unknown name or an uncastable value throws. THROW_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value is dropped. CLAMP_ON_VIOLATION, + /// Violations are clamped or dropped; an unknown name or an uncastable value throws. + CLAMP_ON_VIOLATION_THROW_ON_INVALID, }; struct Constraint @@ -165,7 +174,8 @@ class SettingsConstraints bool checkImpl(const Settings & current_settings, SettingChange & change, ReactionOnViolation reaction, - SettingSource source) const; + SettingSource source, + bool ignore_unchanged_settings = false) const; bool checkImpl(const MergeTreeSettings & current_settings, SettingChange & change, ReactionOnViolation reaction) const; diff --git a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp index b1bf4f7edb96..7df726a74610 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp @@ -24,6 +24,8 @@ #include +#include + #include constexpr size_t AGGREGATE_FUNCTION_GROUP_ARRAY_MAX_ELEMENT_SIZE = 0xFFFFFF; @@ -90,6 +92,17 @@ struct GroupArraySamplerData size_t total_values = 0; pcg32_fast rng; + /// The counter may come from a deserialized state, so it can be arbitrarily large, + /// and wrapping it around would make `genRandom` divide by zero. + void addTotalValues(UInt64 count) + { + UInt64 new_total_values = 0; + if (common::addOverflow(static_cast(total_values), count, new_total_values)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The number of values in groupArraySample state overflows: {} + {}", total_values, count); + total_values = new_total_values; + } + UInt64 genRandom(size_t lim) { chassert(lim != 0); @@ -160,7 +173,7 @@ class GroupArrayNumericImpl final void insertWithSampler(Data & a, const T & v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v, arena); else @@ -183,7 +196,10 @@ class GroupArrayNumericImpl final const auto & row_value = assert_cast &>(*columns[0]).getData()[row_num]; auto & cur_elems = this->data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -275,8 +291,8 @@ class GroupArrayNumericImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); @@ -525,7 +541,7 @@ class GroupArrayGeneralImpl final void insertWithSampler(Data & a, const Node * v, Arena * arena) const { - ++a.total_values; + a.addTotalValues(1); if (a.value.size() < max_elems) a.value.push_back(v->clone(arena), arena); else @@ -547,7 +563,10 @@ class GroupArrayGeneralImpl final { auto & cur_elems = data(place); - ++cur_elems.total_values; + if constexpr (Trait::sampler == Sampler::NONE) + ++cur_elems.total_values; + else + cur_elems.addTotalValues(1); if constexpr (Trait::sampler == Sampler::NONE) { @@ -642,8 +661,8 @@ class GroupArrayGeneralImpl final } else { + cur_elems.addTotalValues(rhs_elems.total_values); cur_elems.randomShuffle(); - cur_elems.total_values += rhs_elems.total_values; for (size_t i = 0; i < max_elems; ++i) { UInt64 rnd = cur_elems.genRandom(cur_elems.total_values); diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp index 8c61d13923ca..610937b52f5f 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.cpp @@ -61,8 +61,14 @@ void forEachSecretArgumentNode( continue; } + if (const auto masked = secret_arguments.masked_arguments.find(n); masked != secret_arguments.masked_arguments.end()) + { + on_secret(n, masked->second ? secretValueSlot(arguments[n]) : arguments[n]); + continue; + } + const bool in_span = secret_arguments.start <= n && n < secret_arguments.start + secret_arguments.count; - if (in_span || secret_arguments.masked_arguments.contains(n) || secret_arguments.replaced_arguments.contains(n)) + if (in_span || secret_arguments.replaced_arguments.contains(n)) on_secret(n, secretValueSlot(arguments[n])); } } diff --git a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h index 6afdd5d3a952..ecd7322afc29 100644 --- a/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h +++ b/src/Analyzer/FunctionSecretArgumentsFinderTreeNode.h @@ -122,7 +122,8 @@ using FunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeN using TableFunctionSecretArgumentsFinderTreeNode = FunctionSecretArgumentsFinderTreeNodeImpl; /// Visits the secret value slots selected by a finder result in a resolved argument list, for the -/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members and the arguments +/// query-tree surfaces (`EXPLAIN QUERY TREE`, projection names): the span members, the individually +/// masked arguments (whole, unless masked as a named `key = value`) and the arguments /// with a partial replacement (for a `key = value` argument, its value; a tree dump cannot represent /// partial masking, so the whole value is masked: fail closed), and the values of the nested secret /// maps (`headers(..)` / `extra_credentials(..)`; a malformed child is visited whole). The callback diff --git a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp index 44c9ee3df51b..b95cc0fd9410 100644 --- a/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp +++ b/src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp @@ -550,6 +550,10 @@ std::tuple getTypedNodesForOptimizati if (!storage->supportsOptimizationToSubcolumns() || storage->isVirtualColumn(column.name, storage_snapshot->metadata)) return {}; + /// Without buckets the key subcolumn `m.key_` reads the whole Map, so `m['key']` is not rewritten to it. + if (function_node->getFunctionName() == "arrayElement" && isMap(column.type) && !storage->hasBucketedMapSerialization()) + return {}; + auto column_in_table = storage_snapshot->tryGetColumn(GetColumnsOptions(GetColumnsOptions::All).withSubcolumns(), column.name); if (!column_in_table || !column_in_table->type->equals(*column.type)) return {}; diff --git a/src/Analyzer/QueryTreeBuilder.cpp b/src/Analyzer/QueryTreeBuilder.cpp index 285edf278e72..16cab878c838 100644 --- a/src/Analyzer/QueryTreeBuilder.cpp +++ b/src/Analyzer/QueryTreeBuilder.cpp @@ -302,22 +302,28 @@ QueryTreeNodePtr QueryTreeBuilder::buildSelectExpression( set_query.changes.removeSetting("offset"); } - /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) used to be applied to - /// the per-node context unchecked, letting a user override `readonly`, `CONST` and `MIN`/`MAX` - /// constraints - e.g. `additional_table_filters`, which the Planner reads from this context. - /// Clamp it instead of throwing, as done for other settings crossing execution contexts - /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are - /// dropped, out-of-bounds values are clamped, so a view whose inner clause violates the - /// reader's constraints keeps working. A top-level clause still throws - /// (`applySettingsFromQuery`). Clamp a copy: the `QueryNode` keeps the clause as written, so - /// the tree's AST and hash are unchanged, and every node executing the subquery clamps it - /// against its own constraints. `SETTINGS name = DEFAULT` stays ignored here - see #115415. + /// A nested `SETTINGS` clause (a subquery, a CTE, a view's inner query) is clamped to the session's + /// settings constraints, as done for other settings crossing execution contexts + /// (`getSQLSecurityOverriddenContext`, secondary queries, DDL replay): violating changes are dropped, + /// out-of-bounds values are clamped, so a view whose inner clause violates the reader's constraints + /// keeps working. A top-level clause still throws (`applySettingsFromQuery`). An unknown name or an + /// uncastable value throws as for a top-level clause, on every server that executes the query. The + /// node records the effective `changes`: the ones that survive, with their clamped values and the + /// literals as written, so `toAST`, the tree hash, the `Planner` and the shards receiving the + /// subquery see what was applied. `SETTINGS name = DEFAULT` stays ignored here - see #115415. if (!set_query.changes.empty()) { - auto checked_changes = set_query.changes; - updated_context->clampToSettingsConstraints(checked_changes, SettingSource::QUERY); - updated_context->applySettingsChanges(checked_changes); - settings_changes = set_query.changes; + /// One change at a time, so that each is clamped against the context as the preceding changes + /// left it. Clamping the whole clause as a batch checks every change against the context as it + /// was before the clause - so `SETTINGS use_query_cache = 1, use_query_cache = 0` could resolve + /// differently from the last-wins reading the clause has everywhere else. + for (const auto & change : set_query.changes) + { + SettingsChanges single_change{change}; + updated_context->clampToSettingsConstraintsRejectingInvalidChanges(single_change, SettingSource::QUERY); + updated_context->applySettingsChanges(single_change); + settings_changes.insert(settings_changes.end(), single_change.begin(), single_change.end()); + } } } diff --git a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp index e5ec3cc7c4e1..56109118b128 100644 --- a/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp +++ b/src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp @@ -114,7 +114,7 @@ void QueryAnalyzer::evaluateScalarSubqueryIfNeeded(QueryTreeNodePtr & node, Iden scalar_block = scalars_cache.at(node_with_hash); } - else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasScalar(str_hash)) + else if (context->hasQueryContext() && can_use_global_scalars && context->getQueryContext()->hasComputedScalar(str_hash)) { scalar_block = context->getQueryContext()->getScalar(str_hash); scalar_subquery_to_scalar_value_global.emplace(node_with_hash, scalar_block); diff --git a/src/Backups/BackupIO_AzureBlobStorage.cpp b/src/Backups/BackupIO_AzureBlobStorage.cpp index eb2126f1dd9f..cd08f6e339e3 100644 --- a/src/Backups/BackupIO_AzureBlobStorage.cpp +++ b/src/Backups/BackupIO_AzureBlobStorage.cpp @@ -2,6 +2,7 @@ #include #if USE_AZURE_BLOB_STORAGE +#include #include #include #include @@ -29,6 +30,17 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +namespace +{ + /// An Azure disk configured with `connection_string` is described by that whole string. + String maskedDescription(const DataSourceDescription & description) + { + String result = description.description; + maskAzureConnectionStringSecrets(result); + return result; + } +} + BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const AzureBlobStorage::ConnectionParams & connection_params_, const String & blob_path_, @@ -37,7 +49,7 @@ BackupReaderAzureBlobStorage::BackupReaderAzureBlobStorage( const WriteSettings & write_settings_, const ContextPtr & context_) : BackupReaderDefault(read_settings_, write_settings_, getLogger("BackupReaderAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -85,7 +97,7 @@ void BackupReaderAzureBlobStorage::copyFileToDisk(const String & path_in_backup, DiskPtr destination_disk, const String & destination_path, WriteMode write_mode) { auto destination_data_source_description = destination_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, destination_data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", data_source_description.description, maskedDescription(destination_data_source_description)); if (destination_data_source_description.object_storage_type == ObjectStorageType::Azure && destination_data_source_description.is_encrypted == encrypted_in_backup) { @@ -132,7 +144,7 @@ BackupWriterAzureBlobStorage::BackupWriterAzureBlobStorage( const ContextPtr & context_, bool attempt_to_create_container) : BackupWriterDefault(read_settings_, write_settings_, getLogger("BackupWriterAzureBlobStorage")) - , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURL(), false, false, ""} + , data_source_description{DataSourceType::ObjectStorage, ObjectStorageType::Azure, MetadataStorageType::None, connection_params_.getConnectionURLWithoutQuery(), false, false, ""} , connection_params(connection_params_) , blob_path(blob_path_) { @@ -162,7 +174,7 @@ void BackupWriterAzureBlobStorage::copyFileFromDisk( { /// Use the native copy as a more optimal way to copy a file from AzureBlobStorage to AzureBlobStorage if it's possible. auto source_data_source_description = src_disk->getDataSourceDescription(); - LOG_TRACE(log, "Source description {}, destination description {}", source_data_source_description.description, data_source_description.description); + LOG_TRACE(log, "Source description {}, destination description {}", maskedDescription(source_data_source_description), data_source_description.description); if (source_data_source_description.object_storage_type == ObjectStorageType::Azure && source_data_source_description.is_encrypted == copy_encrypted) { diff --git a/src/Backups/BackupMetadataFinder.cpp b/src/Backups/BackupMetadataFinder.cpp index 46115481a708..4b3534b9b24b 100644 --- a/src/Backups/BackupMetadataFinder.cpp +++ b/src/Backups/BackupMetadataFinder.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -287,6 +288,16 @@ void BackupMetadataFinder::findTableInBackupImpl( ParserCreateQuery create_parser; ASTPtr create_table_query = parseQuery(create_parser, create_query_str, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + /// `BACKUP` writes the full definition, without `AS` (see `cleanupObjectDefinitionFromTemporaryFlags`). A definition that + /// inherits its engine with `AS` would let the access check of the restore see no engine, so it is rejected. + if (const auto & create = create_table_query->as(); !create.as_table.empty()) + throw Exception( + ErrorCodes::CANNOT_RESTORE_TABLE, + "The definition of {} in the backup uses AS {}, which BACKUP never writes", + tableNameWithTypeToString(table_name_in_backup.database, table_name_in_backup.table, false), + backQuoteIfNeed(create.as_table)); + applyCustomStoragePolicy(create_table_query); renameDatabaseAndTableNameInCreateQuery(create_table_query, renaming_map, context->getGlobalContext()); String create_table_query_str = create_table_query->formatWithSecretsOneLine(); diff --git a/src/Backups/RestorerFromBackup.cpp b/src/Backups/RestorerFromBackup.cpp index b1cfe0451a94..5c47fd9cea18 100644 --- a/src/Backups/RestorerFromBackup.cpp +++ b/src/Backups/RestorerFromBackup.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,7 @@ namespace Setting extern const SettingsUInt64 backup_restore_keeper_max_retries; extern const SettingsSeconds lock_acquire_timeout; extern const SettingsBool restore_replicated_merge_tree_to_shared_merge_tree; + extern const SettingsBool restore_replace_external_engines_to_null; } namespace ErrorCodes @@ -276,6 +278,7 @@ void RestorerFromBackup::loadSystemAccessTables() void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const { AccessRightsElements required_access; + AccessRights required_access_rights; { std::lock_guard lock{mutex}; @@ -310,7 +313,17 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const continue; } - if (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE) + const ASTCreateQuery & create = table_info.create_table_query->as(); + const bool is_temporary = (table_name.database == DatabaseCatalog::TEMPORARY_DATABASE); + + /// The definition comes from the backup, and the table is created by an internal query that checks + /// nothing, so settings that send the data elsewhere are authorized here, as for `CREATE`. + /// An external engine replaced by `Null` sends nothing, but temporary tables keep their engine. + if (restore_settings.create_table != RestoreTableCreationMode::kMustExist + && (is_temporary || !context->getSettingsRef()[Setting::restore_replace_external_engines_to_null])) + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + + if (is_temporary) { if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) required_access.emplace_back(AccessType::CREATE_TEMPORARY_TABLE); @@ -318,7 +331,6 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const } AccessFlags flags; - const ASTCreateQuery & create = table_info.create_table_query->as(); if (restore_settings.create_table != RestoreTableCreationMode::kMustExist) { @@ -346,15 +358,12 @@ void RestorerFromBackup::checkAccessForObjectsFoundInBackup() const required_access.emplace_back(flags, table_name.database, table_name.table); } + required_access_rights = AccessRights{required_access}; + /// Partial revokes in restored grants must not remove the rights required to restore other objects. if (access_restorer) - insertAtEnd(required_access, access_restorer->getRequiredAccess()); + required_access_rights.makeUnion(access_restorer->getRequiredAccess()); } - /// We convert to AccessRights to check if we have the rights contained in our current access. - /// This handles the situation when restoring partial revoked grants: - /// GRANT SELECT ON *.* - /// REVOKE SELECT FROM systems.* - const auto & required_access_rights = AccessRights{required_access}; const auto & current_user_access_rights = context->getAccess()->getAccessRightsWithImplicit(); if (current_user_access_rights->contains(required_access_rights)) return; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 88dcaa1fa6ab..469b3b3ad16f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -359,6 +359,10 @@ if (USE_PARQUET) add_object_library(clickhouse_processors_formats_impl_parquet Processors/Formats/Impl/Parquet) endif() +if (USE_ORC) + add_object_library(clickhouse_processors_formats_impl_orc Processors/Formats/Impl/ORC) +endif() + if (TARGET ch_contrib::nuraft) add_object_library(clickhouse_coordination Coordination) endif() @@ -642,11 +646,6 @@ endif() target_link_libraries (clickhouse_common_io PUBLIC ch_contrib::fast_float) -if (USE_ORC) - target_link_libraries(dbms PUBLIC ${ORC_LIBRARIES}) - target_include_directories(dbms SYSTEM BEFORE PUBLIC ${ORC_INCLUDE_DIR} "${PROJECT_BINARY_DIR}/contrib/orc/c++/include") -endif () - if (TARGET ch_contrib::rocksdb) target_link_libraries(dbms PUBLIC ch_contrib::rocksdb) endif() @@ -773,6 +772,10 @@ if (ENABLE_TESTS) clickhouse_common_config clickhouse_common_zookeeper) + if (TARGET ch_contrib::brotli) + target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::brotli) + endif() + if (TARGET ch_contrib::simdjson) target_link_libraries(unit_tests_dbms PRIVATE ch_contrib::simdjson) endif() diff --git a/src/Client/ClientBase.cpp b/src/Client/ClientBase.cpp index dfa4234f2042..aa2e00344b73 100644 --- a/src/Client/ClientBase.cpp +++ b/src/Client/ClientBase.cpp @@ -3582,13 +3582,13 @@ void ClientBase::runInteractive() #if USE_REPLXX - replxx::Replxx::highlighter_callback_with_pos_t highlight_callback{}; + ReplxxLineReader::Highlighter highlight_callback{}; if (getClientConfiguration().getBool("highlight", true)) { - highlight_callback = [this](const String & query, std::vector & colors, int pos) + highlight_callback = [this](const String & query, std::vector & colors, int pos, bool & last_is_delimiter) { - highlight(query, colors, *client_context, pos); + highlight(query, colors, *client_context, pos, &last_is_delimiter); }; } diff --git a/src/Client/ClientBaseHelpers.cpp b/src/Client/ClientBaseHelpers.cpp index 3955d1d8edf2..28e01896beb4 100644 --- a/src/Client/ClientBaseHelpers.cpp +++ b/src/Client/ClientBaseHelpers.cpp @@ -155,7 +155,7 @@ static size_t countCodePointsWithSeqLength(const String & query, const char * en return code_points; } -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position) +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter) { using namespace replxx; @@ -512,14 +512,16 @@ void highlight(const String & query, std::vector & colors } /// This is a callback for the client/local app to better find query end. Note: this is a kludge, remove it. + if (!last_is_delimiter) + return; if (last_token.type == TokenType::Semicolon || last_token.type == TokenType::VerticalDelimiter || query.ends_with(';') || query.ends_with("\\G")) /// This is for raw data in INSERT queries, which is not necessarily tokenized. { - ReplxxLineReader::setLastIsDelimiter(true); + *last_is_delimiter = true; } else if (last_token.type != TokenType::Whitespace) { - ReplxxLineReader::setLastIsDelimiter(false); + *last_is_delimiter = false; } } @@ -528,7 +530,7 @@ String highlighted(const String & query, const Context & context) const size_t num_code_points = countCodePointsWithSeqLength(query, query.data() + query.size()); std::vector colors(num_code_points, replxx::Replxx::Color::DEFAULT); - highlight(query, colors, context, 0); + highlight(query, colors, context, 0, nullptr); String res; size_t query_size = query.size(); diff --git a/src/Client/ClientBaseHelpers.h b/src/Client/ClientBaseHelpers.h index 4e41e605f3f7..ad02976550df 100644 --- a/src/Client/ClientBaseHelpers.h +++ b/src/Client/ClientBaseHelpers.h @@ -24,7 +24,9 @@ std::string getChineseZodiac(); bool isCloudEndpoint(const std::string & host); #if USE_REPLXX -void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position); +/// If `last_is_delimiter` is not null, it is set to whether the query ends with a delimiter (and left +/// intact if the query ends with whitespace). +void highlight(const String & query, std::vector & colors, const Context & context, int cursor_position, bool * last_is_delimiter); String highlighted(const String & query, const Context & context); #endif diff --git a/src/Client/ReplxxLineReader.cpp b/src/Client/ReplxxLineReader.cpp index 14842dbfd77e..c909f14beb44 100644 --- a/src/Client/ReplxxLineReader.cpp +++ b/src/Client/ReplxxLineReader.cpp @@ -286,12 +286,6 @@ void convertHistoryFile(const std::string & path, replxx::Replxx & rx) namespace DB { -static bool replxx_last_is_delimiter = false; -void ReplxxLineReader::setLastIsDelimiter(bool flag) -{ - replxx_last_is_delimiter = flag; -} - ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) : LineReader ( @@ -360,7 +354,12 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) rx.set_indent_multiline(false); if (highlighter) - rx.set_highlighter_callback(highlighter); + { + rx.set_highlighter_callback([this](const String & query, std::vector & colors, int cursor_position) + { + highlighter(query, colors, cursor_position, last_is_delimiter); + }); + } /// By default C-p/C-n bound to COMPLETE_NEXT/COMPLETE_PREV, /// bind C-p/C-n to history-previous/history-next like readline. @@ -376,9 +375,9 @@ ReplxxLineReader::ReplxxLineReader(ReplxxLineReader::Options && options) { /// If we allow multiline and there is already something in the input, start a newline. /// NOTE: Lexer is only available if we use highlighter. - if (highlighter && multiline && !replxx_last_is_delimiter) + if (highlighter && multiline && !last_is_delimiter) return rx.invoke(Replxx::ACTION::NEW_LINE, code); - replxx_last_is_delimiter = false; + last_is_delimiter = false; return rx.invoke(Replxx::ACTION::COMMIT_LINE, code); }; /// bind C-j to ENTER action. diff --git a/src/Client/ReplxxLineReader.h b/src/Client/ReplxxLineReader.h index cdaa5cab6be1..0dae383f8d53 100644 --- a/src/Client/ReplxxLineReader.h +++ b/src/Client/ReplxxLineReader.h @@ -12,6 +12,11 @@ namespace DB class ReplxxLineReader : public LineReader { public: + /// The highlighter callback of replxx, which also reports whether the last token of the + /// query is a delimiter: it sets `last_is_delimiter` to true or false, or leaves it intact + /// when this cannot be determined (e.g. the query ends with whitespace). + using Highlighter = std::function & colors, int cursor_position, bool & last_is_delimiter)>; + struct Options { Suggest & suggest; @@ -24,7 +29,7 @@ class ReplxxLineReader : public LineReader Patterns extenders; Patterns delimiters; std::span word_break_characters; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; std::istream & input_stream = std::cin; std::ostream & output_stream = std::cout; int in_fd = STDIN_FILENO; @@ -38,10 +43,6 @@ class ReplxxLineReader : public LineReader void enableBracketedPaste() override; void disableBracketedPaste() override; - /// If highlight is on, we will set a flag to denote whether the last token is a delimiter. - /// This is useful to determine the behavior of key when multiline is enabled. - static void setLastIsDelimiter(bool flag); - /// Set text to be prepopulated in the next readLine call void setInitialText(const String & text) override; private: @@ -51,7 +52,13 @@ class ReplxxLineReader : public LineReader void openEditor(bool format_query); replxx::Replxx rx; - replxx::Replxx::highlighter_callback_with_pos_t highlighter; + Highlighter highlighter; + + /// If highlight is on, the highlighter reports whether the last token is a delimiter. + /// This is used to determine the behavior of key when multiline is enabled. + /// It is a member rather than a global, because several readers can work concurrently + /// in one process (client sessions embedded into the server). + bool last_is_delimiter = false; const char * word_break_characters; diff --git a/src/Columns/ColumnArray.cpp b/src/Columns/ColumnArray.cpp index d572873dca0b..b1bc0921a153 100644 --- a/src/Columns/ColumnArray.cpp +++ b/src/Columns/ColumnArray.cpp @@ -978,17 +978,17 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi memset(&nested_filt[offsetAt(i)], 0, sizeAt(i)); } - auto res = ColumnArray::create(data->cloneEmpty()); - ssize_t nested_result_size_hint = 0; if (result_size_hint < 0) nested_result_size_hint = result_size_hint; else if (result_size_hint && result_size_hint < 1000000000 && data->size() < 1000000000) /// Avoid overflow. nested_result_size_hint = result_size_hint * data->size() / size; - res->data = data->filter(nested_filt, nested_result_size_hint); + /// See the comment in `indexImpl` about building the nested result first. + ColumnPtr res_data = data->filter(nested_filt, nested_result_size_hint); - Offsets & res_offsets = res->getOffsets(); + auto res_offsets_column = ColumnOffsets::create(); + Offsets & res_offsets = res_offsets_column->getData(); if (result_size_hint) res_offsets.reserve_exact(result_size_hint > 0 ? result_size_hint : size); @@ -1002,7 +1002,7 @@ ColumnPtr ColumnArray::filterGeneric(const Filter & filt, ssize_t result_size_hi } } - return res; + return ColumnArray::create(res_data, std::move(res_offsets_column)); } ColumnPtr ColumnArray::filterNullable(const Filter & filt, ssize_t result_size_hint) const @@ -1236,10 +1236,8 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit PaddedPODArray & nested_indexes = nested_indexes_column->getData(); nested_indexes.reserve_exact(getOffsets().back()); - auto res = ColumnArray::create(data->cloneEmpty()); - - Offsets & res_offsets = res->getOffsets(); - res_offsets.resize_exact(limit); + auto res_offsets_column = ColumnOffsets::create(limit); + Offsets & res_offsets = res_offsets_column->getData(); size_t current_offset = 0; for (size_t i = 0; i < limit; ++i) @@ -1250,10 +1248,10 @@ ColumnPtr ColumnArray::indexImpl(const PaddedPODArray & indexes, size_t limit res_offsets[i] = current_offset; } - if (current_offset != 0) - res->data = data->index(*nested_indexes_column, current_offset); - - return res; + /// Build the nested result first: an empty clone of `data` copies its whole nested structure, which for + /// `Dynamic` is as deep as the data, and every level of this recursion would hold one. + ColumnPtr res_data = current_offset != 0 ? data->index(*nested_indexes_column, current_offset) : data->cloneEmpty(); + return ColumnArray::create(res_data, std::move(res_offsets_column)); } INSTANTIATE_INDEX_IMPL(ColumnArray) diff --git a/src/Columns/ColumnDynamic.cpp b/src/Columns/ColumnDynamic.cpp index 59ed075737df..446f5c38042e 100644 --- a/src/Columns/ColumnDynamic.cpp +++ b/src/Columns/ColumnDynamic.cpp @@ -314,6 +314,8 @@ void ColumnDynamic::get(size_t n, Field & res) const void ColumnDynamic::getValueNameImpl(WriteBufferFromOwnString & name_buf, size_t n, const Options & options) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); /// Check if value is not in shared variant. if (variant_col.globalDiscriminatorAt(n) != getSharedVariantDiscriminator()) @@ -338,6 +340,8 @@ void ColumnDynamic::insertFrom(const IColumn & src_, size_t n) void ColumnDynamic::doInsertFrom(const IColumn & src_, size_t n) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); /// Same variants: copy the Variant column directly. Skip this fast path when the source has values in @@ -417,6 +421,8 @@ void ColumnDynamic::insertRangeFrom(const IColumn & src_, size_t start, size_t l void ColumnDynamic::doInsertRangeFrom(const IColumn & src_, size_t start, size_t length) #endif { + checkStackSize(); + if (start + length > src_.size()) throw Exception(ErrorCodes::PARAMETER_OUT_OF_BOUND, "Parameter out of bound in ColumnDynamic::insertRangeFrom method. " "[start({}) + length({}) > src.size()({})]", start, length, src_.size()); @@ -649,6 +655,8 @@ void ColumnDynamic::insertManyFrom(const IColumn & src_, size_t position, size_t void ColumnDynamic::doInsertManyFrom(const IColumn & src_, size_t position, size_t length) #endif { + checkStackSize(); + const auto & dynamic_src = assert_cast(src_); auto & variant_col = getVariantColumn(); @@ -862,6 +870,8 @@ void ColumnDynamic::skipSerializedInArena(ReadBuffer & in) const void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const { + checkStackSize(); + const auto & variant_col = getVariantColumn(); auto discr = variant_col.globalDiscriminatorAt(n); if (discr == ColumnVariant::NULL_DISCRIMINATOR) @@ -892,6 +902,7 @@ void ColumnDynamic::updateHashWithValue(size_t n, SipHash & hash) const void ColumnDynamic::updateHashWithValueRange(size_t begin, size_t end, SipHash & hash) const { + checkStackSize(); variant_column_ptr->updateHashWithValueRange(begin, end, hash); } @@ -901,6 +912,8 @@ int ColumnDynamic::compareAt(size_t n, size_t m, const IColumn & rhs, int nan_di int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_direction_hint) const #endif { + checkStackSize(); + const auto & left_variant = getVariantColumn(); const auto & right_dynamic = assert_cast(rhs); const auto & right_variant = right_dynamic.getVariantColumn(); @@ -1050,6 +1063,7 @@ void ColumnDynamic::updatePermutation(IColumn::PermutationSortDirection directio ColumnPtr ColumnDynamic::compress(bool force_compression) const { + checkStackSize(); ColumnPtr variant_compressed = variant_column_ptr->compress(force_compression); size_t byte_size = variant_compressed->byteSize(); return ColumnCompressed::create(size(), byte_size, @@ -1061,6 +1075,7 @@ ColumnPtr ColumnDynamic::compress(bool force_compression) const ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const { + checkStackSize(); std::unordered_map variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) variants_checkpoints[name] = variant_column_ptr->getVariantByGlobalDiscriminator(discr).getCheckpoint(); @@ -1069,6 +1084,7 @@ ColumnCheckpointPtr ColumnDynamic::getCheckpoint() const void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const { + checkStackSize(); auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; for (const auto & [name, discr] : variant_info.variant_name_to_discriminator) @@ -1086,6 +1102,7 @@ void ColumnDynamic::updateCheckpoint(ColumnCheckpoint & checkpoint) const void ColumnDynamic::rollback(const ColumnCheckpoint & checkpoint) { + checkStackSize(); const auto & variants_checkpoints = assert_cast(checkpoint).variants_checkpoints; /// Manually rollback internals of Variant column @@ -1158,6 +1175,7 @@ void ColumnDynamic::getAllTypeNamesInto(UnorderedSetWithMemoryTracking & void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); if (source_columns.empty()) return; @@ -1181,6 +1199,7 @@ void ColumnDynamic::prepareForSquashing(const Columns & source_columns, size_t f void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, size_t factor) { + checkStackSize(); /// Internal variants of source dynamic columns may differ. /// We want to preallocate memory for all variants we will have after squashing. /// It may happen that the total number of variants in source columns will @@ -1288,6 +1307,8 @@ void ColumnDynamic::prepareVariantsForSquashing(const Columns & source_columns, bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const { + checkStackSize(); + if (const auto * rhs_concrete = typeid_cast(&rhs)) return max_dynamic_types == rhs_concrete->max_dynamic_types && global_max_dynamic_types == rhs_concrete->global_max_dynamic_types && variant_info.variant_name == rhs_concrete->variant_info.variant_name @@ -1297,6 +1318,8 @@ bool ColumnDynamic::dynamicStructureEquals(const IColumn & rhs) const void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_columns, std::optional max_dynamic_subcolumns) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "chooseDynamicStructureForMerge should be called only on empty Dynamic column"); @@ -1431,6 +1454,8 @@ void ColumnDynamic::chooseDynamicStructureForMerge(const Columns & source_column void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) { + checkStackSize(); + if (!empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "takeExactDynamicStructureFrom should be called only on empty Dynamic column"); @@ -1453,6 +1478,8 @@ void ColumnDynamic::takeExactDynamicStructureFrom(const IColumn & source) void ColumnDynamic::fixDynamicStructure() { + checkStackSize(); + /// Reduce max_dynamic_types to the number of selected variants, so there will be no possibility /// to extend selected variants on inserts into this column. /// -1 because we don't count shared variant in the limit. @@ -1487,6 +1514,8 @@ ColumnDynamic::StatisticsPtr ColumnDynamic::getOrCalculateStatistics() const void ColumnDynamic::takeOrCalculateStatisticsFrom(const Columns & source_columns) { + checkStackSize(); + /// Assumes dynamic structure has already been set by `takeExactDynamicStructureFrom` or `chooseDynamicStructureForMerge`. Statistics new_statistics; /// Collect total sizes for variants that are not in our structure (candidates for shared variant statistics). diff --git a/src/Columns/ColumnDynamic.h b/src/Columns/ColumnDynamic.h index cac25ec194e5..594512677430 100644 --- a/src/Columns/ColumnDynamic.h +++ b/src/Columns/ColumnDynamic.h @@ -7,6 +7,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,10 @@ namespace DB * When the limit on number of dynamic types is exceeded, all values * with new types are inserted into special shared variant with type String * that contains values and their types in binary format. + * + * Values nest into each other through variants like Array(Dynamic) to a depth that comes + * from the data, not from the declared type, so methods that recurse into the Variant + * column call checkStackSize. */ class ColumnDynamic final : public COWHelper, ColumnDynamic> { @@ -116,12 +121,14 @@ class ColumnDynamic final : public COWHelper, Colum MutableColumnPtr cloneEmpty() const override { + checkStackSize(); /// Keep current dynamic structure return Base::create(variant_column->cloneEmpty(), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumnPtr cloneResized(size_t size) const override { + checkStackSize(); return Base::create(variant_column->cloneResized(size), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } @@ -181,6 +188,7 @@ class ColumnDynamic final : public COWHelper, Colum void popBack(size_t n) override { + checkStackSize(); variant_column_ptr->popBack(n); } @@ -204,42 +212,50 @@ class ColumnDynamic final : public COWHelper, Colum void updateHashFast(SipHash & hash) const override { + checkStackSize(); variant_column_ptr->updateHashFast(hash); } ColumnPtr filter(const Filter & filt, ssize_t result_size_hint) const override { + checkStackSize(); return create(variant_column_ptr->filter(filt, result_size_hint), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } void filter(const Filter & filt) override { + checkStackSize(); variant_column_ptr->filter(filt); statistics.reset(); } void expand(const Filter & mask, bool inverted) override { + checkStackSize(); variant_column_ptr->expand(mask, inverted); } ColumnPtr permute(const Permutation & perm, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->permute(perm, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr index(const IColumn & indexes, size_t limit) const override { + checkStackSize(); return create(variant_column_ptr->index(indexes, limit), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } ColumnPtr replicate(const Offsets & replicate_offsets) const override { + checkStackSize(); return create(variant_column_ptr->replicate(replicate_offsets), variant_info, max_dynamic_types, global_max_dynamic_types, statistics); } MutableColumns scatter(size_t num_columns, const Selector & selector) const override { + checkStackSize(); MutableColumns scattered_variant_columns = variant_column_ptr->scatter(num_columns, selector); MutableColumns scattered_columns; scattered_columns.reserve(num_columns); @@ -257,6 +273,7 @@ class ColumnDynamic final : public COWHelper, Colum bool hasEqualValues() const override { + checkStackSize(); return variant_column_ptr->hasEqualValues(); } @@ -287,31 +304,37 @@ class ColumnDynamic final : public COWHelper, Colum void shrinkToFit() override { + checkStackSize(); variant_column_ptr->shrinkToFit(); } void ensureOwnership() override { + checkStackSize(); variant_column_ptr->ensureOwnership(); } size_t byteSize() const override { + checkStackSize(); return variant_column_ptr->byteSize(); } size_t byteSizeAt(size_t n) const override { + checkStackSize(); return variant_column_ptr->byteSizeAt(n); } size_t allocatedBytes() const override { + checkStackSize(); return variant_column_ptr->allocatedBytes(); } void protect() override { + checkStackSize(); variant_column_ptr->protect(); } @@ -323,11 +346,17 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumn(MutableColumnCallback callback) override { + /// Callers like IColumn::mutate recurse into the subcolumns through this method. + checkStackSize(); callback(variant_column); variant_column_ptr = assert_cast(variant_column.get()); } - void forEachSubcolumn(ColumnCallback callback) const override { callback(variant_column); } + void forEachSubcolumn(ColumnCallback callback) const override + { + checkStackSize(); + callback(variant_column); + } /// Dynamic columns manage their own variant_info type metadata. /// The default convertToFullIfNeeded recurses into subcolumns and strips LowCardinality @@ -337,6 +366,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachMutableSubcolumnRecursively(RecursiveMutableColumnCallback callback) override { + checkStackSize(); callback(*variant_column); variant_column_ptr = assert_cast(variant_column.get()); variant_column->forEachMutableSubcolumnRecursively(callback); @@ -344,6 +374,7 @@ class ColumnDynamic final : public COWHelper, Colum void forEachSubcolumnRecursively(RecursiveColumnCallback callback) const override { + checkStackSize(); callback(*variant_column); variant_column->forEachSubcolumnRecursively(callback); } @@ -374,11 +405,13 @@ class ColumnDynamic final : public COWHelper, Colum void finalize() override { + checkStackSize(); variant_column_ptr->finalize(); } bool isFinalized() const override { + checkStackSize(); return variant_column_ptr->isFinalized(); } diff --git a/src/Columns/ColumnLowCardinality.cpp b/src/Columns/ColumnLowCardinality.cpp index 9a76fde596b9..a6540dbf60c3 100644 --- a/src/Columns/ColumnLowCardinality.cpp +++ b/src/Columns/ColumnLowCardinality.cpp @@ -234,7 +234,7 @@ void ColumnLowCardinality::insertRangeFromFullColumn(const IColumn & src, size_t idx.insertIndexesRange(*inserted_indexes, 0, length); } -static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) +void ColumnLowCardinality::checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) { auto check_for_type = [&](auto type) { @@ -248,14 +248,14 @@ static void checkIndexesAreLimited(const IColumn & indexes, UInt64 limit) size_t num_rows = data.size(); if (num_rows == 0) return true; - UInt64 max_position = 0; + ColumnType max_position = 0; for (size_t i = 0; i < num_rows; ++i) - max_position = std::max(max_position, data[i]); + max_position = std::max(max_position, data[i]); - if (max_position >= limit) + if (static_cast(max_position) >= limit) throw Exception(ErrorCodes::INCORRECT_DATA, "Index for LowCardinality is out of range. Dictionary size is {}, " - "but found index with value {}", limit, max_position); + "but found index with value {}", limit, static_cast(max_position)); return true; }; diff --git a/src/Columns/ColumnLowCardinality.h b/src/Columns/ColumnLowCardinality.h index 8538b4cededf..d03921bef1fe 100644 --- a/src/Columns/ColumnLowCardinality.h +++ b/src/Columns/ColumnLowCardinality.h @@ -94,6 +94,7 @@ class ColumnLowCardinality final : public COWHelper +#include #include #include #include @@ -16,6 +17,12 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace FailPoints +{ + extern const char reverse_index_build_index_throw[]; } template @@ -432,17 +439,25 @@ void ReverseIndex::buildIndex() if (!column) throw Exception(ErrorCodes::LOGICAL_ERROR, "ReverseIndex can't build index because index column wasn't set."); + /// Build everything into local variables and publish them only at the end, so that an exception + /// thrown midway (for example, `MEMORY_LIMIT_EXCEEDED` from an allocation in `calcHashes`) does not + /// leave a half-built index behind: a non-null `index` with a null `saved_hash` would make the next + /// `insert` dereference a null pointer. auto size = column->size(); - index = std::make_unique(size); + auto new_index = std::make_unique(size); + fiu_do_on(FailPoints::reverse_index_build_index_throw, + throw Exception(ErrorCodes::MEMORY_LIMIT_EXCEEDED, "Injected failure while building ReverseIndex");); + + ColumnUInt64::MutablePtr new_saved_hash; if constexpr (use_saved_hash) - saved_hash = calcHashes(); + new_saved_hash = calcHashes(); - auto & state = index->getState(); + auto & state = new_index->getState(); state.index_column = column; state.base_index = base_index; if constexpr (use_saved_hash) - state.saved_hash_column = &saved_hash->getData(); + state.saved_hash_column = &new_saved_hash->getData(); using IteratorType = typename IndexMapType::iterator; IteratorType iterator; @@ -452,15 +467,18 @@ void ReverseIndex::buildIndex() { UInt64 hash; if constexpr (use_saved_hash) - hash = saved_hash->getElement(row); + hash = new_saved_hash->getElement(row); else hash = getHash(column->getDataAt(row)); - index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); + new_index->reverseIndexEmplace(row + base_index, iterator, inserted, hash, column->getDataAt(row)); if (!inserted) throw Exception(ErrorCodes::LOGICAL_ERROR, "Duplicating keys found in ReverseIndex."); } + + index = std::move(new_index); + saved_hash = std::move(new_saved_hash); } template @@ -484,37 +502,58 @@ UInt64 ReverseIndex::insert(std::string_view data) if (!index) buildIndex(); - using IteratorType = typename IndexMapType::iterator; - IteratorType iterator; - bool inserted; - - auto hash = getHash(data); - UInt64 num_rows = size(); - - if constexpr (use_saved_hash) + try { - auto & column_data = saved_hash->getData(); - if (column_data.size() <= num_rows) - column_data.resize(num_rows + 1); - column_data[num_rows] = hash; - } - else - column->insertData(data.data(), data.size()); + using IteratorType = typename IndexMapType::iterator; + IteratorType iterator; + bool inserted = false; - index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + auto hash = getHash(data); + UInt64 num_rows = size(); - if constexpr (use_saved_hash) - { - if (inserted) + if constexpr (use_saved_hash) + { + auto & column_data = saved_hash->getData(); + if (column_data.size() <= num_rows) + column_data.resize(num_rows + 1); + column_data[num_rows] = hash; + } + else column->insertData(data.data(), data.size()); + + index->reverseIndexEmplace(num_rows + base_index, iterator, inserted, hash, data); + + if constexpr (use_saved_hash) + { + if (inserted) + column->insertData(data.data(), data.size()); + } + else + { + if (!inserted) + column->popBack(1); + } + + return iterator->getValue(); } - else + catch (...) { - if (!inserted) - column->popBack(1); - } + /// The hash table may now disagree with the column: for example, the key was already added to the + /// hash table, but `insertData` failed, so the key refers to a row that does not exist. Drop the index, + /// it is rebuilt from the column on the next use. + index = nullptr; + saved_hash = nullptr; - return iterator->getValue(); + if constexpr (std::is_same_v) + { + /// `ColumnString::insertData` appends to `chars` before it grows `offsets`. If the latter failed, the bytes + /// of the row that was never added are still there and would become a prefix of the next inserted value. + const auto & offsets = column->getOffsets(); + column->getChars().resize_assume_reserved(offsets.empty() ? 0 : offsets.back()); + } + + throw; + } } template diff --git a/src/Columns/tests/gtest_reverse_index_exception_safety.cpp b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp new file mode 100644 index 000000000000..f0826e7359d1 --- /dev/null +++ b/src/Columns/tests/gtest_reverse_index_exception_safety.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int MEMORY_LIMIT_EXCEEDED; +} + +namespace DB::FailPoints +{ + extern const char reverse_index_build_index_throw[]; +} + +using namespace DB; + +/// Mimics what happens during an asynchronous insert flush under memory pressure: the first insert into a +/// `LowCardinality` dictionary throws `MEMORY_LIMIT_EXCEEDED` while the reverse index is being built, the error +/// is handled by the caller, and the same dictionary is reused for the next entry. The index must either be +/// fully built or absent, never a non-null hash table paired with a null saved-hash array. +TEST(ReverseIndex, ExceptionWhileBuildingIndexLeavesNoHalfBuiltIndex) +{ + auto column = ColumnUnique::create(DataTypeString()); + + FailPointInjection::enableFailPoint(FailPoints::reverse_index_build_index_throw); + try + { + column->uniqueInsertData("a", 1); + FAIL() << "Expected an exception from the failpoint"; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::MEMORY_LIMIT_EXCEEDED); + } + FailPointInjection::disableFailPoint(FailPoints::reverse_index_build_index_throw); + + /// Index 0 is the default value (empty string). + EXPECT_EQ(column->size(), 1u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("b", 1), 2u); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("", 0), 0u); + EXPECT_EQ(column->size(), 3u); + EXPECT_EQ(column->getDataAt(1), "a"); + EXPECT_EQ(column->getDataAt(2), "b"); +} + +/// The same reuse after a failure inside `insert` itself: the key is already in the hash table and the string bytes are +/// already appended to `chars` when growing `offsets` fails. The dictionary must come back to the state before the +/// insert, so that the next inserted value does not get the failed one as a prefix and lookups stay correct. +TEST(ReverseIndex, ExceptionWhileInsertingDataKeepsDictionaryConsistent) +{ + MainThreadStatus::getInstance(); + auto & thread_tracker = CurrentThread::get().memory_tracker; + + auto column = ColumnUnique::create(DataTypeString()); + ASSERT_EQ(column->uniqueInsertData("a", 1), 1u); + + /// Leave `offsets` without spare capacity and `chars` with plenty, so that growing `offsets` is the only + /// allocation of the next insert. + auto & nested = assert_cast(column->getNestedColumn()->assumeMutableRef()); + nested.getOffsets().shrink_to_fit(); + nested.getChars().reserve(nested.getChars().size() + 1024); + + const Int64 saved_untracked_limit = CurrentThread::get().untracked_memory_limit; + const Int64 saved_thread_hard_limit = thread_tracker.getHardLimit(); + const Int64 saved_total_hard_limit = total_memory_tracker.getHardLimit(); + + auto lift_limits = [&] + { + total_memory_tracker.setHardLimit(saved_total_hard_limit); + thread_tracker.setHardLimit(saved_thread_hard_limit); + CurrentThread::get().untracked_memory_limit = saved_untracked_limit; + }; + SCOPE_EXIT_SAFE(lift_limits()); + + /// Make even a tiny allocation reach the trackers and fail: no per-thread untracked buffer, limits of one byte. + CurrentThread::get().untracked_memory_limit = 0; + CurrentThread::flushUntrackedMemory(); + total_memory_tracker.resetCounters(); + thread_tracker.resetCounters(); + total_memory_tracker.setHardLimit(1); + thread_tracker.setHardLimit(1); + + bool thrown = false; + int code = 0; + try + { + column->uniqueInsertData("bb", 2); + } + catch (const Exception & e) + { + thrown = true; + code = e.code(); + } + + /// Lift the limits before anything else, the assertions allocate. + lift_limits(); + + ASSERT_TRUE(thrown) << "the insert was expected to fail under the memory limit"; + EXPECT_EQ(code, ErrorCodes::MEMORY_LIMIT_EXCEEDED); + + EXPECT_EQ(column->size(), 2u); + EXPECT_EQ(nested.getChars().size(), nested.getOffsets().back()); + + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->getDataAt(2), "c"); + EXPECT_EQ(column->uniqueInsertData("bb", 2), 3u); + EXPECT_EQ(column->getDataAt(3), "bb"); + EXPECT_EQ(column->uniqueInsertData("a", 1), 1u); + EXPECT_EQ(column->uniqueInsertData("c", 1), 2u); + EXPECT_EQ(column->size(), 4u); +} diff --git a/src/Common/CurrentMetrics.cpp b/src/Common/CurrentMetrics.cpp index 84d3b3c5bd0e..c88478725f6e 100644 --- a/src/Common/CurrentMetrics.cpp +++ b/src/Common/CurrentMetrics.cpp @@ -323,6 +323,8 @@ M(AsyncInsertCacheSize, "Number of async insert hash id in cache") \ M(IcebergMetadataFilesCacheBytes, "Size of the Iceberg metadata cache in bytes") \ M(IcebergMetadataFilesCacheFiles, "Number of cached files in the Iceberg metadata cache") \ + M(GlueCatalogSchemaCacheBytes, "Size of the cache of current Iceberg schema field types in Glue catalogs in bytes") \ + M(GlueCatalogSchemaCacheEntries, "Number of entries in the cache of current Iceberg schema field types in Glue catalogs") \ M(ParquetMetadataCacheBytes, "Size of the Parquet metadata cache in bytes") \ M(ParquetMetadataCacheFiles, "Number of cached files in the Parquet metadata cache") \ M(AvroSchemaCacheBytes, "Size of the Avro schema cache in bytes") \ diff --git a/src/Common/DateLUTImpl.h b/src/Common/DateLUTImpl.h index 4ac32f91a97e..690a6496ab53 100644 --- a/src/Common/DateLUTImpl.h +++ b/src/Common/DateLUTImpl.h @@ -561,21 +561,15 @@ class DateLUTImpl { const LUTIndex index = findIndex(t); - /// Calculate daylight saving offset first. - /// Because the "amount_of_offset_change" in LUT entry only exists in the change day, it's costly to scan it from the very begin. - /// but we can figure out all the accumulated offsets from 1970-01-01 to that day just by get the whole difference between lut[].date, - /// and then, we can directly subtract multiple 86400s to get the real DST offsets for the leap seconds is not considered now. - Time res = (lut[index].date - lut[daynum_offset_epoch].date) % 86400; - - /// As so far to know, the maximal DST offset couldn't be more than 2 hours, so after the modulo operation the remainder - /// will sits between [-offset --> 0 --> offset] which respectively corresponds to moving clock forward or backward. - res = res > 43200 ? (86400 - res) : (0 - res); + /// The offset at the start of the day: local midnight is `day_number * 86400` seconds of local + /// time from the epoch, while `date` is the UTC instant of that same midnight. + Time res = (static_cast(index.toUnderType()) - daynum_offset_epoch) * 86400 - lut[index].date; /// Check if has a offset change during this day. Add the change when cross the line if (lut[index].amount_of_offset_change() != 0 && t >= lut[index].date + lut[index].time_at_offset_change()) res += lut[index].amount_of_offset_change(); - return res + offset_at_start_of_epoch; + return res; } diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 875173c92b8b..7dfb2f297886 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -34,6 +34,7 @@ static struct InitFiu #define APPLY_FOR_FAILPOINTS(ONCE, REGULAR, PAUSEABLE_ONCE, PAUSEABLE) \ ONCE(replicated_merge_tree_commit_zk_fail_after_op) \ ONCE(replicated_queue_fail_next_entry) \ + ONCE(reverse_index_build_index_throw) \ REGULAR(replicated_queue_unfail_entries) \ ONCE(replicated_merge_tree_insert_quorum_fail_0) \ REGULAR(replicated_merge_tree_commit_zk_fail_when_recovering_from_hw_fault) \ @@ -96,6 +97,7 @@ static struct InitFiu PAUSEABLE_ONCE(finish_clean_quorum_failed_parts) \ PAUSEABLE_ONCE(smt_wait_next_mutation) \ PAUSEABLE_ONCE(delta_lake_metadata_iterate_pause) \ + PAUSEABLE_ONCE(rmt_restore_replica_pause_before_metadata_version_raise) \ PAUSEABLE(dummy_pausable_failpoint) \ ONCE(execute_query_calling_empty_set_result_func_on_exception) \ ONCE(terminate_with_exception) \ @@ -129,6 +131,7 @@ static struct InitFiu REGULAR(database_replicated_delay_recovery) \ REGULAR(database_replicated_delay_entry_execution) \ PAUSEABLE(database_replicated_stop_entry_execution) \ + PAUSEABLE_ONCE(database_replicated_pause_before_initial_query_execution) \ REGULAR(remove_merge_tree_part_delay) \ REGULAR(plain_object_storage_copy_temp_source_file_fail_on_file_move) \ REGULAR(plain_object_storage_copy_temp_target_file_fail_on_file_move) \ diff --git a/src/Common/RemoteHostFilter.cpp b/src/Common/RemoteHostFilter.cpp index 6f953f48d48b..5b5da5ec7c6b 100644 --- a/src/Common/RemoteHostFilter.cpp +++ b/src/Common/RemoteHostFilter.cpp @@ -110,6 +110,10 @@ bool RemoteHostFilter::checkForDirectEntry(const std::string & str) const /// Allow everything by default. return true; + /// Connectors take the host as a C string and stop at the first NUL, so the checked string must not contain one. + if (str.contains('\0')) + return false; + std::lock_guard guard(hosts_mutex); if (primary_hosts.contains(str)) diff --git a/src/Common/Scheduler/CPUSlotsAllocation.cpp b/src/Common/Scheduler/CPUSlotsAllocation.cpp index a11e4a6feb9a..30d9d735e60d 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.cpp +++ b/src/Common/Scheduler/CPUSlotsAllocation.cpp @@ -7,6 +7,7 @@ #include #include #include +#include namespace ProfileEvents { @@ -72,6 +73,10 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker for (CPUSlotRequest & request : requests) request.allocation = this; + wait_thread_group = CurrentThread::getGroup(); + if (wait_thread_group) + wait_counters = &wait_thread_group->performance_counters; + std::unique_lock lock{schedule_mutex}; while (allocated < total_slots) { @@ -79,7 +84,7 @@ CPUSlotsAllocation::CPUSlotsAllocation(SlotCount master_slots_, SlotCount worker { queue->enqueueRequest(current_request); scheduled_slot_increment.emplace(CurrentMetrics::ConcurrencyControlScheduled); - wait_timer.emplace(CurrentThread::getProfileEvents().timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); + wait_timer.emplace(wait_counters->timer(ProfileEvents::ConcurrencyControlWaitMicroseconds)); break; } else // noncompeting slot - provide for free diff --git a/src/Common/Scheduler/CPUSlotsAllocation.h b/src/Common/Scheduler/CPUSlotsAllocation.h index d8963f14b8cf..caaf37139b25 100644 --- a/src/Common/Scheduler/CPUSlotsAllocation.h +++ b/src/Common/Scheduler/CPUSlotsAllocation.h @@ -17,6 +17,7 @@ namespace DB { class CPUSlotsAllocation; +class ThreadGroup; // Represents a resource request for a cpu slot for a single thread class CPUSlotRequest final : public ResourceRequest @@ -113,6 +114,9 @@ class CPUSlotsAllocation final : public ISlotAllocation std::vector requests; // Requests per every slot CPUSlotRequest * current_request; std::optional scheduled_slot_increment; + /// `wait_timer` may end on another thread after the creating one has exited, so it counts into the query's group, kept alive here. + std::shared_ptr wait_thread_group; + ProfileEvents::Counters * wait_counters = &ProfileEvents::global_counters; std::optional wait_timer; }; diff --git a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp index 0c6ba16e64d4..cdc0b8f1ad07 100644 --- a/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp +++ b/src/Common/Scheduler/Nodes/tests/gtest_workload_resource_manager.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -49,6 +51,7 @@ namespace ProfileEvents { extern const Event ConcurrencyControlUpscales; extern const Event ConcurrencyControlDownscales; + extern const Event ConcurrencyControlWaitMicroseconds; } namespace CurrentMetrics @@ -1068,6 +1071,41 @@ TEST(SchedulerWorkloadResourceManager, CPUSchedulingRoundRobin) t.wait(); } +/// The wait for a CPU slot is accounted to the query even when the allocation outlives the thread that created it +/// (here: destroyed on another thread while its request is still queued, like a `KILL QUERY` of a waiting query). +TEST(SchedulerWorkloadResourceManager, CPUSlotsWaitTimerOutlivesCreatingThread) +{ + ResourceTest t; + t.query("CREATE RESOURCE cpu (MASTER THREAD, WORKER THREAD)"); + t.query("CREATE WORKLOAD all SETTINGS max_concurrent_threads = 1"); + ClassifierPtr c = t.manager->acquire("all"); + ResourceLink link = c->get("cpu"); + + /// Takes the only slot, so the next allocation keeps its request queued. + auto blocker = std::make_shared(1, 0, link, link); + auto blocker_slot = blocker->acquire(); + + std::weak_ptr weak_group; + SlotAllocationPtr allocation; + std::thread([&] + { + DB::ThreadStatus thread_status; + auto group = std::make_shared(Context::getGlobalContextInstance(), 0); + weak_group = group; + CurrentThread::attachToGroupIfDetached(group); + allocation = std::make_shared(1, 0, link, link); + CurrentThread::detachFromGroupIfNotDetached(); + }).join(); + + ASSERT_TRUE(allocation->isRequesting()); + /// The creating thread is gone, so only the allocation can still own the group. + ThreadGroupPtr group = weak_group.lock(); + ASSERT_NE(group, nullptr); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + allocation.reset(); + EXPECT_GE(group->performance_counters[ProfileEvents::ConcurrencyControlWaitMicroseconds], 10'000); +} + TEST(SchedulerWorkloadResourceManager, CPUSchedulingFairness) { ResourceTest t; diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 15b5d71e193c..3054e98b8259 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -116,7 +116,10 @@ ThreadStatus::ThreadStatus() last_rusage = std::make_unique(); memory_tracker.setDescription("Thread"); - log = getLogger("ThreadStatus"); + /// A `ThreadStatus` is created for every job of a thread pool, and `getLogger` locks the global mutex of the + /// registry of loggers, so all threads of the pools would contend on it. + static const LoggerPtr thread_status_log = getLogger("ThreadStatus"); + log = thread_status_log; current_thread = this; diff --git a/src/Common/ZooKeeper/ZooKeeperConstants.h b/src/Common/ZooKeeper/ZooKeeperConstants.h index d5c5cc119fb5..7e61d02e91c1 100644 --- a/src/Common/ZooKeeper/ZooKeeperConstants.h +++ b/src/Common/ZooKeeper/ZooKeeperConstants.h @@ -92,6 +92,8 @@ static constexpr int32_t PASSWORD_LENGTH = 16; static constexpr int32_t MAX_STRING_OR_ARRAY_SIZE = 1 << 28; /// 256 MiB /// Upper bound on elements reserved up front when reading an array; the declared size is attacker-controlled static constexpr int32_t MAX_ARRAY_PREALLOCATION = 4096; +/// Bytes read per step when reading a string; the declared size is attacker-controlled, so memory grows with the bytes received +static constexpr int32_t MAX_STRING_PREALLOCATION = 1 << 16; /// 64 KiB static constexpr int32_t DEFAULT_SESSION_TIMEOUT_MS = 30000; static constexpr int32_t DEFAULT_MIN_SESSION_TIMEOUT_MS = 10000; static constexpr int32_t DEFAULT_MAX_SESSION_TIMEOUT_MS = 100000; diff --git a/src/Common/ZooKeeper/ZooKeeperIO.cpp b/src/Common/ZooKeeper/ZooKeeperIO.cpp index 88de2b4dc01d..c872bdac795e 100644 --- a/src/Common/ZooKeeper/ZooKeeperIO.cpp +++ b/src/Common/ZooKeeper/ZooKeeperIO.cpp @@ -93,11 +93,24 @@ void read(std::string & s, ReadBuffer & in) if (size > MAX_STRING_OR_ARRAY_SIZE) throw Exception(Error::ZMARSHALLINGERROR,"Too large string size while reading from ZooKeeper {}", size); - s.resize(size); - size_t read_bytes = in.read(s.data(), size); - if (read_bytes != static_cast(size)) - throw Exception( - Error::ZMARSHALLINGERROR, "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", size, read_bytes); + /// Memory must track bytes actually read, not the declared size: + /// do not pre-allocate for an attacker-controlled length. + s.clear(); + size_t remaining = static_cast(size); + while (remaining > 0) + { + const size_t chunk = std::min(remaining, MAX_STRING_PREALLOCATION); + const size_t old_size = s.size(); + s.resize(old_size + chunk); + const size_t read_bytes = in.read(s.data() + old_size, chunk); + if (read_bytes != chunk) + throw Exception( + Error::ZMARSHALLINGERROR, + "Buffer size read from Zookeeper is not big enough. Expected {}. Got {}", + size, + old_size + read_bytes); + remaining -= chunk; + } } void read(ACL & acl, ReadBuffer & in) diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index d368e482aa8c..a4f762ec2d57 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -2,14 +2,69 @@ #include +#include #include #include #include +#include namespace DB { +/** Hides the secrets of an Azure connection string as the Azure SDK reads it (`Azure::Storage::_internal::ParseConnectionString`, + * `contrib/azure/sdk/storage/azure-storage-common/src/storage_credential.cpp`): a key runs to '=' and its value to ';', keys + * match exactly, and the last copy of a repeated key wins. Splitting at every ';' first can only hide more than the SDK reads. + * - secret keys: `AccountName=a;AccountKey=K;SharedAccessSignature=S` -> `AccountName=a;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]` + * - repeated keys: `AccountKey=K1;AccountKey=K2` -> `AccountKey=[HIDDEN];AccountKey=[HIDDEN]` + * - an endpoint is a url, so a query in it is a SAS: `BlobEndpoint=https://h/?sig=S` or `BlobEndpoint=https://u@h/` -> `BlobEndpoint=[HIDDEN]` + * - the whole string is hidden when a '?', '#' or '@' is still shown, or when it has one and holds a url outside the pair + * values (':' or '/' in a key or in a part without '='; no key has them): `https://h/?sig=S` or `https://u:p=s@h/` -> `[HIDDEN]` + * Returns whether anything was hidden. + */ +inline bool maskAzureConnectionStringSecrets(std::string & str) +{ + static constexpr std::array secret_keys = {"AccountKey", "SharedAccessSignature"}; + auto is_secret_key = [](std::string_view key) { return std::ranges::find(secret_keys, key) != secret_keys.end(); }; + + const bool has_url_delimiters = str.find_first_of("?#@") != std::string::npos; + bool url_outside_values = false; + std::string result; + size_t copied = 0; + bool masked = false; + for (size_t part_begin = 0; part_begin <= str.length();) + { + const size_t part_end = std::min(str.find(';', part_begin), str.length()); + const std::string_view part = std::string_view(str).substr(part_begin, part_end - part_begin); + const size_t equals = part.find('='); + if (part.substr(0, equals).find_first_of(":/") != std::string_view::npos) + url_outside_values = true; + if (equals != std::string_view::npos + && (is_secret_key(part.substr(0, equals)) || part.substr(equals + 1).find_first_of("?@") != std::string_view::npos)) + { + const size_t value_begin = part_begin + equals + 1; + result.append(str, copied, value_begin - copied); + result.append("[HIDDEN]"); + copied = part_end; + masked = true; + } + part_begin = part_end + 1; + } + + if (masked) + { + result.append(str, copied, std::string::npos); + str = std::move(result); + } + + if (str.find_first_of("?#@") != std::string::npos || (url_outside_values && has_url_delimiters)) + { + str = "[HIDDEN]"; + return true; + } + return masked; +} + inline bool maskURIPassword(std::string * uri) { return RE2::Replace(uri, R"(([^:]+://[^:]*):([^@]*)@(.*))", "\\1:[HIDDEN]@\\3"); diff --git a/src/Common/mysqlxx/Connection.cpp b/src/Common/mysqlxx/Connection.cpp index f9f2d3e5d1aa..8614bed72705 100644 --- a/src/Common/mysqlxx/Connection.cpp +++ b/src/Common/mysqlxx/Connection.cpp @@ -114,6 +114,14 @@ void Connection::connect(const char* db, if (mysql_ssl_set(driver.get(), ifNotEmpty(ssl_key), ifNotEmpty(ssl_cert), ifNotEmpty(ssl_ca), nullptr, nullptr)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// Without an explicit socket, use TCP to the given port: otherwise `localhost` goes to the library's default socket. + if (!ifNotEmpty(socket)) + { + unsigned protocol = MYSQL_PROTOCOL_TCP; + if (mysql_options(driver.get(), MYSQL_OPT_PROTOCOL, &protocol)) + throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + } + if (!mysql_real_connect(driver.get(), server, user, password, db, port, ifNotEmpty(socket), driver->client_flag)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); diff --git a/src/Common/mysqlxx/Pool.cpp b/src/Common/mysqlxx/Pool.cpp index 7173adf3326c..58d54882fa6c 100644 --- a/src/Common/mysqlxx/Pool.cpp +++ b/src/Common/mysqlxx/Pool.cpp @@ -9,11 +9,61 @@ #include #include #include +#include #include #include #include +namespace DB::ErrorCodes +{ + extern const int BAD_ARGUMENTS; +} + +namespace +{ + +/// `mysql_real_connect` reinterprets these hosts and port 0; reject them so it dials exactly what `remote_url_allow_hosts` checked. +void checkConnectionTarget(const std::string & server, unsigned port, const std::string & socket) +{ + std::string_view meaning; + if (server.contains('\0')) + meaning = "the end of the host"; + else if (server.find_first_of(";=") != std::string::npos) + meaning = "a connection string"; + else if (server.contains("://")) + meaning = "a connection plugin URL"; + else if (server.contains(',')) + meaning = "a list of hosts"; + + if (!meaning.empty()) + { + std::string printable; + for (const char c : server) + printable += c == '\0' ? std::string_view("\\0") : std::string_view(&c, 1); + + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL host '{}' contains syntax which the MySQL client library would read as {}. " + "Specify a plain host and port, and use the `socket` and `ssl_*` settings instead", + printable, meaning); + } + + if (socket.contains('\0')) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, "MySQL socket for host '{}' contains a NUL byte, where the MySQL client library would end it", server); + + /// The client library uses the socket only for an empty host or `localhost`, otherwise it connects over TCP. + const bool uses_socket = !socket.empty() && (server.empty() || server == "localhost"); + if (port == 0 && !uses_socket) + throw DB::Exception( + DB::ErrorCodes::BAD_ARGUMENTS, + "MySQL port 0 for host '{}' would be replaced by the default port of the MySQL client library. Specify the port explicitly", + server); +} + +} + namespace mysqlxx { @@ -367,6 +417,9 @@ void Pool::initialize() Pool::Connection * Pool::allocConnection(bool dont_throw_if_failed_first_time) { + /// All connections of the pool are created here. + checkConnectionTarget(server, port, socket); + auto conn_ptr = std::make_unique(); try diff --git a/src/Common/tests/gtest_distrusted_certificates.cpp b/src/Common/tests/gtest_distrusted_certificates.cpp new file mode 100644 index 000000000000..5931feea9f6b --- /dev/null +++ b/src/Common/tests/gtest_distrusted_certificates.cpp @@ -0,0 +1,137 @@ +#include "config.h" + +#if USE_SSL + +#include + +#include +#include + +#include +#include +#include + +#include +#include + + +namespace +{ + +/// `emSign ECC Root CA - G3`, distrusted. +constexpr std::string_view emsign_ecc_root_g3 = R"( +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +)"; + +/// `EM DV TLS CA - G3B` cross-signed by `AAA Certificate Services`, distrusted by the key of the certificate issued by `emSign Root TLS CA - G3`. +constexpr std::string_view em_dv_tls_ca_g3b_cross_signed = R"( +-----BEGIN CERTIFICATE----- +MIIDzjCCAragAwIBAgIRAKAk/fS6Zlx4XOSgIEg4WLcwDQYJKoZIhvcNAQELBQAw +ezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV +BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0yNTA1MTQwMDAwMDBaFw0y +ODEyMzEyMzU5NTlaMD8xCzAJBgNVBAYTAk5MMRMwEQYDVQQKDAplTXVkaHJhIEJW +MRswGQYDVQQDDBJFTSBEViBUTFMgQ0EgLSBHM0IwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAATnntnASpdzxHNeUREdqFrCvV5kqzdLgOEsvCA47B5PDjuBL8mFnh5nr7BO +L4vJf3SFumWqkR7opORbYtXMA9Vr5nizw4y03JN8okYOI4RTyJKTXSnUT5HhVga2 +PM7atGijggE1MIIBMTAfBgNVHSMEGDAWgBSgEQojPpbxB+zirynvgqV/0DCktDAd +BgNVHQ4EFgQU4h4v5xwZOQ5VS2LBICRXNSSKJRQwDgYDVR0PAQH/BAQDAgEGMBIG +A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC +MDEGA1UdIAQqMCgwCAYGZ4EMAQIBMA0GCysGAQQBg44hAQABMA0GCysGAQQBg44h +AQJkMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0FB +QUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEF +BQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBCwUAA4IB +AQBzQ1IoqpdotM6gFrR4Q3YrKifOLeaj5XXunldpVE/vZn2TxC2y0s8oYiLR5ICE +wqVXSB7N6BM1Mp+Nif7Jbhb2IswAfSR4Iik8+B0iRmi7lYoNlycCgHjmsjOmZaxM +QkPmjXAJbG5f4V41OsvJZmS7lI3r0IuvEDVX3GAZ13on6IImSs9ybNpHQ7NCqkMQ +7wH4uAO1dtpFycgJSdHaCOhHjrox2BTYGLdpUrYwY3EOAjlZ8UGgsxs7mG+xquMl +bN1LFURwfnkVMP3T/DBIZ/ys2+lNFyxK3FlArrV4/000uTnVB1lO8oGORYdXoT5V +GUyRCEIDhF5TBUuKF4E3kf1h +-----END CERTIFICATE-----)"; + +/// `emSign Root CA - G1`, not affected. +constexpr std::string_view emsign_root_g1 = R"( +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +)"; + +using X509Ptr = std::unique_ptr; + +X509Ptr parseCertificate(std::string_view pem) +{ + std::unique_ptr bio(BIO_new_mem_buf(pem.data(), static_cast(pem.size())), BIO_free); + X509Ptr certificate(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr), X509_free); + EXPECT_NE(certificate, nullptr); + return certificate; +} + +/// Verifies a trusted self-signed certificate the same way a TLS connection of a Poco context does it. +int verifyTrustedRoot(std::string_view pem) +{ + Poco::Net::Context context(Poco::Net::Context::CLIENT_USE, Poco::Net::Context::Params{}); + X509Ptr certificate = parseCertificate(pem); + X509_STORE * store = SSL_CTX_get_cert_store(context.sslContext()); + EXPECT_EQ(X509_STORE_add_cert(store, certificate.get()), 1); + + std::unique_ptr store_ctx(X509_STORE_CTX_new(), X509_STORE_CTX_free); + EXPECT_EQ(X509_STORE_CTX_init(store_ctx.get(), store, certificate.get(), nullptr), 1); + X509_STORE_CTX_set_verify_cb(store_ctx.get(), SSL_CTX_get_verify_callback(context.sslContext())); + + if (X509_verify_cert(store_ctx.get()) == 1) + return X509_V_OK; + return X509_STORE_CTX_get_error(store_ctx.get()); +} + +} + + +TEST(DistrustedCertificates, Check) +{ + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_ecc_root_g3).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(em_dv_tls_ca_g3b_cross_signed).get()), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(Poco::Net::checkDistrustedCertificate(parseCertificate(emsign_root_g1).get()), X509_V_OK); +} + +TEST(DistrustedCertificates, RejectedEvenIfTrusted) +{ + EXPECT_EQ(verifyTrustedRoot(emsign_ecc_root_g3), X509_V_ERR_CERT_REVOKED); + EXPECT_EQ(verifyTrustedRoot(emsign_root_g1), X509_V_OK); +} + +#endif diff --git a/src/Common/tests/gtest_file_channel_rotation_failure.cpp b/src/Common/tests/gtest_file_channel_rotation_failure.cpp new file mode 100644 index 000000000000..d4ca3bee239b --- /dev/null +++ b/src/Common/tests/gtest_file_channel_rotation_failure.cpp @@ -0,0 +1,133 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Log rotation must not leave `FileChannel` with a deleted `LogFile` when the process has no free file descriptors. + +namespace +{ + +/// glibc defines `RLIMIT_NOFILE` as a self-referential macro, which trips -Wdisabled-macro-expansion inside gtest macros. +const auto nofile_resource = RLIMIT_NOFILE; + +struct DescriptorTableGuard +{ + struct rlimit original_limit{}; + std::vector descriptors; + + void release() + { + for (int fd : descriptors) + ::close(fd); + descriptors.clear(); + EXPECT_EQ(0, setrlimit(nofile_resource, &original_limit)); + } + + ~DescriptorTableGuard() { release(); } +}; + +int setSoftLimit(rlim_t value, const struct rlimit & original_limit) +{ + struct rlimit limit = original_limit; + limit.rlim_cur = value; + return setrlimit(nofile_resource, &limit); +} + +int fillDescriptorTable(DescriptorTableGuard & guard) +{ + while (true) + { + int fd = ::open("/dev/null", O_RDONLY | O_CLOEXEC); + if (fd < 0) + return errno; + guard.descriptors.push_back(fd); + } +} + +Poco::Message makeMessage(const std::string & text) +{ + return Poco::Message("gtest_file_channel_rotation_failure", text, Poco::Message::PRIO_INFORMATION); +} + +void expectNoFreeDescriptors(Poco::FileChannel & channel, const std::string & text) +{ + try + { + channel.log(makeMessage(text)); + ADD_FAILURE() << "Expected EMFILE while logging: " << text; + } + catch (const Poco::FileException & e) + { + EXPECT_EQ(EMFILE, e.code()) << e.displayText(); + } +} + +std::string readFile(const std::string & path) +{ + std::ifstream in(path); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +} + +TEST(FileChannelRotation, NoFreeDescriptorsDuringRotation) +{ + const auto dir = std::filesystem::temp_directory_path() / ("gtest_file_channel_rotation_" + std::to_string(::getpid())); + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + struct DirectoryGuard + { + std::filesystem::path path; + ~DirectoryGuard() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + } directory_guard{dir}; + const std::string path = (dir / "server.log").string(); + + Poco::AutoPtr channel = new Poco::FileChannel(path); + channel->setProperty(Poco::FileChannel::PROP_ROTATION, "1K"); + channel->setProperty(Poco::FileChannel::PROP_ARCHIVE, "number"); + channel->setProperty(Poco::FileChannel::PROP_COMPRESS, "false"); + + DescriptorTableGuard guard; + ASSERT_EQ(0, getrlimit(nofile_resource, &guard.original_limit)); + const rlim_t limit = std::min({guard.original_limit.rlim_cur, guard.original_limit.rlim_max - 1, 1024}); + + /// The log file gets descriptor `limit`, so closing it in `archive` frees no descriptor below the limit. + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + ASSERT_EQ(EMFILE, fillDescriptorTable(guard)); + ASSERT_EQ(0, setSoftLimit(limit + 1, guard.original_limit)); + ASSERT_NO_THROW(channel->open()); + ASSERT_EQ(0, setSoftLimit(limit, guard.original_limit)); + + ASSERT_NO_THROW(channel->log(makeMessage(std::string(2048, 'x')))); + + expectNoFreeDescriptors(*channel, "rotation without free descriptors"); + EXPECT_TRUE(std::filesystem::exists(path + ".0")); + EXPECT_EQ(0u, channel->size()); + expectNoFreeDescriptors(*channel, "still no free descriptors"); + + guard.release(); + + const std::string marker = "logged after descriptors were released"; + ASSERT_NO_THROW(channel->log(makeMessage(marker))); + channel->close(); + EXPECT_NE(std::string::npos, readFile(path).find(marker)); +} diff --git a/src/Coordination/Changelog.cpp b/src/Coordination/Changelog.cpp index 26f8cff05cae..dd4d3a9e8cff 100644 --- a/src/Coordination/Changelog.cpp +++ b/src/Coordination/Changelog.cpp @@ -2568,6 +2568,8 @@ void Changelog::applyEntriesFromBuffer(uint64_t index, nuraft::buffer & buffer) { uint64_t cur_index = index + i; int buf_size = buffer.get_int(); + if (buf_size < 0 || static_cast(buf_size) > buffer.size() - buffer.pos()) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Log entry {} in a log pack has invalid size {}", cur_index, buf_size); nuraft::ptr buf_local = nuraft::buffer::alloc(buf_size); buffer.get(buf_local); diff --git a/src/Coordination/tests/gtest_coordination.cpp b/src/Coordination/tests/gtest_coordination.cpp index 291bc4236055..6f0a8d868f51 100644 --- a/src/Coordination/tests/gtest_coordination.cpp +++ b/src/Coordination/tests/gtest_coordination.cpp @@ -172,6 +172,69 @@ TYPED_TEST(CoordinationTest, CreateRequestDoesNotPreallocateOversizedACLs) } } +TEST(CoordinationSerialization, StringReadDoesNotPreallocateDeclaredSize) +{ + /// Invariant: memory must track bytes actually read, not the declared string length. + const size_t chunk = Coordination::MAX_STRING_PREALLOCATION; + + auto expect_marshalling_error = [](DB::ReadBuffer & rbuf, std::string & s) + { + try + { + Coordination::read(s, rbuf); + FAIL() << "Expected ZMARSHALLINGERROR"; + } + catch (const Coordination::Exception & e) + { + EXPECT_EQ(e.code, Coordination::Error::ZMARSHALLINGERROR); + } + }; + + { + /// The largest allowed length is declared, but no payload bytes follow. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 2 * chunk); + } + + { + /// The input ends after one complete chunk. + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(Coordination::MAX_STRING_OR_ARRAY_SIZE, wbuf); + const std::string first_chunk(chunk, 'x'); + wbuf.write(first_chunk.data(), first_chunk.size()); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + expect_marshalling_error(rbuf, s); + EXPECT_LE(s.capacity(), 4 * chunk); + } + + { + /// A string that needs more than one chunk is read completely, and the next field is aligned. + std::string expected(chunk + 1, '\0'); + for (size_t i = 0; i < expected.size(); ++i) + expected[i] = static_cast(i % 251); + + DB::WriteBufferFromNuraftBuffer wbuf; + Coordination::write(expected, wbuf); + Coordination::write(static_cast(42), wbuf); + + DB::ReadBufferFromNuraftBuffer rbuf(wbuf.getBuffer()); + std::string s; + int32_t next = 0; + Coordination::read(s, rbuf); + Coordination::read(next, rbuf); + EXPECT_EQ(s, expected); + EXPECT_EQ(next, 42); + EXPECT_TRUE(rbuf.eof()); + } +} + template struct SimpliestRaftServer { diff --git a/src/Coordination/tests/gtest_coordination_changelog.cpp b/src/Coordination/tests/gtest_coordination_changelog.cpp index c0a33caadbdd..fa3ec468e04e 100644 --- a/src/Coordination/tests/gtest_coordination_changelog.cpp +++ b/src/Coordination/tests/gtest_coordination_changelog.cpp @@ -479,6 +479,45 @@ TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsEmpty) changelog_reader.init(5, 0); } +TYPED_TEST(CoordinationChangelogTest, ChangelogTestBatchOperationsInvalidSize) +{ + ChangelogDirTest test("./logs"); + this->setLogDirectory("./logs"); + + DB::KeeperLogStore changelog( + DB::LogFileSettings{.force_sync = true, .compress_logs = this->enable_compression, .rotate_interval = 100}, + DB::FlushSettings(), + this->keeper_context); + changelog.init(0, 0); + auto entry = getLogEntry("hello_world", 10); + changelog.append(entry); + changelog.end_of_append_batch(0, 0); + waitDurableLogs(changelog); + + /// A pack of one entry holds the entry count, the entry size and the entry itself. A peer controls the size, + /// so only the size is rewritten here. + auto entries = changelog.pack(1, 1); + const auto entry_size = static_cast(entries->size() - 2 * sizeof(int32_t)); + auto apply_with_size = [&](int32_t size) + { + entries->pos(sizeof(int32_t)); + entries->put(size); + changelog.apply_pack(2, *entries); + }; + + /// On master a size past the entry over-reads the pack in `nuraft::buffer::get` and a negative size + /// wraps the allocation size in `nuraft::buffer::alloc`. + EXPECT_THROW(apply_with_size(entry_size + 1), DB::Exception); + EXPECT_THROW(apply_with_size(-1), DB::Exception); + EXPECT_EQ(changelog.next_slot(), 2); + + apply_with_size(entry_size); + changelog.apply_pack(3, *changelog.pack(1, 0)); + changelog.end_of_append_batch(0, 0); + EXPECT_EQ(changelog.next_slot(), 3); + EXPECT_EQ(changelog.entry_at(2)->get_term(), 10); +} + TYPED_TEST(CoordinationChangelogTest, ChangelogTestWriteAtPreviousFile) { diff --git a/src/Core/BackgroundSchedulePool.cpp b/src/Core/BackgroundSchedulePool.cpp index e0511c7643fe..227db0b72fb5 100644 --- a/src/Core/BackgroundSchedulePool.cpp +++ b/src/Core/BackgroundSchedulePool.cpp @@ -414,10 +414,12 @@ void BackgroundSchedulePool::scheduleDelayedTask(TaskInfo & task, size_t ms, std { std::lock_guard lock(delayed_tasks_mutex); + /// Insert before erasing the old entry: if the insertion throws, the task keeps its old entry and `task.iterator` stays valid. + auto it = delayed_tasks.emplace(current_time + (ms * 1000), task.shared_from_this()); if (task.delayed) delayed_tasks.erase(task.iterator); - task.iterator = delayed_tasks.emplace(current_time + (ms * 1000), task.shared_from_this()); + task.iterator = it; task.delayed = true; } diff --git a/src/Core/Field.cpp b/src/Core/Field.cpp index 8afadfc8ac9e..ca0f375ed111 100644 --- a/src/Core/Field.cpp +++ b/src/Core/Field.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -369,6 +370,9 @@ bool Field::operator== (const Field & rhs) const Field getBinaryValue(UInt8 type, ReadBuffer & buf) { + /// Containers are read recursively, and the nesting depth comes from the data. + checkStackSize(); + switch (static_cast(type)) { case Field::Types::Null: diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 0042be8fe8a1..31643b8133cd 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -1408,6 +1408,13 @@ Compression method for Arrow output format. Supported codecs: lz4_frame, zstd, n )", 0) \ DECLARE(Bool, output_format_arrow_date_as_uint16, false, R"( Write Date values as plain 16-bit numbers (read back as UInt16), instead of converting to a 32-bit Arrow DATE32 type (read back as Date32). +)", 0) \ + DECLARE(UInt64, output_format_arrow_max_record_batch_size_bytes, 2147483646, R"( +Upper bound on the `Utf8`, `Binary` and `List` buffers of a single record batch in the `Arrow` and `ArrowStream` output formats. A block whose strings, binary values or list elements exceed this is written as several record batches. + +This is a limit that splits large blocks. The default is the largest value Arrow can address, because it offsets those buffers with 32-bit integers; a larger value has no effect. + +Only the buffers named above are bounded: a column of a fixed-width type has no offsets to overflow and stays in one batch. A single row never splits either, so a row above the limit still produces a batch that exceeds it. )", 0) \ \ DECLARE(Bool, output_format_orc_string_as_string, true, R"( diff --git a/src/Core/PostgreSQLProtocol.h b/src/Core/PostgreSQLProtocol.h index 20349d50560c..74accb0cef73 100644 --- a/src/Core/PostgreSQLProtocol.h +++ b/src/Core/PostgreSQLProtocol.h @@ -55,6 +55,14 @@ namespace PostgreSQLProtocol namespace Messaging { +/** Upper bound for the declared length of a message that is parsed before the client is authenticated. + * The payload of such a message is bounded by its declared length, but that length is chosen by an + * unauthenticated client, so the length itself must be bounded as well. Otherwise a client declares + * the Int32 maximum and makes the server buffer up to 2 GiB of payload before it gives up. + * PostgreSQL uses the same limit for its startup packet. + */ +constexpr Int32 max_unauthenticated_message_size = 10000; + enum class FrontMessageType : Int32 { // first message types @@ -307,14 +315,26 @@ class FrontMessage : public IMessage virtual void deserialize(ReadBuffer & in) = 0; protected: + /** Parses the payload of a message inside a buffer that ends at the declared length. + * `max_size` bounds the declared length itself. Pass it for every message that is parsed before the + * client is authenticated, because that client chooses the length. A frame rejected by `max_size` is + * left unread in the stream, so only a caller whose error closes the connection may pass a limit. + */ template - static void deserializePayload(ReadBuffer & in, std::string_view message_name, F && deserialize_payload) + static void deserializePayload( + ReadBuffer & in, + std::string_view message_name, + F && deserialize_payload, + Int32 max_size = std::numeric_limits::max()) { Int32 size = 0; readBinaryBigEndian(size, in); if (size < 4) throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT, "Wrong message length {} in {}, it must be at least 4", size, message_name); + if (size > max_size) + throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT, + "Wrong message length {} in {}, it must not exceed {}", size, message_name, max_size); const size_t payload_size = static_cast(size - 4); LimitReadBuffer payload_in(in, {.read_no_less = payload_size, .read_no_more = payload_size}); @@ -598,7 +618,7 @@ class SASLInitialResponse : public Messaging::FrontMessage "Wrong SASL mechanism length {} in SASLInitialResponse, it must not be less than -1", size_sasl_mechanism); if (size_sasl_mechanism > 0) readStringOfDeclaredSize(sasl_mechanism, size_sasl_mechanism, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override @@ -646,7 +666,7 @@ class SASLResponse : public Messaging::FrontMessage deserializePayload(in, "SASLResponse message", [this](ReadBuffer & payload_in) { readStringUntilEOF(sasl_mechanism, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override @@ -687,7 +707,7 @@ class PasswordMessage : FrontMessage deserializePayload(in, "PasswordMessage", [this](ReadBuffer & payload_in) { readNullTerminated(password, payload_in); - }); + }, max_unauthenticated_message_size); } MessageType getMessageType() const override diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index ac119469ccd0..6cbd2e052809 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -1270,6 +1270,10 @@ Possible values: - `2` — `SELECT` and `INSERT` will be executed on each shard from/to the underlying table of the distributed engine. Setting `enable_parallel_replicas = 1` is needed when using this setting. + +:::note +The rewritten query, including every expression of the `SELECT` (subqueries, UDFs, and so on), is executed on the shards under the credentials of the cluster configuration — the same trust model as other shard-side processing, such as the subqueries of a non-`GLOBAL` `IN`. Configure an interserver secret (the `secret` element of the cluster configuration) if shard-side reads must be authorized as the calling user. +::: )", 0) \ DECLARE(UInt64, distributed_group_by_no_merge, 0, R"( Do not merge aggregation states from different servers for distributed query processing, you can use this in case it is for certain that there are different keys on different shards diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 62e4d873e09d..caf53da95654 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -41,6 +41,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() /// Note: please check if the key already exists to prevent duplicate entries. addSettingsChanges(settings_changes_history, "26.3", { + {"output_format_arrow_max_record_batch_size_bytes", 2147483646, 2147483646, "New setting bounding the size of one record batch in `Arrow` and `ArrowStream` output. The default is Arrow's own addressing limit, so it does not change behavior."}, {"variant_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Variant implementation"}, {"dynamic_throw_on_type_mismatch", true, true, "New setting to control type mismatch behavior in default Dynamic implementation"}, {"defer_partition_pruning_after_final", false, true, "Gates the FINAL planner's unconditional skipping of partition pruning when the partition-key column is not in the sorting key. The behavior change itself shipped silently in 26.3 via https://github.com/ClickHouse/ClickHouse/pull/98242; this entry retroactively documents it so `compatibility = '26.2'` restores the pre-regression behavior (0 = prune before FINAL, fast; 1 = defer pruning, correctness-safe)."}, diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp index 4b0be9872423..1b1665c4abff 100644 --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp @@ -607,6 +607,13 @@ void SerializationLowCardinality::deserializeBinaryBulkWithMultipleStreams( bool has_additional_keys = low_cardinality_state->index_type.has_additional_keys; bool column_is_empty = low_cardinality_column.empty(); + /// Indexes come from the stream. + if (low_cardinality_state->index_type.need_global_dictionary) + { + const size_t num_additional_keys = additional_keys ? additional_keys->size() : 0; + ColumnLowCardinality::checkIndexesAreLimited(*indexes_column, global_dictionary->size() + num_additional_keys); + } + if (!low_cardinality_state->index_type.need_global_dictionary) { if (additional_keys == nullptr) diff --git a/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp new file mode 100644 index 000000000000..4ea6070e820a --- /dev/null +++ b/src/DataTypes/Serializations/tests/gtest_low_cardinality_serialization.cpp @@ -0,0 +1,179 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int INCORRECT_DATA; +} + +using namespace DB; + +namespace +{ + +/// The MergeTree layout: the dictionary in one stream, the indexes and the additional keys in another. +template +auto makeGetter(Buffer & keys, Buffer & indexes) +{ + return [&keys, &indexes](const ISerialization::SubstreamPath & path) -> BufferPtr + { + if (!path.empty() && path.back().type == ISerialization::Substream::DictionaryKeys) + return &keys; + return &indexes; + }; +} + +struct Streams +{ + std::string keys; + std::string indexes; +}; + +Streams serialize(const DataTypePtr & type, const IColumn & column, size_t max_dictionary_size) +{ + WriteBufferFromOwnString keys; + WriteBufferFromOwnString indexes; + auto serialization = type->getDefaultSerialization(); + ISerialization::SerializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.low_cardinality_max_dictionary_size = max_dictionary_size; + settings.low_cardinality_use_single_dictionary_for_part = false; + ISerialization::SerializeBinaryBulkStatePtr state; + serialization->serializeBinaryBulkStatePrefix(column, settings, state); + serialization->serializeBinaryBulkWithMultipleStreams(column, 0, column.size(), settings, state); + serialization->serializeBinaryBulkStateSuffix(settings, state); + keys.finalize(); + indexes.finalize(); + return {keys.str(), indexes.str()}; +} + +ColumnPtr deserialize(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + ReadBufferFromString keys(streams.keys); + ReadBufferFromString indexes(streams.indexes); + auto serialization = type->getDefaultSerialization(); + ISerialization::DeserializeBinaryBulkSettings settings; + settings.getter = makeGetter(keys, indexes); + settings.native_format = false; + ISerialization::DeserializeBinaryBulkStatePtr state; + serialization->deserializeBinaryBulkStatePrefix(settings, state, nullptr); + ColumnPtr column = type->createColumn(); + serialization->deserializeBinaryBulkWithMultipleStreams(column, 0, rows, settings, state, nullptr); + return column; +} + +void expectIncorrectData(const DataTypePtr & type, const Streams & streams, size_t rows) +{ + try + { + deserialize(type, streams, rows); + FAIL() << "accepted an index past the keys"; + } + catch (const Exception & e) + { + ASSERT_EQ(e.code(), ErrorCodes::INCORRECT_DATA) << e.message(); + } +} + +/// Calls `check` for `LowCardinality(String)` and `LowCardinality(Nullable(UInt64))`, each serialized with a dictionary +/// of 2 keys (so most values become additional keys) and with one large enough for all values (no additional keys). +template +void forEachCase(Check && check) +{ + for (bool nullable : {false, true}) + { + DataTypePtr inner = nullable ? makeNullable(std::make_shared()) : std::make_shared(); + auto type = std::make_shared(inner); + auto column = type->createColumn(); + for (size_t i = 0; i < 20; ++i) + { + if (nullable) + column->insert(i % 6 == 0 ? Field() : Field(UInt64(i % 6))); + else + column->insert(String(1, static_cast('a' + i % 5))); + } + + for (size_t max_dictionary_size : {2, 8192}) + { + SCOPED_TRACE(type->getName() + " with max dictionary size " + std::to_string(max_dictionary_size)); + auto streams = serialize(type, *column, max_dictionary_size); + + constexpr UInt64 need_global_dictionary_bit = 1ULL << 8; + constexpr UInt64 has_additional_keys_bit = 1ULL << 9; + const UInt64 index_type = unalignedLoadLittleEndian(streams.indexes.data()); + const bool has_additional_keys = (index_type & has_additional_keys_bit) != 0; + ASSERT_NE(index_type & need_global_dictionary_bit, 0u); + ASSERT_EQ(has_additional_keys, max_dictionary_size == 2); + ASSERT_LE(index_type & 0xff, 3u); + + /// The keys stream starts with the version, then the number of keys; the indexes stream starts with the index type, + /// then the number of additional keys if there are any. + const UInt64 num_keys = unalignedLoadLittleEndian(streams.keys.data() + 8) + + (has_additional_keys ? unalignedLoadLittleEndian(streams.indexes.data() + 8) : 0); + const size_t index_width = 1ULL << (index_type & 0xff); + + check(type, *column, std::move(streams), num_keys, index_width); + } + } +} + +} + +TEST(SerializationLowCardinality, ValidStreamsRoundTrip) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64, size_t) + { + auto result = deserialize(type, streams, column.size()); + ASSERT_EQ(result->size(), column.size()); + for (size_t i = 0; i < column.size(); ++i) + ASSERT_EQ((*result)[i], column[i]) << "row " << i; + }); +} + +/// The indexes come from the data, so they have to be checked against the keys of the dictionary and the additional keys. +TEST(SerializationLowCardinality, IndexPastTheKeysIsRejected) +{ + MainThreadStatus::getInstance(); + forEachCase([](const DataTypePtr & type, const IColumn & column, Streams streams, UInt64 num_keys, size_t index_width) + { + const size_t rows = column.size(); + const size_t indexes_begin = streams.indexes.size() - rows * index_width; + + /// The same indexes as `UInt64` (index type 3, the low byte of the index type) read back the same values... + Streams wide{streams.keys, streams.indexes.substr(0, indexes_begin)}; + wide.indexes[0] = 3; + for (size_t row = 0; row < rows; ++row) + { + UInt64 index = 0; + for (size_t i = 0; i < index_width; ++i) + index |= UInt64(static_cast(streams.indexes[indexes_begin + row * index_width + i])) << (8 * i); + for (size_t i = 0; i < 8; ++i) + wide.indexes.push_back(static_cast(index >> (8 * i))); + } + auto result = deserialize(type, wide, rows); + ASSERT_EQ(result->size(), rows); + for (size_t row = 0; row < rows; ++row) + ASSERT_EQ((*result)[row], column[row]) << "row " << row; + + /// ...and the largest possible last index is rejected before `mapIndexWithAdditionalKeys` sizes its overflow map by it. + std::fill(wide.indexes.end() - 8, wide.indexes.end(), '\xff'); + expectIncorrectData(type, wide, rows); + + /// The last index of the original stream becomes the first value past the keys. + ASSERT_LE(num_keys, std::numeric_limits::max() >> (64 - 8 * index_width)); + for (size_t i = 0; i < index_width; ++i) + streams.indexes[streams.indexes.size() - index_width + i] = static_cast(num_keys >> (8 * i)); + expectIncorrectData(type, streams, rows); + }); +} diff --git a/src/Databases/DataLake/GlueCatalog.cpp b/src/Databases/DataLake/GlueCatalog.cpp index df08b71baf8a..3ab1c7067a12 100644 --- a/src/Databases/DataLake/GlueCatalog.cpp +++ b/src/Databases/DataLake/GlueCatalog.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -77,8 +78,8 @@ namespace DB::ServerSetting namespace CurrentMetrics { - extern const Metric MarkCacheBytes; - extern const Metric MarkCacheFiles; + extern const Metric GlueCatalogSchemaCacheBytes; + extern const Metric GlueCatalogSchemaCacheEntries; } namespace DataLake @@ -95,7 +96,7 @@ GlueCatalog::GlueCatalog( , region(settings_.region) , settings(settings_) , table_engine_definition(table_engine_definition_) - , metadata_objects(CurrentMetrics::MarkCacheBytes, CurrentMetrics::MarkCacheFiles, 1024) + , current_schema_field_types(CurrentMetrics::GlueCatalogSchemaCacheBytes, CurrentMetrics::GlueCatalogSchemaCacheEntries, 16_MiB) { DB::S3::CredentialsConfiguration creds_config; creds_config.use_environment_credentials = true; @@ -466,7 +467,7 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet const String & metadata_uri = table_specific_properties->iceberg_metadata_file_location; - if (!metadata_objects.get(metadata_uri)) + auto [field_types, _] = current_schema_field_types.getOrSet(metadata_uri, [&] { auto [object_storage, bucket_name, metadata_path] = createObjectStorageForEarlyTableAccess(metadata_uri, table_metadata); const auto & read_settings = getContext()->getReadSettings(); @@ -479,28 +480,42 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(metadata_file_content); auto metadata_object = result.extract(); - metadata_objects.set(metadata_uri, std::make_shared(metadata_object)); - } + return std::make_shared(getCurrentSchemaFieldTypes(metadata_object)); + }); + + auto it = field_types->find(column_name); + return it != field_types->end() && it->second == DB::Iceberg::f_timestamptz; +} - auto metadata_object = *metadata_objects.get(metadata_uri); +GlueCatalog::FieldTypes GlueCatalog::getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object) +{ + FieldTypes result; auto current_schema_id = metadata_object->getValue("current-schema-id"); auto schemas = metadata_object->getArray(DB::Iceberg::f_schemas); for (size_t i = 0; i < schemas->size(); ++i) { auto schema = schemas->getObject(static_cast(i)); - if (schema->getValue("schema-id") == current_schema_id) + if (schema->getValue("schema-id") != current_schema_id) + continue; + + auto fields = schema->getArray(DB::Iceberg::f_fields); + for (size_t j = 0; j < fields->size(); ++j) { - auto fields = schema->getArray(DB::Iceberg::f_fields); - for (size_t j = 0; j < fields->size(); ++j) - { - auto field = fields->getObject(static_cast(j)); - if (field->getValue(DB::Iceberg::f_name) == column_name) - return field->getValue(DB::Iceberg::f_type) == DB::Iceberg::f_timestamptz; - } + auto field = fields->getObject(static_cast(j)); + auto type = field->get(DB::Iceberg::f_type); + if (type.isString()) + result.emplace(field->getValue(DB::Iceberg::f_name), type.extract()); } } + return result; +} - return false; +size_t GlueCatalog::FieldTypesWeightFunction::operator()(const FieldTypes & field_types) const +{ + size_t result = 0; + for (const auto & [name, type] : field_types) + result += sizeof(FieldTypes::value_type) + name.size() + type.size(); + return result; } GlueCatalog::ObjectStorageWithPath GlueCatalog::createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const diff --git a/src/Databases/DataLake/GlueCatalog.h b/src/Databases/DataLake/GlueCatalog.h index c65c69a2a75a..e0485de5e0e0 100644 --- a/src/Databases/DataLake/GlueCatalog.h +++ b/src/Databases/DataLake/GlueCatalog.h @@ -83,9 +83,18 @@ class GlueCatalog final : public ICatalog, private DB::WithContext const String & column_name, const String & glue_column_type); + using FieldTypes = std::unordered_map; + + static FieldTypes getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object); + private: void createNamespaceIfNotExists(const String & namespace_name) const; + struct FieldTypesWeightFunction + { + size_t operator()(const FieldTypes & field_types) const; + }; + std::unique_ptr glue_client; const LoggerPtr log; std::shared_ptr credentials_provider; @@ -112,7 +121,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext ObjectStorageWithPath createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const; - mutable DB::CacheBase metadata_objects; + mutable DB::CacheBase, FieldTypesWeightFunction> current_schema_field_types; }; } diff --git a/src/Databases/DataLake/HiveCatalog.cpp b/src/Databases/DataLake/HiveCatalog.cpp index b86f70dfc4b5..918ed836737e 100644 --- a/src/Databases/DataLake/HiveCatalog.cpp +++ b/src/Databases/DataLake/HiveCatalog.cpp @@ -10,8 +10,10 @@ #include #include #include +#include #include #include +#include #include namespace DB::ErrorCodes @@ -64,11 +66,23 @@ std::pair parseHostPort(const String & url) } } +std::shared_ptr createSocket(const String & base_url, const DB::ContextPtr & context) +{ + auto [host, port] = parseHostPort(base_url); + + /// Also rejects control characters such as NUL, which `getaddrinfo` would truncate the host at. + context->getRemoteHostFilter().checkAndGetCanonicalHostAndPort( + host + ":" + std::to_string(port), static_cast(port), "Hive metastore address"); + + return std::make_shared(host, port); +} + } -HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr) +HiveCatalog::HiveCatalog(const std::string & warehouse_, const std::string & base_url_, DB::ContextPtr context_) : ICatalog(warehouse_) - , socket(new apache::thrift::transport::TSocket(parseHostPort(base_url_).first, parseHostPort(base_url_).second)) + , DB::WithContext(context_) + , socket(createSocket(base_url_, context_)) , transport(new apache::thrift::transport::TBufferedTransport(socket)) , protocol(new apache::thrift::protocol::TBinaryProtocol(transport)) , client(protocol) diff --git a/src/Databases/DatabaseReplicated.cpp b/src/Databases/DatabaseReplicated.cpp index 94d0aa46efd8..8428ea1c4c20 100644 --- a/src/Databases/DatabaseReplicated.cpp +++ b/src/Databases/DatabaseReplicated.cpp @@ -63,6 +63,7 @@ #include #include #include +#include #include #include @@ -798,14 +799,14 @@ void DatabaseReplicated::createEmptyLogEntry(const ZooKeeperPtr & current_zookee bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, SyncReplicaMode mode) { chassert(mode == SyncReplicaMode::DEFAULT || mode == SyncReplicaMode::STRICT); - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - return false; - } + /// The worker can be stopped and replaced concurrently (`SYSTEM RESTORE DATABASE REPLICA`, `DROP DATABASE`): + /// the reference keeps it alive, and a stopped worker returns from the wait. + auto worker = tryGetDDLWorker(); + if (!worker) + return false; if (mode == SyncReplicaMode::DEFAULT) - return ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms); + return worker->waitForReplicaToProcessAllEntries(timeout_ms); Stopwatch elapsed; while (true) @@ -814,15 +815,19 @@ bool DatabaseReplicated::waitForReplicaToProcessAllEntries(UInt64 timeout_ms, Sy if (elapsed_ms > timeout_ms) return false; - if (ddl_worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) + if (worker->waitForReplicaToProcessAllEntries(timeout_ms - elapsed_ms)) return true; - UInt32 our_log_ptr = ddl_worker->getLogPointer(); + UInt32 our_log_ptr = worker->getLogPointer(); UInt32 max_log_ptr = parse(getZooKeeper()->get(fs::path(zookeeper_path) / "max_log_ptr")); bool became_synced = our_log_ptr + db_settings[DatabaseReplicatedSetting::max_replication_lag_to_enqueue] >= max_log_ptr; if (became_synced) return true; + /// The worker was stopped (e.g. by `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE`), it will not make progress. + if (worker->isStopped()) + return false; + /// max_log_ptr might be increased while we were waiting - retry until replication lag is below the threshold } } @@ -995,11 +1000,36 @@ void DatabaseReplicated::initDDLWorkerUnlocked() chassert(!is_probably_dropped.load()); chassert(!ddl_worker_initialized.load()); - ddl_worker = std::make_unique(this, getContext()); + replaceDDLWorkerUnlocked(std::make_shared(this, getContext())); ddl_worker->startup(); ddl_worker_initialized = true; } +std::shared_ptr DatabaseReplicated::tryGetDDLWorker() const +{ + std::lock_guard lock{ddl_worker_mutex}; + if (!ddl_worker || is_probably_dropped) + return nullptr; + return ddl_worker; +} + +std::shared_ptr DatabaseReplicated::replaceDDLWorkerUnlocked(std::shared_ptr new_worker) +{ + std::lock_guard lock{ddl_worker_ptr_mutex}; + std::swap(ddl_worker, new_worker); + return new_worker; +} + +bool DatabaseReplicated::isDDLWorkerCurrentlyActive() const +{ + std::shared_ptr worker; + { + std::lock_guard lock{ddl_worker_ptr_mutex}; + worker = ddl_worker; + } + return worker && worker->isCurrentlyActive(); +} + void DatabaseReplicated::restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper) { auto local_context = getContext(); @@ -1058,7 +1088,7 @@ void DatabaseReplicated::reinitializeDDLWorker() ddl_worker->shutdown(); { ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } } @@ -1279,7 +1309,7 @@ bool DatabaseReplicated::checkDigestValid(const ContextPtr & local_context) cons LOG_TEST(log, "Current in-memory metadata digest: {}", tables_metadata_digest); /// Database is probably being dropped - if (!local_context->getZooKeeperMetadataTransaction() && (!ddl_worker || !ddl_worker->isCurrentlyActive())) + if (!local_context->getZooKeeperMetadataTransaction() && !isDDLWorkerCurrentlyActive()) return true; /// SYSTEM RESTART REPLICA temporarily removes a table from the in-memory tables map @@ -1385,13 +1415,12 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex if (is_readonly) throw Exception(ErrorCodes::NO_ZOOKEEPER, "Database is in readonly mode, because it cannot connect to ZooKeeper"); - String host_fqdn_id; - { - std::lock_guard lock{ddl_worker_mutex}; - if (!ddl_worker || is_probably_dropped) - throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); - host_fqdn_id = ddl_worker->getCommonHostID(); - } + /// Hold our own reference: `SYSTEM RESTORE DATABASE REPLICA` or `DROP DATABASE` can stop and replace the worker + /// while this query waits in `tryEnqueueAndExecuteEntry`. A stopped worker makes it throw instead of executing. + auto worker = tryGetDDLWorker(); + if (!worker) + throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Database is not initialized or is being dropped"); + String host_fqdn_id = worker->getCommonHostID(); if (!flags.internal && query_context->isDDLOrOnClusterInternal()) throw Exception(ErrorCodes::INCORRECT_QUERY, "It's not initial query. ON CLUSTER is not allowed for Replicated database."); @@ -1406,7 +1435,7 @@ BlockIO DatabaseReplicated::tryEnqueueReplicatedDDL(const ASTPtr & query, Contex entry.tracing_context = OpenTelemetry::CurrentContext(); entry.initial_query_id = query_context->getClientInfo().initial_query_id; entry.is_backup_restore = flags.distributed_backup_restore; - String node_path = ddl_worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); + String node_path = worker->tryEnqueueAndExecuteEntry(entry, query_context, flags.internal); Strings hosts_to_wait; Strings unfiltered_hosts = getZooKeeper()->getChildren(zookeeper_path + "/replicas"); @@ -2078,10 +2107,63 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) auto component_guard = Coordination::setCurrentComponent("DatabaseReplicated::restoreDatabaseMetadataInKeeper"); waitDatabaseStarted(); + /// Concurrent restores of the same database would stop and re-create the DDL worker under each other + /// and race on the replication state that `initDatabaseReplica` rewrites (e.g. `max_log_ptr_at_creation`). + std::lock_guard restore_lock{restore_in_keeper_mutex}; + auto zookeeper = getZooKeeper(); if (!zookeeper) throw Exception(ErrorCodes::NO_ZOOKEEPER, "No ZooKeeper"); + /// Stop this replica's DDL worker before the calls below re-initialize replication state: + /// its recovery reads `max_log_ptr_at_creation` and compares the Keeper metadata with the + /// local table set, which those calls rewrite, and a recovery running against a half-updated + /// view detaches local tables into `_broken_replicated_tables`. + std::shared_ptr old_worker; + { + std::lock_guard lock{ddl_worker_mutex}; + old_worker = ddl_worker; + } + + /// Initial queries admitted by the worker execute and commit on their own threads, and `shutdown` does not wait + /// for them. Wait for them before rewriting the replication state: otherwise a query could commit its metadata + /// while the recovery of the new worker compares the Keeper snapshot with the local tables, and the recovery + /// would move the just created table to `_broken_replicated_tables` (or drop it). + /// Stop admitting new initial queries, but keep the worker running while waiting: an admitted query may depend + /// on it, e.g. an `ALTER` of a `ReplicatedMergeTree` table with `alter_sync` waits for its `ALTER_METADATA` entry, + /// which the table executes only while `canExecuteReplicatedMetadataAlter` is true. + /// Not under `ddl_worker_mutex`, because these queries may need it. + if (old_worker) + { + LOG_TRACE(log, "Waiting for initial queries before restoring database metadata in Keeper."); + old_worker->stopInitialQueries(); + old_worker->waitForForegroundTasks(); + } + + { + std::lock_guard lock{ddl_worker_mutex}; + /// Only `restoreDatabaseInKeeper` (serialized by `restore_in_keeper_mutex`) creates a new worker after startup, + /// so the worker is either still the same or was removed by a concurrent `DROP DATABASE`. + chassert(!ddl_worker || ddl_worker == old_worker); + if (ddl_worker) + { + LOG_TRACE(log, "Stopping DDL worker before restoring database metadata in Keeper."); + ddl_worker->shutdown(); + ddl_worker_initialized = false; + replaceDDLWorkerUnlocked(nullptr); + } + } + old_worker.reset(); + + /// If the restore fails, reinitialize the DDL worker so the database remains functional. + /// SAFE: the body runs while an exception propagates and can itself throw (thread + /// creation), which must not replace the restore's own error. + bool need_reinitialize_ddl_worker = true; + SCOPE_EXIT_SAFE({ + if (need_reinitialize_ddl_worker) + reinitializeDDLWorker(); + }); + try { restoreDatabaseNodesInKeeper(zookeeper); @@ -2099,6 +2181,8 @@ void DatabaseReplicated::restoreDatabaseInKeeper(ContextPtr) /// Force the database to recover to update the restored metadata auto current_zookeeper = getZooKeeper(); current_zookeeper->set(replica_path + "/digest", DatabaseReplicatedDDLWorker::FORCE_AUTO_RECOVERY_DIGEST); + + need_reinitialize_ddl_worker = false; reinitializeDDLWorker(); } @@ -2173,7 +2257,7 @@ void DatabaseReplicated::shutdown() { std::lock_guard lock{ddl_worker_mutex}; ddl_worker_initialized = false; - ddl_worker = nullptr; + replaceDDLWorkerUnlocked(nullptr); } DatabaseAtomic::shutdown(); } @@ -2184,7 +2268,7 @@ void DatabaseReplicated::dropTable(ContextPtr local_context, const String & tabl waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); + assert(txn || !isDDLWorkerCurrentlyActive() || startsWith(table_name, ".inner_id.") || startsWith(table_name, ".tmp.inner_id.")); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); @@ -2293,7 +2377,7 @@ void DatabaseReplicated::commitCreateTable(const ASTCreateQuery & query, const S ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); String statement = getObjectDefinitionFromCreateQuery(query.clone()); if (txn && txn->isInitialQuery() && !txn->isCreateOrReplaceQuery()) @@ -2321,7 +2405,7 @@ void DatabaseReplicated::commitAlterTable(const StorageID & table_id, const String & statement, ContextPtr query_context) { auto txn = query_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_id.table_name); @@ -2361,7 +2445,7 @@ void DatabaseReplicated::detachTablePermanently(ContextPtr local_context, const throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Support for DETACH TABLE PERMANENTLY is disabled"); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery()) { /// We have to remove metadata from zookeeper, because we do not distinguish permanently detached tables @@ -2386,7 +2470,7 @@ void DatabaseReplicated::removeDetachedPermanentlyFlag(ContextPtr local_context, waitDatabaseStarted(); auto txn = local_context->getZooKeeperMetadataTransaction(); - assert(!ddl_worker->isCurrentlyActive() || txn); + assert(txn || !isDDLWorkerCurrentlyActive()); if (txn && txn->isInitialQuery() && attach) { String metadata_zk_path = zookeeper_path + "/metadata/" + escapeForFileName(table_name); diff --git a/src/Databases/DatabaseReplicated.h b/src/Databases/DatabaseReplicated.h index aa1f030cb971..d0c6e9377560 100644 --- a/src/Databases/DatabaseReplicated.h +++ b/src/Databases/DatabaseReplicated.h @@ -230,6 +230,15 @@ class DatabaseReplicated : public DatabaseAtomic void stopLoading() override; void initDDLWorkerUnlocked() TSA_REQUIRES(ddl_worker_mutex); + /// Returns a reference to the DDL worker taken under `ddl_worker_mutex`, or nullptr if the database + /// is not initialized yet or is being dropped. + std::shared_ptr tryGetDDLWorker() const; + /// Assigns `ddl_worker` and returns the previous worker. Requires both mutexes, see `ddl_worker_ptr_mutex`. + std::shared_ptr replaceDDLWorkerUnlocked(std::shared_ptr new_worker) + TSA_REQUIRES(ddl_worker_mutex); + /// Whether the current DDL worker exists and is active. Does not take `ddl_worker_mutex`, + /// so it is safe to call from the callbacks of DDL queries executed by the worker. + bool isDDLWorkerCurrentlyActive() const; void restoreDatabaseNodesInKeeper(const ZooKeeperPtr & zookeeper); void reinitializeDDLWorker(); @@ -257,9 +266,20 @@ class DatabaseReplicated : public DatabaseAtomic std::atomic_bool is_probably_dropped = false; std::atomic_bool is_recovering = false; std::atomic_bool ddl_worker_initialized = false; - std::unique_ptr ddl_worker; + /// Shared, so that a query thread that uses the worker outside of `ddl_worker_mutex` (e.g. waiting in + /// `tryEnqueueAndExecuteEntry`) keeps it alive while `shutdown`, `restoreDatabaseInKeeper` or + /// `reinitializeDDLWorker` concurrently stop and replace it. Such a thread must take its own reference + /// under the mutex with `tryGetDDLWorker` and never dereference this member without the lock. + std::shared_ptr ddl_worker; mutable std::mutex ddl_worker_mutex; + /// Protects only the `ddl_worker` pointer itself: it is assigned under both mutexes and can be read under either. + /// Unlike `ddl_worker_mutex`, it is never held while the worker is shut down (and its threads are joined), + /// so the callbacks of DDL queries (`commitCreateTable`, `dropTable`, ...) can take it with `isDDLWorkerCurrentlyActive` + /// even when they are executed by the worker's threads or concurrently with `SYSTEM RESTORE DATABASE REPLICA`. + mutable std::mutex ddl_worker_ptr_mutex; UInt32 max_log_ptr_at_creation = 0; + /// Serializes `restoreDatabaseInKeeper`. Taken before `ddl_worker_mutex`. + std::mutex restore_in_keeper_mutex; /// Usually operation with metadata are single-threaded because of the way replication works, /// but StorageReplicatedMergeTree may call alterTable outside from DatabaseReplicatedDDLWorker causing race conditions. diff --git a/src/Databases/DatabaseReplicatedWorker.cpp b/src/Databases/DatabaseReplicatedWorker.cpp index 9112adf427d9..b3e7c1edd804 100644 --- a/src/Databases/DatabaseReplicatedWorker.cpp +++ b/src/Databases/DatabaseReplicatedWorker.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -49,6 +50,7 @@ namespace FailPoints extern const char database_replicated_delay_recovery[]; extern const char database_replicated_delay_entry_execution[]; extern const char database_replicated_stop_entry_execution[]; + extern const char database_replicated_pause_before_initial_query_execution[]; } @@ -160,9 +162,35 @@ void DatabaseReplicatedDDLWorker::shutdown() active_node_holder.reset(); active_node_holder_zookeeper.reset(); + /// Waiters in `tryEnqueueAndExecuteEntry` and `waitForReplicaToProcessAllEntries` (which may outlive the + /// shutdown, holding a reference to this worker) check `stop_flag` under `mutex`. Taking it before notifying + /// guarantees that each of them either sees the flag or receives the notification. + { + std::lock_guard lock{mutex}; + for (const auto & event : log_ptr_waiters) + event->set(); + } + wait_current_task_change.notify_all(); +} + +void DatabaseReplicatedDDLWorker::stopInitialQueries() +{ + { + std::lock_guard lock{mutex}; + initial_queries_stopped = true; + } wait_current_task_change.notify_all(); } +void DatabaseReplicatedDDLWorker::waitForForegroundTasks() +{ + std::unique_lock lock{mutex}; + chassert(stop_flag || initial_queries_stopped); + if (foreground_tasks) + LOG_TRACE(log, "Waiting for {} admitted initial queries", foreground_tasks); + foreground_tasks_finished.wait(lock, [&] { return foreground_tasks == 0; }); +} + void DatabaseReplicatedDDLWorker::initializeReplication() { /// Check if we need to recover replica. @@ -357,19 +385,31 @@ bool DatabaseReplicatedDDLWorker::waitForReplicaToProcessAllEntries(UInt64 timeo return zookeeper->expired() || current_task >= max_log || stop_flag; }); - if (!processed) + if (!processed || stop_flag) return false; } - /// Lets now wait for max_log_ptr to be processed - Coordination::Stat stat; + /// Lets now wait for max_log_ptr to be processed. + /// The event is set either by the watch or by `shutdown`, so a stopped worker does not wait for the whole timeout. auto event_ptr = std::make_shared(); + { + std::lock_guard lock{mutex}; + if (stop_flag) + return false; + log_ptr_waiters.insert(event_ptr); + } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + log_ptr_waiters.erase(event_ptr); + }); + + Coordination::Stat stat; auto new_log = zookeeper->get(our_log_ptr_path, &stat, event_ptr); if (new_log == toString(max_log_ptr)) return true; - return event_ptr->tryWait(timeout_ms); + return event_ptr->tryWait(timeout_ms) && !stop_flag; } @@ -473,9 +513,9 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr { assert(zookeeper->expired() || current_task <= entry_name); - if (zookeeper->expired() || stop_flag) + if (zookeeper->expired() || stop_flag || initial_queries_stopped) { - LOG_TRACE(log, "Not enqueueing query: {}", stop_flag ? "replication stopped" : "ZooKeeper session expired"); + LOG_TRACE(log, "Not enqueueing query: {}", zookeeper->expired() ? "ZooKeeper session expired" : "replication stopped"); throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "ZooKeeper session expired or replication stopped, try again"); } @@ -491,8 +531,21 @@ String DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry(DDLLogEntry & entr if (!processed) throw Exception(ErrorCodes::UNFINISHED, "Timeout: Cannot enqueue query on this replica, " "most likely because replica is busy with previous queue entries"); + + /// The predicate above has checked `stop_flag` and `initial_queries_stopped` under `mutex`, + /// so `waitForForegroundTasks` will wait for this query. + ++foreground_tasks; } + SCOPE_EXIT({ + std::lock_guard lock{mutex}; + --foreground_tasks; + if (foreground_tasks == 0) + foreground_tasks_finished.notify_all(); + }); + + FailPointInjection::pauseFailPoint(FailPoints::database_replicated_pause_before_initial_query_execution); + if (entry.parent_table_uuid.has_value() && !checkParentTableExists(entry.parent_table_uuid.value())) throw Exception(ErrorCodes::TABLE_IS_DROPPED, "Parent table doesn't exist"); diff --git a/src/Databases/DatabaseReplicatedWorker.h b/src/Databases/DatabaseReplicatedWorker.h index 5583f112662f..1f03d0722955 100644 --- a/src/Databases/DatabaseReplicatedWorker.h +++ b/src/Databases/DatabaseReplicatedWorker.h @@ -2,6 +2,9 @@ #include #include #include +#include + +#include namespace DB { @@ -31,8 +34,21 @@ class DatabaseReplicatedDDLWorker : public DDLWorker void shutdown() override; + /// Returns false on timeout or if the worker is stopped before or during the wait. bool waitForReplicaToProcessAllEntries(UInt64 timeout_ms); + /// The worker was shut down. A stopped worker is never restarted, the database replaces it with a new one. + bool isStopped() const { return stop_flag; } + + /// Makes `tryEnqueueAndExecuteEntry` reject new initial queries (as if the worker was stopped), + /// while the worker itself keeps running. Irreversible: the database replaces such a worker afterwards. + void stopInitialQueries(); + + /// Waits until the initial queries that `tryEnqueueAndExecuteEntry` admitted for execution finish. + /// They execute and commit on the submitting threads, so `shutdown` (which joins only the worker's + /// own threads) does not wait for them. Requires `stopInitialQueries` or `shutdown` to be called before. + void waitForForegroundTasks(); + static String enqueueQueryImpl(const ZooKeeperPtr & zookeeper, DDLLogEntry & entry, DatabaseReplicated * const database, bool committed = false, Coordination::Requests additional_checks = {}); /// NOLINT @@ -68,6 +84,15 @@ class DatabaseReplicatedDDLWorker : public DDLWorker std::condition_variable wait_current_task_change; String current_task; + /// The number of initial queries being executed by `tryEnqueueAndExecuteEntry` on the submitting threads. + /// Protected by `mutex`, see `waitForForegroundTasks`. + size_t foreground_tasks = 0; + std::condition_variable foreground_tasks_finished; + /// Set by `stopInitialQueries`. Protected by `mutex`. + bool initial_queries_stopped = false; + /// Events of `waitForReplicaToProcessAllEntries` waiting for our `log_ptr` in Keeper to change. + /// `shutdown` sets them, so that the waiters return without waiting for the timeout. + std::unordered_set> log_ptr_waiters; std::atomic logs_to_keep = std::numeric_limits::max(); std::atomic_bool unsynced_after_recovery = false; diff --git a/src/Databases/MySQL/DatabaseMySQL.cpp b/src/Databases/MySQL/DatabaseMySQL.cpp index 1c85c1ef38d7..ce3ca3203f83 100644 --- a/src/Databases/MySQL/DatabaseMySQL.cpp +++ b/src/Databases/MySQL/DatabaseMySQL.cpp @@ -38,6 +38,7 @@ # include # include # include +# include # include #if CLICKHOUSE_CLOUD @@ -643,6 +644,14 @@ void registerDatabaseMySQL(DatabaseFactory & factory) configuration.username = safeGetLiteralValue(arguments[2], engine_name); configuration.password = safeGetLiteralValue(arguments[3], engine_name); } + + /// Skip only the server's own metadata replay. + if (!(args.is_metadata_replay && args.mode >= LoadingStrictnessLevel::ATTACH)) + { + for (const auto & address : configuration.addresses) + args.context->getRemoteHostFilter().checkHostAndPort(address.first, toString(address.second)); + } + mysql_settings->loadFromQueryContext(args.context, *engine_define); if (engine_define->settings) mysql_settings->loadFromQuery(*engine_define); diff --git a/src/Dictionaries/MongoDBDictionarySource.cpp b/src/Dictionaries/MongoDBDictionarySource.cpp index 437dc9639d5b..21fc0088c6ba 100644 --- a/src/Dictionaries/MongoDBDictionarySource.cpp +++ b/src/Dictionaries/MongoDBDictionarySource.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -45,7 +46,7 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) Block & sample_block, ContextPtr context, const std::string & /* default_database */, - bool /* created_from_ddl */) + bool created_from_ddl) { const auto config_prefix = root_config_prefix + ".mongodb"; auto configuration = std::make_shared(); @@ -102,6 +103,10 @@ void registerDictionarySourceMongoDB(DictionarySourceFactory & factory) configuration->checkHosts(context); configuration->checkCollection(); + /// A DDL dictionary is loaded by the server with the global context, so no session setting can permit server credentials here. + if (created_from_ddl && context->getApplicationType() != Context::ApplicationType::LOCAL) + configuration->checkServerCredentialsForDictionary(); + return std::make_unique(dict_struct, std::move(configuration), std::make_shared(sample_block)); }; #else diff --git a/src/Dictionaries/SSDCacheDictionaryStorage.h b/src/Dictionaries/SSDCacheDictionaryStorage.h index e6a732ef34a1..afbf9c3170e2 100644 --- a/src/Dictionaries/SSDCacheDictionaryStorage.h +++ b/src/Dictionaries/SSDCacheDictionaryStorage.h @@ -1370,9 +1370,10 @@ class SSDCacheDictionaryStorage final : public ICacheDictionaryStorage if (memory_buffer_partitions.size() < configuration.max_partitions_count) { /// Try tro create next partition without reusing old partitions - ++current_partition_index; file_buffer.allocateSizeForNextPartition(); memory_buffer_partitions.emplace_back(configuration.block_size, configuration.write_buffer_blocks_size); + /// Advance only after both calls succeed, so the index stays valid if one of them throws. + ++current_partition_index; } else { diff --git a/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp b/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp index 7d5849f91375..8c8226001be9 100644 --- a/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp +++ b/src/Dictionaries/YAMLRegExpTreeDictionarySource.cpp @@ -256,7 +256,7 @@ void parseMatchList(UInt64 parent_id, UInt64 & id, const YAML::Node & node, Resu { if (!node.IsSequence()) { - throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Configuration {} must be a yaml list of match rules", node.as()); + throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "Configuration must be a yaml list of match rules"); } for (const auto & child_node : node) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp index 41e7a8ced5cf..cc7273537fa2 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp @@ -88,6 +88,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int AZURE_BLOB_STORAGE_ERROR; extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; } @@ -227,6 +228,28 @@ String ConnectionParams::getConnectionURL() const return endpoint.storage_account_url; } +String ConnectionParams::getConnectionURLWithoutQuery() const +{ + if (std::holds_alternative(auth_method)) + { + try + { + /// `ParseConnectionString` appends the SAS of the connection string to `BlobServiceUrl` as its query. + auto url = Azure::Storage::_internal::ParseConnectionString(endpoint.storage_account_url).BlobServiceUrl; + const auto query = url.GetQueryParameters(); + for (const auto & [key, value] : query) + url.RemoveQueryParameter(key); + return url.GetAbsoluteUrl(); + } + catch (const std::logic_error & e) + { + translateAzureSdkParseError(e); + } + } + + return endpoint.storage_account_url.substr(0, endpoint.storage_account_url.find_first_of("?#")); +} + std::unique_ptr ConnectionParams::createForService() const { try @@ -359,6 +382,13 @@ std::unique_ptr getContainerClient(const ConnectionParams & par } } +String getETag(const Azure::ETag & etag, const String & blob_path) +{ + if (!etag.HasValue()) + throw Exception(ErrorCodes::AZURE_BLOB_STORAGE_ERROR, "Azure Blob Storage endpoint did not return an ETag for blob {}", blob_path); + return etag.ToString(); +} + AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { if (config.has(config_prefix + ".account_key") && config.has(config_prefix + ".account_name")) diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h index b282df96fae8..7387f59df565 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.h @@ -146,6 +146,8 @@ struct ConnectionParams String getContainer() const { return endpoint.container_name; } String getConnectionURL() const; + /// Without the query, which can be a SAS, for where the url only names the endpoint (logs, errors, cache keys). + String getConnectionURLWithoutQuery() const; std::unique_ptr createForService() const; std::unique_ptr createForContainer() const; @@ -163,6 +165,10 @@ BlobClientOptions getClientOptions( AuthMethod getAuthMethod(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); +/// `ETag` is an optional response header, and `Azure::ETag::ToString` aborts the process when the tag is absent +/// (also in release builds). Use this function instead: it throws an exception when the endpoint did not send the tag. +String getETag(const Azure::ETag & etag, const String & blob_path); + #endif Endpoint processEndpoint(const Poco::Util::AbstractConfiguration & config, const String & config_prefix); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp index 80d0714c83ab..d59df48d18a7 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.cpp @@ -100,7 +100,7 @@ class AzureIteratorAsync final : public IObjectStorageIteratorAsync .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); @@ -209,7 +209,7 @@ void AzureObjectStorage::listObjects(const std::string & path, RelativePathsWith .last_modified = Poco::Timestamp::fromEpochTime( std::chrono::duration_cast( static_cast(blob.Details.LastModified).time_since_epoch()).count()), - .etag = blob.Details.ETag.ToString(), + .etag = AzureBlobStorage::getETag(blob.Details.ETag, blob.Name), .tags = {}, .attributes = {}, })); diff --git a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp index 241e8c8f7550..ec6a692f6fe6 100644 --- a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp +++ b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp @@ -81,6 +81,7 @@ AsynchronousBoundedReadBuffer::AsynchronousBoundedReadBuffer( { use_page_cache = true; buffer_size = read_settings.page_cache_block_size; + padded = false; } LOG_TEST(log, "Using buffer size {} while reading {}", buffer_size, file_name); diff --git a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp index 672d1bfbf8fb..f206567eea2a 100644 --- a/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp +++ b/src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp @@ -431,7 +431,7 @@ void ReadBufferFromAzureBlobStorage::setMetadataFromResponse(const Azure::Storag { ObjectMetadata new_metadata; new_metadata.size_bytes = blob_size; - new_metadata.etag = details.ETag.ToString(); + new_metadata.etag = AzureBlobStorage::getETag(details.ETag, path); new_metadata.last_modified = static_cast(details.LastModified).time_since_epoch().count(); if (!details.Metadata.empty()) { diff --git a/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp new file mode 100644 index 000000000000..161256caba5b --- /dev/null +++ b/src/Disks/tests/gtest_azure_read_buffer_missing_etag.cpp @@ -0,0 +1,106 @@ +#include "config.h" + +#if USE_AZURE_BLOB_STORAGE + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ + extern const int AZURE_BLOB_STORAGE_ERROR; +} + +namespace +{ + +class OwningBodyStream : public Azure::Core::IO::BodyStream +{ +public: + explicit OwningBodyStream(std::vector data_) : data(std::move(data_)) { } + + int64_t Length() const override { return static_cast(data.size()); } + + void Rewind() override { position = 0; } + +private: + size_t OnRead(uint8_t * buffer, size_t count, const Azure::Core::Context &) override + { + const size_t to_read = std::min(count, data.size() - position); + if (to_read != 0) + memcpy(buffer, data.data() + position, to_read); + position += to_read; + return to_read; + } + + std::vector data; + size_t position = 0; +}; + +/// A fake Azure endpoint that serves a 10-byte blob in a response without the optional `ETag` header. +class EndpointWithoutETag : public Azure::Core::Http::HttpTransport +{ +public: + std::unique_ptr Send(Azure::Core::Http::Request &, const Azure::Core::Context &) override + { + constexpr size_t blob_size = 10; + auto response = std::make_unique( + 1, 1, Azure::Core::Http::HttpStatusCode::PartialContent, "Partial Content"); + response->SetHeader("Content-Length", std::to_string(blob_size)); + response->SetHeader("Content-Range", "bytes 0-" + std::to_string(blob_size - 1) + "/" + std::to_string(blob_size)); + response->SetHeader("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT"); + response->SetHeader("x-ms-blob-type", "BlockBlob"); + response->SetBodyStream(std::make_unique(std::vector(blob_size, 'a'))); + return response; + } +}; + +} + +/// `Azure::ETag::ToString` aborts the process on an absent tag, also in release builds. +/// A download response without `ETag` must fail the read with an exception instead. +TEST(AzureReadBuffer, MissingETagIsAnException) +{ + Azure::Storage::Blobs::BlobClientOptions client_options; + client_options.Retry.MaxRetries = 0; + client_options.Transport.Transport = std::make_shared(); + + auto container_client = std::make_shared( + Azure::Storage::Blobs::BlobContainerClient("http://azure.invalid/container", client_options), /* blob_prefix */ ""); + + DB::ReadBufferFromAzureBlobStorage buffer( + container_client, + "blob", + DB::ReadSettings{}, + /* max_single_read_retries */ 1, + /* max_single_download_retries */ 1); + + std::optional error_code; + try + { + std::string data; + DB::readStringUntilEOF(data, buffer); + } + catch (const DB::Exception & e) + { + error_code = e.code(); + } + ASSERT_EQ(error_code, std::optional(DB::ErrorCodes::AZURE_BLOB_STORAGE_ERROR)); +} + +#endif diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index 807bf03ce4f7..d82cf35bef76 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -313,6 +313,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se format_settings.arrow.output_fixed_string_as_fixed_byte_array = settings[Setting::output_format_arrow_fixed_string_as_fixed_byte_array]; format_settings.arrow.output_compression_method = settings[Setting::output_format_arrow_compression_method]; format_settings.arrow.output_date_as_uint16 = settings[Setting::output_format_arrow_date_as_uint16]; + format_settings.arrow.output_max_record_batch_bytes = settings[Setting::output_format_arrow_max_record_batch_size_bytes]; format_settings.orc.allow_missing_columns = settings[Setting::input_format_orc_allow_missing_columns]; format_settings.orc.row_batch_size = settings[Setting::input_format_orc_row_batch_size]; format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference = settings[Setting::input_format_orc_skip_columns_with_unsupported_types_in_schema_inference]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 8cc2792c21f8..7ad2d29e34f3 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -5,9 +5,15 @@ #include #include +#include + namespace DB { +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, and the Apache Arrow +/// builders additionally reject the last representable value. +constexpr UInt64 MAX_ARROW_BUFFER_SIZE = std::numeric_limits::max() - 1; + /** * Various tweaks for input/output formats. Text serialization/deserialization * of data types also depend on some of these settings. It is different from @@ -166,6 +172,8 @@ struct FormatSettings bool output_fixed_string_as_fixed_byte_array = true; ArrowCompression output_compression_method = ArrowCompression::NONE; bool output_date_as_uint16 = false; + /// Upper bound on one record batch. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; } arrow{}; struct diff --git a/src/Formats/ProtobufSerializer.cpp b/src/Formats/ProtobufSerializer.cpp index 420d951ed7c0..49089ea851d0 100644 --- a/src/Formats/ProtobufSerializer.cpp +++ b/src/Formats/ProtobufSerializer.cpp @@ -4122,6 +4122,9 @@ namespace if (!name_and_type) return std::nullopt; const auto * tuple_type = assert_cast(name_and_type->type.get()); + /// The key or the value of the map entry was skipped as unsupported, so the map is skipped as a whole. + if (tuple_type->getElements().size() != 2) + return std::nullopt; return NameAndTypePair{name_and_type->name, std::make_shared(tuple_type->getElements())}; } diff --git a/src/Functions/HasSubsequenceImpl.h b/src/Functions/HasSubsequenceImpl.h index 30a522ea50a6..17f370e68344 100644 --- a/src/Functions/HasSubsequenceImpl.h +++ b/src/Functions/HasSubsequenceImpl.h @@ -127,6 +127,8 @@ class HasSubsequenceImpl : public IFunction if (!needle_size) return 1; + if (!haystack_size) + return 0; auto haystack_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(haystack_pos), haystack_end - haystack_pos); auto needle_code_point = UTF8::convertUTF8ToCodePoint(reinterpret_cast(needle_pos), needle_end - needle_pos); diff --git a/src/Functions/URL/protocol.h b/src/Functions/URL/protocol.h index 5e90f538ff1e..5542458a75d9 100644 --- a/src/Functions/URL/protocol.h +++ b/src/Functions/URL/protocol.h @@ -10,6 +10,9 @@ namespace DB /// Extracts scheme from given url. inline std::string_view getURLScheme(const char * data, size_t size) { + if (size == 0) + return {}; + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) const char * pos = data; const char * end = data + size; diff --git a/src/IO/CachedInMemoryReadBufferFromFile.cpp b/src/IO/CachedInMemoryReadBufferFromFile.cpp index c3241d65aede..c2489460cad5 100644 --- a/src/IO/CachedInMemoryReadBufferFromFile.cpp +++ b/src/IO/CachedInMemoryReadBufferFromFile.cpp @@ -26,6 +26,8 @@ CachedInMemoryReadBufferFromFile::CachedInMemoryReadBufferFromFile( , inner_read_until_position(read_until_position) { cache_key.offset = 0; + /// The working buffer is a page cache cell, an exact-size allocation: nothing past its end is readable. + padded = false; } String CachedInMemoryReadBufferFromFile::getFileName() const diff --git a/src/IO/ReadWriteBufferFromHTTP.cpp b/src/IO/ReadWriteBufferFromHTTP.cpp index 02834987d538..29d108ac9ca2 100644 --- a/src/IO/ReadWriteBufferFromHTTP.cpp +++ b/src/IO/ReadWriteBufferFromHTTP.cpp @@ -28,7 +28,8 @@ bool isRetriableError(const Poco::Net::HTTPResponse::HTTPStatus http_status) noe Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND, Poco::Net::HTTPResponse::HTTPStatus::HTTP_FORBIDDEN, Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_IMPLEMENTED, - Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED}; + Poco::Net::HTTPResponse::HTTPStatus::HTTP_METHOD_NOT_ALLOWED, + Poco::Net::HTTPResponse::HTTPStatus::HTTP_CONFLICT}; return std::all_of( non_retriable_errors.begin(), non_retriable_errors.end(), [&](const auto status) { return http_status != status; }); diff --git a/src/IO/S3/Client.cpp b/src/IO/S3/Client.cpp index 33dd73a0f579..8e09316d4de7 100644 --- a/src/IO/S3/Client.cpp +++ b/src/IO/S3/Client.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -78,6 +79,7 @@ namespace Setting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; extern const int TOO_MANY_REDIRECTS; } @@ -1196,6 +1198,21 @@ std::unique_ptr ClientFactory::create( // NOLINT if (!server_side_encryption_customer_key_base64.empty()) { + /// `base64Decode` throws on characters outside the alphabet but skips whitespace and ignores padding bits, + /// so the round trip below accepts only the canonical base64 of an AES-256 key, the only key SSE-C takes. + String customer_key; + try + { + customer_key = base64Decode(server_side_encryption_customer_key_base64); + } + catch (const Poco::DataFormatException &) + { + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + } + + if (customer_key.size() != AES256_KEY_BYTES || base64Encode(customer_key) != server_side_encryption_customer_key_base64) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "`server_side_encryption_customer_key_base64` must be a base64-encoded 256-bit key"); + /// See Client::GeneratePresignedUrlWithSSEC(). headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, @@ -1204,10 +1221,8 @@ std::unique_ptr ClientFactory::create( // NOLINT headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY, server_side_encryption_customer_key_base64}); - Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode(server_side_encryption_customer_key_base64); - String str_buffer(reinterpret_cast(buffer.GetUnderlyingData()), buffer.GetLength()); headers.push_back({Aws::S3::SSEHeaders::SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5, - Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(str_buffer))}); + Aws::Utils::HashingUtils::Base64Encode(Aws::Utils::HashingUtils::CalculateMD5(customer_key))}); } // These will be added after request signing diff --git a/src/IO/S3/Client.h b/src/IO/S3/Client.h index 61ee4ead3dc0..ac7fd172617b 100644 --- a/src/IO/S3/Client.h +++ b/src/IO/S3/Client.h @@ -333,6 +333,8 @@ class Client : private Aws::S3::S3Client class ClientFactory { public: + static constexpr size_t AES256_KEY_BYTES = 32; + ~ClientFactory(); static ClientFactory & instance(); diff --git a/src/IO/SharedThreadPools.cpp b/src/IO/SharedThreadPools.cpp index c299fc8175e5..29e65bf483a8 100644 --- a/src/IO/SharedThreadPools.cpp +++ b/src/IO/SharedThreadPools.cpp @@ -43,6 +43,9 @@ namespace CurrentMetrics extern const Metric MergeTreeSnapshotCommitThreads; extern const Metric MergeTreeSnapshotCommitThreadsActive; extern const Metric MergeTreeSnapshotCommitThreadsScheduled; + extern const Metric ParquetEncoderThreads; + extern const Metric ParquetEncoderThreadsActive; + extern const Metric ParquetEncoderThreadsScheduled; } namespace DB @@ -236,4 +239,10 @@ StaticThreadPool & getFormatParsingThreadPool() return instance; } +StaticThreadPool & getParquetEncoderThreadPool() +{ + static StaticThreadPool instance("ParquetEncoderThreadPool", CurrentMetrics::ParquetEncoderThreads, CurrentMetrics::ParquetEncoderThreadsActive, CurrentMetrics::ParquetEncoderThreadsScheduled); + return instance; +} + } diff --git a/src/IO/SharedThreadPools.h b/src/IO/SharedThreadPools.h index 505688083347..2e8d17d2529c 100644 --- a/src/IO/SharedThreadPools.h +++ b/src/IO/SharedThreadPools.h @@ -91,4 +91,6 @@ StaticThreadPool & getMergeTreePrefixesDeserializationThreadPool(); StaticThreadPool & getFormatParsingThreadPool(); +StaticThreadPool & getParquetEncoderThreadPool(); + } diff --git a/src/IO/tests/gtest_brotli_decoder.cpp b/src/IO/tests/gtest_brotli_decoder.cpp new file mode 100644 index 000000000000..d7b8ade6a3f3 --- /dev/null +++ b/src/IO/tests/gtest_brotli_decoder.cpp @@ -0,0 +1,58 @@ +#include "config.h" + +#if USE_BROTLI + +#include +#include + +#include +#include +#include +#include +#include + +TEST(BrotliDecoder, RejectInvalidBlockSwitch) +{ + // A block switch is invalid when the stream declares only one block type. + // From https://github.com/nodejs/node/blob/main/test/parallel/test-zlib-invalid-input.js. + constexpr std::array input = { + 0x20, 0x00, 0x10, 0x41, 0x41, 0x41, 0xfc, 0xff, 0xff, 0x07, 0x00, + 0x22, 0x28, 0xf0, 0x0b, 0x60, 0xf7, 0xf4, 0x1f, 0x00, 0x00, 0x00}; + + for (size_t chunk_size : {input.size(), size_t{1}}) + { + std::unique_ptr state( + BrotliDecoderCreateInstance(nullptr, nullptr, nullptr), &BrotliDecoderDestroyInstance); + ASSERT_NE(state.get(), nullptr); + + std::array output{}; + size_t total_output = 0; + BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + + for (size_t offset = 0; offset < input.size() && result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;) + { + size_t available_input = std::min(chunk_size, input.size() - offset); + const size_t provided_input = available_input; + const uint8_t * next_input = input.data() + offset; + do + { + uint8_t * next_output = output.data(); + size_t available_output = output.size(); + result = BrotliDecoderDecompressStream( + state.get(), &available_input, &next_input, &available_output, &next_output, nullptr); + total_output += output.size() - available_output; + ASSERT_LT(total_output, 64 * 1024 * 1024); + } + while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT); + offset += provided_input - available_input; + if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) + ASSERT_GT(provided_input - available_input, 0); + } + + EXPECT_EQ(result, BROTLI_DECODER_RESULT_ERROR); + // -17 is the `BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH` code added by the fix. + EXPECT_EQ(BrotliDecoderGetErrorCode(state.get()), static_cast(-17)); + } +} + +#endif diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index 8aa24023956f..b5599a2b6ee6 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -124,12 +124,18 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_) : query(query_->clone()) , query_str_with_secrets(query->formatWithSecretsOneLine()) , user_id(user_id_) , current_roles(current_roles_) + , current_user(current_user_) + , initial_user(initial_user_) + , authenticated_user(authenticated_user_) , settings(std::make_unique(settings_)) , data_kind(data_kind_) { @@ -147,6 +153,13 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery( } } + /// Length-prefix each field: update(String) streams only bytes and the queue is keyed + /// by hash alone, so otherwise "a"/"a"/"aaa" and "aa"/"aa"/"a" would collide. + for (const String & identity_field : {current_user, initial_user, authenticated_user}) + { + siphash.update(identity_field.size()); + siphash.update(identity_field); + } setting_changes = settings->changes(); for (auto it = setting_changes.begin(); it != setting_changes.end();) @@ -172,6 +185,9 @@ AsynchronousInsertQueue::InsertQuery::InsertQuery(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -187,6 +203,9 @@ AsynchronousInsertQueue::InsertQuery::operator=(const InsertQuery & other) query_str_with_secrets = other.query_str_with_secrets; user_id = other.user_id; current_roles = other.current_roles; + current_user = other.current_user; + initial_user = other.initial_user; + authenticated_user = other.authenticated_user; settings = std::make_unique(*other.settings); data_kind = other.data_kind; hash = other.hash; @@ -533,7 +552,16 @@ AsynchronousInsertQueue::PushResult AsynchronousInsertQueue::pushDataChunk(ASTPt if (insert_query.format == "Values") entry->query_parameters = query_context->getQueryParameters(); - InsertQuery key{query, query_context->getUserID(), query_context->getCurrentRoles(), settings, data_kind}; + const auto & client_info = query_context->getClientInfo(); + InsertQuery key{ + query, + query_context->getUserID(), + query_context->getCurrentRoles(), + client_info.current_user, + client_info.initial_user, + client_info.authenticated_user, + settings, + data_kind}; InsertDataPtr data_to_process; std::future progress_future; @@ -980,6 +1008,14 @@ try insert_context->setCurrentRoles(key.current_roles); } + /// Context::setUser only restores the access-control identity, not the ClientInfo user + /// names. Restore them from the originating query so currentUser()/user()/ + /// authenticatedUser() and the materialized views triggered by the flush observe the + /// inserting user instead of an empty string. + insert_context->setCurrentUserName(key.current_user); + insert_context->setInitialUserName(key.initial_user); + insert_context->setAuthenticatedUserName(key.authenticated_user); + insert_context->setSettings(*key.settings); /// Set initial_query_id, because it's used in InterpreterInsertQuery for table lock. diff --git a/src/Interpreters/AsynchronousInsertQueue.h b/src/Interpreters/AsynchronousInsertQueue.h index 81a6fb36ab6f..f9eed199e90a 100644 --- a/src/Interpreters/AsynchronousInsertQueue.h +++ b/src/Interpreters/AsynchronousInsertQueue.h @@ -85,6 +85,14 @@ class AsynchronousInsertQueue : public WithContext String query_str_with_secrets; std::optional user_id; std::vector current_roles; + /// Client identity of the originating INSERT query (ClientInfo user names). + /// Restored on the flush context so currentUser()/user()/authenticatedUser() and + /// the materialized views triggered by the flush observe the inserting user instead + /// of an empty string. Part of the batching key so inserts from different identities + /// (e.g. impersonation, forwarded distributed queries) are never coalesced. + String current_user; + String initial_user; + String authenticated_user; std::unique_ptr settings; AsynchronousInsertQueueDataKind data_kind; @@ -94,6 +102,9 @@ class AsynchronousInsertQueue : public WithContext const ASTPtr & query_, const std::optional & user_id_, const std::vector & current_roles_, + const String & current_user_, + const String & initial_user_, + const String & authenticated_user_, const Settings & settings_, AsynchronousInsertQueueDataKind data_kind_); @@ -103,7 +114,7 @@ class AsynchronousInsertQueue : public WithContext StorageID getStorageID() const; private: - auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, setting_changes); } + auto toTupleCmp() const { return std::tie(data_kind, query_str_with_secrets, user_id, current_roles, current_user, initial_user, authenticated_user, setting_changes); } std::vector setting_changes; }; diff --git a/src/Interpreters/Cache/EvictionCandidates.cpp b/src/Interpreters/Cache/EvictionCandidates.cpp index 35500747622d..3a639da3bb33 100644 --- a/src/Interpreters/Cache/EvictionCandidates.cpp +++ b/src/Interpreters/Cache/EvictionCandidates.cpp @@ -323,7 +323,8 @@ void EvictionCandidates::evict() } catch (...) { - failed_candidates.total_cache_size += candidate->file_segment->getDownloadedSize(); + /// Sum up reserved size, which is the queue entry size. + failed_candidates.total_cache_size += candidate->size(); failed_candidates.total_cache_elements += 1; failed_key_candidates.candidates.push_back(candidate); diff --git a/src/Interpreters/Cache/FileCache.cpp b/src/Interpreters/Cache/FileCache.cpp index a2dacdb03547..864a831cf935 100644 --- a/src/Interpreters/Cache/FileCache.cpp +++ b/src/Interpreters/Cache/FileCache.cpp @@ -2512,23 +2512,25 @@ bool FileCache::doDynamicResizeImpl( for (const auto & candidate : key_candidates) { const auto & file_segment = candidate->file_segment; + /// Restore the original queue entry size. For partial segments it is reserved size. + const auto restored_size = candidate->size(); LOG_DEBUG( - log, "Adding back file segment after failed eviction: {}:{}, size: {}", - file_segment->key(), file_segment->offset(), file_segment->getDownloadedSize()); + log, "Adding back file segment after failed eviction: {}:{}, restored size: {}, downloaded size: {}", + file_segment->key(), file_segment->offset(), restored_size, file_segment->getDownloadedSize()); auto original_queue_type = eviction_candidates.getOriginalQueueType(candidate.get()); auto main_priority_iterator = main_priority->addForRestore( key_metadata, file_segment->offset(), - file_segment->getDownloadedSize(), + restored_size, original_queue_type, cache_write_lock, &state_lock); candidate->setRemovedFlag(*locked_key, /* value */false); - file_segment->setQueueIterator(main_priority_iterator); + file_segment->restoreQueueIteratorAfterDelayedRemoval(main_priority_iterator); } } diff --git a/src/Interpreters/Cache/FileSegment.cpp b/src/Interpreters/Cache/FileSegment.cpp index 22befb6f0ef4..5a8a8cb8e25d 100644 --- a/src/Interpreters/Cache/FileSegment.cpp +++ b/src/Interpreters/Cache/FileSegment.cpp @@ -177,6 +177,7 @@ void FileSegment::setQueueIterator(Priority::IteratorPtr iterator) auto lk = lock(); if (queue_iterator) throw Exception(ErrorCodes::LOGICAL_ERROR, "Queue iterator cannot be set twice"); + chassert(!on_delayed_removal); queue_iterator = iterator; } @@ -187,6 +188,17 @@ void FileSegment::markDelayedRemovalAndResetQueueIterator() queue_iterator = {}; } +void FileSegment::restoreQueueIteratorAfterDelayedRemoval( + Priority::IteratorPtr iterator) +{ + auto lk = lock(); + chassert(iterator); + chassert(on_delayed_removal); + chassert(!queue_iterator); + queue_iterator = std::move(iterator); + on_delayed_removal = false; +} + size_t FileSegment::getCurrentWriteOffset() const { return range().left + downloaded_size; @@ -1034,6 +1046,10 @@ bool FileSegment::assertCorrectnessUnlocked(const FileSegmentGuard::Lock & lock) } } + /// A restored queue iterator must clear the delayed-removal state. + if (queue_iterator) + chassert(!on_delayed_removal); + switch (download_state.load()) { case State::EMPTY: @@ -1088,7 +1104,7 @@ bool FileSegment::assertCorrectnessUnlocked(const FileSegmentGuard::Lock & lock) chassert(file_size <= range().size()); chassert(downloaded_size <= range().size()); - chassert(queue_iterator); + chassert(queue_iterator || on_delayed_removal); check_iterator(queue_iterator); break; } diff --git a/src/Interpreters/Cache/FileSegment.h b/src/Interpreters/Cache/FileSegment.h index 7321cbeb1464..86e2048516c8 100644 --- a/src/Interpreters/Cache/FileSegment.h +++ b/src/Interpreters/Cache/FileSegment.h @@ -181,6 +181,10 @@ friend class FileCache; /// Because of reserved_size in tryReserve(). void markDelayedRemovalAndResetQueueIterator(); + /// Restore a queue iterator after dynamic-resize eviction failed. + /// The segment must have been marked by `markDelayedRemovalAndResetQueueIterator`. + void restoreQueueIteratorAfterDelayedRemoval(Priority::IteratorPtr iterator); + KeyMetadataPtr tryGetKeyMetadata() const; KeyMetadataPtr getKeyMetadata() const; @@ -297,6 +301,7 @@ friend class FileCache; /// Because of reserved_size in tryReserve(). std::atomic hits_count = 0; /// cache hits. std::atomic ref_count = 0; /// Used for getting snapshot state + /// Guarded by `segment_guard`. Set while dynamic-resize eviction is pending. bool on_delayed_removal = false; CurrentMetrics::Increment metric_increment{CurrentMetrics::CacheFileSegments}; diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index aa63ec626fc7..c3f710e251d1 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1192,6 +1192,15 @@ void ContextSharedMutex::lockSharedImpl() ProfileEvents::increment(ProfileEvents::ContextLockWaitMicroseconds, watch.elapsedMicroseconds()); } +/// An entry of `ContextData::scalars`. `from_client` is true when the block arrived from the client +/// over the wire (`Context::addClientScalar`) rather than being computed by the server, so that +/// `Context::hasComputedScalar` can keep such a block out of the analyzer's scalar-subquery cache. +struct ScalarEntry +{ + Block block; + bool from_client = false; +}; + ContextData::ContextData() { settings = std::make_unique(); @@ -2383,7 +2392,10 @@ std::pair Context::setConcurrentThreadsSoftLimit(UInt64 num, UIn Scalars Context::getScalars() const { std::lock_guard lock(mutex); - return scalars; + Scalars res; + for (const auto & [name, entry] : scalars) + res.emplace(name, entry.block); + return res; } @@ -2398,7 +2410,7 @@ Block Context::getScalar(const String & name) const // often, so 'bad arguments' for now. throw Exception(ErrorCodes::BAD_ARGUMENTS, "Scalar {} doesn't exist (internal bug)", backQuoteIfNeed(name)); } - return it->second; + return it->second.block; } std::optional Context::tryGetSpecialScalar(const String & name) const @@ -2528,7 +2540,18 @@ void Context::addScalar(const String & name, const Block & block) throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); std::lock_guard lock(mutex); - scalars[name] = block; + /// A server-computed value overrides any client-supplied one of the same name and is trusted. + scalars[name] = ScalarEntry{block, /*from_client=*/ false}; +} + + +void Context::addClientScalar(const String & name, const Block & block) +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + scalars[name] = ScalarEntry{block, /*from_client=*/ true}; } @@ -2551,6 +2574,16 @@ bool Context::hasScalar(const String & name) const return scalars.contains(name); } +bool Context::hasComputedScalar(const String & name) const +{ + if (isGlobalContext()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have scalars"); + + std::lock_guard lock(mutex); + auto it = scalars.find(name); + return it != scalars.end() && !it->second.from_client; +} + void Context::addQueryAccessInfo( const StorageID & table_id, const Names & column_names) @@ -3201,6 +3234,13 @@ void Context::clampToSettingsConstraintsWithLock(SettingsChanges & changes, Sett doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); } +void Context::clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source) +{ + getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.clampRejectingInvalidChanges(*settings, changes, source); + if (getApplicationType() == ApplicationType::LOCAL || getApplicationType() == ApplicationType::SERVER) + doSettingsSanityCheckClamp(*settings, getLogger("SettingsSanity")); +} + void Context::checkMergeTreeSettingsConstraintsWithLock(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { getSettingsConstraintsAndCurrentProfilesWithLock()->constraints.check(merge_tree_settings, changes); @@ -3284,6 +3324,21 @@ void Context::clampToSettingsConstraints(SettingsChanges & changes, SettingSourc clampToSettingsConstraintsWithLock(changes, source); } +void Context::clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source) +{ + if (std::ranges::any_of(changes, isProfileChange)) + { + changes = enforceConstraintsAlongProfileChanges(shared_from_this(), changes, [source](Context & context, SettingsChanges & segment) + { + context.clampToSettingsConstraintsRejectingInvalidChanges(segment, source); + }); + return; + } + + SharedLockGuard lock(mutex); + clampToSettingsConstraintsRejectingInvalidChangesWithLock(changes, source); +} + void Context::checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const { SharedLockGuard lock(mutex); @@ -6999,6 +7054,12 @@ void Context::setInitialUserName(const String & initial_user_name) need_recalculate_access = true; } +void Context::setAuthenticatedUserName(const String & authenticated_user_name) +{ + client_info.authenticated_user = authenticated_user_name; + need_recalculate_access = true; +} + void Context::setInitialAddress(const Poco::Net::SocketAddress & initial_address) { client_info.initial_address = std::make_shared(initial_address); diff --git a/src/Interpreters/Context.h b/src/Interpreters/Context.h index e2fcb1224695..d732882f83e9 100644 --- a/src/Interpreters/Context.h +++ b/src/Interpreters/Context.h @@ -164,6 +164,10 @@ class DDLWorker; class ITableFunction; using TableFunctionPtr = std::shared_ptr; class Block; +/// An entry of the query scalar map: the scalar block plus whether it came from the client. +/// Defined in Context.cpp, where `Block` is complete; here `std::map` only needs the forward +/// declaration, the same way `Scalars` is a `std::map` over the forward-declared `Block`. +struct ScalarEntry; class ActionLocksManager; using ActionLocksManagerPtr = std::shared_ptr; class ShellCommand; @@ -395,8 +399,13 @@ class ContextData String insert_format; /// Format, used in insert query. TemporaryTablesMapping external_tables_mapping; - /// Query scalars - Scalars scalars; + /// Query scalars. Each entry carries whether it was supplied by the client over the wire (the + /// `Scalar` packet, i.e. the `clickhouse-client --external ... --scalar` feature or an initiator + /// shipping scalars to a shard) rather than computed by the server itself. The origin travels with + /// the block so that the analyzer's scalar-subquery cache (which keys on the query-tree hash) never + /// mistakes a client-supplied block for an already-computed subquery result; without this a client + /// could forge the result of a scalar subquery used in a row policy and bypass the policy. + std::map scalars; /// Used to store constant values which are different on each instance during distributed plan, such as _shard_num. Scalars special_scalars; @@ -942,6 +951,7 @@ class Context: public ContextData, public std::enable_shared_from_this void setCurrentUserName(const String & current_user_name); void setCurrentAddress(const Poco::Net::SocketAddress & current_address); void setInitialUserName(const String & initial_user_name); + void setAuthenticatedUserName(const String & authenticated_user_name); void setInitialAddress(const Poco::Net::SocketAddress & initial_address); void setInitialQueryId(const String & initial_query_id); void setInitialQueryStartTime(std::chrono::time_point initial_query_start_time); @@ -981,6 +991,16 @@ class Context: public ContextData, public std::enable_shared_from_this void addScalar(const String & name, const Block & block); bool hasScalar(const String & name) const; + /// Add a scalar received from the client over the wire (the `Scalar` packet). Unlike `addScalar`, + /// the entry is marked as client-supplied so that `hasComputedScalar` will not report it as a + /// server-computed subquery result. Explicit readers (`__getScalar`, `_shard_num`, forwarding to + /// shards) still see it through `getScalar` / `hasScalar` / `getScalars`. + void addClientScalar(const String & name, const Block & block); + /// Like `hasScalar`, but returns true only for scalars the server computed itself, never for + /// client-supplied ones. The analyzer's scalar-subquery cache must use this so that a forged + /// client scalar cannot stand in for the result of a (e.g. row-policy) scalar subquery. + bool hasComputedScalar(const String & name) const; + std::optional tryGetSpecialScalar(const String & name) const; void addSpecialScalar(const String & name, const Block & block); @@ -1117,6 +1137,7 @@ class Context: public ContextData, public std::enable_shared_from_this /// For the resets of a statement that also changes `profile`: `changes_applied_first` decides their constraints. void checkSettingsConstraintsForSettingsReset(const std::vector & names, const SettingsChanges & changes_applied_first, SettingSource source); void clampToSettingsConstraints(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChanges(SettingsChanges & changes, SettingSource source); void checkMergeTreeSettingsConstraints(const MergeTreeSettings & merge_tree_settings, const SettingsChanges & changes) const; /// Reset settings to default value @@ -1810,6 +1831,7 @@ class Context: public ContextData, public std::enable_shared_from_this void checkSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source); + void clampToSettingsConstraintsRejectingInvalidChangesWithLock(SettingsChanges & changes, SettingSource source); void checkSettingsConstraintsWithLock(const AlterSettingsProfileElements & profile_elements, SettingSource source) const; void clampToSettingsConstraintsWithLock(SettingsChanges & changes, SettingSource source) const; diff --git a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp index dc247f5119e3..bd217badfadf 100644 --- a/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp +++ b/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp @@ -156,7 +156,7 @@ void ExecuteScalarSubqueriesMatcher::visit(const ASTSubquery & subquery, ASTPtr } else { - if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasScalar(scalar_query_hash_str)) + if (data.getContext()->hasQueryContext() && data.getContext()->getQueryContext()->hasComputedScalar(scalar_query_hash_str)) { if (!data.getContext()->getViewSource()) { diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index 2ad408df7443..9976d55c6111 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -24,12 +25,17 @@ #include #include #include +#include #include #include +#include #include #include +#include #include +#include #include +#include #include #include #include @@ -62,6 +68,7 @@ namespace ServerSetting namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int LOGICAL_ERROR; extern const int INCORRECT_QUERY; extern const int NOT_IMPLEMENTED; @@ -73,6 +80,83 @@ namespace ErrorCodes extern const int SUPPORT_IS_DISABLED; } +namespace +{ + +/// A setting that sends the table's data elsewhere copies the data as it is stored, so nothing can filter the rows +/// that a row policy hides. It reads only the query and the access entities, +/// not the table, so it runs on the initiator. The database is resolved only for such a setting, so that other queries +/// do not need a current database. +void checkNoRowPolicyForExport(const ASTAlterQuery & alter, const ContextPtr & context) +{ + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::MODIFY_SETTING || !command.settings_changes) + continue; + + const auto & changes = command.settings_changes->as().changes; + if (StorageFactory::instance().getExportAccessOfAnyEngine(changes).empty()) + continue; + + const String database = context->resolveDatabase(alter.getDatabase()); + auto row_policy_filter = context->getRowPolicyFilter(database, alter.getTable(), RowPolicyFilterType::SELECT_FILTER); + if (row_policy_filter && !row_policy_filter->isAlwaysTrue()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "Cannot change the settings of table {}.{} that send its data elsewhere because a row policy applies to it. " + "The data is copied as it is stored, so its rows cannot be filtered", + backQuoteIfNeed(database), backQuoteIfNeed(alter.getTable())); + } +} + +/// A `Replicated`-database host applies the statement without the submitting user. `ON CLUSTER` does +/// not reach this: it is refused unless its hosts run as the initiating user. +void checkAddedIndexPermissions(const ASTAlterQuery & alter, const StoragePtr & table, const ContextPtr & context) +{ + if (!table) + return; + + bool adds_transform = false; + for (const auto & child : alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + + if (const auto * declaration = command.index_decl->as()) + if (hasTextIndexPreOrPostProcessor(*declaration)) + adds_transform = true; + } + + /// Against the schema the whole statement produces: a command of the same statement can change what + /// an alias in a transform expands to. Transforms only, so other statements get no extra analysis. + if (!adds_transform) + return; + + AlterCommands commands; + for (const auto & child : alter.command_list->children) + { + const auto * command_ast = child->as(); + if (command_ast->type == ASTAlterCommand::EXECUTE_COMMAND) + continue; + if (auto command = AlterCommand::parse(command_ast)) + commands.emplace_back(std::move(*command)); + } + + /// The same sequence as `executeToTable`: `apply` relies on the checks before it, and it authorizes + /// the added indices as the user. + StorageInMemoryMetadata metadata = table->getInMemoryMetadata(); + commands.validate(table, context); + commands.prepare(metadata); + table->checkAlterIsPossible(commands, context); + /// As the storages do before `apply`: an explicit `ADD STATISTICS` replaces an implicit one. + removeImplicitStatistics(metadata.columns); + commands.apply(metadata, context); +} + +} + InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, ContextMutablePtr context_) : WithMutableContext(context_), query_ptr(query_ptr_) { } @@ -130,15 +214,37 @@ BlockIO InterpreterAlterQuery::executeToTable(const ASTAlterQuery & alter) DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_alter = captured_query_ptr->as(); + for (const auto & child : captured_alter.command_list->children) + { + const auto & command = child->as(); + if (command.type != ASTAlterCommand::ADD_INDEX || !command.index_decl) + continue; + if (const auto * declaration = command.index_decl->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + } + }; + /// The hosts run the entry without the user, so the row policy is checked here before the entry is enqueued. + checkNoRowPolicyForExport(alter, getContext()); return executeDDLQueryOnCluster(query_ptr, getContext(), params); } getContext()->checkAccess(getRequiredAccess()); + checkNoRowPolicyForExport(alter, getContext()); if (!table_id) throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(alter.getDatabase())); DatabasePtr database = DatabaseCatalog::instance().getDatabase(table_id.database_name); + + checkAddedIndexPermissions(alter, table, getContext()); + if (database->shouldReplicateQuery(getContext(), query_ptr)) { auto guard = DatabaseCatalog::instance().getDDLGuard(table_id.database_name, table_id.table_name, database.get()); @@ -624,6 +730,20 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand(const AS case ASTAlterCommand::MODIFY_SETTING: { required_access.emplace_back(AccessType::ALTER_SETTINGS, database, table); + + /// A setting that sends the table's data elsewhere, e.g. the move destination of a queue, is the same data flow as + /// `INSERT INTO FUNCTION s3(...) SELECT * FROM
`. The creator of the table supplied its source and credentials, + /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator + /// of `ON CLUSTER` can check them without the table. + if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) + { + auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + if (!export_access.empty()) + { + required_access.append_range(std::move(export_access)); + required_access.emplace_back(AccessType::SELECT, database, table); + } + } break; } case ASTAlterCommand::ATTACH_PARTITION: diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index 715a96ebc0b7..d0a1ce770c76 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -34,10 +34,12 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -146,6 +148,7 @@ namespace Setting namespace ServerSetting { + extern const ServerSettingsBool distributed_ddl_use_initial_user_and_roles; extern const ServerSettingsBool ignore_empty_sql_security_in_create_view_query; extern const ServerSettingsUInt64 max_database_num_to_throw; extern const ServerSettingsUInt64 max_dictionary_num_to_throw; @@ -988,6 +991,14 @@ InterpreterCreateQuery::TableProperties InterpreterCreateQuery::getTableProperti if (!create.columns_list) create.set(create.columns_list, make_intrusive()); + /// Authorize the text index transforms of every definition the user supplies now. A replay of stored + /// metadata is not checked, so such a table still attaches. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + { + for (const auto & index : properties.indices) + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + ASTPtr new_columns = formatColumns(properties.columns); ASTPtr new_indices = formatIndices(properties.indices); ASTPtr new_constraints = formatConstraints(properties.constraints); @@ -1714,6 +1725,11 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) /// Set and retrieve list of columns, indices and constraints. Set table engine if needed. Rewrite query in canonical way. TableProperties properties = getTablePropertiesAndNormalizeCreateQuery(create, mode); + /// Only here is an engine inherited through `AS` known, and nothing is enqueued or created yet. + /// A replay of a stored definition was checked when it was created. + if (isFreshTableDefinition(mode, create.attach_short_syntax)) + checkExportAccess(create); + DatabasePtr database; bool need_add_to_database = !create.isTemporary(); // In case of an ON CLUSTER query, the database may not be present on the initiator node @@ -2500,6 +2516,20 @@ BlockIO InterpreterCreateQuery::executeQueryOnCluster(ASTCreateQuery & create) prepareOnClusterQuery(create, getContext(), create.cluster); DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccess(); + params.additional_access_check = [captured_query_ptr = query_ptr](bool throw_if_unresolved) + { + /// `throw_if_unresolved` means the hosts do not run the query as this user. + if (!throw_if_unresolved) + return; + + const auto & captured_create = captured_query_ptr->as(); + if (!captured_create.columns_list || !captured_create.columns_list->indices) + return; + + for (const auto & index : captured_create.columns_list->indices->children) + if (const auto * declaration = index->as()) + rejectTextIndexTransformWithoutInitiatorUser(*declaration); + }; return executeDDLQueryOnCluster(query_ptr, getContext(), params); } @@ -2539,6 +2569,46 @@ BlockIO InterpreterCreateQuery::execute() if (inherited.storage && inherited.storage->engine) getContext()->checkAccess(AccessType::TABLE_ENGINE, inherited.storage->engine->name); + + /// setEngine copies only the outer engine of a `TimeSeries` source, and the worker copies + /// its inner engines while normalizing, so add the ones this query does not give itself + if (inherited.is_time_series_table) + { + auto as_create_ptr = DatabaseCatalog::instance().getDatabase(inherited.as_database)->getCreateTableQuery(inherited.as_table, getContext()); + const auto & as_create = as_create_ptr->as(); + if (as_create.targets) + for (const auto & target : as_create.targets->targets) + if (target.inner_engine && !inherited.getTargetInnerEngine(target.kind)) + inherited.setTargetInnerEngine(target.kind, target.inner_engine->clone()); + } + + /// the worker inherits the move destination of the source too, and runs with no user + checkExportAccess(inherited); + + /// A worker copies the source's indices with no user, so declare their transforms here. + if (inherited.storage && inherited.storage->engine && endsWith(inherited.storage->engine->name, "MergeTree")) + { + /// Before resolving it: an error below would otherwise disclose a source the user + /// cannot see. + getContext()->checkAccess(AccessType::SHOW_COLUMNS, create.as_database, create.as_table); + StoragePtr as_storage = resolveStorageProxyLoading( + DatabaseCatalog::instance().getTable({create.as_database, create.as_table}, getContext())); + /// The query dispatches `AS src`, so each host materializes its own source, which + /// may define the transform differently from the one authorized here. + const bool workers_use_initiator_user + = getContext()->getServerSettings()[ServerSetting::distributed_ddl_use_initial_user_and_roles] + && on_cluster_version >= DDLLogEntry::INITIATOR_USER_VERSION; + + auto as_storage_metadata = as_storage->getInMemoryMetadataPtr(); + for (const auto & index : as_storage_metadata->getSecondaryIndices()) + { + if (index.isImplicitlyCreated()) + continue; + if (!workers_use_initiator_user) + rejectTextIndexTransformWithoutInitiatorUser(index); + checkTextIndexPreAndPostProcessorPermissions(index, getContext()); + } + } } return executeQueryOnCluster(create); @@ -2623,9 +2693,28 @@ AccessRightsElements InterpreterCreateQuery::getRequiredAccess() const if (create.storage && create.storage->engine) required_access.emplace_back(AccessType::TABLE_ENGINE, create.storage->engine->name); + /// `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the table data and then moves it to the + /// data path of the new table. Reading it needs `READ` on the FILE source like the `file` function does, and + /// taking it away from `user_files` needs `WRITE`, like renaming files after processing does. Without this, + /// `CREATE TABLE` on a table of their own would let a user read or consume any data staged in `user_files`. + if (create.has_attach_from_path) + required_access.emplace_back(AccessType::READ | AccessType::WRITE, toStringSource(AccessTypeObjects::Source::FILE)); + + /// Settings that send the table's data elsewhere, e.g. the move destination of a queue, need the grants of that place. + required_access.append_range(StorageFactory::instance().getExportAccess(create)); + return required_access; } +void InterpreterCreateQuery::checkExportAccess(const ASTCreateQuery & create) const +{ + /// Internal queries (initiated by the server itself) always have access to everything. + if (internal) + return; + + getContext()->checkAccess(StorageFactory::instance().getExportAccess(create)); +} + void InterpreterCreateQuery::extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr &, ContextPtr) const { if (!as_table_saved.empty()) diff --git a/src/Interpreters/InterpreterCreateQuery.h b/src/Interpreters/InterpreterCreateQuery.h index 9692dcdedbb6..674965cc7e00 100644 --- a/src/Interpreters/InterpreterCreateQuery.h +++ b/src/Interpreters/InterpreterCreateQuery.h @@ -112,6 +112,10 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext void setEngine(ASTCreateQuery & create) const; AccessRightsElements getRequiredAccess() const; + /// The part of `getRequiredAccess` for settings that send the table's data elsewhere, checked again once + /// `setEngine` has resolved an engine inherited through `AS`, which `getRequiredAccess` cannot see. + void checkExportAccess(const ASTCreateQuery & create) const; + /// Create IStorage and add it to database. If table already exists and IF NOT EXISTS specified, do nothing and return false. bool doCreateTable(ASTCreateQuery & create, const TableProperties & properties, DDLGuardPtr & ddl_guard, LoadingStrictnessLevel mode); BlockIO doCreateOrReplaceTable(ASTCreateQuery & create, const InterpreterCreateQuery::TableProperties & properties, LoadingStrictnessLevel mode); diff --git a/src/Interpreters/JIT/CHJIT.cpp b/src/Interpreters/JIT/CHJIT.cpp index 67c3068d0e0c..85609a0f5f07 100644 --- a/src/Interpreters/JIT/CHJIT.cpp +++ b/src/Interpreters/JIT/CHJIT.cpp @@ -427,7 +427,12 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function { std::lock_guard lock(jit_lock); - auto module = createModuleForCompilation(); + /// A fresh context per compile: `LLVMContext` never frees the constants it interns, and the optimizer + /// creates new ones for every distinct literal, so a long-lived context grows without bound. + /// Declared before `module`, which must be destroyed first. + auto context = std::make_unique(); + + auto module = createModuleForCompilation(*context); compile_function(*module); auto module_info = compileModule(std::move(module)); @@ -435,7 +440,7 @@ CHJIT::CompiledModule CHJIT::compileModule(std::function return module_info; } -std::unique_ptr CHJIT::createModuleForCompilation() +std::unique_ptr CHJIT::createModuleForCompilation(llvm::LLVMContext & context) { std::unique_ptr module = std::make_unique("jit" + std::to_string(current_module_key), context); module->setDataLayout(layout); diff --git a/src/Interpreters/JIT/CHJIT.h b/src/Interpreters/JIT/CHJIT.h index 89d446fd3b34..04788222136e 100644 --- a/src/Interpreters/JIT/CHJIT.h +++ b/src/Interpreters/JIT/CHJIT.h @@ -89,7 +89,7 @@ class CHJIT private: - std::unique_ptr createModuleForCompilation(); + std::unique_ptr createModuleForCompilation(llvm::LLVMContext & context); CompiledModule compileModule(std::unique_ptr module); @@ -99,7 +99,6 @@ class CHJIT static std::unique_ptr getTargetMachine(); - llvm::LLVMContext context; std::unique_ptr machine; llvm::DataLayout layout; std::unique_ptr compiler; diff --git a/src/Interpreters/executeDDLQueryOnCluster.cpp b/src/Interpreters/executeDDLQueryOnCluster.cpp index 514f390e93ff..b2e6a3880daf 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.cpp +++ b/src/Interpreters/executeDDLQueryOnCluster.cpp @@ -194,6 +194,12 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, ContextPtr context, entry.initiator_user = context->getUserName(); entry.initiator_user_roles = context->getAccessControl().tryReadNames(context->getCurrentRoles()); } + + /// The workers run the query as the initiator's user and roles only if the entry carries them. + const bool workers_use_initiator_user = !entry.initiator_user.empty() && entry.version >= DDLLogEntry::INITIATOR_USER_VERSION; + if (params.additional_access_check) + params.additional_access_check(/* throw_if_unresolved = */ !workers_use_initiator_user); + ddl_worker.updateHostIDs(entry.hosts); String node_path = ddl_worker.enqueueQuery(entry, params.retries_info); diff --git a/src/Interpreters/executeDDLQueryOnCluster.h b/src/Interpreters/executeDDLQueryOnCluster.h index 69e0c38834e6..f98f9bb4aafc 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.h +++ b/src/Interpreters/executeDDLQueryOnCluster.h @@ -7,6 +7,8 @@ #include #include +#include + namespace zkutil { @@ -38,6 +40,12 @@ struct DDLQueryOnClusterParams /// Privileges which the current user should have to execute a query. AccessRightsElements access_to_check; + /// An authorization check which must run after the standard cluster and query checks but before enqueueing. + /// It receives whether the workers run the query without the initiator's user: they run it as that user and + /// roles only when `distributed_ddl_use_initial_user_and_roles` is enabled and `distributed_ddl_entry_format_version` + /// carries the initiator's user. + std::function additional_access_check; + /// Use retries when creating nodes "query-0000000000", "query-0000000001", "query-0000000002" in ZooKeeper. ZooKeeperRetriesInfo retries_info; }; diff --git a/src/Interpreters/tests/gtest_async_insert_key.cpp b/src/Interpreters/tests/gtest_async_insert_key.cpp index 0f4095a05bee..327525b4db5c 100644 --- a/src/Interpreters/tests/gtest_async_insert_key.cpp +++ b/src/Interpreters/tests/gtest_async_insert_key.cpp @@ -37,13 +37,59 @@ TEST(AsyncInsertKey, SettingsChanges) auto kind = AsynchronousInsertQueueDataKind::Parsed; - AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, settings1, kind); - AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, settings2, kind); - AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, settings3, kind); - AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, settings4, kind); + AsynchronousInsertQueue::InsertQuery key1(query, {}, {}, {}, {}, {}, settings1, kind); + AsynchronousInsertQueue::InsertQuery key2(query, {}, {}, {}, {}, {}, settings2, kind); + AsynchronousInsertQueue::InsertQuery key3(query, {}, {}, {}, {}, {}, settings3, kind); + AsynchronousInsertQueue::InsertQuery key4(query, {}, {}, {}, {}, {}, settings4, kind); EXPECT_EQ(key1, key2); EXPECT_NE(key1, key3); EXPECT_NE(key2, key3); EXPECT_NE(key3, key4); } + +TEST(AsyncInsertKey, IdentityHashIsNotAmbiguous) +{ + String query_str = "INSERT INTO test (a, b, c) VALUES (1, 2, 3)"; + ParserInsertQuery parser(query_str.data() + query_str.size(), false); + ASTPtr query = parseQuery(parser, query_str, DBMS_DEFAULT_MAX_QUERY_SIZE, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); + + Settings settings; + settings.set("async_insert", 1); + + auto kind = AsynchronousInsertQueueDataKind::Parsed; + + auto make_key = [&](const String & current_user, const String & initial_user, const String & authenticated_user) + { + return AsynchronousInsertQueue::InsertQuery( + query, {}, {}, current_user, initial_user, authenticated_user, settings, kind); + }; + + /// The three identity fields are variable-length strings folded into the queue key hash, + /// and the queue is indexed by hash alone. Without a length delimiter "a"/"a"/"aaa" and + /// "aa"/"aa"/"a" stream the same bytes ("aaaaa") and collide, which would route a second + /// user's insert into the first user's pending batch and flush it under the wrong + /// ClientInfo. The keys must differ both by hash and by equality. + auto key_a = make_key("a", "a", "aaa"); + auto key_b = make_key("aa", "aa", "a"); + EXPECT_NE(key_a.hash, key_b.hash); + EXPECT_NE(key_a, key_b); + + /// A field boundary shift across the current/initial split must also be distinguished. + auto key_c = make_key("a", "b", ""); + auto key_d = make_key("a", "", "b"); + EXPECT_NE(key_c.hash, key_d.hash); + EXPECT_NE(key_c, key_d); + + /// Same identity still hashes the same and compares equal (batching preserved). + auto key_e = make_key("alice", "alice", "alice"); + auto key_f = make_key("alice", "alice", "alice"); + EXPECT_EQ(key_e.hash, key_f.hash); + EXPECT_EQ(key_e, key_f); + + /// Distinct identities never coalesce. + auto key_g = make_key("alice", "alice", "alice"); + auto key_h = make_key("bob", "bob", "bob"); + EXPECT_NE(key_g.hash, key_h.hash); + EXPECT_NE(key_g, key_h); +} diff --git a/src/Interpreters/tests/gtest_filecache.cpp b/src/Interpreters/tests/gtest_filecache.cpp index 77be320656d2..8e3f36c7c3f3 100644 --- a/src/Interpreters/tests/gtest_filecache.cpp +++ b/src/Interpreters/tests/gtest_filecache.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -1913,3 +1914,220 @@ TEST_F(FileCacheTest, QueryLimitConcurrentReleaseNoLeak) ASSERT_EQ(found.get(), nullptr); } } + +TEST_F(FileCacheTest, PartiallyDownloadedDynamicResizeAssertion) +{ + /// Regression: dynamic resize temporarily clears the queue iterator before + /// evicting a `PARTIALLY_DOWNLOADED` segment. The invariant must allow that + /// delayed-removal state. + + ServerUUID::setRandomForUnitTests(); + DB::ThreadStatus thread_status; + + Poco::XML::DOMParser dom_parser; + std::string xml(R"CONFIG()CONFIG"); + Poco::AutoPtr document = dom_parser.parseString(xml); + Poco::AutoPtr config = new Poco::Util::XMLConfiguration(document); + getMutableContext().context->setConfig(config); + + auto query_context = DB::Context::createCopy(getContext().context); + query_context->makeQueryContext(); + query_context->setCurrentQueryId("partial_dl_dynamic_resize"); + chassert(&DB::CurrentThread::get() == &thread_status); + auto query_scope_holder = DB::QueryScope::create(query_context); + + DB::FileCacheSettings settings; + settings[FileCacheSetting::path] = cache_base_path; + settings[FileCacheSetting::max_size] = 16; + settings[FileCacheSetting::max_elements] = 4; + settings[FileCacheSetting::max_file_segment_size] = 8; + settings[FileCacheSetting::boundary_alignment] = 8; + settings[FileCacheSetting::load_metadata_asynchronously] = false; + settings[FileCacheSetting::cache_policy] = FileCachePolicy::LRU; + settings[FileCacheSetting::allow_dynamic_cache_resize] = true; + + auto cache = std::make_shared("partial_dl_resize", settings); + cache->initialize(); + + const auto & user = FileCache::getCommonOrigin(); + auto key = DB::FileCacheKey::fromPath("partial_dl_resize_key"); + + /// Segment 1: `PARTIALLY_DOWNLOADED` with reserved size 8 and downloaded size 3. + { + auto holder = cache->getOrSet(key, 0, 8, /*file_size=*/8, {}, 0, user); + ASSERT_EQ(holder->size(), 1u); + auto seg = *holder->begin(); + ASSERT_EQ(seg->state(), State::EMPTY); + + ASSERT_EQ(seg->getOrSetDownloader(), FileSegment::getCallerId()); + ASSERT_EQ(seg->state(), State::DOWNLOADING); + + std::string failure_reason; + ASSERT_TRUE(seg->reserve(/*size_to_reserve=*/8, /*lock_wait_timeout_milliseconds=*/1000, failure_reason)); + + /// `seg->write` expects the key directory to exist, as in `download`. + auto key_str = key.toString(); + auto subdir = fs::path(cache_base_path) / key_str.substr(0, 3) / key_str; + if (!fs::exists(subdir)) + fs::create_directories(subdir); + std::string data(3, 'a'); + seg->write(data.data(), data.size(), seg->getCurrentWriteOffset()); + + FileSegment::complete( + FileSegmentPtr(seg), + /*allow_background_download=*/false, + /*force_shrink_to_downloaded_size=*/false); + + ASSERT_EQ(seg->state(), State::PARTIALLY_DOWNLOADED) + << "Test setup did not produce a PARTIALLY_DOWNLOADED segment; " + "got: " << FileSegment::stateToString(seg->state()); + ASSERT_EQ(seg->getReservedSize(), 8u); + ASSERT_EQ(seg->getDownloadedSize(), 3u); + } + + /// Segment 2: a `DOWNLOADED` segment to make resize evict real entries. + { + auto holder = cache->getOrSet(key, 8, 8, /*file_size=*/16, {}, 0, user); + ASSERT_EQ(holder->size(), 1u); + auto seg = *holder->begin(); + ASSERT_EQ(seg->state(), State::EMPTY); + download(seg, /*complete=*/true); + ASSERT_EQ(seg->state(), State::DOWNLOADED); + } + + /// Sanity: the partial segment is still in `PARTIALLY_DOWNLOADED`. + { + auto infos = cache->getFileSegmentInfos(key, user.user_id); + ASSERT_EQ(infos.size(), 2u); + bool found_partial = false; + for (const auto & info : infos) + { + if (info.range_left == 0 && info.range_right == 7) + { + ASSERT_EQ(info.state, State::PARTIALLY_DOWNLOADED); + ASSERT_EQ(info.downloaded_size, 3u); + found_partial = true; + } + } + ASSERT_TRUE(found_partial); + } + + /// Trigger resize while the partial segment is in delayed-removal state. + DB::FileCacheSettings new_settings = settings; + new_settings[FileCacheSetting::max_size] = 4; + DB::FileCacheSettings actual_settings = settings; + + ASSERT_NO_THROW(cache->applySettingsIfPossible(new_settings, actual_settings)); + + ASSERT_LE(cache->getUsedCacheSize(), 4u); +} + +TEST_F(FileCacheTest, FailedEvictionRestorePreservesInvariants) +{ + /// Regression: failed eviction must restore queue entries with reserved size + /// and clear delayed-removal state on the segment. + + ServerUUID::setRandomForUnitTests(); + DB::ThreadStatus thread_status; + + Poco::XML::DOMParser dom_parser; + std::string xml(R"CONFIG()CONFIG"); + Poco::AutoPtr document = dom_parser.parseString(xml); + Poco::AutoPtr config = new Poco::Util::XMLConfiguration(document); + getMutableContext().context->setConfig(config); + + auto query_context = DB::Context::createCopy(getContext().context); + query_context->makeQueryContext(); + query_context->setCurrentQueryId("failed_eviction_restore"); + chassert(&DB::CurrentThread::get() == &thread_status); + auto query_scope_holder = DB::QueryScope::create(query_context); + + DB::FileCacheSettings settings; + settings[FileCacheSetting::path] = cache_base_path; + settings[FileCacheSetting::max_size] = 16; + settings[FileCacheSetting::max_elements] = 4; + settings[FileCacheSetting::max_file_segment_size] = 8; + settings[FileCacheSetting::boundary_alignment] = 8; + settings[FileCacheSetting::load_metadata_asynchronously] = false; + settings[FileCacheSetting::cache_policy] = FileCachePolicy::LRU; + settings[FileCacheSetting::allow_dynamic_cache_resize] = true; + + auto cache = std::make_shared("failed_eviction_restore", settings); + cache->initialize(); + + const auto & user = FileCache::getCommonOrigin(); + auto key = DB::FileCacheKey::fromPath("failed_eviction_restore_key"); + + /// `PARTIALLY_DOWNLOADED` segment, reserved size 8 and downloaded size 3. + { + auto holder = cache->getOrSet(key, 0, 8, /*file_size=*/8, {}, 0, user); + auto seg = *holder->begin(); + ASSERT_EQ(seg->getOrSetDownloader(), FileSegment::getCallerId()); + std::string failure_reason; + ASSERT_TRUE(seg->reserve(/*size_to_reserve=*/8, /*lock_wait_timeout_milliseconds=*/1000, failure_reason)); + + auto key_str = key.toString(); + auto subdir = fs::path(cache_base_path) / key_str.substr(0, 3) / key_str; + if (!fs::exists(subdir)) + fs::create_directories(subdir); + std::string data(3, 'a'); + seg->write(data.data(), data.size(), seg->getCurrentWriteOffset()); + + FileSegment::complete(FileSegmentPtr(seg), false, false); + ASSERT_EQ(seg->state(), State::PARTIALLY_DOWNLOADED); + ASSERT_EQ(seg->getReservedSize(), 8u); + ASSERT_EQ(seg->getDownloadedSize(), 3u); + } + + /// Second segment to keep the cache full and force eviction during resize. + { + auto holder = cache->getOrSet(key, 8, 8, /*file_size=*/16, {}, 0, user); + auto seg = *holder->begin(); + download(seg, /*complete=*/true); + ASSERT_EQ(seg->state(), State::DOWNLOADED); + } + + /// Both priority entries account for reserved size. + ASSERT_EQ(cache->getUsedCacheSize(), 16u); + ASSERT_EQ(cache->getFileSegmentsNum(), 2u); + + /// Force the failed-eviction restore loop to run. + { + DB::FailPointInjection::enableFailPoint("file_cache_dynamic_resize_fail_to_evict"); + SCOPE_EXIT({ + DB::FailPointInjection::disableFailPoint("file_cache_dynamic_resize_fail_to_evict"); + }); + + /// Trigger resize. The restore path must keep total queue size at 16. + DB::FileCacheSettings new_settings = settings; + new_settings[FileCacheSetting::max_size] = 4; + DB::FileCacheSettings actual_settings = settings; + + ASSERT_NO_THROW(cache->applySettingsIfPossible(new_settings, actual_settings)); + + /// Failed eviction reverts limits to the previous value. + ASSERT_EQ(actual_settings[FileCacheSetting::max_size].value, 16u); + + /// Release-visible check for restored reserved-size accounting. + ASSERT_EQ(cache->getUsedCacheSize(), 16u); + ASSERT_EQ(cache->getFileSegmentsNum(), 2u); + + /// All segments must still be reachable from the priority queue. + { + auto infos = cache->getFileSegmentInfos(key, user.user_id); + ASSERT_EQ(infos.size(), 2u); + for (const auto & info : infos) + ASSERT_NE(info.queue_entry_type, FileCacheQueueEntryType::None); + } + } + + /// A second resize verifies delayed-removal state was cleared. + { + DB::FileCacheSettings second_new_settings = settings; + second_new_settings[FileCacheSetting::max_size] = 4; + DB::FileCacheSettings second_actual = settings; + + ASSERT_NO_THROW(cache->applySettingsIfPossible(second_new_settings, second_actual)); + ASSERT_LE(cache->getUsedCacheSize(), 4u); + } +} diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index 8509d3903c38..e2698652f3fc 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -72,6 +73,16 @@ namespace return AzureConnectionValue::PlainStorageAccountURL; } + /// The keys an Azure named collection accepts (`StorageAzureConfiguration`). An override with any + /// other key, which can name any credential, is rejected only after the statement is logged. + bool isAzureCollectionKey(std::string_view key) + { + static const std::unordered_set keys = {"blob_path", "container", "format", "compression", "structure", + "compression_method", "account_name", "account_key", "connection_string", "storage_account_url", "partition_strategy", + "partition_columns_in_data_file", "client_id", "tenant_id"}; + return keys.contains(key); + } + /// The backup engines whose locator names a destination with no credential in it, each with the /// argument count it accepts. `BackupFactory` registers exactly these plus `S3` and `AzureBlobStorage`. std::optional credentialFreeBackupEngineArity(const String & engine_name) @@ -607,43 +618,147 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageFunctionSecretArguments( /// azureBlobStorageCluster('cluster_name', 'conn_string/storage_account_url', ...) has 'conn_string/storage_account_url' as its second argument. size_t url_arg_idx = is_cluster_function ? 1 : 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + + /// The other values are hidden before a connection string is: hiding that replaces its whole argument. if (!is_cluster_function && isNamedCollectionName(0)) { /// azureBlobStorage(named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(1); + maskUnreadAzureCollectionOverrides(1); + findSecretNamedArgument("account_key", 1); if (maskAzureConnectionString(-1, true, 1)) return; - findSecretNamedArgument("account_key", 1); + maskUnshowableAzureConnectionOverrides(1); return; } if (is_cluster_function && isNamedCollectionName(1)) { /// azureBlobStorageCluster(cluster, named_collection, ..., account_key = 'account_key', ...) + maskPositionalsAfterAzureCollection(2); + maskUnreadAzureCollectionOverrides(2); + findSecretNamedArgument("account_key", 2); if (maskAzureConnectionString(-1, true, 2)) return; - findSecretNamedArgument("account_key", 2); + maskUnshowableAzureConnectionOverrides(2); return; } - if (maskAzureConnectionString(url_arg_idx)) + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + + if (const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx)) + markSecretArgument(*credential_arg_idx); + + if (maskAzureConnectionString(arg(url_arg_idx))) return; - /// We should check other arguments first because we don't need to do any replacement in case of - /// azureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - /// azureBlobStorageCluster(cluster, connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) + if (arg(url_arg_idx) < function->arguments->size()) + maskUnshowableAzureConnectionValue(arg(url_arg_idx), *function->arguments->at(arg(url_arg_idx)), /* argument_is_named= */ false); +} + +void FunctionSecretArgumentsFinder::maskAzureExtraCredentials() +{ + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + if (const auto f = function->arguments->at(i)->getFunction(); f && f->name() == "extra_credentials") + markSecretArgument(i); + } +} + +std::optional FunctionSecretArgumentsFinder::tryGetAzureKey(const AbstractFunction & equals) +{ + String key; + if (equals.arguments && equals.arguments->size() == 2 && tryGetStringFromArgument(*equals.arguments->at(0), &key) + && isAzureCollectionKey(key)) + return key; + return {}; +} + +void FunctionSecretArgumentsFinder::maskUnreadAzureCollectionOverrides(size_t start) +{ + std::vector connection_overrides; + for (size_t i = start, size = function->arguments->size(); i < size; ++i) { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) + const auto f = function->arguments->at(i)->getFunction(); + if (!f || f->name() != "equals") + continue; + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if (!(tryGetStringFromArgument(*f->arguments->at(1), nullptr) || f->arguments->at(1)->tryGetLiteralText(nullptr))) + markSecretArgument(i, /* argument_is_named= */ true); + if (key == "connection_string" || key == "storage_account_url") + connection_overrides.push_back(i); + } + + if (connection_overrides.size() > 1) + for (const size_t i : connection_overrides) + markSecretArgument(i, /* argument_is_named= */ true); +} + +std::vector FunctionSecretArgumentsFinder::azureSlotArguments(size_t start) +{ + std::vector slots; + size_t extra_credentials = 0; + for (size_t i = 0, size = function->arguments->size(); i < size; ++i) + { + const auto argument = function->arguments->at(i); + if (argument->isSettings()) + continue; + const auto f = i < start ? nullptr : argument->getFunction(); + if (f && f->name() == "extra_credentials") { - if (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg)) - return; + ++extra_credentials; + continue; + } + if (f && f->name() == "equals" && f->arguments && f->arguments->size() == 2) + { + const auto key = tryGetAzureKey(*f); + if (!key) + markSecretArgument(i); + else if ((key != "partition_strategy" && key != "partition_columns_in_data_file") || !f->arguments->at(1)->tryGetLiteralText(nullptr)) + markSecretArgument(i, /* argument_is_named= */ true); + continue; } + slots.push_back(i); } - /// We're going to replace 'account_key' with '[HIDDEN]' if account_key is used in the signature - if (url_arg_idx + 4 < count) - markSecretArgument(url_arg_idx + 4); + if (extra_credentials > 1) + { + maskEveryArgument(); + return {}; + } + return slots; +} + +std::optional FunctionSecretArgumentsFinder::azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const +{ + const size_t count = slot_arguments.size(); + if (count == url_arg_idx + 2) + return slot_arguments[url_arg_idx + 1]; + if (count <= url_arg_idx + 4) + return {}; + String fourth_arg; + if (count <= url_arg_idx + 7 && tryGetStringFromArgument(slot_arguments[url_arg_idx + 3], &fourth_arg) + && (fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg))) + return {}; + return slot_arguments[url_arg_idx + 4]; +} + +void FunctionSecretArgumentsFinder::maskPositionalsAfterAzureCollection(size_t start) +{ + for (size_t i = start, size = function->arguments->size(); i < size; ++i) + { + const auto f = function->arguments->at(i)->getFunction(); + if (!f || (f->name() != "equals" && f->name() != "extra_credentials")) + markSecretArgument(i); + } } bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named, size_t start) @@ -663,32 +778,38 @@ bool FunctionSecretArgumentsFinder::maskAzureConnectionString(ssize_t url_arg_id return false; } - if (!url_arg.starts_with("http")) + if (!url_arg.starts_with("http") && maskAzureConnectionStringSecrets(url_arg)) { - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - if (RE2::Replace(&url_arg, account_key_pattern, "AccountKey=[HIDDEN]\\1")) - { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; - } + chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments + result.start = url_arg_idx; + result.are_named = argument_is_named; + result.count = 1; + result.replacement = url_arg; + return true; + } - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - if (RE2::Replace(&url_arg, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1")) + return false; +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionValue( + size_t index, const AbstractFunction::Argument & value, bool argument_is_named) +{ + String text; + if (!value.tryGetString(&text, /* allow_identifier= */ false) || classifyAzureConnectionValue(text) == AzureConnectionValue::Unmaskable) + markSecretArgument(index, argument_is_named); +} + +void FunctionSecretArgumentsFinder::maskUnshowableAzureConnectionOverrides(size_t start) +{ + for (const auto * key : {"connection_string", "storage_account_url"}) + { + for (ssize_t i = findNamedArgument(nullptr, key, start); i >= 0; i = findNamedArgument(nullptr, key, static_cast(i) + 1)) { - chassert(result.count == 0); /// We shouldn't use replacement with masking other arguments - result.start = url_arg_idx; - result.are_named = argument_is_named; - result.count = 1; - result.replacement = url_arg; - return true; + const auto index = static_cast(i); + /// `findNamedArgument` returns only an `equals` function with two arguments. + maskUnshowableAzureConnectionValue(index, *function->arguments->at(index)->getFunction()->arguments->at(1), /* argument_is_named= */ true); } } - - return false; } bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit) @@ -701,8 +822,10 @@ bool FunctionSecretArgumentsFinder::azureCollectionArgumentsAreShowable(size_t s { /// A key this rule cannot read hides which credential the override carries; a value that is /// no plain literal or identifier can nest one (`headers('Authorization' = '...')`). + String key; if (argument_function->arguments && argument_function->arguments->size() == 2 - && tryGetStringFromArgument(*argument_function->arguments->at(0), nullptr) + && tryGetStringFromArgument(*argument_function->arguments->at(0), &key) + && isAzureCollectionKey(key) && (tryGetStringFromArgument(*argument_function->arguments->at(1), nullptr) || argument_function->arguments->at(1)->tryGetLiteralText(nullptr))) continue; @@ -1043,6 +1166,12 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format, [account_name, account_key, ...]) size_t url_arg_idx = 0; + /// The query is formatted for logging before validation rejects a positional argument after a + /// `key = value` one, and the slot it was meant for is unknowable: hide every such positional. + classifyPositionalArguments(); + + maskAzureExtraCredentials(); + if (isNamedCollectionName(url_arg_idx)) { /// AzureBlobStorage(named_collection, ..., account_key = 'account_key', ...) @@ -1057,28 +1186,15 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - /// We should check other arguments first because we don't need to do any replacement in case of - /// AzureBlobStorage(connection_string|storage_account_url, container_name, blobpath, format) -- in this case there is no account_key argument - size_t count = function->arguments->size(); - bool fourth_argument_is_format = false; - if ((url_arg_idx + 4 <= count) && (count <= url_arg_idx + 7)) - { - String fourth_arg; - if (tryGetStringFromArgument(url_arg_idx + 3, &fourth_arg)) - fourth_argument_is_format = fourth_arg == "auto" || KnownFormatNames::instance().exists(fourth_arg); - } - /// Which argument holds a credential: the two-argument shape takes a shared access signature beside - /// the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. - std::optional credential_arg_idx; - if (count == url_arg_idx + 2) - credential_arg_idx = url_arg_idx + 1; - else if (!fourth_argument_is_format && (url_arg_idx + 4 < count)) - credential_arg_idx = url_arg_idx + 4; + /// Slot `n` is the raw argument `arg(n)`; past the end it is an index no argument has. + const auto slot_arguments = azureSlotArguments(url_arg_idx); + auto arg = [&](size_t slot) { return slot < slot_arguments.size() ? slot_arguments[slot] : function->arguments->size(); }; + const auto credential_arg_idx = azureCredentialArgument(slot_arguments, url_arg_idx); /// The engine reads this argument as a connection string or as a plain account url; a value of /// another shape is read by neither rule below, and a hidden connection string replaces it whole. String connection_value; - const auto shape = tryGetStringFromArgument(url_arg_idx, &connection_value) + const auto shape = tryGetStringFromArgument(arg(url_arg_idx), &connection_value) ? classifyAzureConnectionValue(connection_value) : AzureConnectionValue::Unmaskable; if (shape == AzureConnectionValue::Unmaskable || (shape == AzureConnectionValue::ConnectionString && credential_arg_idx)) @@ -1087,7 +1203,7 @@ void FunctionSecretArgumentsFinder::findAzureBlobStorageTableEngineSecretArgumen return; } - if (maskAzureConnectionString(url_arg_idx)) + if (maskAzureConnectionString(arg(url_arg_idx))) return; if (credential_arg_idx) diff --git a/src/Parsers/FunctionSecretArgumentsFinder.h b/src/Parsers/FunctionSecretArgumentsFinder.h index b2c0f511ebbd..161a9754aa52 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.h +++ b/src/Parsers/FunctionSecretArgumentsFinder.h @@ -28,6 +28,9 @@ class AbstractFunction /// The exact literal text of any scalar literal (`1`, `true`, `1.5`), with strings quoted. /// Lets a reconstructor keep non-string values like `use_environment_credentials = 1` visible. virtual bool tryGetLiteralText(String * res) const = 0; + /// A `SETTINGS` clause among the arguments (`remote(..., SETTINGS ...)`): not a positional + /// argument, and it hides its own secret values when formatted. + virtual bool isSettings() const { return false; } }; class Arguments { @@ -164,12 +167,37 @@ class FunctionSecretArgumentsFinder void findS3FunctionSecretArguments(bool is_cluster_function); void findAzureBlobStorageFunctionSecretArguments(bool is_cluster_function); + /// Hides every `extra_credentials(...)` whole, its keys included: a key can be written as anything, a credential too. + void maskAzureExtraCredentials(); + /// The key of a `key = value` argument if it is one of the keys an Azure named collection accepts. Any other left + /// operand can be the credential itself (`'sp=r&sig=...' = 'x'`), so its argument is hidden whole. + static std::optional tryGetAzureKey(const AbstractFunction & equals); + /// Hides every override from `start` on that this rule cannot read: one whose key an Azure named collection does not + /// accept or whose value is no plain literal (it can nest a credential), and every connection override when there are + /// several: only one is read, and only one can be partly shown. + void maskUnreadAzureCollectionOverrides(size_t start); + /// The raw indexes of the arguments the Azure parser assigns slots to, the ones before `start` (the cluster name) as + /// written: it strips the `SETTINGS` clause and the first `extra_credentials(...)`, and a `key = value` takes no slot. + /// Also hides the value of a key the explicit form does not read (all of an argument whose key is no Azure key), and + /// every argument when a second `extra_credentials(...)` shifts the slots. + std::vector azureSlotArguments(size_t start); + /// The raw index of the argument holding a credential, if any: the two-argument shape takes a shared access signature + /// beside the url (`endpoint.sas_auth`), the longer ones an `account_key` - unless the fourth names a format. + std::optional azureCredentialArgument(const std::vector & slot_arguments, size_t url_arg_idx) const; + /// After the collection name every argument must be an override or `extra_credentials(...)`; a positional one is + /// invalid but logged before validation rejects it, and can be a credential. + void maskPositionalsAfterAzureCollection(size_t start); bool maskAzureConnectionString(ssize_t url_arg_idx, bool argument_is_named = false, size_t start = 0); /// Whether the arguments an `AzureBlobStorage(named_collection, ...)` destination or table takes /// from `start` can be shown: only an argument written here can carry a credential, and each has /// to be readable enough to tell that it does not. `positional_limit` bounds the plain literals /// read beside the overrides: one filename for a backup locator, none for a table engine. bool azureCollectionArgumentsAreShowable(size_t start, size_t positional_limit); + /// Hides a connection value that no rule here can show: a URL carrying a credential of its own + /// (`user:key@`, a SAS `?sig=...`), or a value that is not a plain string literal. + void maskUnshowableAzureConnectionValue(size_t index, const AbstractFunction::Argument & value, bool argument_is_named); + /// The same, for the `connection_string` and `storage_account_url` overrides of a named collection from `start` on. + void maskUnshowableAzureConnectionOverrides(size_t start); /// Masks the secrets of every URL form (`url`/`urlCluster` table functions, the `URL` table /// engine, and their named-collection variants): the userinfo password of the url positional or a /// named `url = ...` override, and the `headers(...)` values at any position. `url` is at diff --git a/src/Parsers/FunctionSecretArgumentsFinderAST.h b/src/Parsers/FunctionSecretArgumentsFinderAST.h index 754411535c8d..6d0c5c050342 100644 --- a/src/Parsers/FunctionSecretArgumentsFinderAST.h +++ b/src/Parsers/FunctionSecretArgumentsFinderAST.h @@ -5,6 +5,7 @@ #include #include #include +#include namespace DB @@ -24,6 +25,7 @@ class FunctionAST : public AbstractFunction return nullptr; } bool isIdentifier() const override { return argument->as(); } + bool isSettings() const override { return argument->as(); } bool tryGetString(String * res, bool allow_identifier) const override { if (const auto * literal = argument->as()) diff --git a/src/Parsers/Lexer.cpp b/src/Parsers/Lexer.cpp index 8806ed24492c..abb35a149bc5 100644 --- a/src/Parsers/Lexer.cpp +++ b/src/Parsers/Lexer.cpp @@ -116,7 +116,7 @@ Token quotedHexOrBinString(const char *& pos, const char * const token_begin, co Token Lexer::nextToken() { Token res = nextTokenImpl(); - if (max_query_size && res.end > begin + max_query_size) + if (begin && max_query_size && res.end > begin + max_query_size) res.type = TokenType::ErrorMaxQuerySizeExceeded; if (res.isSignificant()) prev_significant_token_type = res.type; diff --git a/src/Parsers/tests/gtest_Parser.cpp b/src/Parsers/tests/gtest_Parser.cpp index 22f73a45a039..429e65d8d125 100644 --- a/src/Parsers/tests/gtest_Parser.cpp +++ b/src/Parsers/tests/gtest_Parser.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -38,6 +39,13 @@ std::ostream & operator<<(std::ostream & ostr, const ParserTestCase & test_case) return ostr << "ParserTestCase input: " << input_text; } +TEST(Lexer, NullInputWithMaxQuerySize) +{ + Lexer lexer(nullptr, nullptr, 262144); + Token token = lexer.nextToken(); + EXPECT_EQ(TokenType::EndOfStream, token.type); +} + TEST_P(ParserTest, parseQuery) { const auto & parser = std::get<0>(GetParam()); diff --git a/src/Processors/Chunk.cpp b/src/Processors/Chunk.cpp index 0564131c8768..aef99bd3dee0 100644 --- a/src/Processors/Chunk.cpp +++ b/src/Processors/Chunk.cpp @@ -69,13 +69,11 @@ void Chunk::checkNumRowsIsConsistent() MutableColumns Chunk::mutateColumns() { - size_t num_columns = columns.size(); - MutableColumns mutable_columns(num_columns); - for (size_t i = 0; i < num_columns; ++i) - mutable_columns[i] = IColumn::mutate(std::move(columns[i])); - - columns.clear(); - num_rows = 0; + MutableColumns mutable_columns(columns.size()); + /// Detach first: `IColumn::mutate` consumes the column even when it throws, and a chunk never holds a null column. + Columns detached_columns = detachColumns(); + for (size_t i = 0; i < detached_columns.size(); ++i) + mutable_columns[i] = IColumn::mutate(std::move(detached_columns[i])); return mutable_columns; } diff --git a/src/Processors/Formats/IInputFormat.h b/src/Processors/Formats/IInputFormat.h index 2b1eb5a447e8..a2e2f693ef54 100644 --- a/src/Processors/Formats/IInputFormat.h +++ b/src/Processors/Formats/IInputFormat.h @@ -130,6 +130,8 @@ class IInputFormat : public ISource void needOnlyCount() { need_only_count = true; } + virtual void prefetch() {} + protected: ReadBuffer & getReadBuffer() const { chassert(in); return *in; } diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp new file mode 100644 index 000000000000..8f76772b9ef6 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.cpp @@ -0,0 +1,319 @@ +#include + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace DB +{ + +namespace +{ + +/// The largest `n <= end - begin` for which the non-decreasing `offsets` grow by at most `limit` over +/// rows [begin, begin + n). +size_t maxRowsByOffsets(const IColumn::Offsets & offsets, size_t begin, size_t end, UInt64 limit) +{ + const UInt64 base = offsets[static_cast(begin) - 1]; + const auto * first = offsets.data() + begin; + const auto * it = std::upper_bound(first, offsets.data() + end, base + limit); + return static_cast(it - first); +} + +/// A writer either materializes the column or dictionary-encodes it; measuring it as materialized bounds +/// both, since a batch's dictionary holds at most the distinct values of its rows. `canBeInsideLowCardinality` +/// allows only fixed-width types, `String` and `FixedString`, and of those only the two string types reach +/// a 32-bit-offset buffer. +size_t maxRowsForLowCardinality( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const DataTypePtr values_type = removeNullable(removeLowCardinality(type)); + const auto & low_cardinality = assert_cast(column); + const IColumn & values_column = *low_cardinality.getDictionary().getNestedNotNullableColumn(); + + if (isFixedString(values_type)) + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(values_column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + + if (!isString(values_type)) + return num_rows; + + const auto & values = assert_cast(values_column); + const auto & value_offsets = values.getOffsets(); + + /// Scanning the indexes is only needed when the whole dictionary repeated on every row could overflow: + /// no single value is larger than all of them together. This is O(1), unlike finding the largest value, + /// so it does not add work proportional to the dictionary for every batch of a split chunk. + const UInt64 dictionary_bytes = values.empty() ? 0 : value_offsets.back(); + if (dictionary_bytes == 0 || num_rows <= max_batch_bytes / dictionary_bytes) + return num_rows; + + const auto & indexes = low_cardinality.getIndexes(); + UInt64 total = 0; + for (size_t row = begin; row != end; ++row) + { + const auto index = static_cast(indexes.getUInt(row)); + total += value_offsets[index] - value_offsets[index - 1]; + if (total > max_batch_bytes) + return row - begin; + } + return num_rows; +} + +/// A `Variant` becomes an Arrow dense union, whose own buffers are bounded by the row count; only its +/// children, holding one alternative's rows each, can overflow. +size_t maxRowsForVariant( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + const auto & variant_column = assert_cast(column); + const auto & variant_type = assert_cast(*type); + const size_t num_variants = variant_column.getNumVariants(); + const auto & local_discriminators = variant_column.getLocalDiscriminators(); + const auto & variant_offsets = variant_column.getOffsets(); + + /// Within a contiguous row range the offsets of each alternative are contiguous too (see + /// `ColumnVariant::updateHashWithValueRange`), so [begin, end) maps to the range + /// [nested_begin, nested_begin + nested_rows) of every alternative. + std::vector nested_begin(num_variants, 0); + std::vector nested_rows(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows[local_discr] == 0) + nested_begin[local_discr] = variant_offsets[row]; + ++nested_rows[local_discr]; + } + + std::vector nested_rows_that_fit(num_variants); + bool all_fit = true; + for (size_t local_discr = 0; local_discr != num_variants; ++local_discr) + { + const auto global_discr + = variant_column.globalDiscriminatorByLocal(static_cast(local_discr)); + nested_rows_that_fit[local_discr] = maxRowsFittingOneArrowBatch( + variant_column.getVariantByLocalDiscriminator(local_discr), + variant_type.getVariant(global_discr), + nested_begin[local_discr], + nested_begin[local_discr] + nested_rows[local_discr], + fixed_string_as_fixed_byte_array, max_batch_bytes); + all_fit &= nested_rows_that_fit[local_discr] == nested_rows[local_discr]; + } + if (all_fit) + return num_rows; + + /// Some alternative cannot take all of its rows: cut at the row where it runs out. + std::vector nested_rows_taken(num_variants, 0); + for (size_t row = begin; row != end; ++row) + { + const auto local_discr = local_discriminators[row]; + if (local_discr == ColumnVariant::NULL_DISCRIMINATOR) + continue; + if (nested_rows_taken[local_discr] == nested_rows_that_fit[local_discr]) + return row - begin; + ++nested_rows_taken[local_discr]; + } + return num_rows; +} + +} + +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Arrow cannot address more than this however the caller was configured. + max_batch_bytes = std::min(max_batch_bytes, MAX_ARROW_BUFFER_SIZE); + + if (type->lowCardinality()) + return maxRowsForLowCardinality(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + if (isVariant(type)) + return maxRowsForVariant(column, type, begin, end, fixed_string_as_fixed_byte_array, max_batch_bytes); + + /// A null row is written as a zero-length slot, so measuring the nested column only overestimates. + if (type->isNullable()) + { + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + removeNullable(type), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + + switch (WhichDataType(type).idx) + { + case TypeIndex::String: + { + return maxRowsByOffsets(assert_cast(column).getOffsets(), begin, end, max_batch_bytes); + } + case TypeIndex::FixedString: + { + if (fixed_string_as_fixed_byte_array) + return num_rows; + const size_t n = assert_cast(column).getN(); + return n == 0 ? num_rows : std::min(num_rows, max_batch_bytes / n); + } + case TypeIndex::Array: + { + const auto & array = assert_cast(column); + const auto & offsets = array.getOffsets(); + const size_t nested_begin = offsets[static_cast(begin) - 1]; + const size_t nested_rows = maxRowsFittingOneArrowBatch( + array.getData(), + assert_cast(*type).getNestedType(), + nested_begin, + offsets[end - 1], + fixed_string_as_fixed_byte_array, max_batch_bytes); + return maxRowsByOffsets(offsets, begin, end, std::min(nested_rows, max_batch_bytes)); + } + case TypeIndex::Map: + { + /// Both writers encode a Map exactly as its nested `Array(Tuple(key, value))`. + return maxRowsFittingOneArrowBatch( + assert_cast(column).getNestedColumn(), + assert_cast(*type).getNestedType(), + begin, + end, + fixed_string_as_fixed_byte_array, max_batch_bytes); + } + case TypeIndex::Tuple: + { + const auto & tuple = assert_cast(column); + const auto & elements = assert_cast(*type).getElements(); + size_t rows = num_rows; + for (size_t i = 0; i != elements.size(); ++i) + { + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + tuple.getColumn(i), elements[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + } + return rows; + } + /// Fixed-width Arrow types: a single values buffer, no offsets, nothing to exceed. + case TypeIndex::UInt8: + case TypeIndex::UInt16: + case TypeIndex::UInt32: + case TypeIndex::UInt64: + case TypeIndex::UInt128: + case TypeIndex::UInt256: + case TypeIndex::Int8: + case TypeIndex::Int16: + case TypeIndex::Int32: + case TypeIndex::Int64: + case TypeIndex::Int128: + case TypeIndex::Int256: + case TypeIndex::Float32: + case TypeIndex::Float64: + case TypeIndex::Enum8: + case TypeIndex::Enum16: + case TypeIndex::Date: + case TypeIndex::Date32: + case TypeIndex::DateTime: + case TypeIndex::DateTime64: + case TypeIndex::Time: + case TypeIndex::Time64: + case TypeIndex::Decimal32: + case TypeIndex::Decimal64: + case TypeIndex::Decimal128: + case TypeIndex::Decimal256: + case TypeIndex::IPv4: + case TypeIndex::IPv6: + case TypeIndex::UUID: + case TypeIndex::Interval: + { + return num_rows; + } + default: + { + /// A type with no Arrow equivalent is written by serializing each value, so bounding its + /// encoded size would mean serializing twice. The encoder rejects a batch that overflows. + return num_rows; + } + } +} + +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes) +{ + chassert(columns.size() == types.size()); + const size_t num_rows = end - begin; + if (num_rows == 0) + return 0; + + /// Some limits (`Variant`, `LowCardinality`) take time linear in the rows they are given, so measuring + /// the whole remainder of a chunk for each of its batches would be quadratic. The window grows instead: + /// the limit of a prefix is the limit of the whole range capped at the prefix's length, so the first + /// window that does not fit entirely gives the answer, and the work stays proportional to the rows + /// emitted, plus the initial window. + static constexpr size_t initial_window = 8192; + size_t window = std::min(num_rows, initial_window); + while (true) + { + /// Two columns never share an Arrow buffer, so the smallest per-column limit applies. + size_t rows = window; + for (size_t i = 0; i < columns.size() && rows != 0; ++i) + rows = std::min( + rows, + maxRowsFittingOneArrowBatch( + *columns[i], types[i], begin, begin + rows, fixed_string_as_fixed_byte_array, max_batch_bytes)); + + if (rows < window || window == num_rows) + return rows; + window = std::min(num_rows, window * 2); + } +} + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBatchRowLimit.h b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h new file mode 100644 index 000000000000..c532138a8da0 --- /dev/null +++ b/src/Processors/Formats/Impl/ArrowBatchRowLimit.h @@ -0,0 +1,47 @@ +#pragma once + +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include +#include +#include + +namespace DB +{ + +/// The largest `n` such that rows [begin, begin + n) of `column` stay within `max_batch_bytes`; writers +/// split an oversized chunk accordingly. Returns 0 only when the first row does not fit on its own, which +/// the writer then lets Arrow reject. `ColumnConst` and the sparse/replicated representations are not +/// handled; callers materialize first. +/// +/// `LowCardinality` is measured as materialized, which only over-splits when it is written as an Arrow +/// dictionary. A dictionary larger than one buffer is not covered at all: its bytes do not depend on the +/// row count, because `ColumnLowCardinality::insertRangeFrom` keeps a shared source dictionary whole, so +/// every slice re-emits it. Arrow rejects such a chunk. +/// +/// A type with no Arrow equivalent is not covered either, since only serializing its values reveals their +/// encoded size. Both uncovered shapes are rejected by the writer instead of being split. +size_t maxRowsFittingOneArrowBatch( + const IColumn & column, + const DataTypePtr & type, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes = MAX_ARROW_BUFFER_SIZE); + +/// The largest `n` such that rows [begin, begin + n) of every column stay within `max_batch_bytes`: the +/// number of rows of the next record batch of a chunk. The work is proportional to the returned number of +/// rows rather than to `end - begin`, so splitting a chunk into many batches stays linear. +size_t maxRowsFittingOneArrowBatch( + const Columns & columns, + const DataTypes & types, + size_t begin, + size_t end, + bool fixed_string_as_fixed_byte_array, + UInt64 max_batch_bytes); + +} + +#endif diff --git a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp index 1a71a4a32447..7c0dfb0044ae 100644 --- a/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ArrowBlockOutputFormat.cpp @@ -64,6 +64,7 @@ void ArrowBlockOutputFormat::consume(Chunk chunk) .use_signed_indexes_for_dictionary = format_settings.arrow.use_signed_indexes_for_dictionary, .use_64_bit_indexes_for_dictionary = format_settings.arrow.use_64_bit_indexes_for_dictionary, .output_date_as_uint16 = format_settings.arrow.output_date_as_uint16, + .output_max_record_batch_bytes = format_settings.arrow.output_max_record_batch_bytes, }); } diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp index 4699b1b2fdf0..7c2d5b54eed9 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.cpp @@ -1,7 +1,7 @@ #pragma clang diagnostic ignored "-Wreserved-identifier" #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include #include diff --git a/src/Processors/Formats/Impl/ArrowBufferedStreams.h b/src/Processors/Formats/Impl/ArrowBufferedStreams.h index ecb6ef8cb6fe..510e3ee4c26e 100644 --- a/src/Processors/Formats/Impl/ArrowBufferedStreams.h +++ b/src/Processors/Formats/Impl/ArrowBufferedStreams.h @@ -3,7 +3,7 @@ #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp index ffac42b86605..a9b508893a8f 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp @@ -1,7 +1,7 @@ #include #include -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h index e06cce04579d..bf0e3ecf828a 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.h @@ -5,7 +5,7 @@ #include "config.h" -#if USE_ARROW || USE_ORC || USE_PARQUET +#if USE_ARROW || USE_PARQUET #include #include diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp index 60f89e76aeef..f4e991cc1643 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp @@ -21,9 +21,12 @@ #include #include #include +#include #include #include +#include + #include #include #include @@ -66,6 +69,7 @@ namespace DB extern const int LOGICAL_ERROR; extern const int DECIMAL_OVERFLOW; extern const int ILLEGAL_COLUMN; + extern const int TOO_LARGE_ARRAY_SIZE; } static const std::initializer_list>> internal_type_to_arrow_type = @@ -517,6 +521,18 @@ namespace DB throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot fill arrow array {} with {} data", value_type->name(), column_type->getName()); } + /// Arrow's `Utf8`/`Binary` builders take an int32 length and their `Append` skips the copy when it is + /// negative, so a narrowed size would store an empty value instead of failing. + static void checkStringSizeFitsArrowOffsets(size_t size, const String & column_name, const String & format_name) + { + if (size > MAX_ARROW_BUFFER_SIZE) + throw Exception( + ErrorCodes::TOO_LARGE_ARRAY_SIZE, + "Cannot write a value of {} bytes of column {} to {}: `Utf8`/`Binary` offsets are 32-bit, so a single " + "value cannot be larger than {} bytes", + size, column_name, format_name, MAX_ARROW_BUFFER_SIZE); + } + template static void fillArrowArrayWithStringColumnData( ColumnPtr write_column, @@ -541,6 +557,7 @@ namespace DB else { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); } checkStatus(status, write_column->getName(), format_name); @@ -551,6 +568,7 @@ namespace DB for (size_t string_i = start; string_i < end; ++string_i) { std::string_view string_ref = internal_column.getDataAt(string_i); + checkStringSizeFitsArrowOffsets(string_ref.size(), write_column->getName(), format_name); status = builder.Append(string_ref.data(), static_cast(string_ref.size())); checkStatus(status, write_column->getName(), format_name); } @@ -1200,37 +1218,72 @@ namespace DB for (const auto & chunk : chunks) { - /// For arrow::Table creation + /// Normalize once per chunk, so that it is not repeated for each row range below. + Columns columns(columns_num); + DataTypes column_types(columns_num); for (size_t column_i = 0; column_i < columns_num; ++column_i) { - const ColumnWithTypeAndName & header_column = header_columns[column_i]; - auto column = chunk.getColumns()[column_i]; - + auto column = chunk.getColumns()[column_i]->convertToFullColumnIfConst()->convertToFullColumnIfReplicated(); + auto column_type = header_columns[column_i].type; if (!settings.low_cardinality_as_dictionary) column = recursiveRemoveLowCardinality(column); - - std::unique_ptr array_builder; - arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); - checkStatus(status, column->getName(), format_name); - - fillArrowArray( - header_column.name, - column, - header_column.type, - nullptr, - array_builder.get(), - format_name, - 0, - column->size(), - settings, - dictionary_values); - - std::shared_ptr arrow_array; - status = array_builder->Finish(&arrow_array); - checkStatus(status, column->getName(), format_name); - - table_data.at(column_i).emplace_back(std::move(arrow_array)); + columns[column_i] = std::move(column); + column_types[column_i] = std::move(column_type); } + + /// The row limit is measured on types matching the columns: without dictionary output the + /// `LowCardinality` columns were materialized above. + DataTypes measured_types = column_types; + if (!settings.low_cardinality_as_dictionary) + for (auto & type : measured_types) + type = recursiveRemoveLowCardinality(type); + + /// A chunk that exceeds the 32-bit Arrow offsets becomes several arrays of the ChunkedArray. + const size_t num_rows = chunk.getNumRows(); + size_t offset = 0; + do + { + size_t rows = maxRowsFittingOneArrowBatch( + columns, + measured_types, + offset, + num_rows, + settings.output_fixed_string_as_fixed_byte_array, + settings.output_max_record_batch_bytes); + /// A row that does not fit on its own cannot be represented at all; the leaf encoders reject it. + rows = std::min(std::max(rows, 1), num_rows - offset); + + /// For arrow::Table creation + for (size_t column_i = 0; column_i < columns_num; ++column_i) + { + const ColumnWithTypeAndName & header_column = header_columns[column_i]; + ColumnPtr column = columns[column_i]; + + std::unique_ptr array_builder; + arrow::Status status = MakeBuilder(ArrowMemoryPool::instance(), arrow_schema->field(static_cast(column_i))->type(), &array_builder); + checkStatus(status, column->getName(), format_name); + + fillArrowArray( + header_column.name, + column, + column_types[column_i], + nullptr, + array_builder.get(), + format_name, + offset, + offset + rows, + settings, + dictionary_values); + + std::shared_ptr arrow_array; + status = array_builder->Finish(&arrow_array); + checkStatus(status, column->getName(), format_name); + + table_data.at(column_i).emplace_back(std::move(arrow_array)); + } + + offset += rows; + } while (offset < num_rows); } std::vector> columns; diff --git a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h index 2544faf9ed1d..160a78ed1c9f 100644 --- a/src/Processors/Formats/Impl/CHColumnToArrowColumn.h +++ b/src/Processors/Formats/Impl/CHColumnToArrowColumn.h @@ -4,6 +4,7 @@ #if USE_ARROW || USE_PARQUET #include +#include #include #include @@ -33,6 +34,8 @@ class CHColumnToArrowColumn bool use_64_bit_indexes_for_dictionary = false; /// Output Date as UInt16 instead of Arrow DATE32 for backward compatibility. bool output_date_as_uint16 = false; + /// Upper bound on one record batch; a chunk holding more is written as several. + UInt64 output_max_record_batch_bytes = MAX_ARROW_BUFFER_SIZE; }; CHColumnToArrowColumn(const Block & header, const std::string & format_name_, const Settings & settings_); diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp index 58e797b4d591..a6e69f02d3a8 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp @@ -59,7 +59,7 @@ MsgPackRowInputFormat::MsgPackRowInputFormat(SharedHeader header_, std::unique_p void MsgPackRowInputFormat::resetParser() { IRowInputFormat::resetParser(); - visitor.reset(); + parser.init(); } void MsgPackRowInputFormat::setReadBuffer(ReadBuffer & in_) @@ -83,7 +83,7 @@ void MsgPackVisitor::set_info(IColumn & column, DataTypePtr type, UInt8 & read) info_stack.push(Info{column, type, false, std::nullopt, &read}); } -void MsgPackVisitor::reset() +void MsgPackVisitor::init() { info_stack = {}; } @@ -667,10 +667,10 @@ DataTypePtr MsgPackSchemaReader::getDataType(const msgpack::object & object, siz msgpack::object_map object_map = object.via.map; if (object_map.size) { - auto key_type = removeNullable(getDataType(object_map.ptr[0].key, depth + 1)); + auto key_type = getDataType(object_map.ptr[0].key, depth + 1); auto value_type = getDataType(object_map.ptr[0].val, depth + 1); if (key_type && value_type) - return std::make_shared(key_type, value_type); + return std::make_shared(removeNullable(key_type), value_type); } return nullptr; } diff --git a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h index be9dd30d6e8f..323df67d9707 100644 --- a/src/Processors/Formats/Impl/MsgPackRowInputFormat.h +++ b/src/Processors/Formats/Impl/MsgPackRowInputFormat.h @@ -52,7 +52,8 @@ class MsgPackVisitor : public msgpack::null_visitor /// Update info_stack void set_info(IColumn & column, DataTypePtr type, UInt8 & read); - void reset(); + /// Called by msgpack's parse_helper::init. + void init(); private: /// Stack is needed to process arrays and maps diff --git a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp index 96bb9b23ef3c..a39c4d82ec12 100644 --- a/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/MySQLDumpRowInputFormat.cpp @@ -377,8 +377,12 @@ static bool tryToExtractStructureFromCreateQuery(ReadBuffer & in, NamesAndTypesL if (!create_query) return false; + /// `CREATE TABLE ... LIKE` has no column list, and a column list with only indexes or constraints has no columns. + if (!create_query->columns_list) + return false; + const auto * create_defines = create_query->columns_list->as(); - if (!create_defines) + if (!create_defines || !create_defines->columns) return false; structure = getColumnsList(create_defines->columns); @@ -431,9 +435,10 @@ static void readFirstCreateAndInsertQueries(ReadBuffer & in, String & table_name if (type == MySQLQueryType::CREATE) { /// If we have CREATE query, we can extract columns names and types from it. + /// `tryToExtractStructureFromCreateQuery` reads the CREATE query up to and including its `;`, + /// so the next query must not be skipped: it can be the first INSERT query. if (tryToExtractStructureFromCreateQuery(in, structure_from_create)) column_names = structure_from_create.getNames(); - skipQuery(in); insert_query_present = skipToInsertQuery(table_name, in); } diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp index 0e999852c352..b2f26243171e 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp @@ -3,6 +3,7 @@ #if USE_ORC #include +#include #include #include #include @@ -10,8 +11,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include @@ -25,20 +29,26 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include +#include +#include #include #include #include -#include #include #include #include @@ -47,10 +57,11 @@ #include #include -#include #include +#include + namespace DB { namespace ErrorCodes @@ -66,9 +77,12 @@ extern const int TOO_DEEP_RECURSION; ORCInputStream::ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch) - : in(in_), file_size(file_size_), supports_read_at(use_prefetch && in_.supportsReadAt()) + : in(in_) + , file_size(file_size_) + , use_offset_based_read(in_.supportsReadAt()) + , use_async_prefetch(use_prefetch && use_offset_based_read) { - if (supports_read_at) + if (use_async_prefetch) async_runner = threadPoolCallbackRunnerUnsafe(getIOThreadPool().get(), ThreadName::ORC_FILE); } @@ -77,20 +91,23 @@ UInt64 ORCInputStream::getLength() const return file_size; } -UInt64 ORCInputStream::getNaturalReadSize() const -{ - return 128 * 1024; -} - void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) { - if (supports_read_at) + if (use_offset_based_read) { size_t bytes_read = 0; while (bytes_read < length) { size_t bytes_to_read = length - bytes_read; size_t n = in.readBigAt(reinterpret_cast(buf) + bytes_read, bytes_to_read, offset + bytes_read, nullptr); + if (n == 0) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Truncated or corrupted ORC input: readBigAt returned 0 bytes at offset {} ({} bytes remaining of {} requested from base offset {})", + offset + bytes_read, + bytes_to_read, + length, + offset); bytes_read += n; } } @@ -104,7 +121,7 @@ void ORCInputStream::read(void * buf, UInt64 length, UInt64 offset) std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_t offset) { - if (supports_read_at) + if (use_async_prefetch) { return async_runner( [this, buf, length, offset] @@ -129,7 +146,7 @@ std::future ORCInputStream::readAsync(void * buf, uint64_t length, uint64_ } } -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled) { bool has_file_size = isBufferWithFileSize(in); @@ -142,14 +159,15 @@ asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_pref return asORCInputStreamLoadIntoMemory(in, is_cancelled); } -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled) { - size_t magic_size = strlen(ORC_MAGIC_BYTES); + static constexpr std::string_view orc_magic_bytes = "ORC"; + size_t magic_size = orc_magic_bytes.size(); std::string file_data(magic_size, '\0'); /// Avoid loading the whole file if it doesn't seem to even be in the correct format. size_t bytes_read = in.read(file_data.data(), magic_size); - if (bytes_read < magic_size || file_data != ORC_MAGIC_BYTES) + if (bytes_read < magic_size || file_data != orc_magic_bytes) throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file"); { @@ -161,53 +179,157 @@ std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in return std::make_unique(std::move(file_data), file_size); } -/// The default ORC memory pool allocates with `std::malloc`, which returns a null pointer when it -/// fails - and the library dereferences it - and which is invisible to the memory tracker. A -/// malformed file can ask for an arbitrarily large buffer, so allocate through `operator new` -/// instead: it is accounted for and it throws instead of returning null. -class ORCMemoryPool : public orc::MemoryPool +/// Defined below, next to the read path that also uses it. The sargs path resolves predicate column +/// names through the same recursive walk, so pruning and reading always agree on the column. +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case); + +struct ORCPredicateColumnTypes { -public: - char * malloc(uint64_t size) override { return new char[size]; } - void free(char * p) override { delete[] p; } + DataTypePtr result_type; + DataTypePtr declared_type; }; -orc::MemoryPool & getORCMemoryPool() +struct ORCSubcolumnInfo { - static ORCMemoryPool pool; - return pool; + ISerialization::SubstreamData data; + ISerialization::SubstreamPath substreams_path; +}; + +/// Finds a subcolumn of `type` together with the substreams path that leads to it. +static std::optional tryGetORCSubcolumnInfo(const IDataType & type, std::string_view subcolumn_name) +{ + std::optional result; + auto data = ISerialization::SubstreamData(type.getDefaultSerialization()).withType(type.getPtr()); + IDataType::forEachSubcolumn( + [&](const ISerialization::SubstreamPath & path, const String & name, const ISerialization::SubstreamData & subcolumn_data) + { + if (!result && name == subcolumn_name) + result = ORCSubcolumnInfo{subcolumn_data, path}; + }, + data); + return result; } -static const orc::Type * getORCTypeByName(const orc::Type & schema, const String & name, bool ignore_case) +/// True when `path` is a named tuple element at every level, so it is a file leaf with its own +/// statistics. Nullable, LowCardinality and Array are transparent; anything else is refused, +/// which is what rejects Map/Variant/JSON/Dynamic and `.null`, `.size0`, `.keys`, `.values`. +static bool isNamedTupleElementPath(const IDataType & type, std::string_view path, bool ignore_case) { - for (UInt64 i = 0; i != schema.getSubtypeCount(); ++i) - if (boost::equals(schema.getFieldName(i), name) || (ignore_case && boost::iequals(schema.getFieldName(i), name))) - return schema.getSubtype(i); - return nullptr; + const IDataType * current = &type; + while (true) + { + if (const auto * nullable = typeid_cast(current)) + current = nullable->getNestedType().get(); + else if (const auto * low_cardinality = typeid_cast(current)) + current = low_cardinality->getDictionaryType().get(); + else if (const auto * array = typeid_cast(current)) + current = array->getNestedType().get(); + else + break; + } + + const auto * tuple = typeid_cast(current); + if (!tuple || !tuple->hasExplicitNames()) + return false; + + if (tuple->tryGetPositionByName(path, ignore_case)) + return true; + + /// An element name may itself contain dots, so every split has to be considered. + for (size_t dot = path.find('.'); dot != std::string_view::npos; dot = path.find('.', dot + 1)) + { + auto head = path.substr(0, dot); + auto tail = path.substr(dot + 1); + if (head.empty() || tail.empty()) + continue; + if (auto position = tuple->tryGetPositionByName(head, ignore_case)) + if (isNamedTupleElementPath(*tuple->getElement(*position), tail, ignore_case)) + return true; + } + return false; +} + +/// Resolves a named tuple element and retains its declared type before ancestor wrappers are applied. +static std::optional findTupleElementKeyTypes( + const Block & header, const String & name, bool ignore_case) +{ + for (auto [column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(name)) + { + const auto * column = header.findByName(String(column_name), ignore_case); + if (!column || !isNamedTupleElementPath(*column->type, subcolumn_name, ignore_case)) + continue; + if (auto subcolumn = tryGetORCSubcolumnInfo(*column->type, subcolumn_name)) + { + const auto & path = subcolumn->substreams_path; + chassert(!path.empty() && path.back().data.type); + /// A dotted field name can also resolve to a virtual subcolumn of another element. + if (path.back().type != ISerialization::Substream::TupleElement) + continue; + return ORCPredicateColumnTypes{subcolumn->data.type, path.back().data.type}; + } + } + return {}; +} + +/// Resolves predicate types from the reader header, which can contain only the parent tuple column. +static std::optional findHeaderTypesByPath( + const Block & header, const String & name, bool ignore_case) +{ + if (const auto * column = header.findByName(name, ignore_case)) + return ORCPredicateColumnTypes{column->type, column->type}; + return findTupleElementKeyTypes(header, name, ignore_case); +} + +/// KeyCondition derives its key names from this block, and the ORC header carries only the parent +/// column, so a tuple element predicate would degrade to `unknown`. Only the local copy grows; +/// the reader header stays as it is, so the read path is unaffected. +static Block buildORCKeyConditionBlock(const Block & header, const ActionsDAG * filter_dag, bool ignore_case) +{ + if (!filter_dag) + return header; + + Block keys = header; + for (const auto & required : filter_dag->getRequiredColumns()) + { + if (keys.has(required.name)) + continue; + if (auto types = findTupleElementKeyTypes(header, required.name, ignore_case)) + keys.insert({types->result_type->createColumn(), types->result_type, required.name}); + } + return keys; } -static bool isDictionaryEncoded(const orc::StripeInformation * stripe_info, const orc::Type * orc_type) +static bool isDictionaryEncoded(const ORC::Proto::StripeFooter * stripe_footer, const ORC::Type * orc_type) { - if (!stripe_info) + if (!stripe_footer) return false; - auto encoding = stripe_info->getColumnEncoding(orc_type->getColumnId()); - return encoding == orc::ColumnEncodingKind_DICTIONARY || encoding == orc::ColumnEncodingKind_DICTIONARY_V2; + UInt64 column_id = orc_type->getColumnId(); + if (column_id >= stripe_footer->columns.size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Failed to read ORC schema: the first stripe has no encoding for column {}, it has {} column encodings", + column_id, + stripe_footer->columns.size()); + + auto encoding = stripe_footer->columns[column_id].kind; + return encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY || encoding == ORC::Proto::ColumnEncodingKind::DICTIONARY_V2; } static DataTypePtr parseORCType( - const orc::Type * orc_type, + const ORC::Type * orc_type, bool skip_columns_with_unsupported_types, bool dictionary_as_low_cardinality, - const orc::StripeInformation * stripe_info, + const ORC::Proto::StripeFooter * stripe_info, bool & skipped, size_t max_depth = DBMS_DEFAULT_MAX_PARSER_DEPTH, size_t depth = 0) { - assert(orc_type != nullptr); + chassert(orc_type != nullptr); - /// ORC LIST/MAP/STRUCT types can be nested arbitrarily deep and the ORC library does not bound - /// the nesting, so reject deep nesting early (before building the type) with an explicit limit. + /// ORC LIST/MAP/STRUCT types can be nested deep (the ORC reader allows up to 2000 levels) + /// so reject deep nesting early (before building the type) with an explicit limit. /// This keeps schema inference cheap and interruptible instead of recursing over (and later /// walking) a pathologically deep type. checkStackSize is a last-resort backstop. /// max_depth == 0 means unlimited (matching the SQL parser), leaving only checkStackSize. @@ -220,34 +342,111 @@ static DataTypePtr parseORCType( checkStackSize(); const int subtype_count = static_cast(orc_type->getSubtypeCount()); + + /// ORC union maps to the ClickHouse Variant type. It is handled before the switch below so the + /// switch stays non-exhaustive (its default handles unsupported types). Variant sorts and + /// de-duplicates its nested types, but ORC keeps a separate physical stream per branch, so two + /// branches with identical types cannot be represented as a Variant; reject them explicitly + /// instead of silently squashing them. A branch that is itself a union is rejected too: it + /// would map to a Variant, which Variant does not allow to nest. + if (orc_type->getKind() == ORC::TypeKind::UNION) + { + /// A union with more branches than Variant can hold (ColumnVariant::MAX_NESTED_COLUMNS) + /// is valid ORC but not representable; reject it through the normal unsupported-type / + /// skip path before any branch is parsed - otherwise the DataTypeVariant constructor + /// throws a generic BAD_ARGUMENTS and the skip setting is never consulted. + if (static_cast(subtype_count) > ColumnVariant::MAX_NESTED_COLUMNS) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported: Variant supports at most {} nested types", + subtype_count, ColumnVariant::MAX_NESTED_COLUMNS); + } + + DataTypes nested_types; + std::unordered_set seen_type_names; + nested_types.reserve(subtype_count); + for (int i = 0; i < subtype_count; ++i) + { + const auto * subtype = orc_type->getSubtype(i); + + /// A union branch that is itself a union would map to a Variant, and Variant does not + /// allow a nested Variant. Reject it through the normal unsupported-type / skip path + /// here, before the outer DataTypeVariant is constructed - otherwise its constructor + /// throws a confusing BAD_ARGUMENTS ("Nested Variant types are not allowed") and the + /// skip setting is never consulted because the inner union has already been parsed. + if (subtype->getKind() == ORC::TypeKind::UNION) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported", + orc_type->toString()); + } + + auto parsed_type = parseORCType( + subtype, skip_columns_with_unsupported_types, dictionary_as_low_cardinality, stripe_info, skipped, max_depth, depth + 1); + if (skipped) + return {}; + + /// Branch identity must not depend on the stripe's physical encoding: a + /// dictionary-encoded branch parses as LowCardinality(...), which would let e.g. + /// uniontype with one dictionary-encoded branch slip past this check + /// (and the read would then fail on any stripe where the encodings agree). + if (!seen_type_names.insert(recursiveRemoveLowCardinality(parsed_type)->getName()).second) + { + if (skip_columns_with_unsupported_types) + { + skipped = true; + return {}; + } + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported", + orc_type->toString()); + } + nested_types.push_back(parsed_type); + } + return std::make_shared(nested_types); + } + switch (orc_type->getKind()) { - case orc::TypeKind::BOOLEAN: + case ORC::TypeKind::BOOLEAN: return DataTypeFactory::instance().get("Bool"); - case orc::TypeKind::BYTE: + case ORC::TypeKind::BYTE: return std::make_shared(); - case orc::TypeKind::SHORT: + case ORC::TypeKind::SHORT: return std::make_shared(); - case orc::TypeKind::INT: + case ORC::TypeKind::INT: return std::make_shared(); - case orc::TypeKind::LONG: + case ORC::TypeKind::LONG: return std::make_shared(); - case orc::TypeKind::FLOAT: + case ORC::TypeKind::FLOAT: return std::make_shared(); - case orc::TypeKind::DOUBLE: + case ORC::TypeKind::DOUBLE: return std::make_shared(); - case orc::TypeKind::DATE: + case ORC::TypeKind::DATE: return std::make_shared(); - case orc::TypeKind::TIMESTAMP: + case ORC::TypeKind::TIMESTAMP: return std::make_shared(9); - case orc::TypeKind::TIMESTAMP_INSTANT: + case ORC::TypeKind::TIMESTAMP_INSTANT: return std::make_shared(9, "UTC"); - case orc::TypeKind::CHAR: - case orc::TypeKind::VARCHAR: - case orc::TypeKind::BINARY: - case orc::TypeKind::STRING: { + case ORC::TypeKind::CHAR: + case ORC::TypeKind::VARCHAR: + case ORC::TypeKind::BINARY: + case ORC::TypeKind::STRING: { DataTypePtr type; - if (orc_type->getKind() == orc::TypeKind::CHAR) + if (orc_type->getKind() == ORC::TypeKind::CHAR) type = std::make_shared(orc_type->getMaximumLength()); else type = std::make_shared(); @@ -258,7 +457,7 @@ static DataTypePtr parseORCType( return type; } - case orc::TypeKind::DECIMAL: { + case ORC::TypeKind::DECIMAL: { UInt64 precision = orc_type->getPrecision(); UInt64 scale = orc_type->getScale(); if (precision == 0) @@ -268,7 +467,7 @@ static DataTypePtr parseORCType( } return createDecimal(precision, scale); } - case orc::TypeKind::LIST: { + case ORC::TypeKind::LIST: { if (subtype_count != 1) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc List type {}", orc_type->toString()); @@ -279,7 +478,7 @@ static DataTypePtr parseORCType( return std::make_shared(nested_type); } - case orc::TypeKind::MAP: { + case ORC::TypeKind::MAP: { if (subtype_count != 2) throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid Orc Map type {}", orc_type->toString()); @@ -295,7 +494,7 @@ static DataTypePtr parseORCType( return std::make_shared(key_type, value_type); } - case orc::TypeKind::STRUCT: { + case ORC::TypeKind::STRUCT: { DataTypes nested_types; Strings nested_names; nested_types.reserve(subtype_count); @@ -322,7 +521,7 @@ static DataTypePtr parseORCType( throw Exception( ErrorCodes::UNKNOWN_TYPE, - "Unsupported ORC type '{}'." + "Unsupported ORC type '{}'. " "If you want to skip columns with unsupported types, " "you can enable setting input_format_orc_skip_columns_with_unsupported_types_in_schema_inference", orc_type->toString()); @@ -330,30 +529,30 @@ static DataTypePtr parseORCType( } } -static std::optional convertORCTypeToPredicateType(const orc::Type & orc_type) +static std::optional convertORCTypeToPredicateType(const ORC::Type & orc_type) { switch (orc_type.getKind()) { - case orc::BOOLEAN: - return orc::PredicateDataType::BOOLEAN; - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: - return orc::PredicateDataType::LONG; - case orc::FLOAT: - case orc::DOUBLE: - return orc::PredicateDataType::FLOAT; - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: - return orc::PredicateDataType::STRING; - case orc::DATE: - return orc::PredicateDataType::DATE; - case orc::TIMESTAMP: - return orc::PredicateDataType::TIMESTAMP; - case orc::DECIMAL: - return orc::PredicateDataType::DECIMAL; + case ORC::BOOLEAN: + return ORC::PredicateDataType::BOOLEAN; + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: + return ORC::PredicateDataType::LONG; + case ORC::FLOAT: + case ORC::DOUBLE: + return ORC::PredicateDataType::FLOAT; + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: + return ORC::PredicateDataType::STRING; + case ORC::DATE: + return ORC::PredicateDataType::DATE; + case ORC::TIMESTAMP: + return ORC::PredicateDataType::TIMESTAMP; + case ORC::DECIMAL: + return ORC::PredicateDataType::DECIMAL; default: return {}; } @@ -370,23 +569,23 @@ static String getColumnNameFromKeyCondition(const KeyCondition & key_condition, throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't get column from KeyCondition with indice {}", indice); } -static std::optional -convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) +static std::optional +convertFieldToORCLiteral(const ORC::Type & orc_type, const Field & field, DataTypePtr type_hint = nullptr) { try { /// We always fallback to return null if possible CH type hint not consistent with ORC type switch (orc_type.getKind()) { - case orc::BOOLEAN: { + case ORC::BOOLEAN: { /// May throw exception auto val = field.safeGet(); - return orc::Literal(val != 0); + return ORC::Literal(val != 0); } - case orc::BYTE: - case orc::SHORT: - case orc::INT: - case orc::LONG: { + case ORC::BYTE: + case ORC::SHORT: + case ORC::INT: + case ORC::LONG: { /// May throw exception. /// /// In particular, it'll throw if we request the column as unsigned, like this: @@ -394,30 +593,30 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy /// We have to reject this, otherwise it would miss values > 127 (because /// they're treated as negative by ORC). auto val = field.safeGet(); - return orc::Literal(val); + return ORC::Literal(val); } - case orc::FLOAT: - case orc::DOUBLE: { - Float64 val; + case ORC::FLOAT: + case ORC::DOUBLE: { + Float64 val = 0; if (field.tryGet(val)) - return orc::Literal(val); + return ORC::Literal(val); break; } - case orc::VARCHAR: - case orc::CHAR: - case orc::STRING: { + case ORC::VARCHAR: + case ORC::CHAR: + case ORC::STRING: { String str; if (field.tryGet(str)) - return orc::Literal(str.data(), str.size()); + return ORC::Literal(str.data(), str.size()); break; } - case orc::DATE: { - Int64 val; + case ORC::DATE: { + Int64 val = 0; if (field.tryGet(val)) - return orc::Literal(orc::PredicateDataType::DATE, val); + return ORC::Literal(ORC::PredicateDataType::DATE, val); break; } - case orc::TIMESTAMP: { + case ORC::TIMESTAMP: { if (type_hint && isDateTime64(type_hint)) { const auto * datetime64_type = typeid_cast(type_hint.get()); @@ -426,15 +625,23 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy } DecimalField ts; - if (field.tryGet(ts)) + if (field.tryGet(ts) && ts.getScale() <= 9) { - Int64 secs = (ts.getValue() / ts.getScaleMultiplier()).convertTo(); - Int32 nanos = (ts.getValue() - (ts.getValue() / ts.getScaleMultiplier()) * ts.getScaleMultiplier()).convertTo(); - return orc::Literal(secs, nanos); + /// The nanoseconds are not negative, as in the reference implementation and in the statistics. + const Int64 value = ts.getValue().value; + const Int64 multiplier = ts.getScaleMultiplier().value; + Int64 secs = value / multiplier; + Int64 rest = value % multiplier; + if (rest < 0) + { + rest += multiplier; + --secs; + } + return ORC::Literal(secs, static_cast(rest * (1'000'000'000 / multiplier))); } break; } - case orc::DECIMAL: { + case ORC::DECIMAL: { auto precision = orc_type.getPrecision(); if (precision == 0) precision = 38; @@ -445,8 +652,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -455,8 +662,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy if (field.tryGet(val)) { Int64 right = val.getValue().convertTo(); - return orc::Literal( - orc::Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + Int128(right), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } else if (precision <= DecimalUtils::max_precision) @@ -464,10 +671,8 @@ convertFieldToORCLiteral(const orc::Type & orc_type, const Field & field, DataTy DecimalField val; if (field.tryGet(val)) { - Int64 high = val.getValue().value.items[1]; - UInt64 low = static_cast(val.getValue().value.items[0]); - return orc::Literal( - orc::Int128(high, low), static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); + return ORC::Literal( + val.getValue().value, static_cast(orc_type.getPrecision()), static_cast(orc_type.getScale())); } } break; @@ -538,9 +743,9 @@ static bool evaluateRPNElement(const Field & field, const KeyCondition::RPNEleme static void buildORCSearchArgumentImpl( const KeyCondition & key_condition, const Block & header, - const orc::Type & schema, + const ORC::Type & schema, KeyCondition::RPN & rpn_stack, - orc::SearchArgumentBuilder & builder, + ORC::SearchArgumentBuilder & builder, const FormatSettings & format_settings) { if (rpn_stack.empty()) @@ -572,7 +777,7 @@ static void buildORCSearchArgumentImpl( /// Key filter expressions like "func(col) > 100" are not supported for ORC filter push down if (!curr.monotonic_functions_chain.empty()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -583,16 +788,32 @@ static void buildORCSearchArgumentImpl( { if (!set_index || set_index->getOrderedSet().size() != 1 || set_index->hasMonotonicFunctionsChain()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } String column_name = getColumnNameFromKeyCondition(key_condition, curr.getKeyColumn()); - const auto * orc_type = getORCTypeByName(schema, column_name, format_settings.orc.case_insensitive_column_matching); + const bool ignore_case = format_settings.orc.case_insensitive_column_matching; + + /// The predicate column may be a tuple element (`t.x`), which the ORC header does not + /// carry as a flat entry, so resolve it through the type as well as through the schema. + auto column_types = findHeaderTypesByPath(header, column_name, ignore_case); + if (!column_types) + { + builder.literal(ORC::TruthValue::YES_NO_NULL); + break; + } + + /// The resolver rewrites the type it is given when it descends a LIST (a flattened + /// Nested column), so give it a scratch copy: the guards below must judge the key's + /// own type, which is what KeyCondition's RPN holds. + const auto & column_type = column_types->result_type; + auto resolved_type = column_type; + const auto * orc_type = traverseDownORCTypeByName(column_name, &schema, resolved_type, ignore_case); if (!orc_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } @@ -607,30 +828,34 @@ static void buildORCSearchArgumentImpl( /// down filters would result in different outputs. bool skipped = false; auto expect_type = makeNullableRecursively(parseORCType(orc_type, true, false, nullptr, skipped, format_settings.max_parser_depth), format_settings); - const ColumnWithTypeAndName * column = header.findByName(column_name, format_settings.orc.case_insensitive_column_matching); - if (!expect_type || !column) + if (!expect_type) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - auto nested_type = removeNullable(recursiveRemoveLowCardinality(column->type)); + auto nested_type = removeNullable(recursiveRemoveLowCardinality(column_type)); auto expect_nested_type = removeNullable(expect_type); if (!nested_type->equals(*expect_nested_type)) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } - /// If null_as_default is true, the only difference is nullable, and the evaluations of current RPNElement based on default and null field - /// have the same result, we still should push down current filter. - if (format_settings.null_as_default && !column->type->isNullable() && !column->type->isLowCardinalityNullable()) + /// A non-nullable element converts NULL to its default even when a nullable ancestor makes + /// its extracted type nullable. Pruning must agree with the values produced by the reader. + const auto & declared_type = column_types->declared_type; + if (format_settings.null_as_default && !isNullableOrLowCardinalityNullable(declared_type)) { - bool match_if_null = evaluateRPNElement({}, curr); - bool match_if_default = evaluateRPNElement(column->type->getDefault(), curr); + /// Use the column default inserted by `insertNullAsDefaultIfNeeded`. It differs from + /// the type default for `Date32`. + auto default_column = declared_type->createColumn(); + default_column->insertDefault(); + const bool match_if_null = evaluateRPNElement({}, curr); + const bool match_if_default = evaluateRPNElement((*default_column)[0], curr); if (match_if_default != match_if_null) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } } @@ -638,13 +863,21 @@ static void buildORCSearchArgumentImpl( auto predicate_type = convertORCTypeToPredicateType(*orc_type); if (!predicate_type.has_value()) { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); break; } if (need_wrap_not) builder.startNot(); + /// A relaxed atom can be false even when its approximation is true. Preserve that + /// possibility before negation, as `KeyCondition` does with `can_be_false`. + if (curr.relaxed) + { + builder.startAnd(); + builder.literal(ORC::TruthValue::YES_NO); + } + if (contains_is_null) { builder.isNull(orc_type->getColumnId(), *predicate_type); @@ -656,8 +889,8 @@ static void buildORCSearchArgumentImpl( bool has_right_bound = !range.right.isPositiveInfinity(); if (!has_left_bound && !has_right_bound) { - /// Transform whole range orc::TruthValue::YES_NULL - builder.literal(orc::TruthValue::YES_NULL); + /// Transform whole range ORC::TruthValue::YES_NULL + builder.literal(ORC::TruthValue::YES_NULL); } else if (has_left_bound && has_right_bound && range.left_included && range.right_included && range.left == range.right) { @@ -666,15 +899,15 @@ static void buildORCSearchArgumentImpl( if (literal.has_value()) builder.equals(orc_type->getColumnId(), *predicate_type, *literal); else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } else { - std::optional left_literal; + std::optional left_literal; if (has_left_bound) left_literal = convertFieldToORCLiteral(*orc_type, range.left); - std::optional right_literal; + std::optional right_literal; if (has_right_bound) right_literal = convertFieldToORCLiteral(*orc_type, range.right); @@ -694,7 +927,7 @@ static void buildORCSearchArgumentImpl( builder.end(); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_right_bound) @@ -707,7 +940,7 @@ static void buildORCSearchArgumentImpl( builder.lessThan(orc_type->getColumnId(), *predicate_type, *right_literal); } else - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); } if (has_left_bound && has_right_bound) @@ -721,7 +954,7 @@ static void buildORCSearchArgumentImpl( const auto & set_column = ordered_set[0]; bool fail = false; - std::vector literals; + std::vector literals; literals.reserve(set_column->size()); for (size_t i = 0; i < set_column->size(); ++i) { @@ -735,15 +968,28 @@ static void buildORCSearchArgumentImpl( literals.emplace_back(*literal); } - /// set has zero element - if (literals.empty()) - builder.literal(orc::TruthValue::YES); - else if (fail) - builder.literal(orc::TruthValue::YES_NO_NULL); + if (fail) + builder.literal(ORC::TruthValue::YES_NO_NULL); + else if (literals.empty()) + builder.literal(ORC::TruthValue::NO); else + { + /// A set without NULL has no NULL matches. ORC evaluates `IN` as NULL for a + /// NULL key, so exclude NULL explicitly before applying any outer negation. + /// This preserves `nullIn` and `notNullIn` semantics. For regular nullable + /// `IN`, it can only retain extra rows, which the query filter removes. + builder.startAnd(); + builder.startNot(); + builder.isNull(orc_type->getColumnId(), *predicate_type); + builder.end(); builder.in(orc_type->getColumnId(), *predicate_type, literals); + builder.end(); + } } + if (curr.relaxed) + builder.end(); + if (need_wrap_not) builder.end(); @@ -755,7 +1001,7 @@ static void buildORCSearchArgumentImpl( case KeyCondition::RPNElement::FUNCTION_POINT_IN_POLYGON: case KeyCondition::RPNElement::FUNCTION_UNKNOWN: { - builder.literal(orc::TruthValue::YES_NO_NULL); + builder.literal(ORC::TruthValue::YES_NO_NULL); rpn_stack.pop_back(); break; } @@ -787,34 +1033,45 @@ static void buildORCSearchArgumentImpl( } case KeyCondition::RPNElement::ALWAYS_FALSE: { - builder.literal(orc::TruthValue::NO); + builder.literal(ORC::TruthValue::NO); rpn_stack.pop_back(); break; } case KeyCondition::RPNElement::ALWAYS_TRUE: { - builder.literal(orc::TruthValue::YES); + builder.literal(ORC::TruthValue::YES); rpn_stack.pop_back(); break; } } } -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings) +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings) { auto rpn_stack = key_condition.getRPN(); if (rpn_stack.empty()) return nullptr; - auto builder = orc::SearchArgumentFactory::newBuilder(); + auto builder = std::make_unique(); buildORCSearchArgumentImpl(key_condition, header, schema, rpn_stack, *builder, format_settings); return builder->build(); } +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options) +{ + auto reader = std::make_unique(std::move(stream), options); + if (reader->getType().getKind() != ORC::STRUCT) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC files whose root type is not a struct are not supported, the file has root type {}", + reader->getType().toString()); + return reader; +} + static void getFileReader( ReadBuffer & in, - std::unique_ptr & file_reader, + std::unique_ptr & file_reader, const FormatSettings & format_settings, bool use_prefetch, size_t min_bytes_for_seek, @@ -823,16 +1080,18 @@ static void getFileReader( if (is_stopped) return; - orc::ReaderOptions options; - options.setMemoryPool(getORCMemoryPool()); - options.setCacheOptions(orc::CacheOptions{.holeSizeLimit = min_bytes_for_seek, .rangeSizeLimit = 10 * 1024 * 1024UL}); + /// The ranges with the gaps up to `min_bytes_for_seek` are read with one request. + static constexpr UInt64 default_range_size_limit = 10 * 1024 * 1024UL; + ORC::ReaderOptions options; + options.hole_size_limit = min_bytes_for_seek; + options.range_size_limit = std::max(default_range_size_limit, min_bytes_for_seek); auto input_stream = asORCInputStream(in, format_settings, use_prefetch, is_stopped); - file_reader = orc::createReader(std::move(input_stream), options); + file_reader = createORCReader(std::move(input_stream), options); } -static const orc::Type * -traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type, DataTypePtr & type, bool ignore_case) +static const ORC::Type * +traverseDownORCTypeByName(const std::string & target, const ORC::Type * orc_type, DataTypePtr & type, bool ignore_case) { /// Recurses the file-controlled ORC type tree. The matching CH type (and the requested column /// name) bound the depth in practice, but keep a stack backstop here too, since this runs in @@ -842,39 +1101,50 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type if (target.empty()) return orc_type; - auto search_struct_field = [&](const std::string & target_, const orc::Type * type_) -> std::pair + auto search_struct_field = [&](const std::string & target_, const ORC::Type * type_) -> std::pair { - auto target_copy = target_; - if (ignore_case) - boost::to_lower(target_copy); - - for (size_t i = 0; i < type_->getSubtypeCount(); ++i) + auto search_pass = [&](bool fold) -> std::pair { - auto field_name = type_->getFieldName(i); - if (ignore_case) - boost::to_lower(field_name); + auto target_copy = target_; + if (fold) + boost::to_lower(target_copy); - if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + for (size_t i = 0; i < type_->getSubtypeCount(); ++i) { - return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + auto field_name = type_->getFieldName(i); + if (fold) + boost::to_lower(field_name); + + if (startsWith(target_copy, field_name) && (target_copy.size() == field_name.size() || target_copy[field_name.size()] == '.')) + { + return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)}; + } } - } - return {"", nullptr}; + return {"", nullptr}; + }; + + /// A field spelled exactly like the request always wins: a struct may hold several fields + /// whose names differ only by case, and case-folding first binds the request to whichever + /// of them the file lists first. + auto exact_match = search_pass(/*fold=*/false); + if (exact_match.second || !ignore_case) + return exact_match; + return search_pass(/*fold=*/true); }; - if (orc::STRUCT == orc_type->getKind()) + if (ORC::STRUCT == orc_type->getKind()) { const auto [next_target, next_orc_type] = search_struct_field(target, orc_type); return next_orc_type ? traverseDownORCTypeByName(next_target, next_orc_type, type, ignore_case) : nullptr; } - if (orc::LIST == orc_type->getKind()) + if (ORC::LIST == orc_type->getKind()) { /// For cases in which header contains subcolumns flattened from nested columns. /// For example, "a Nested(x String, y Int64)" is flattened to "a.x Array(String), a.y Array(Int64)", and ORC file schema is still "a array>". /// In this case, we should skip possible array type and traverse down to its nested struct type. const auto * array_type = typeid_cast(removeNullable(type).get()); const auto * orc_nested_type = orc_type->getSubtype(0); - if (array_type && orc::STRUCT == orc_nested_type->getKind()) + if (array_type && ORC::STRUCT == orc_nested_type->getKind()) { auto next_type_and_target = search_struct_field(target, orc_nested_type); const auto & next_target = next_type_and_target.first; @@ -890,8 +1160,37 @@ traverseDownORCTypeByName(const std::string & target, const orc::Type * orc_type return nullptr; } -static void -updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_case, std::unordered_set & include_typeids) +/// Forward declarations: updateIncludeTypeIds needs the union branch-hint machinery (defined +/// below, near readColumnFromORCColumn, which is where it is also used) to prune struct-branch +/// fields the same way the read path does. See computeOrcUnionBranchHints. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive); +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type); +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching); + +/// Binds a name to a field of an ORC struct type. A field spelled exactly like the name always +/// wins over one that only matches case-folded, so a struct holding several fields whose names +/// differ only by case resolves the name to the same field everywhere. +static std::optional findORCStructFieldByName(const ORC::Type * orc_type, const String & name, bool ignore_case) +{ + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (name == orc_type->getFieldName(i)) + return i; + + if (ignore_case) + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + if (boost::iequals(name, orc_type->getFieldName(i))) + return i; + + return std::nullopt; +} + +/// Also collects the ORC structs that are requested as a `Tuple`. +static void updateIncludeTypeIds( + DataTypePtr type, + const ORC::Type * orc_type, + bool ignore_case, + std::unordered_set & include_typeids, + std::vector & requested_structs) { /// Recurses the file-controlled ORC type tree in lockstep with the (parser-bounded) CH type. /// Keep a stack backstop here too: this runs in prepareFileReader, before the @@ -908,71 +1207,121 @@ updateIncludeTypeIds(DataTypePtr type, const orc::Type * orc_type, bool ignore_c auto non_nullable_type = removeNullable(type); switch (orc_type->getKind()) { - case orc::LIST: { + case ORC::LIST: { const auto * array_type = typeid_cast(non_nullable_type.get()); if (array_type) { - updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids); + updateIncludeTypeIds(array_type->getNestedType(), orc_type->getSubtype(0), ignore_case, include_typeids, requested_structs); + return; } - return; + break; } - case orc::MAP: { + case ORC::MAP: { const auto * map_type = typeid_cast(non_nullable_type.get()); if (map_type) { - updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids); - updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids); + updateIncludeTypeIds(map_type->getKeyType(), orc_type->getSubtype(0), ignore_case, include_typeids, requested_structs); + updateIncludeTypeIds(map_type->getValueType(), orc_type->getSubtype(1), ignore_case, include_typeids, requested_structs); + return; } - return; + break; } - case orc::STRUCT: { + case ORC::STRUCT: { /// To make sure tuple field pruning work fine, we should include only the fields of ORC struct type which are also contained in CH tuple types, instead of all fields of ORC struct type. /// For example, CH tupe type in header is "x Tuple(a String)", ORC struct type is "x struct", then only type id of field "x.a" should be included. /// For tuple field pruning purpose, we should never include "x.b" for it is not required in format header. const auto * tuple_type = typeid_cast(non_nullable_type.get()); if (tuple_type) { + requested_structs.push_back(orc_type); if (tuple_type->hasExplicitNames()) { - std::unordered_map orc_field_name_to_index; - orc_field_name_to_index.reserve(orc_type->getSubtypeCount()); - for (size_t struct_i = 0; struct_i < orc_type->getSubtypeCount(); ++struct_i) - { - String field_name = orc_type->getFieldName(struct_i); - if (ignore_case) - boost::to_lower(field_name); - - orc_field_name_to_index[field_name] = struct_i; - } - const auto & element_names = tuple_type->getElementNames(); for (size_t tuple_i = 0; tuple_i < element_names.size(); ++tuple_i) { - String element_name = element_names[tuple_i]; - if (ignore_case) - boost::to_lower(element_name); - - if (orc_field_name_to_index.contains(element_name)) - { + if (auto field_i = findORCStructFieldByName(orc_type, element_names[tuple_i], ignore_case)) updateIncludeTypeIds( - tuple_type->getElement(tuple_i), - orc_type->getSubtype(orc_field_name_to_index[element_name]), - ignore_case, - include_typeids); - } + tuple_type->getElement(tuple_i), orc_type->getSubtype(*field_i), ignore_case, include_typeids, requested_structs); } } else { for (size_t i = 0; i < tuple_type->getElements().size() && i < orc_type->getSubtypeCount(); ++i) - updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids); + updateIncludeTypeIds(tuple_type->getElement(i), orc_type->getSubtype(i), ignore_case, include_typeids, requested_structs); } + return; + } + break; + } + case ORC::UNION: { + /// ORC union maps to the ClickHouse Variant type. A branch that gets a forced type hint + /// (the same way readColumnFromORCColumn computes it - see computeOrcUnionBranchHints) + /// is selected by recursing into the hint, so a STRUCT branch keeps the named-tuple + /// field pruning above: a field the hint's tuple does not reference (e.g. an + /// unsupported or corrupt one) is never added to include_typeids. A branch without a + /// forced hint is read in full, matching readColumnFromORCColumn's "no guess is ever + /// made" policy, so its entire subtree is selected. Every branch always contributes at + /// least one id, so ORC's ColumnSelector::selectParents never falls back to its "fully + /// select every branch or none" override for partial branch selection, and the union's + /// own tag stream is selected as the automatic parent of the selected branches. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, non_nullable_type, ignore_case); + for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) + { + const auto * branch_orc_type = orc_type->getSubtype(i); + if (branch_hints[i]) + updateIncludeTypeIds(branch_hints[i], branch_orc_type, ignore_case, include_typeids, requested_structs); + else + include_typeids.insert(branch_orc_type->getColumnId()); } return; } default: return; } + + /// A requested type of another kind reads the whole node, and the cast to the requested type converts it or throws. + include_typeids.insert(orc_type->getColumnId()); +} + +/// Whether a column of the subtree of `orc_type`, or one of its ancestors (which reads the subtree whole), is included. +static bool isORCTypeRead( + const ORC::Type & root, const ORC::Type & orc_type, const std::unordered_set & include_typeids) +{ + for (UInt64 id = orc_type.getColumnId(); id <= orc_type.getMaximumColumnId(); ++id) + { + if (include_typeids.contains(id)) + return true; + } + + const ORC::Type * node = &root; + while (node && node->getColumnId() < orc_type.getColumnId()) + { + if (include_typeids.contains(node->getColumnId())) + return true; + + const ORC::Type * child = nullptr; + for (UInt64 i = 0; i < node->getSubtypeCount() && !child; ++i) + { + if (node->getSubtype(i)->getMaximumColumnId() >= orc_type.getColumnId()) + child = node->getSubtype(i); + } + node = child; + } + return false; +} + +/// The field of an ORC struct with the fewest columns, or the struct itself if it has no fields. +static const ORC::Type & getNarrowestORCStructField(const ORC::Type & orc_struct) +{ + const ORC::Type * narrowest = &orc_struct; + for (UInt64 i = 0; i < orc_struct.getSubtypeCount(); ++i) + { + const auto * field = orc_struct.getSubtype(i); + if (narrowest == &orc_struct + || field->getMaximumColumnId() - field->getColumnId() < narrowest->getMaximumColumnId() - narrowest->getColumnId()) + narrowest = field; + } + return *narrowest; } NativeORCBlockInputFormat::NativeORCBlockInputFormat( @@ -999,34 +1348,51 @@ void NativeORCBlockInputFormat::prepareFileReader() return; if (format_filter_info) - format_filter_info->initKeyConditionOnce(getPort().getHeader()); - - std::unique_ptr stripe_info; - if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); - - orc_column_to_ch_column = std::make_unique( - getPort().getHeader(), - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.orc.case_insensitive_column_matching, - format_settings.orc.dictionary_as_low_cardinality); + format_filter_info->initKeyConditionOnce(buildORCKeyConditionBlock( + getPort().getHeader(), + format_filter_info->filter_actions_dag.get(), + format_settings.orc.case_insensitive_column_matching)); const bool ignore_case = format_settings.orc.case_insensitive_column_matching; const auto & header = getPort().getHeader(); const auto & file_schema = file_reader->getType(); std::unordered_set include_typeids; + std::vector requested_structs; for (const auto & column : header) { auto adjusted_type = column.type; const auto * orc_type = traverseDownORCTypeByName(column.name, &file_schema, adjusted_type, ignore_case); if (orc_type) - updateIncludeTypeIds(adjusted_type, orc_type, ignore_case, include_typeids); + updateIncludeTypeIds(adjusted_type, orc_type, ignore_case, include_typeids, requested_structs); + } + + /// A requested struct none of whose requested fields is in the file is still read, through its narrowest field, + /// for its presence and the sizes of the lists and maps around it; `matchORCTupleElementsByName` then fills the + /// requested fields with defaults. Inner structs first, as a read inner one makes its parents read. + std::ranges::sort(requested_structs, std::greater{}, &ORC::Type::getColumnId); + std::unordered_set count_only_fields; + for (const auto * orc_struct : requested_structs) + { + if (isORCTypeRead(file_schema, *orc_struct, include_typeids)) + continue; + const auto & narrowest = getNarrowestORCStructField(*orc_struct); + include_typeids.insert(narrowest.getColumnId()); + if (&narrowest != orc_struct) + count_only_fields.insert(narrowest.getColumnId()); } include_indices.assign(include_typeids.begin(), include_typeids.end()); + orc_column_to_ch_column = std::make_unique( + getPort().getHeader(), + format_settings.orc.allow_missing_columns, + format_settings.null_as_default, + format_settings.orc.case_insensitive_column_matching, + format_settings.orc.dictionary_as_low_cardinality, + format_settings.date_time_overflow_behavior, + std::move(count_only_fields)); + if (format_settings.orc.filter_push_down && format_filter_info && format_filter_info->key_condition && !sargs) - sargs = buildORCSearchArgument(*format_filter_info->key_condition, getPort().getHeader(), file_reader->getType(), format_settings); + sargs = buildORCSearchArgument(*format_filter_info->key_condition, header, file_schema, format_settings); selected_stripes = calculateSelectedStripes(static_cast(file_reader->getNumberOfStripes()), skip_stripes); read_iterator = 0; @@ -1048,7 +1414,7 @@ void NativeORCBlockInputFormat::prefetchStripes() int stripe = selected_stripes[prefetch_iterator]; stripes.push_back(stripe); - total_stripe_size += file_reader->getStripe(stripe)->getLength(); + total_stripe_size += ORC::Reader::getStripeLength(file_reader->getStripe(stripe)); ++prefetch_iterator; } @@ -1079,32 +1445,31 @@ std::vector NativeORCBlockInputFormat::calculateSelectedStripes(int num_str bool NativeORCBlockInputFormat::prepareStripeReader() { - assert(file_reader); + chassert(file_reader); if (read_iterator >= selected_stripes.size()) return false; int current_stripe = selected_stripes[read_iterator]; - current_stripe_info = file_reader->getStripe(current_stripe); - if (!current_stripe_info->getNumberOfRows()) + current_stripe_info = &file_reader->getStripe(current_stripe); + if (!current_stripe_info->number_of_rows) throw Exception(ErrorCodes::INCORRECT_DATA, "ORC stripe {} has no rows", current_stripe); - orc::RowReaderOptions row_reader_options; - row_reader_options.setEnableLazyDecoding(format_settings.orc.dictionary_as_low_cardinality); - row_reader_options.includeTypes(include_indices); - row_reader_options.setTimezoneName(format_settings.orc.reader_time_zone_name); - row_reader_options.range(current_stripe_info->getOffset(), current_stripe_info->getLength()); + ORC::RowReaderOptions row_reader_options; + row_reader_options.enable_lazy_decoding = format_settings.orc.dictionary_as_low_cardinality; + row_reader_options.include_types = include_indices; + row_reader_options.timezone_name = format_settings.orc.reader_time_zone_name; + row_reader_options.range_offset = current_stripe_info->offset; + row_reader_options.range_length = ORC::Reader::getStripeLength(*current_stripe_info); if (format_settings.orc.filter_push_down && sargs) - { - row_reader_options.searchArgument(sargs); - } + row_reader_options.search_argument = sargs; stripe_reader = file_reader->createRowReader(row_reader_options); ++read_iterator; if (use_prefetch) { /// Release outdated buffer before boundary to avoid OOM - file_reader->releaseBuffer(current_stripe_info->getOffset()); + file_reader->releaseBuffer(current_stripe_info->offset); /// Prefetch next selected stripe prefetchStripes(); @@ -1127,7 +1492,7 @@ Chunk NativeORCBlockInputFormat::read() int current_stripe = selected_stripes[read_iterator]; ++read_iterator; - return getChunkForCount(file_reader->getStripe(current_stripe)->getNumberOfRows()); + return getChunkForCount(file_reader->getStripe(current_stripe).number_of_rows); } if (!stripe_reader) @@ -1139,14 +1504,12 @@ Chunk NativeORCBlockInputFormat::read() if (is_stopped) return {}; - /// TODO: figure out why reuse batch would cause asan fatals in https://s3.amazonaws.com/clickhouse-test-reports/55330/be39d23af2d7e27f5ec7f168947cf75aeaabf674/stateless_tests__asan__[4_4].html - /// Not sure if it is a false positive case. Notice that reusing batch will speed up reading ORC by 1.15x. + /// The values are decoded directly into the columns of the batch, which are then handed over to the chunk. Stopwatch time; - auto batch = stripe_reader->createRowBatch(format_settings.orc.row_batch_size); + auto batch = stripe_reader->createRowBatch(); while (true) { - bool ok = stripe_reader->next(*batch); - if (ok) + if (stripe_reader->next(*batch, static_cast(format_settings.orc.row_batch_size))) break; /// No more rows to read in current stripe, continue to prepare reading next stripe @@ -1163,7 +1526,7 @@ Chunk NativeORCBlockInputFormat::read() orc_column_to_ch_column->orcTableToCHChunk(res, &schema, batch.get(), num_rows, &block_missing_values); LOG_TEST(getLogger("NativeORCBlockInputFormat"), "Convert {} rows take {} ms", num_rows, time.elapsedMilliseconds()); - approx_bytes_read_for_chunk = num_rows * current_stripe_info->getLength() / current_stripe_info->getNumberOfRows(); + approx_bytes_read_for_chunk = num_rows * ORC::Reader::getStripeLength(*current_stripe_info) / current_stripe_info->number_of_rows; return res; } @@ -1188,33 +1551,41 @@ NativeORCSchemaReader::NativeORCSchemaReader(ReadBuffer & in_, const FormatSetti { } -NamesAndTypesList NativeORCSchemaReader::readSchema() +void NativeORCSchemaReader::initializeIfNeeded() { - std::unique_ptr file_reader; - std::atomic is_stopped = 0; + if (initialized) + return; getFileReader(in, file_reader, format_settings, false, 0, is_stopped); + initialized = true; +} + +NamesAndTypesList NativeORCSchemaReader::readSchema() +{ + initializeIfNeeded(); const auto & schema = file_reader->getType(); Block header; - std::unique_ptr stripe_info; + std::optional first_stripe_footer; if (file_reader->getNumberOfStripes()) - stripe_info = file_reader->getStripe(0); + first_stripe_footer = file_reader->readStripeFooter(0); - for (size_t i = 0; i < schema.getSubtypeCount(); ++i) { - const std::string & name = schema.getFieldName(i); - const orc::Type * orc_type = schema.getSubtype(i); + for (size_t i = 0; i < schema.getSubtypeCount(); ++i) + { + const std::string & name = schema.getFieldName(i); + const ORC::Type * orc_type = schema.getSubtype(i); - bool skipped = false; - DataTypePtr type = parseORCType( - orc_type, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.orc.dictionary_as_low_cardinality, - stripe_info.get(), - skipped, - format_settings.max_parser_depth); - if (!skipped) - header.insert(ColumnWithTypeAndName{type, name}); + bool skipped = false; + DataTypePtr type = parseORCType( + orc_type, + format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + format_settings.orc.dictionary_as_low_cardinality, + first_stripe_footer ? &*first_stripe_footer : nullptr, + skipped, + format_settings.max_parser_depth); + if (!skipped) + header.insert(ColumnWithTypeAndName{type, name}); + } } /// ORC doesn't have non-nullable data types. @@ -1223,26 +1594,36 @@ NamesAndTypesList NativeORCSchemaReader::readSchema() return header.getNamesAndTypesList(); } +std::optional NativeORCSchemaReader::readNumberOrRows() +{ + initializeIfNeeded(); + return file_reader->getNumberOfRows(); +} + ORCColumnToCHColumn::ORCColumnToCHColumn( const Block & header_, bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_, - bool dictionary_as_low_cardinality_) + bool dictionary_as_low_cardinality_, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_, + std::unordered_set count_only_fields_) : header(header_) , allow_missing_columns(allow_missing_columns_) , null_as_default(null_as_default_) , case_insensitive_matching(case_insensitive_matching_) , dictionary_as_low_cardinality(dictionary_as_low_cardinality_) + , date_time_overflow_behavior(date_time_overflow_behavior_) + , count_only_fields(std::move(count_only_fields_)) { } void ORCColumnToCHColumn::orcTableToCHChunk( - Chunk & res, const orc::Type * schema, const orc::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, const ORC::Type * schema, const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values) { - const auto * struct_batch = dynamic_cast(table); + const auto * struct_batch = dynamic_cast(table); if (!struct_batch) - throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", struct_batch->toString()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table must be StructVectorBatch but is {}", demangle(typeid(*table).name())); if (schema->getSubtypeCount() != struct_batch->fields.size()) throw Exception( @@ -1250,24 +1631,26 @@ void ORCColumnToCHColumn::orcTableToCHChunk( size_t field_num = struct_batch->fields.size(); NameToColumnPtr name_to_column_ptr; + /// The file's own spellings, in file order: the keys above are what a request is matched + /// against, and a case-folded match has to pick among them in a fixed order. + Names orc_field_names; + orc_field_names.reserve(field_num); for (size_t i = 0; i < field_num; ++i) { - auto name = schema->getFieldName(i); + const auto & name = schema->getFieldName(i); const auto * field = struct_batch->fields[i]; if (!field) throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC table field {} is null", name); - if (case_insensitive_matching) - boost::to_lower(name); - - name_to_column_ptr[std::move(name)] = {field, schema->getSubtype(i)}; + name_to_column_ptr[name] = {field, schema->getSubtype(i)}; + orc_field_names.push_back(name); } - orcColumnsToCHChunk(res, name_to_column_ptr, num_rows, block_missing_values); + orcColumnsToCHChunk(res, name_to_column_ptr, orc_field_names, num_rows, block_missing_values); } /// Creates a null bytemap from ORC's not-null bytemap -static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_column) +static ColumnPtr readByteMapFromORCColumn(const ORC::ColumnVectorBatch * orc_column) { if (!orc_column->hasNulls) return ColumnUInt8::create(orc_column->numElements, static_cast(0)); @@ -1282,70 +1665,67 @@ static ColumnPtr readByteMapFromORCColumn(const orc::ColumnVectorBatch * orc_col } -static const orc::ColumnVectorBatch * getNestedORCColumn(const orc::ListVectorBatch * orc_column) +/// A branch of an ORC union can be non-null at the union level yet select a null payload; ORC +/// leaves a placeholder (a default value) at such positions. When the branch is later cast to an +/// explicit Variant alternative, a value-checking cast (e.g. Int8 -> Enum8, or the same inside a +/// Tuple field) would reject those placeholders even though the rows are never read (they become +/// the Variant NULL discriminator). Overwrite every null-payload row with a copy of a non-null row +/// before casting; the copied values are discarded downstream. If every row is a null payload there +/// is nothing to read, so a null is returned and the caller uses a default-valued column instead. +static ColumnPtr replaceNullPayloadRowsWithValidRow(const ColumnPtr & column, const NullMap & null_map) +{ + size_t valid_row = column->size(); + for (size_t row = 0; row < column->size(); ++row) + if (!null_map[row]) + { + valid_row = row; + break; + } + + if (valid_row == column->size()) + return nullptr; + + auto result = column->cloneEmpty(); + result->reserve(column->size()); + for (size_t row = 0; row < column->size(); ++row) + result->insertFrom(*column, null_map[row] ? valid_row : row); + return result; +} + + +static const ORC::ColumnVectorBatch * getNestedORCColumn(const ORC::ListVectorBatch * orc_column) { return orc_column->elements.get(); } +/// The reader decodes the lengths directly into the end offsets, as in `ColumnArray`. template static ColumnPtr readOffsetsFromORCListColumn(const BatchType * orc_column) { - auto offsets_column = ColumnUInt64::create(); - ColumnArray::Offsets & offsets_data = assert_cast &>(*offsets_column).getData(); - offsets_data.reserve(orc_column->numElements); - - for (size_t i = 0; i < orc_column->numElements; ++i) - offsets_data.push_back(orc_column->offsets[i + 1]); - - return offsets_column; + return orc_column->offsets; } +/// The values of the primitive types are decoded directly into the columns (with zeros for the nulls). static ColumnWithTypeAndName -readColumnWithBooleanData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithBooleanData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_bool_column = dynamic_cast(orc_column); - auto internal_type = DataTypeFactory::instance().get("Bool"); - auto internal_column = internal_type->createColumn(); - auto & column_data = assert_cast &>(*internal_column).getData(); - - column_data.reserve(orc_bool_column->numElements); - for (size_t i = 0; i < orc_bool_column->numElements; ++i) - { - if (!orc_bool_column->hasNulls || orc_bool_column->notNull[i]) - column_data.push_back(static_cast(orc_bool_column->data[i])); - else - column_data.push_back(static_cast(0)); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_bool_column = typeid_cast(*orc_column); + return {orc_bool_column.column, DataTypeFactory::instance().get("Bool"), column_name}; } -template +template static ColumnWithTypeAndName -readColumnWithNumericData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readColumnWithNumericData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - auto internal_type = std::make_shared>(); - auto internal_column = internal_type->createColumn(); - auto & column_data = static_cast &>(*internal_column).getData(); - const auto * orc_int_column = dynamic_cast(orc_column); - - column_data.reserve(orc_int_column->numElements); - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(NumericType(orc_int_column->data[i])); - else - column_data.push_back(NumericType{}); - } - - return {std::move(internal_column), internal_type, column_name}; + const auto & orc_numeric_column = typeid_cast &>(*orc_column); + return {orc_numeric_column.column, std::make_shared>(), column_name}; } template static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( - const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name, bool nullable) + const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name, bool nullable) { /// Fill CH holder_column with ORC dictionary /// Note that holder_column is always a ColumnString or ColumnFixedstring whether nullable is true or false, because ORC dictionary doesn't contain null values. @@ -1358,60 +1738,45 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( DataTypePtr nested_type = nullable ? std::make_shared(holder_type) : holder_type; auto internal_type = std::make_shared(std::move(nested_type)); - const auto & orc_str_column = dynamic_cast(*orc_column); + const auto & orc_str_column = dynamic_cast(*orc_column); size_t rows = orc_str_column.numElements; - const auto & orc_dict = *orc_str_column.dictionary; - if (orc_dict.dictionaryOffset.size() <= 1) + const auto & orc_dict = assert_cast(*orc_str_column.dictionary->column); + size_t dict_size = orc_dict.size(); + if (dict_size == 0) { + /// Only nulls can be encoded with an empty dictionary. + for (size_t i = 0; i < rows; ++i) + { + if (!orc_str_column.hasNulls || orc_str_column.notNull[i]) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC dictionary index {} at row {} is out of range [0, 0)", + orc_str_column.index[i], i); + } auto result_column = internal_type->createColumn(); result_column->insertManyDefaults(rows); return {std::move(result_column), internal_type, column_name}; } - size_t dict_size = orc_dict.dictionaryOffset.size() - 1; - auto holder_column = holder_type->createColumn(); + /// The dictionary of ORC is already a `ColumnString`, which is the holder for `String`. + ColumnPtr holder_column = orc_str_column.dictionary->column; if constexpr (fixed_string) { const size_t n = orc_type->getMaximumLength(); - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - size_t reserve_size = dict_size * n; - column_chars.resize_exact(reserve_size); - size_t curr_offset = 0; + auto fixed_holder_column = ColumnFixedString::create(n); + PaddedPODArray & column_chars = fixed_holder_column->getChars(); + column_chars.resize_fill(dict_size * n); for (size_t i = 0; i < dict_size; ++i) { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - if (buf_size > n) + auto value = orc_dict.getDataAt(i); + if (value.size() > n) throw Exception( ErrorCodes::INCORRECT_DATA, "ORC dictionary entry {} has size {} that exceeds the declared FixedString length {}", - i, buf_size, n); - memcpy(&column_chars[curr_offset], buf, buf_size); - /// resize_exact does not zero-initialize, so pad shorter entries to keep FixedString values - /// deterministic and to avoid leaking uninitialized heap memory. - if (buf_size < n) - memset(&column_chars[curr_offset + buf_size], 0, n - buf_size); - curr_offset += n; - } - } - else - { - auto & concrete_holder_column = assert_cast(*holder_column); - PaddedPODArray & column_chars = concrete_holder_column.getChars(); - PaddedPODArray & column_offsets = concrete_holder_column.getOffsets(); - - column_chars.resize_exact(orc_dict.dictionaryBlob.size()); - column_offsets.resize_exact(dict_size); - size_t curr_offset = 0; - for (size_t i = 0; i < dict_size; ++i) - { - const auto * buf = orc_dict.dictionaryBlob.data() + orc_dict.dictionaryOffset[i]; - size_t buf_size = orc_dict.dictionaryOffset[i + 1] - orc_dict.dictionaryOffset[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; + i, value.size(), n); + memcpy(&column_chars[i * n], value.data(), value.size()); } + holder_column = std::move(fixed_holder_column); } /// Insert CH dictionary_column from holder_column @@ -1475,57 +1840,22 @@ static ColumnWithTypeAndName readColumnWithEncodedStringOrFixedStringData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithStringData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static const ColumnString & getStringColumnFromBatch(const ORC::ColumnVectorBatch * orc_column, ColumnPtr & holder) { - auto internal_type = std::make_shared(); - auto internal_column = internal_type->createColumn(); - PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); - PaddedPODArray & column_offsets = assert_cast(*internal_column).getOffsets(); - - const auto * orc_str_column = dynamic_cast(orc_column); - size_t reserve_size = 0; - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - reserve_size += orc_str_column->length[i]; - } - - column_chars.resize_exact(reserve_size); - column_offsets.resize_exact(orc_str_column->numElements); - - size_t curr_offset = 0; - if (!orc_str_column->hasNulls) - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - column_offsets[i] = curr_offset; - } - } - else - { - for (size_t i = 0; i < orc_str_column->numElements; ++i) - { - if (orc_str_column->notNull[i]) - { - const auto * buf = orc_str_column->data[i]; - size_t buf_size = orc_str_column->length[i]; - memcpy(&column_chars[curr_offset], buf, buf_size); - curr_offset += buf_size; - } + holder = ORC::getStringColumn(dynamic_cast(*orc_column)); + return assert_cast(*holder); +} - column_offsets[i] = curr_offset; - } - } - return {std::move(internal_column), internal_type, column_name}; +static ColumnWithTypeAndName +readColumnWithStringData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) +{ + ColumnPtr column; + getStringColumnFromBatch(orc_column, column); + return {column, std::make_shared(), column_name}; } static ColumnWithTypeAndName -readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const orc::Type * orc_type, const String & column_name) +readColumnWithFixedStringData(const ORC::ColumnVectorBatch * orc_column, const ORC::Type * orc_type, const String & column_name) { size_t fixed_len = orc_type->getMaximumLength(); auto internal_type = std::make_shared(fixed_len); @@ -1533,25 +1863,22 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o PaddedPODArray & column_chars = assert_cast(*internal_column).getChars(); column_chars.reserve(orc_column->numElements * fixed_len); - const auto * orc_str_column = dynamic_cast(orc_column); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - { - const Int64 length = orc_str_column->length[i]; - if (length < 0 || static_cast(length) > fixed_len) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "ORC string value at row {} has size {} that doesn't fit into FixedString({})", - i, length, fixed_len); + /// The null values are empty strings. + auto value = strings.getDataAt(i); + if (value.size() > fixed_len) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "ORC string value at row {} has size {} that doesn't fit into FixedString({})", + i, value.size(), fixed_len); - column_chars.insert_assume_reserved(orc_str_column->data[i], orc_str_column->data[i] + length); - /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. - if (static_cast(length) < fixed_len) - column_chars.resize_fill(column_chars.size() + (fixed_len - static_cast(length))); - } - else - column_chars.resize_fill(column_chars.size() + fixed_len); + column_chars.insert_assume_reserved(value.data(), value.data() + value.size()); + /// Zero-pad shorter values to the fixed width to keep the FixedString layout consistent. + if (value.size() < fixed_len) + column_chars.resize_fill(column_chars.size() + (fixed_len - value.size())); } return {std::move(internal_column), internal_type, column_name}; @@ -1560,10 +1887,10 @@ readColumnWithFixedStringData(const orc::ColumnVectorBatch * orc_column, const o template static ColumnWithTypeAndName readColumnWithDecimalDataCast( - const orc::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, DataTypePtr internal_type) { using NativeType = typename DecimalType::NativeType; - static_assert(std::is_same_v || std::is_same_v); + static_assert(std::is_same_v || std::is_same_v); auto internal_column = internal_type->createColumn(); auto & column_data = static_cast &>(*internal_column).getData(); @@ -1574,13 +1901,10 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( { if (!orc_decimal_column->hasNulls || orc_decimal_column->notNull[i]) { - DecimalType decimal_value; - if constexpr (std::is_same_v) + DecimalType decimal_value{}; + if constexpr (std::is_same_v) { - Int128 int128_value; - int128_value.items[0] = orc_decimal_column->values[i].getLowBits(); - int128_value.items[1] = orc_decimal_column->values[i].getHighBits(); - decimal_value.value = static_cast(int128_value); + decimal_value.value = static_cast(orc_decimal_column->values[i]); } else decimal_value.value = static_cast(orc_decimal_column->values[i]); @@ -1595,26 +1919,30 @@ static ColumnWithTypeAndName readColumnWithDecimalDataCast( } static ColumnWithTypeAndName -readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv6ColumnFromBinaryData(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { /// If at least one value size is not 16 bytes, fallback to reading String column and further cast to IPv6. - if ((!orc_str_column->hasNulls || orc_str_column->notNull[i]) && orc_str_column->length[i] != sizeof(IPv6)) - return readColumnWithStringData(orc_column, column_name); + if ((!orc_column->hasNulls || orc_column->notNull[i]) && strings.getDataAt(i).size() != sizeof(IPv6)) + return {holder, std::make_shared(), column_name}; } auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & ipv6_column = assert_cast(*internal_column); - ipv6_column.reserve(orc_str_column->numElements); + ipv6_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) - ipv6_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + if (!orc_column->hasNulls || orc_column->notNull[i]) + { + auto value = strings.getDataAt(i); + ipv6_column.insertData(value.data(), value.size()); + } else ipv6_column.insertDefault(); } @@ -1623,49 +1951,46 @@ readIPv6ColumnFromBinaryData(const orc::ColumnVectorBatch * orc_column, const St } static ColumnWithTypeAndName -readIPv4ColumnWithInt32Data(const orc::ColumnVectorBatch * orc_column, const String & column_name) +readIPv4ColumnWithInt32Data(const ORC::ColumnVectorBatch * orc_column, const String & column_name) { - const auto * orc_int_column = dynamic_cast(orc_column); + const auto & data = typeid_cast(*orc_column).getData(); auto internal_type = std::make_shared(); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); - column_data.reserve(orc_int_column->numElements); - - for (size_t i = 0; i < orc_int_column->numElements; ++i) - { - if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) - column_data.push_back(static_cast(orc_int_column->data[i])); - else - column_data.push_back(0); - } + column_data.resize(data.size()); + /// The null values are zeros. + for (size_t i = 0; i < data.size(); ++i) + column_data[i] = static_cast(data[i]); return {std::move(internal_column), internal_type, column_name}; } template static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) + const ORC::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & column_type) { - const auto * orc_str_column = dynamic_cast(orc_column); + ColumnPtr holder; + const auto & strings = getStringColumnFromBatch(orc_column, holder); auto internal_column = column_type->createColumn(); auto & integer_column = assert_cast(*internal_column); - integer_column.reserve(orc_str_column->numElements); + integer_column.reserve(orc_column->numElements); - for (size_t i = 0; i < orc_str_column->numElements; ++i) + for (size_t i = 0; i < orc_column->numElements; ++i) { - if (!orc_str_column->hasNulls || orc_str_column->notNull[i]) + if (!orc_column->hasNulls || orc_column->notNull[i]) { - if (sizeof(typename ColumnType::ValueType) != orc_str_column->length[i]) + auto value = strings.getDataAt(i); + if (sizeof(typename ColumnType::ValueType) != value.size()) throw Exception( ErrorCodes::INCORRECT_DATA, "ValueType size {} of column {} is not equal to size of binary data {}", sizeof(typename ColumnType::ValueType), integer_column.getName(), - orc_str_column->length[i]); + value.size()); - integer_column.insertData(orc_str_column->data[i], orc_str_column->length[i]); + integer_column.insertData(value.data(), value.size()); } else { @@ -1676,11 +2001,21 @@ static ColumnWithTypeAndName readColumnWithBigNumberFromBinaryData( } static ColumnWithTypeAndName readColumnWithDateData( - const orc::ColumnVectorBatch * orc_column, const String & column_name, const DataTypePtr & type_hint) + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & raw_type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { + /// The hint is the raw header type: `readColumnFromORCColumn` strips an outer Nullable but not + /// LowCardinality, so e.g. a LowCardinality(DateTime('UTC')) target would fall through to the + /// raw Int32 branch below and the later context-less cast would read the day count as unix + /// seconds. Strip the wrappers so such targets take the same branches as the plain types. + const DataTypePtr type_hint = raw_type_hint ? removeNullable(recursiveRemoveLowCardinality(raw_type_hint)) : nullptr; + DataTypePtr internal_type; bool check_date32_range = false; bool check_date_range = false; + bool check_datetime_range = false; /// Make result type Date32 when requested type is actually Date32 or when we use schema inference if (!type_hint || isDate32(*type_hint)) @@ -1696,12 +2031,23 @@ static ColumnWithTypeAndName readColumnWithDateData( internal_type = std::make_shared(); check_date_range = true; } + else if (isDateTime(*type_hint)) + { + /// Keep the intermediate as Date32, so the later cast converts the day count to midnight + /// of that day instead of reading it as unix seconds. The cast is context-less, so + /// `date_time_overflow_behavior` does not reach it and a day number whose midnight does + /// not fit into DateTime would wrap to an unrelated timestamp. Validate the range here + /// against the same [0, MAX_DATETIME_DAY_NUM] window that `ToDateTimeImpl` uses. + internal_type = std::make_shared(); + check_datetime_range = true; + } else { internal_type = std::make_shared(); } - const auto * orc_int_column = dynamic_cast(orc_column); + const auto * orc_int_column = dynamic_cast(orc_column); + const auto & orc_int_data = orc_int_column->getData(); auto internal_column = internal_type->createColumn(); PaddedPODArray & column_data = assert_cast &>(*internal_column).getData(); column_data.reserve(orc_int_column->numElements); @@ -1710,25 +2056,50 @@ static ColumnWithTypeAndName readColumnWithDateData( { if (!orc_int_column->hasNulls || orc_int_column->notNull[i]) { - Int32 days_num = static_cast(orc_int_column->data[i]); - if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < -DAYNUM_OFFSET_EPOCH)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", - days_num, - column_name, - -DAYNUM_OFFSET_EPOCH, - DATE_LUT_MAX_EXTEND_DAY_NUM); + /// Range-check the original Int64 day count before narrowing to Int32, + /// otherwise a malformed value could wrap into an apparently valid date. + Int64 days_num = orc_int_data[i]; + if (check_date32_range && (days_num > DATE_LUT_MAX_EXTEND_DAY_NUM || days_num < (-DAYNUM_OFFSET_EPOCH))) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < (-DAYNUM_OFFSET_EPOCH)) ? (-DAYNUM_OFFSET_EPOCH) : DATE_LUT_MAX_EXTEND_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date32, which is [{}, {}]", + days_num, + column_name, + (-DAYNUM_OFFSET_EPOCH), + DATE_LUT_MAX_EXTEND_DAY_NUM); + } if (check_date_range && (days_num > DATE_LUT_MAX_DAY_NUM || days_num < 0)) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", - days_num, - column_name, - DATE_LUT_MAX_DAY_NUM); + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : DATE_LUT_MAX_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the range of type Date, which is [0, {}]", + days_num, + column_name, + DATE_LUT_MAX_DAY_NUM); + } + + if (check_datetime_range && (days_num > MAX_DATETIME_DAY_NUM || days_num < 0)) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + days_num = (days_num < 0) ? 0 : MAX_DATETIME_DAY_NUM; + else + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Input value {} of a column \"{}\" exceeds the day range of type DateTime, which is [0, {}]", + days_num, + column_name, + MAX_DATETIME_DAY_NUM); + } - column_data.push_back(days_num); + column_data.push_back(static_cast(days_num)); } else { @@ -1739,40 +2110,65 @@ static ColumnWithTypeAndName readColumnWithDateData( return {std::move(internal_column), internal_type, column_name}; } -static ColumnWithTypeAndName -readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const String & column_name) +static ColumnWithTypeAndName readColumnWithTimestampData( + const ORC::ColumnVectorBatch * orc_column, + const String & column_name, + const DataTypePtr & type_hint, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior) { - const auto * orc_ts_column = dynamic_cast(orc_column); + const auto * orc_ts_column = dynamic_cast(orc_column); + + /// ORC stores timestamps as (seconds, nanoseconds). ClickHouse used to convert them through a fixed + /// DateTime64(9) intermediate (seconds * 1e9 + nanoseconds), which overflows Int64 for timestamps beyond + /// ~year 2262 even when the requested DateTime64 scale can represent the value (e.g. Iceberg's DateTime64(6)). + /// Read directly at the requested scale so such values round-trip like Parquet, and only handle overflow when + /// even the target scale does not fit Int64. + UInt32 scale = 9; + if (type_hint) + { + const auto * dt64_hint = typeid_cast(removeNullable(recursiveRemoveLowCardinality(type_hint)).get()); + if (dt64_hint) + scale = dt64_hint->getScale(); + } - auto internal_type = std::make_shared(9); + auto internal_type = std::make_shared(scale); auto internal_column = internal_type->createColumn(); auto & column_data = assert_cast(*internal_column).getData(); column_data.reserve(orc_ts_column->numElements); - constexpr Int64 multiplier = 1e9L; + /// Factor to go from nanoseconds down to the target scale (scale is in [0, 9]). + const Int128 divisor = DecimalUtils::scaleMultiplier(9 - scale); + const Int128 int64_min = std::numeric_limits::min(); + const Int128 int64_max = std::numeric_limits::max(); + for (size_t i = 0; i < orc_ts_column->numElements; ++i) { if (!orc_ts_column->hasNulls || orc_ts_column->notNull[i]) { - Int64 timestamp_value; - Int64 seconds = orc_ts_column->data[i]; - Int64 nanoseconds = orc_ts_column->nanoseconds[i]; + const Int64 seconds = orc_ts_column->data[i]; + const Int64 nanoseconds = orc_ts_column->nanoseconds[i]; - /// Check for overflow when converting timestamp to DateTime64(9) - bool overflow = common::mulOverflow(seconds, multiplier, timestamp_value); - overflow |= common::addOverflow(timestamp_value, nanoseconds, timestamp_value); + /// seconds * 1e9 + nanoseconds cannot overflow Int128 (|seconds| < 2^63, product < ~9.2e27 << Int128 max). + const Int128 nanos_total = static_cast(seconds) * 1'000'000'000 + nanoseconds; + /// Integer division truncates toward zero, matching the DateTime64(9) -> DateTime64(scale) cast that ran afterwards. + Int128 value = nanos_total / divisor; - if (overflow) - throw Exception( - ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, - "Timestamp value in column \"{}\" is out of range for DateTime64: seconds={}, nanoseconds={}", - column_name, - seconds, - nanoseconds); + if (value < int64_min || value > int64_max) + { + if (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate) + value = value < int64_min ? int64_min : int64_max; + else + /// Throw for both `throw` and `ignore` (the default): keep the historical behavior and never silently corrupt data. + throw Exception( + ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp value in column \"{}\" is out of range for DateTime64({}): seconds={}, nanoseconds={}", + column_name, + scale, + seconds, + nanoseconds); + } - Decimal64 decimal64; - decimal64.value = timestamp_value; - column_data.emplace_back(std::move(decimal64)); + column_data.push_back(DateTime64(static_cast(value))); } else column_data.push_back(0); @@ -1780,9 +2176,504 @@ readColumnWithTimestampData(const orc::ColumnVectorBatch * orc_column, const Str return {std::move(internal_column), internal_type, column_name}; } +/// Whether a DateTime/DateTime64 target carries an explicit timezone - schema inference produces one +/// (UTC) for the ORC `TIMESTAMP_INSTANT` ("timestamp with local timezone") kind, but an explicit +/// schema may name any timezone. Used to tell the two ORC timestamp kinds apart when matching union +/// branches (see `orcUnionBranchMatchesType`). +static bool orcTimestampTargetHasExplicitTimeZone(const DataTypePtr & type) +{ + const auto * timezone = dynamic_cast(type.get()); + return timezone && timezone->hasExplicitTimeZone(); +} + +/// Whether a ClickHouse numeric type is a widening of an ORC integer branch whose values occupy +/// `orc_size` bytes: a strictly wider integer, or a float that represents every value of that width +/// exactly. The ordinary (non-union) ORC column path gets these conversions for free from the final +/// cast in `orcColumnsToCHChunk`; a union branch has to request them as a per-branch hint, because +/// the final cast of a union column is a `Variant` -> `Variant` cast, which only extends the set of +/// alternatives by exact type name and cannot widen an alternative. Equal-width targets are listed +/// explicitly by the caller (they include the writer's own mappings, such as the unsigned and `Enum` +/// types), so only strictly wider integers are accepted here. +static bool orcIntegerBranchWidensTo(const DataTypePtr & type, size_t orc_size) +{ + const WhichDataType which(type); + if (which.isFloat32()) + return orc_size <= 2; + if (which.isFloat64()) + return orc_size <= 4; + return which.isInteger() && type->getSizeOfValueInMemory() > orc_size; +} + +/// Whether a ClickHouse type can serve as the per-branch type hint for an ORC union branch of the +/// given ORC type. The correspondence is structural (up to Nullable and LowCardinality wrappers), +/// extended with the explicit-schema conversions the reader supports: the integer targets the +/// ordinary column path accepts through the final cast (the unsigned and Enum types of the +/// matching width - they are what the ORC writer maps to these ORC types - int -> IPv4, and the +/// widenings of `orcIntegerBranchWidensTo`, e.g. `Variant(Int64, String)` over +/// `uniontype`) and +/// the special binary readers (binary -> IPv6/Int128/UInt128/Int256/UInt256/Decimal256, +/// char -> big integers and Decimal256). Custom type names matter here: `Bool` is a custom-named +/// `UInt8`, but the writer maps it to BOOLEAN while a plain `UInt8` goes to BYTE, so only BOOLEAN +/// accepts `Bool` - otherwise `Variant(Bool, UInt8)` over `uniontype` would leave +/// both branches ambiguous. The two ORC timestamp kinds need the same care: both read back as plain +/// `DateTime64(9)`, but `TIMESTAMP` is inferred as `DateTime64(9)` and `TIMESTAMP_INSTANT` as +/// `DateTime64(9, 'UTC')`, so `TIMESTAMP_INSTANT` matches only an explicitly time-zoned target while +/// `TIMESTAMP` stays permissive - otherwise `uniontype`, +/// inferred as `Variant(DateTime64(9), DateTime64(9, 'UTC'))`, would leave both branches ambiguous, +/// collapse them to identical `DateTime64(9)`, and be rejected by the duplicate-branch check. Any +/// explicit timezone is accepted (not only `UTC`) so that an explicit schema like +/// `Variant(DateTime64(9), DateTime64(9, 'Europe/Berlin'))` is not rejected; the singles-elimination +/// step decides whether the assignment is forced, and the repair cast relabels the branch to the +/// target timezone (value-preserving for `DateTime64`). Variant sorts its nested types, so the +/// positional correspondence between ORC union branches and Variant alternatives is lost; this +/// predicate is used to reconstruct it. +/// +/// STRUCT branches follow the same named-tuple rules as the non-union ORC struct path: a target +/// tuple with explicit names matches by field name and may project and reorder the ORC struct's +/// fields (the per-branch repair cast then projects/reorders the read tuple to exactly the target), +/// while an unnamed target tuple is matched positionally with the same arity. `case_insensitive` +/// mirrors `input_format_orc_case_insensitive_column_matching` for that name-based matching. +static bool orcUnionBranchMatchesType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type, bool case_insensitive) +{ + checkStackSize(); + + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + /// A boolean holds only 0 and 1, so every integer type is a widening of it. + return which.isUInt8() || which.isEnum8() || orcIntegerBranchWidensTo(type, 0); + case ORC::TypeKind::BYTE: + return which.isInt8() || (which.isUInt8() && !isBool(type)) || which.isEnum8() || orcIntegerBranchWidensTo(type, 1); + case ORC::TypeKind::SHORT: + return which.isInt16() || which.isUInt16() || which.isEnum16() || orcIntegerBranchWidensTo(type, 2); + case ORC::TypeKind::INT: + return which.isInt32() || which.isUInt32() || which.isIPv4() || orcIntegerBranchWidensTo(type, 4); + case ORC::TypeKind::LONG: + return which.isInt64() || which.isUInt64() || orcIntegerBranchWidensTo(type, 8); + case ORC::TypeKind::FLOAT: + return which.isFloat32() || which.isFloat64(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::DATE: + return which.isDate32() || which.isDate(); + case ORC::TypeKind::TIMESTAMP: + /// Permissive: matches any DateTime/DateTime64 alternative. The repair cast relabels the + /// branch to the alternative's timezone, which is value-preserving for DateTime64. + return which.isDateTime64() || which.isDateTime(); + case ORC::TypeKind::TIMESTAMP_INSTANT: + /// Matches only an explicitly time-zoned target so it stays distinct from a TIMESTAMP + /// branch in the same union (both read back as DateTime64(9)); see the comment above the + /// function. + return (which.isDateTime64() || which.isDateTime()) && orcTimestampTargetHasExplicitTimeZone(type); + case ORC::TypeKind::DECIMAL: + return which.isDecimal(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isStringOrFixedString(); + case ORC::TypeKind::BINARY: + return which.isStringOrFixedString() || which.isIPv6() || which.isInt128() || which.isUInt128() || which.isInt256() + || which.isUInt256() || which.isDecimal256(); + case ORC::TypeKind::CHAR: + return which.isStringOrFixedString() || which.isInt128() || which.isUInt128() || which.isInt256() || which.isUInt256() + || which.isDecimal256(); + case ORC::TypeKind::LIST: + return which.isArray() && orc_branch_type->getSubtypeCount() == 1 + && orcUnionBranchMatchesType( + orc_branch_type->getSubtype(0), assert_cast(*type).getNestedType(), case_insensitive); + case ORC::TypeKind::MAP: + { + if (!which.isMap() || orc_branch_type->getSubtypeCount() != 2) + return false; + const auto & map_type = assert_cast(*type); + return orcUnionBranchMatchesType(orc_branch_type->getSubtype(0), map_type.getKeyType(), case_insensitive) + && orcUnionBranchMatchesType(orc_branch_type->getSubtype(1), map_type.getValueType(), case_insensitive); + } + case ORC::TypeKind::STRUCT: + { + if (!which.isTuple()) + return false; + const auto & tuple_type = assert_cast(*type); + const auto & elements = tuple_type.getElements(); + if (tuple_type.hasExplicitNames()) + { + /// Match by field name, like the non-union ORC struct path: the target tuple may be + /// a subset of the ORC struct's fields, in any order. Each target field must map to + /// an ORC field with a recursively matching type; extra ORC fields are projected out + /// by the repair cast. Build a name -> ORC subtype map for the lookup. + std::unordered_map orc_field_by_name; + orc_field_by_name.reserve(orc_branch_type->getSubtypeCount()); + for (size_t i = 0; i < orc_branch_type->getSubtypeCount(); ++i) + { + String field_name = orc_branch_type->getFieldName(i); + if (case_insensitive) + boost::to_lower(field_name); + orc_field_by_name.emplace(std::move(field_name), orc_branch_type->getSubtype(i)); + } + + const auto & element_names = tuple_type.getElementNames(); + for (size_t i = 0; i < elements.size(); ++i) + { + String element_name = element_names[i]; + if (case_insensitive) + boost::to_lower(element_name); + auto it = orc_field_by_name.find(element_name); + if (it == orc_field_by_name.end() || !orcUnionBranchMatchesType(it->second, elements[i], case_insensitive)) + return false; + } + return true; + } + + /// Unnamed tuple: positional, same arity (no ORC field is silently dropped). + if (elements.size() != orc_branch_type->getSubtypeCount()) + return false; + for (size_t i = 0; i < elements.size(); ++i) + if (!orcUnionBranchMatchesType(orc_branch_type->getSubtype(i), elements[i], case_insensitive)) + return false; + return true; + } + case ORC::TypeKind::UNION: + return which.isVariant(); + case ORC::TypeKind::GEOMETRY: + case ORC::TypeKind::GEOGRAPHY: + /// Added in ORC 2.3. We do not read these, so no target type can match such a branch. + return false; + } + + return false; +} + +/// The natural inference pairing of the string-like ORC kinds, used to tie-break their union-branch +/// matching: CHAR is inferred as FixedString of the same length and STRING/VARCHAR as String, but +/// all of them can be *read* as either (see orcUnionBranchMatchesType), so e.g. +/// uniontype with the inferred Variant(FixedString(1), String) leaves both branches +/// with two candidates. Without a hint each branch would materialize per the current stripe's +/// physical encoding (a dictionary-encoded stripe comes back as LowCardinality), making a supported +/// schema fail depending on per-stripe encoding choices; preferring the natural pairing keeps the +/// assignment stable. The target is inspected with the LowCardinality/Nullable wrappers stripped, +/// so a LowCardinality-wrapped alternative (inferred from a dictionary-encoded stripe) pairs the +/// same way. BINARY deliberately has no preference: it is the conversion-rich kind (IPv6, big +/// integers, Decimal256), so a preference could steal a String alternative from a STRING branch. +/// +/// The numeric kinds are tie-broken the same way, for the same reason: they match their widenings +/// too (see `orcIntegerBranchWidensTo`), so e.g. `uniontype` with the explicit +/// schema `Variant(Int8, Int64)` leaves the `BYTE` branch with two candidates. Preferring the +/// natural pairing keeps the exact-width alternative with its own branch and lets the wider +/// alternative go to the branch that needs it. +static bool orcUnionBranchPrefersType(const ORC::Type * orc_branch_type, const DataTypePtr & target_type) +{ + const DataTypePtr type = removeLowCardinality(removeNullableOrLowCardinalityNullable(target_type)); + const WhichDataType which(type); + + switch (orc_branch_type->getKind()) + { + case ORC::TypeKind::BOOLEAN: + return isBool(type); + case ORC::TypeKind::BYTE: + return which.isInt8(); + case ORC::TypeKind::SHORT: + return which.isInt16(); + case ORC::TypeKind::INT: + return which.isInt32(); + case ORC::TypeKind::LONG: + return which.isInt64(); + case ORC::TypeKind::FLOAT: + return which.isFloat32(); + case ORC::TypeKind::DOUBLE: + return which.isFloat64(); + case ORC::TypeKind::CHAR: + return which.isFixedString() + && assert_cast(*type).getN() == orc_branch_type->getMaximumLength(); + case ORC::TypeKind::STRING: + case ORC::TypeKind::VARCHAR: + return which.isString(); + default: + return false; + } +} + +/// Variant sorts its nested types, so the positional correspondence between ORC union branches +/// and the alternatives of an explicit (or inferred) Variant type hint is lost. Reconstruct it +/// structurally: collect the alternatives each branch can be read as (orcUnionBranchMatchesType), +/// then keep only the forced assignments (a branch takes an alternative when it is its only +/// remaining candidate), tie-breaking the string-like branches by their natural inference pairing +/// (orcUnionBranchPrefersType). A branch whose correspondence stays ambiguous is left without a +/// hint (nullptr in the result), so no guess is ever made. Shared between +/// readColumnFromORCColumn (drives the branch conversions) and updateIncludeTypeIds (prunes a +/// hinted STRUCT branch's fields the same way the read path does), so the two stay in sync. +static DataTypes computeOrcUnionBranchHints(const ORC::Type * orc_type, const DataTypePtr & type_hint, bool case_insensitive_matching) +{ + const size_t num_children = orc_type->getSubtypeCount(); + DataTypes branch_hints(num_children); + const auto * variant_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; + if (!variant_hint) + return branch_hints; + + const auto & alternatives = variant_hint->getVariants(); + std::vector> candidates(num_children); + for (size_t i = 0; i < num_children; ++i) + for (size_t a = 0; a < alternatives.size(); ++a) + if (orcUnionBranchMatchesType(orc_type->getSubtype(i), alternatives[a], case_insensitive_matching)) + candidates[i].push_back(a); + + std::vector alternative_taken(alternatives.size(), false); + const auto preferred_candidates = [&](size_t i) + { + std::vector preferred; + for (const size_t a : candidates[i]) + if (orcUnionBranchPrefersType(orc_type->getSubtype(i), alternatives[a])) + preferred.push_back(a); + return preferred; + }; + bool changed = true; + while (changed) + { + changed = false; + for (size_t i = 0; i < num_children; ++i) + { + if (branch_hints[i] || candidates[i].size() != 1) + continue; + const size_t a = candidates[i].front(); + if (alternative_taken[a]) + { + /// Another branch already took this alternative; leave this branch without a hint. + candidates[i].clear(); + continue; + } + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + + if (changed) + continue; + + /// The forced assignments are exhausted. Tie-break the string-like branches by their + /// natural inference pairing (see orcUnionBranchPrefersType): a branch takes the single + /// alternative it prefers among its remaining candidates, unless another unassigned + /// branch uniquely prefers the same one - a contested preference is still ambiguous and no + /// guess is ever made. One assignment at a time, then back to the forced-assignment loop + /// to propagate it. + for (size_t i = 0; i < num_children && !changed; ++i) + { + if (branch_hints[i] || candidates[i].size() < 2) + continue; + const auto preferred = preferred_candidates(i); + if (preferred.size() != 1) + continue; + const size_t a = preferred.front(); + bool contested = false; + for (size_t j = 0; j < num_children && !contested; ++j) + { + if (j == i || branch_hints[j]) + continue; + const auto preferred_j = preferred_candidates(j); + contested = preferred_j.size() == 1 && preferred_j.front() == a; + } + if (contested) + continue; + alternative_taken[a] = true; + branch_hints[i] = alternatives[a]; + changed = true; + for (size_t j = 0; j < num_children; ++j) + if (j != i) + std::erase(candidates[j], a); + } + } + + return branch_hints; +} + +/// Strips Nullable from a Nullable(Tuple) and propagates the struct null map into its elements. +static ColumnWithTypeAndName unwrapORCNullableTuple(const ColumnWithTypeAndName & column) +{ + const auto * type_nullable = typeid_cast(column.type.get()); + if (!type_nullable) + return column; + + const auto * tuple_type = typeid_cast(type_nullable->getNestedType().get()); + if (!tuple_type) + return column; + + const auto & col_nullable = assert_cast(*column.column); + + const auto & null_map_data = col_nullable.getNullMapData(); + bool has_nulls = !memoryIsZero(null_map_data.data(), 0, null_map_data.size()); + + if (!has_nulls) + { + /// No actual nulls — just strip the Nullable wrapper. + return {col_nullable.getNestedColumnPtr(), type_nullable->getNestedType(), column.name}; + } + + /// Propagate the struct null map to each Tuple element. + const auto & inner_tuple = assert_cast(col_nullable.getNestedColumn()); + const auto & null_map_ptr = col_nullable.getNullMapColumnPtr(); + Columns new_elements; + DataTypes new_types; + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + auto elem_col = inner_tuple.getColumnPtr(i); + auto elem_type = tuple_type->getElement(i); + if (elem_type->isNullable()) + { + /// Element already Nullable — merge null maps (struct null OR element null). + const auto & existing = assert_cast(*elem_col); + auto merged = ColumnUInt8::create(null_map_ptr->size()); + const auto & s = assert_cast(*null_map_ptr).getData(); + const auto & e = existing.getNullMapData(); + auto & m = merged->getData(); + for (size_t j = 0; j < s.size(); ++j) + m[j] = s[j] | e[j]; + new_elements.push_back(ColumnNullable::create(existing.getNestedColumnPtr(), std::move(merged))); + new_types.push_back(elem_type); + } + else if (elem_type->canBeInsideNullable()) + { + new_elements.push_back(ColumnNullable::create(elem_col, null_map_ptr)); + new_types.push_back(std::make_shared(elem_type)); + } + else + { + /// Array, Map, etc. — replace values at null positions with type defaults. + const auto & nm = col_nullable.getNullMapData(); + auto mutable_col = elem_col->cloneEmpty(); + for (size_t j = 0; j < elem_col->size(); ++j) + { + if (nm[j]) + mutable_col->insertDefault(); + else + mutable_col->insertFrom(*elem_col, j); + } + new_elements.push_back(std::move(mutable_col)); + new_types.push_back(elem_type); + } + } + + auto result_type = tuple_type->hasExplicitNames() ? std::make_shared(std::move(new_types), tuple_type->getElementNames()) + : std::make_shared(std::move(new_types)); + return {ColumnTuple::create(std::move(new_elements)), result_type, column.name}; +} + +/// Matches the elements of the tuples in `column` to those of the named tuples in `requested_type` by name, through +/// Nullable, Array and Map: a requested element that was not read is filled with defaults, and an element that is +/// not requested is dropped. A CAST would match tuples with no common element names by position instead. +static ColumnWithTypeAndName +matchORCTupleElementsByName(const ColumnWithTypeAndName & column, const DataTypePtr & requested_type, bool case_insensitive) +{ + if (column.type->equals(*requested_type)) + return column; + + if (const auto * nullable_type = typeid_cast(column.type.get())) + { + const auto & nullable_column = assert_cast(*column.column); + auto nested = matchORCTupleElementsByName( + {nullable_column.getNestedColumnPtr(), nullable_type->getNestedType(), column.name}, + removeNullable(requested_type), + case_insensitive); + return { + ColumnNullable::create(nested.column, nullable_column.getNullMapColumnPtr()), + std::make_shared(nested.type), + column.name}; + } + + const auto requested_non_nullable_type = removeNullable(requested_type); + + if (const auto * array_type = typeid_cast(column.type.get())) + { + const auto * requested_array_type = typeid_cast(requested_non_nullable_type.get()); + if (!requested_array_type) + return column; + const auto & array_column = assert_cast(*column.column); + auto nested = matchORCTupleElementsByName( + {array_column.getDataPtr(), array_type->getNestedType(), column.name}, requested_array_type->getNestedType(), case_insensitive); + return { + ColumnArray::create(nested.column, array_column.getOffsetsPtr()), std::make_shared(nested.type), column.name}; + } + + if (const auto * map_type = typeid_cast(column.type.get())) + { + const auto * requested_map_type = typeid_cast(requested_non_nullable_type.get()); + if (!requested_map_type) + return column; + const auto & map_column = assert_cast(*column.column); + auto keys = matchORCTupleElementsByName( + {map_column.getNestedData().getColumnPtr(0), map_type->getKeyType(), "key"}, requested_map_type->getKeyType(), case_insensitive); + auto values = matchORCTupleElementsByName( + {map_column.getNestedData().getColumnPtr(1), map_type->getValueType(), "value"}, + requested_map_type->getValueType(), + case_insensitive); + return { + ColumnMap::create(keys.column, values.column, map_column.getNestedColumn().getOffsetsPtr()), + std::make_shared(keys.type, values.type), + column.name}; + } + + const auto * tuple_type = typeid_cast(column.type.get()); + const auto * requested_tuple_type = typeid_cast(requested_non_nullable_type.get()); + if (!tuple_type || !requested_tuple_type) + return column; + + const auto & tuple_column = assert_cast(*column.column); + const size_t num_rows = tuple_column.size(); + Columns elements; + DataTypes types; + Strings names; + + /// An unnamed tuple is matched by position and keeps its elements, so the CAST rejects a different number of them. + if (!requested_tuple_type->hasExplicitNames()) + { + for (size_t i = 0; i < tuple_type->getElements().size(); ++i) + { + ColumnWithTypeAndName element{tuple_column.getColumnPtr(i), tuple_type->getElement(i), tuple_type->getNameByPosition(i + 1)}; + if (i < requested_tuple_type->getElements().size()) + element = matchORCTupleElementsByName(element, requested_tuple_type->getElement(i), case_insensitive); + elements.push_back(std::move(element.column)); + types.push_back(std::move(element.type)); + } + auto result_column = elements.empty() ? ColumnTuple::create(num_rows) : ColumnTuple::create(std::move(elements)); + return {std::move(result_column), std::make_shared(std::move(types)), column.name}; + } + + for (size_t i = 0; i < requested_tuple_type->getElements().size(); ++i) + { + const auto & requested_element_type = requested_tuple_type->getElement(i); + const auto & name = requested_tuple_type->getNameByPosition(i + 1); + + auto pos = tuple_type->tryGetPositionByName(name, /*case_insensitive=*/false); + if (!pos && case_insensitive) + pos = tuple_type->tryGetPositionByName(name, /*case_insensitive=*/true); + + if (pos) + { + auto element = matchORCTupleElementsByName( + {tuple_column.getColumnPtr(*pos), tuple_type->getElement(*pos), name}, requested_element_type, case_insensitive); + elements.push_back(std::move(element.column)); + types.push_back(std::move(element.type)); + } + else + { + auto element = requested_element_type->createColumn(); + requested_element_type->insertManyDefaultsInto(*element, num_rows); + elements.push_back(std::move(element)); + types.push_back(requested_element_type); + } + names.push_back(name); + } + + auto result_type = std::make_shared(std::move(types), std::move(names)); + auto result_column = elements.empty() ? ColumnTuple::create(num_rows) : ColumnTuple::create(std::move(elements)); + return {std::move(result_column), std::move(result_type), column.name}; +} + ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint) const @@ -1793,8 +2684,8 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( bool skipped = false; - if (!inside_nullable && (orc_column->hasNulls || (type_hint && type_hint->isNullable())) && !orc_column->isEncoded - && (orc_type->getKind() != orc::LIST && orc_type->getKind() != orc::MAP && orc_type->getKind() != orc::STRUCT)) + if (!inside_nullable && (orc_column->hasNulls || (type_hint && isNullableOrLowCardinalityNullable(type_hint))) && !orc_column->isEncoded + && (orc_type->getKind() != ORC::LIST && orc_type->getKind() != ORC::MAP && orc_type->getKind() != ORC::UNION)) { DataTypePtr nested_type_hint; if (type_hint) @@ -1808,11 +2699,209 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( return {nullable_column, nullable_type, column_name}; } + /// ORC union maps to the ClickHouse Variant type. Handled before the switch below so the switch + /// stays non-exhaustive (its default handles unsupported types). + if (orc_type->getKind() == ORC::UNION) + { + const auto * orc_union_column = dynamic_cast(orc_column); + if (!orc_union_column) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC column for union type must be a UnionVectorBatch"); + + const size_t num_children = orc_type->getSubtypeCount(); + const size_t num_rows = orc_union_column->numElements; + + /// Mirror of the schema-inference guard: a union with more branches than Variant can hold + /// (ColumnVariant::MAX_NESTED_COLUMNS) is rejected explicitly instead of letting the + /// DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an explicit + /// structure, since schema inference already rejects oversized unions. + if (num_children > ColumnVariant::MAX_NESTED_COLUMNS) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type with {} branches is not supported (Variant supports at most {} nested types), while reading column {}", + num_children, ColumnVariant::MAX_NESTED_COLUMNS, column_name); + + /// The hints enable the explicit-schema conversions the scalar readers support (e.g. + /// binary -> IPv6) and keep the branch types aligned with the hinted Variant (e.g. + /// Array(Nullable(...)) produced by schema inference). See computeOrcUnionBranchHints for + /// how a branch's forced alternative is reconstructed; updateIncludeTypeIds calls the same + /// function so a hinted STRUCT branch's field pruning matches what is actually read here. + const DataTypes branch_hints = computeOrcUnionBranchHints(orc_type, type_hint, case_insensitive_matching); + + /// Read each ORC union branch into its own column. ORC keeps a separate physical batch per + /// branch. Variant branches are non-nullable, and an ORC union row can be non-null yet + /// select a branch whose payload is null - such a row is represented by the Variant NULL + /// discriminator (see the row loop below). The branch null map is taken directly from the + /// ORC batch rather than from a Nullable result column: complex (LIST/MAP) and + /// dictionary-encoded branches never come back as ColumnNullable, yet their payload can + /// still be null. inside_nullable is set because nulls are handled here rather than by + /// wrapping the branch value in Nullable. + DataTypes branch_types; + Columns branch_columns; + std::vector branch_null_map_columns(num_children); /// keeps the null maps alive + std::vector branch_null_maps(num_children, nullptr); + branch_types.reserve(num_children); + branch_columns.reserve(num_children); + for (size_t i = 0; i < num_children; ++i) + { + /// A union branch that is itself a union would map to a nested Variant, which Variant + /// forbids; reject it explicitly (matching the schema-inference path) instead of letting + /// the DataTypeVariant below throw a confusing BAD_ARGUMENTS. Only reachable with an + /// explicit structure, since schema inference already rejects nested unions. + if (orc_type->getSubtype(i)->getKind() == ORC::UNION) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has a nested union branch, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto branch = readColumnFromORCColumn( + orc_union_column->children[i], orc_type->getSubtype(i), column_name, /*inside_nullable=*/true, branch_hints[i]); + + if (orc_union_column->children[i]->hasNulls) + { + branch_null_map_columns[i] = readByteMapFromORCColumn(orc_union_column->children[i]); + branch_null_maps[i] = &assert_cast(*branch_null_map_columns[i]).getData(); + } + + /// A dictionary-encoded branch read without a hint comes back as + /// LowCardinality(Nullable(...)); Variant alternatives cannot be nullable, so strip the + /// inner Nullable (the nulls are tracked by the branch null map above). + ColumnWithTypeAndName branch_non_nullable{ + removeNullableOrLowCardinalityNullable(branch.column), + removeNullableOrLowCardinalityNullable(branch.type), + branch.name}; + + /// With a per-branch hint the branch must end up as exactly that alternative, so that + /// the resulting Variant type equals the hinted one (e.g. a branch of a + /// non-dictionary-encoded file read for a LowCardinality(String) alternative comes + /// back as plain String). Compared by name, not equals: Variant identity is name-based + /// and e.g. equals cannot tell the custom-named Bool from a plain UInt8, which would + /// skip the Bool -> UInt8 repair cast for a boolean branch hinted as UInt8. + if (branch_hints[i] && branch_hints[i]->getName() != branch_non_nullable.type->getName()) + { + if (branch_null_map_columns[i]) + { + /// A value-checking cast (e.g. Int8 -> Enum8, or the same on a nested Tuple + /// field) must not inspect the placeholder values ORC leaves at null-payload + /// positions - those rows become the Variant NULL discriminator below and are + /// never read. Replace them with a valid, castable row before casting. + /// Wrapping the branch in Nullable is not enough: a Nullable(Tuple) cast would + /// still descend into and reject a null nested field. + if (auto safe = replaceNullPayloadRowsWithValidRow(branch_non_nullable.column, *branch_null_maps[i])) + branch_non_nullable.column + = castColumn({safe, branch_non_nullable.type, branch_non_nullable.name}, branch_hints[i]); + else + /// Every row is a null payload and none is read, so a default-valued column + /// of the target type with the same number of rows is enough. + branch_non_nullable.column + = branch_hints[i]->createColumn()->cloneResized(branch_non_nullable.column->size()); + } + else + { + branch_non_nullable.column = castColumn(branch_non_nullable, branch_hints[i]); + } + branch_non_nullable.type = branch_hints[i]; + } + + branch_types.push_back(branch_non_nullable.type); + branch_columns.push_back(std::move(branch_non_nullable.column)); + } + + /// ORC keeps one physical stream per branch, so branches with identical types cannot be + /// represented as a Variant (which de-duplicates types); reject them explicitly. The + /// identity is compared with LowCardinality stripped, so it does not depend on the current + /// stripe's physical encoding (a dictionary-encoded branch materializes as LowCardinality), + /// mirroring the schema-inference check in parseORCType. + std::unordered_set seen_type_names; + for (const auto & branch_type : branch_types) + if (!seen_type_names.insert(recursiveRemoveLowCardinality(branch_type)->getName()).second) + throw Exception( + ErrorCodes::UNKNOWN_TYPE, + "ORC union type '{}' has branches with identical types, which is not supported, while reading column {}", + orc_type->toString(), column_name); + + auto variant_type = std::make_shared(branch_types); + const auto & global_variants = assert_cast(*variant_type).getVariants(); + + /// Variant stores its branches sorted by type name, so remap ORC tags to global (sorted) + /// discriminators. The Variant sub-columns are built compactly (each must contain exactly + /// the values referenced by its discriminator, in appended order), so they are cloned empty + /// from the ORC branch columns and filled row by row below rather than placed wholesale. + std::unordered_map type_name_to_global; + for (size_t g = 0; g < global_variants.size(); ++g) + type_name_to_global[global_variants[g]->getName()] = static_cast(g); + + MutableColumns variant_columns(global_variants.size()); + std::vector tag_to_global(num_children); + for (size_t i = 0; i < num_children; ++i) + { + auto global = type_name_to_global.at(branch_types[i]->getName()); + tag_to_global[i] = global; + variant_columns[global] = branch_columns[i]->cloneEmpty(); + } + + auto local_discriminators = ColumnVariant::ColumnDiscriminators::create(); + auto & discriminators_data = local_discriminators->getData(); + discriminators_data.resize_exact(num_rows); + + auto offsets = ColumnVariant::ColumnOffsets::create(); + auto & offsets_data = offsets->getData(); + offsets_data.resize_exact(num_rows); + + const UInt8 * tags = orc_union_column->tags.data(); + const uint64_t * orc_offsets = orc_union_column->offsets.data(); + const char * not_null = orc_union_column->hasNulls ? orc_union_column->notNull.data() : nullptr; + + for (size_t row = 0; row < num_rows; ++row) + { + if (not_null && !not_null[row]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const size_t tag = tags[row]; + if (tag >= num_children) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union tag {} for union with {} branches while reading column {}", + tag, num_children, column_name); + + const size_t offset = orc_offsets[row]; + /// A malformed file can point past the selected branch's values; reject it rather than + /// reading out of bounds (the branch column and its null map share this size). + if (offset >= branch_columns[tag]->size()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Invalid ORC union offset {} into branch {} of size {} while reading column {}", + offset, tag, branch_columns[tag]->size(), column_name); + + /// A non-null union row can still select a branch whose payload is null (ORC keeps the + /// union-level null count at 0 in that case). Variant branches are non-nullable, so + /// represent such a row as a Variant NULL rather than the branch's nested default value. + if (branch_null_maps[tag] && (*branch_null_maps[tag])[offset]) + { + discriminators_data[row] = ColumnVariant::NULL_DISCRIMINATOR; + offsets_data[row] = 0; + continue; + } + + const auto global = tag_to_global[tag]; + auto & variant_column = *variant_columns[global]; + discriminators_data[row] = global; + offsets_data[row] = variant_column.size(); + variant_column.insertFrom(*branch_columns[tag], offset); + } + + auto variant_column = ColumnVariant::create(std::move(local_discriminators), std::move(offsets), std::move(variant_columns)); + return {std::move(variant_column), variant_type, column_name}; + } + switch (orc_type->getKind()) { - case orc::STRING: - case orc::BINARY: - case orc::VARCHAR: + case ORC::STRING: + case ORC::BINARY: + case ORC::VARCHAR: { if (type_hint) { @@ -1844,7 +2933,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithStringData(orc_column, column_name); } - case orc::CHAR: + case ORC::CHAR: { if (type_hint) { @@ -1870,32 +2959,32 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( else return readColumnWithFixedStringData(orc_column, orc_type, column_name); } - case orc::BOOLEAN: + case ORC::BOOLEAN: return readColumnWithBooleanData(orc_column, column_name); - case orc::BYTE: - return readColumnWithNumericData(orc_column, column_name); - case orc::SHORT: - return readColumnWithNumericData(orc_column, column_name); - case orc::INT: + case ORC::BYTE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::SHORT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::INT: { /// ORC format doesn't have unsigned integers and we output IPv4 as Int32. /// We should allow to read it back from Int32. if (type_hint && isIPv4(type_hint)) return readIPv4ColumnWithInt32Data(orc_column, column_name); - return readColumnWithNumericData(orc_column, column_name); - } - case orc::LONG: - return readColumnWithNumericData(orc_column, column_name); - case orc::FLOAT: - return readColumnWithNumericData(orc_column, column_name); - case orc::DOUBLE: - return readColumnWithNumericData(orc_column, column_name); - case orc::DATE: - return readColumnWithDateData(orc_column, column_name, type_hint); - case orc::TIMESTAMP: [[fallthrough]]; - case orc::TIMESTAMP_INSTANT: - return readColumnWithTimestampData(orc_column, column_name); - case orc::DECIMAL: + return readColumnWithNumericData(orc_column, column_name); + } + case ORC::LONG: + return readColumnWithNumericData(orc_column, column_name); + case ORC::FLOAT: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DOUBLE: + return readColumnWithNumericData(orc_column, column_name); + case ORC::DATE: + return readColumnWithDateData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::TIMESTAMP: [[fallthrough]]; + case ORC::TIMESTAMP_INSTANT: + return readColumnWithTimestampData(orc_column, column_name, type_hint, date_time_overflow_behavior); + case ORC::DECIMAL: { auto interal_type = parseORCType(orc_type, false, false, nullptr, skipped); @@ -1904,15 +2993,15 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( precision = 38; if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); if (precision <= DecimalUtils::max_precision) - return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); + return readColumnWithDecimalDataCast(orc_column, column_name, interal_type); throw Exception( ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal precision {} in ORC type {} is out of bound", precision, orc_type->toString()); } - case orc::MAP: + case ORC::MAP: { DataTypePtr key_type_hint; DataTypePtr value_type_hint; @@ -1926,13 +3015,18 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } } - const auto * orc_map_column = dynamic_cast(orc_column); + const auto * orc_map_column = dynamic_cast(orc_column); const auto * orc_key_column = orc_map_column->keys.get(); const auto * orc_value_column = orc_map_column->elements.get(); const auto * orc_key_type = orc_type->getSubtype(0); const auto * orc_value_type = orc_type->getSubtype(1); auto key_column = readColumnFromORCColumn(orc_key_column, orc_key_type, "key", false, key_type_hint); + /// A map key cannot be Nullable. + if (!key_type_hint && !DataTypeMap::isValidKeyType(key_column.type)) + key_type_hint = removeNullableOrLowCardinalityNullable(key_column.type); + if (key_type_hint) + key_column = matchORCTupleElementsByName(key_column, key_type_hint, case_insensitive_matching); if (key_type_hint && !key_type_hint->equals(*key_column.type)) { /// Cast key column to target type, because it can happen @@ -1950,7 +3044,7 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( auto map_type = std::make_shared(key_column.type, value_column.type); return {map_column, map_type, column_name}; } - case orc::LIST: + case ORC::LIST: { DataTypePtr nested_type_hint; if (type_hint) @@ -1960,38 +3054,56 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( nested_type_hint = array_type_hint->getNestedType(); } - const auto * orc_list_column = dynamic_cast(orc_column); + const auto * orc_list_column = dynamic_cast(orc_column); const auto * orc_nested_column = getNestedORCColumn(orc_list_column); const auto * orc_nested_type = orc_type->getSubtype(0); auto nested_column = readColumnFromORCColumn(orc_nested_column, orc_nested_type, column_name, false, nested_type_hint); + /// A struct read only for its size has no elements, which `createNested` below rejects. Otherwise the elements + /// are matched after a subcolumn is extracted, as a hint for one can name a path, such as `x.v`. + const auto * read_tuple_type = typeid_cast(removeNullable(nested_column.type).get()); + if (type_hint && isNested(type_hint) && read_tuple_type && read_tuple_type->getElements().empty()) + nested_column = matchORCTupleElementsByName(nested_column, nested_type_hint, case_insensitive_matching); + auto offsets_column = readOffsetsFromORCListColumn(orc_list_column); - auto array_column = ColumnArray::create(nested_column.column, offsets_column); DataTypePtr array_type; - /// If type hint is Nested, we should return Nested type, - /// because we differentiate Nested and simple Array(Tuple) - if (type_hint && isNested(type_hint)) + ColumnPtr array_data_column = nested_column.column; + /// If type hint is Nested and the element is a named Tuple, return the Nested type + /// so that `Nested::flatten` can decompose it into separate arrays. + /// When the element is Nullable(Tuple(...)), unwrap it and propagate the struct null + /// map to each element via `unwrapNullableTuple`. + const auto * tuple_type = type_hint && isNested(type_hint) + ? typeid_cast(removeNullable(nested_column.type).get()) + : nullptr; + if (tuple_type) { - const auto & tuple_type = assert_cast(*nested_column.type); - array_type = createNested(tuple_type.getElements(), tuple_type.getElementNames()); + auto unwrapped = unwrapORCNullableTuple({array_data_column, nested_column.type, column_name}); + array_data_column = unwrapped.column; + const auto & result_tuple = assert_cast(*unwrapped.type); + array_type = createNested(result_tuple.getElements(), result_tuple.getElementNames()); } else { array_type = std::make_shared(nested_column.type); } + auto array_column = ColumnArray::create(array_data_column, offsets_column); return {array_column, array_type, column_name}; } - case orc::STRUCT: + case ORC::STRUCT: { Columns tuple_elements; DataTypes tuple_types; std::vector tuple_names; const auto * tuple_type_hint = type_hint ? typeid_cast(type_hint.get()) : nullptr; - const auto * orc_struct_column = dynamic_cast(orc_column); + const auto * orc_struct_column = dynamic_cast(orc_column); for (size_t i = 0; i < orc_type->getSubtypeCount(); ++i) { + /// Read only for the size and the null map of the struct, so its values are not converted. + if (count_only_fields.contains(orc_type->getSubtype(i)->getColumnId())) + continue; + auto field_name = orc_type->getFieldName(i); DataTypePtr nested_type_hint; @@ -1999,7 +3111,12 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( { if (tuple_type_hint->hasExplicitNames()) { - auto pos = tuple_type_hint->tryGetPositionByName(field_name, case_insensitive_matching); + /// An element spelled exactly like the field wins over one that only matches + /// case-folded, so two fields whose names differ only by case cannot both + /// claim the same element and leave the other one unread. + auto pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/false); + if (!pos && case_insensitive_matching) + pos = tuple_type_hint->tryGetPositionByName(field_name, /*case_insensitive=*/true); if (pos) { nested_type_hint = tuple_type_hint->getElement(*pos); @@ -2034,8 +3151,27 @@ ColumnWithTypeAndName ORCColumnToCHColumn::readColumnFromORCColumn( } void ORCColumnToCHColumn::orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values) + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values) { + /// A file field spelled exactly like the request wins over one that only matches case-folded, + /// so two fields whose names differ only by case are not both answered by the same one. Among + /// fields that only match folded, the first in file order answers. + auto find_orc_column = [&](const String & name) + { + auto it = name_to_column_ptr.find(name); + if (it == name_to_column_ptr.end() && case_insensitive_matching) + { + for (const auto & field_name : orc_field_names) + if (boost::iequals(field_name, name)) + return name_to_column_ptr.find(field_name); + } + return it; + }; + Columns columns_list; columns_list.reserve(header.columns()); std::unordered_map>> nested_tables; @@ -2043,23 +3179,20 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( { const ColumnWithTypeAndName & header_column = header.getByPosition(column_i); - auto search_column_name = header_column.name; - if (case_insensitive_matching) - boost::to_lower(search_column_name); - ColumnWithTypeAndName column; - if (!name_to_column_ptr.contains(search_column_name)) + auto orc_column_it = find_orc_column(header_column.name); + if (orc_column_it == name_to_column_ptr.end()) { bool read_from_nested = false; /// Check if it's a column from nested table. String nested_table_name = Nested::extractTableName(header_column.name); - String search_nested_table_name = nested_table_name; - if (case_insensitive_matching) - boost::to_lower(search_nested_table_name); - if (name_to_column_ptr.contains(search_nested_table_name)) + auto orc_nested_column_it = find_orc_column(nested_table_name); + if (orc_nested_column_it != name_to_column_ptr.end()) { - if (!nested_tables.contains(search_nested_table_name)) + /// Keyed by the file's spelling, so requests that differ only by case share one. + const String & resolved_nested_table_name = orc_nested_column_it->first; + if (!nested_tables.contains(resolved_nested_table_name)) { NamesAndTypesList nested_columns; for (const auto & name_and_type : header.getNamesAndTypesList()) @@ -2069,15 +3202,17 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } auto nested_table_type = Nested::collect(nested_columns).front().type; - auto orc_column_with_type = name_to_column_ptr[search_nested_table_name]; + const auto & orc_column_with_type = orc_nested_column_it->second; ColumnsWithTypeAndName cols = {readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, nested_table_name, false, nested_table_type)}; BlockPtr block_ptr = std::make_shared(cols); auto column_extractor = std::make_shared(*block_ptr, case_insensitive_matching); - nested_tables[search_nested_table_name] = {block_ptr, column_extractor}; + nested_tables[resolved_nested_table_name] = {block_ptr, column_extractor}; } - auto nested_column = nested_tables[search_nested_table_name].second->extractColumn(search_column_name); + /// The requested spelling, not the file's one: the helper matches names + /// case-insensitively itself, and an exact element name outranks a folded match. + auto nested_column = nested_tables[resolved_nested_table_name].second->extractColumn(header_column.name); if (nested_column) { column = *nested_column; @@ -2103,11 +3238,12 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( } else { - auto orc_column_with_type = name_to_column_ptr[search_column_name]; + const auto & orc_column_with_type = orc_column_it->second; column = readColumnFromORCColumn( orc_column_with_type.first, orc_column_with_type.second, header_column.name, false, header_column.type); } + column = matchORCTupleElementsByName(column, header_column.type, case_insensitive_matching); if (null_as_default) insertNullAsDefaultIfNeeded(column, header_column, column_i, block_missing_values); @@ -2118,6 +3254,72 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( res.setColumns(columns_list, num_rows); } +void registerInputFormatORC(FormatFactory & factory); +void registerInputFormatORC(FormatFactory & factory) +{ + factory.registerRandomAccessInputFormat( + "ORC", + [](ReadBuffer & buf, + const Block & sample, + const FormatSettings & settings, + const ReadSettings & read_settings, + bool is_remote_fs, + FormatParserSharedResourcesPtr, + FormatFilterInfoPtr format_filter_info) + { + const bool has_file_size = isBufferWithFileSize(buf); + auto * seekable_in = dynamic_cast(&buf); + const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in + && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; + const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; + return std::make_shared( + buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); + }); + factory.markFormatSupportsSubsetOfColumns("ORC"); +} + +void registerORCSchemaReader(FormatFactory & factory); +void registerORCSchemaReader(FormatFactory & factory) +{ + factory.registerSchemaReader( + "ORC", + [](ReadBuffer & buf, const FormatSettings & settings) + { + return std::make_shared(buf, settings); + } + ); + + factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) + { + return fmt::format( + "schema_inference_make_columns_nullable={};schema_inference_allow_nullable_tuple_type={};" + "dictionary_as_low_cardinality={};skip_columns_with_unsupported_types={};max_parser_depth={}", + settings.schema_inference_make_columns_nullable, + settings.schema_inference_allow_nullable_tuple_type, + settings.orc.dictionary_as_low_cardinality, + settings.orc.skip_columns_with_unsupported_types_in_schema_inference, + settings.max_parser_depth); + }); +} + +} + +#else + +namespace DB +{ + class FormatFactory; + + void registerInputFormatORC(FormatFactory &); + void registerORCSchemaReader(FormatFactory &); + + void registerInputFormatORC(FormatFactory &) + { + } + + void registerORCSchemaReader(FormatFactory &) + { + } } #endif diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h index c58c59889a8c..42cf3556c66e 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.h @@ -6,13 +6,12 @@ #include #include -#include #include #include #include #include #include -#include +#include #include namespace DB @@ -20,21 +19,23 @@ namespace DB class KeyCondition; -class ORCInputStream : public orc::InputStream +class ORCInputStream : public ORC::InputStream { public: ORCInputStream(SeekableReadBuffer & in_, size_t file_size_, bool use_prefetch); - uint64_t getLength() const override; - uint64_t getNaturalReadSize() const override; - void read(void * buf, uint64_t length, uint64_t offset) override; - std::future readAsync(void * buf, uint64_t length, uint64_t offset) override; + UInt64 getLength() const override; + void read(void * buf, UInt64 length, UInt64 offset) override; + std::future readAsync(void * buf, UInt64 length, UInt64 offset) override; const std::string & getName() const override { return name; } protected: SeekableReadBuffer & in; size_t file_size; - bool supports_read_at; + /// Use offset-based reads (ReadBuffer::readBigAt) instead of seek+read; needed for ORC tail. + bool use_offset_based_read; + /// Async wrapper only when caller enabled prefetch and the buffer supports read-at. + bool use_async_prefetch; ThreadPoolCallbackRunnerUnsafe async_runner; std::string name = "ORCInputStream"; @@ -50,22 +51,20 @@ class ORCInputStreamFromString : public ReadBufferFromOwnString, public ORCInput } }; -std::unique_ptr +std::unique_ptr asORCInputStream(ReadBuffer & in, const FormatSettings & settings, bool use_prefetch, std::atomic & is_cancelled); // Reads the whole file into a memory buffer, owned by the returned RandomAccessFile. -std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); +std::unique_ptr asORCInputStreamLoadIntoMemory(ReadBuffer & in, std::atomic & is_cancelled); -/// The memory pool to set on the options of every ORC reader and writer we create: unlike the -/// default one of the library, it is accounted for by the memory tracker and it throws on failure -/// instead of returning a null pointer that the library dereferences. -orc::MemoryPool & getORCMemoryPool(); +/// Creates an ORC file reader; throws INCORRECT_DATA if the root type of the file is not a struct. +std::unique_ptr createORCReader(std::unique_ptr stream, const ORC::ReaderOptions & options); -std::unique_ptr buildORCSearchArgument( - const KeyCondition & key_condition, const Block & header, const orc::Type & schema, const FormatSettings & format_settings); +std::unique_ptr buildORCSearchArgument( + const KeyCondition & key_condition, const Block & header, const ORC::Type & schema, const FormatSettings & format_settings); class ORCColumnToCHColumn; -class NativeORCBlockInputFormat : public IInputFormat +class NativeORCBlockInputFormat final : public IInputFormat { public: NativeORCBlockInputFormat( @@ -96,14 +95,14 @@ class NativeORCBlockInputFormat : public IInputFormat bool prepareStripeReader(); void prefetchStripes(); - std::unique_ptr file_reader; - std::unique_ptr stripe_reader; + std::unique_ptr file_reader; + std::unique_ptr stripe_reader; std::unique_ptr orc_column_to_ch_column; - std::shared_ptr sargs; + std::shared_ptr sargs; // indices of columns to read from ORC file - std::list include_indices; + std::vector include_indices; BlockMissingValues block_missing_values; size_t approx_bytes_read_for_chunk = 0; @@ -115,30 +114,36 @@ class NativeORCBlockInputFormat : public IInputFormat FormatFilterInfoPtr format_filter_info; std::vector selected_stripes; - size_t read_iterator; - size_t prefetch_iterator; + size_t read_iterator{}; + size_t prefetch_iterator{}; - std::unique_ptr current_stripe_info; + const ORC::Proto::StripeInformation * current_stripe_info = nullptr; std::atomic is_stopped{0}; }; -class NativeORCSchemaReader : public ISchemaReader +class NativeORCSchemaReader final : public ISchemaReader { public: NativeORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); NamesAndTypesList readSchema() override; + std::optional readNumberOrRows() override; private: + void initializeIfNeeded(); + const FormatSettings format_settings; + std::unique_ptr file_reader; + std::atomic is_stopped{0}; + bool initialized = false; }; class ORCColumnToCHColumn { public: - using ORCColumnPtr = const orc::ColumnVectorBatch *; - using ORCTypePtr = const orc::Type *; + using ORCColumnPtr = const ORC::ColumnVectorBatch *; + using ORCTypePtr = const ORC::Type *; using ORCColumnWithType = std::pair; using NameToColumnPtr = std::unordered_map; @@ -147,22 +152,28 @@ class ORCColumnToCHColumn bool allow_missing_columns_, bool null_as_default_, bool case_insensitive_matching_ = false, - bool dictionary_as_low_cardinality_ = false); + bool dictionary_as_low_cardinality_ = false, + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior_ = FormatSettings::DateTimeOverflowBehavior::Ignore, + std::unordered_set count_only_fields_ = {}); void orcTableToCHChunk( Chunk & res, - const orc::Type * schema, - const orc::ColumnVectorBatch * table, + const ORC::Type * schema, + const ORC::ColumnVectorBatch * table, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); void orcColumnsToCHChunk( - Chunk & res, NameToColumnPtr & name_to_column_ptr, size_t num_rows, BlockMissingValues * block_missing_values = nullptr); + Chunk & res, + NameToColumnPtr & name_to_column_ptr, + const Names & orc_field_names, + size_t num_rows, + BlockMissingValues * block_missing_values = nullptr); private: ColumnWithTypeAndName readColumnFromORCColumn( - const orc::ColumnVectorBatch * orc_column, - const orc::Type * orc_type, + const ORC::ColumnVectorBatch * orc_column, + const ORC::Type * orc_type, const std::string & column_name, bool inside_nullable, DataTypePtr type_hint = nullptr) const; @@ -173,6 +184,9 @@ class ORCColumnToCHColumn bool null_as_default; bool case_insensitive_matching; bool dictionary_as_low_cardinality; + FormatSettings::DateTimeOverflowBehavior date_time_overflow_behavior; + /// ORC column ids of the struct fields that are read only for the size and the null map of their struct. + const std::unordered_set count_only_fields; }; } #endif diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.cpp b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp new file mode 100644 index 000000000000..f792e8d980ad --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.cpp @@ -0,0 +1,1218 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +RleVersion getRleVersion(const Proto::ColumnEncoding & encoding) +{ + switch (encoding.kind) + { + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DICTIONARY: + return RleVersion::V1; + case Proto::ColumnEncodingKind::DIRECT_V2: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return RleVersion::V2; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding {}", static_cast(encoding.kind)); +} + +std::unique_ptr getRequiredStream(StripeStreams & stripe, UInt64 column_id, Proto::StreamKind kind, const char * stream_name, const char * column_kind) +{ + auto stream = stripe.getStream(column_id, kind); + if (!stream) + throw Exception(ErrorCodes::INCORRECT_DATA, "{} stream not found in ORC {} column {}", stream_name, column_kind, column_id); + return stream; +} + +/// Converts the bytes read into the beginning of a buffer of integers into the integers, in place. +/// BOOLEAN and BYTE: the values are decoded into the bytes of the column. +template +class ByteColumnReaderImpl final : public ColumnReader +{ +public: + ByteColumnReaderImpl(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", type.toString().c_str())) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle.skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle.next(reinterpret_cast(data.data()), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + } + +private: + Decoder rle; +}; + +using BooleanColumnReader = ByteColumnReaderImpl; +using ByteColumnReader = ByteColumnReaderImpl; + +/// SHORT, INT, LONG and DATE: the values are decoded into a column of the matching width. +template +class IntegerColumnReader final : public ColumnReader +{ +public: + IntegerColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "integer"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & data = typeid_cast(batch).prepareColumn(num_values); + rle->next(data.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + std::unique_ptr rle; +}; + +/// FLOAT and DOUBLE: the values are stored as is (little endian), so they are copied into the column. +template +class FloatingColumnReader final : public ColumnReader +{ +public: + FloatingColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , stream(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "floating point")) + { + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + stream->skipBytes(num_values * sizeof(ItemType)); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & data = typeid_cast &>(batch).prepareColumn(num_values); + ItemType * out = data.data(); + + /// The stream has only the non-null values: read them at once to the beginning of the column. + size_t num_present = num_values; + if (not_null) + num_present = std::count_if(not_null, not_null + num_values, [](char c) { return c != 0; }); + + stream->readBytes(reinterpret_cast(out), num_present * sizeof(ItemType)); + if constexpr (std::endian::native == std::endian::big) + for (size_t i = 0; i < num_present; ++i) + out[i] = std::bit_cast(std::byteswap(std::bit_cast(out[i]))); + + if (!not_null) + return; + + /// Move the values to their rows from the back: the k-th value goes to a row i >= k, so it is not overwritten before it is moved. + size_t next_value = num_present; + for (size_t i = num_values; i-- > 0;) + out[i] = not_null[i] ? out[--next_value] : 0; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + stream->seek(positions.at(column_id)); + } + +private: + using Bits = std::conditional_t; + + std::unique_ptr stream; +}; + +/// Converts the lengths in `offsets` into the end offsets (as in `ColumnString` and `ColumnArray`), starting +/// from `total`, and returns the total length. The lengths of the null values are zeros. +UInt64 lengthsToEndOffsets(UInt64 * offsets, size_t num_values, UInt64 column_id, UInt64 total = 0) +{ + for (size_t i = 0; i < num_values; ++i) + { + /// The lengths are non-negative, a negative one is huge as unsigned. + if (offsets[i] > static_cast(std::numeric_limits::max()) || common::addOverflow(total, offsets[i], total) + || total > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid length {} in ORC column {}", static_cast(offsets[i]), column_id); + offsets[i] = total; + } + return total; +} + +/// Reads the strings with their lengths in a separate stream into a `ColumnString`. +ColumnString::MutablePtr readStrings( + IntRleDecoder & length_rle, InputByteStream & blob_stream, size_t num_values, const char * not_null, UInt64 column_id) +{ + /// The buffers grow as the data is decoded: a malformed count or length must not allocate memory + /// before the streams prove to contain the data. + static constexpr size_t MIN_STEP = 64 * 1024; + auto column = ColumnString::create(); + auto & offsets = column->getOffsets(); + UInt64 total = 0; + while (offsets.size() < num_values) + { + size_t done = offsets.size(); + size_t step = std::min(num_values - done, std::max(MIN_STEP, done)); + offsets.resize(done + step); + length_rle.next(offsets.data() + done, step, not_null ? not_null + done : nullptr); + total = lengthsToEndOffsets(offsets.data() + done, step, column_id, total); + } + auto & chars = column->getChars(); + while (chars.size() < total) + { + size_t done = chars.size(); + size_t step = std::min(total - done, std::max(MIN_STEP, done)); + chars.resize(done + step); + blob_stream.readBytes(reinterpret_cast(chars.data() + done), step); + } + return column; +} + +std::shared_ptr loadStringDictionary(UInt64 column_id, StripeStreams & stripe) +{ + const auto & encoding = stripe.getEncoding(column_id); + /// The dictionary is not bounded by the number of rows of the stripe: a column nested in a list or a map + /// can have more values than the stripe has rows. + UInt32 dictionary_size = encoding.dictionary_size; + + auto dictionary = std::make_shared(); + if (dictionary_size == 0) + { + dictionary->column = ColumnString::create(); + return dictionary; + } + + auto length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string dictionary"), false, getRleVersion(encoding)); + auto blob_stream = stripe.getStream(column_id, Proto::StreamKind::DICTIONARY_DATA); + if (!blob_stream) + { + /// All entries can be empty strings, then the stream is not needed. + blob_stream = std::make_unique(std::string_view{}, CompressionKind::NONE, 0, "empty dictionary"); + } + dictionary->column = readStrings(*length_rle, *blob_stream, dictionary_size, nullptr, column_id); + return dictionary; +} + +class StringDictionaryColumnReader final : public ColumnReader +{ +public: + StringDictionaryColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string dictionary"), + false, getRleVersion(stripe.getEncoding(column_id))); + dictionary = loadStringDictionary(column_id, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & string_batch = dynamic_cast(batch); + index.resize(num_values); + rle->next(index.data(), num_values, not_null); + string_batch.isEncoded = false; + string_batch.column = decodeDictionary(assert_cast(*dictionary->column), index.data(), not_null, num_values); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + readIndex(dynamic_cast(batch), num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + } + +private: + void readIndex(EncodedStringVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + batch.isEncoded = true; + batch.dictionary = dictionary; + batch.column = nullptr; + batch.index.resize(num_values); + rle->next(batch.index.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + std::shared_ptr dictionary; + std::unique_ptr rle; + PaddedPODArray index; +}; + +class StringDirectColumnReader final : public ColumnReader +{ +public: + StringDirectColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + length_rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "string"), + false, getRleVersion(stripe.getEncoding(column_id))); + blob_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "string"); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + static constexpr size_t BUFFER_SIZE = 1024; + UInt64 buffer[BUFFER_SIZE]; + size_t done = 0; + size_t total_bytes = 0; + while (done < num_values) + { + size_t step = std::min(BUFFER_SIZE, num_values - done); + length_rle->next(buffer, step, nullptr); + total_bytes += lengthsToEndOffsets(buffer, step, column_id); + done += step; + } + blob_stream->skipBytes(total_bytes); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & string_batch = dynamic_cast(batch); + string_batch.isEncoded = false; + string_batch.column = readStrings(*length_rle, *blob_stream, num_values, batch.hasNulls ? batch.notNull.data() : nullptr, column_id); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + blob_stream->seek(provider); + length_rle->seek(provider); + } + +private: + std::unique_ptr length_rle; + std::unique_ptr blob_stream; +}; + +class TimestampColumnReader final : public ColumnReader +{ +public: + TimestampColumnReader(const Type & type, StripeStreams & stripe, bool is_instant) + : ColumnReader(type, stripe) + , writer_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getWriterTimezone()) + , reader_timezone(is_instant ? DateLUT::instance("UTC") : stripe.getReaderTimezone()) + , same_timezone(&writer_timezone == &reader_timezone || writer_timezone.getTimeZone() == reader_timezone.getTimeZone()) + , writer_offset_of(writer_timezone) + , reader_offset_of(reader_timezone) + { + /// The base of the seconds is 2015-01-01 00:00:00 in the time zone of the writer. + static constexpr Int64 UTC_2015_01_01 = 1420070400; + epoch_offset = UTC_2015_01_01 - writer_timezone.timezoneOffset(UTC_2015_01_01); + + RleVersion version = getRleVersion(stripe.getEncoding(column_id)); + seconds_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "timestamp"), true, version); + nanos_rle = createIntRleDecoder(getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "timestamp"), false, version); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + seconds_rle->skip(num_values); + nanos_rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & timestamp_batch = typeid_cast(batch); + timestamp_batch.data.resize(num_values); + timestamp_batch.nanoseconds.resize(num_values); + Int64 * seconds = timestamp_batch.data.data(); + Int64 * nanos = timestamp_batch.nanoseconds.data(); + seconds_rle->next(seconds, num_values, not_null); + nanos_rle->next(nanos, num_values, not_null); + + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + + const Int64 encoded_nanos = nanos[i]; + /// The lowest 3 bits are the number of the trailing zeros (minus one) that are removed. + UInt64 zeros = nanos[i] & 0x7; + /// An arithmetic shift, as in the reference implementation: some writers (the Arrow + /// adapter) store negative nanoseconds for the timestamps before the epoch. + nanos[i] >>= 3; + if (zeros != 0 && common::mulOverflow(nanos[i], POWERS_OF_TEN_FOR_NANOS[zeros + 1], nanos[i])) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (nanos[i] < -999'999'999 || nanos[i] > 999'999'999) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + Int64 writer_time = 0; + if (common::addOverflow(seconds[i], epoch_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + if (writer_time < 0 && nanos[i] > 999999 && common::subOverflow(writer_time, Int64{1}, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + + if (!same_timezone) + { + /// Keep the same wall clock time when the writer and the reader time zones differ. + Int64 writer_offset = writer_offset_of(writer_time); + Int64 reader_offset = reader_offset_of(writer_time); + if (writer_offset != reader_offset) + { + /// If the adjustment crosses a DST boundary, the offset has to be reevaluated. + Int64 adjusted_time = 0; + if (common::addOverflow(writer_time, writer_offset - reader_offset, adjusted_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + Int64 adjusted_reader_offset = reader_offset_of(adjusted_time); + if (common::addOverflow(writer_time, writer_offset - adjusted_reader_offset, writer_time)) + throwInvalidTimestamp(seconds[i], encoded_nanos); + } + } + seconds[i] = writer_time; + } + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + seconds_rle->seek(provider); + nanos_rle->seek(provider); + } + +private: + static constexpr Int64 POWERS_OF_TEN_FOR_NANOS[9] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; + + [[noreturn]] void throwInvalidTimestamp(Int64 seconds, Int64 encoded_nanos) const + { + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid timestamp in ORC column {}: seconds={}, encoded nanoseconds={}", column_id, seconds, encoded_nanos); + } + + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + const bool same_timezone; + const TimezoneOffset writer_offset_of; + const TimezoneOffset reader_offset_of; + Int64 epoch_offset = 0; + std::unique_ptr seconds_rle; + std::unique_ptr nanos_rle; +}; + +constexpr UInt32 MAX_PRECISION_64 = 18; +constexpr UInt32 MAX_PRECISION_128 = 38; + +constexpr Int64 POWERS_OF_TEN[MAX_PRECISION_64 + 1] = { + 1LL, + 10LL, + 100LL, + 1000LL, + 10000LL, + 100000LL, + 1000000LL, + 10000000LL, + 100000000LL, + 1000000000LL, + 10000000000LL, + 100000000000LL, + 1000000000000LL, + 10000000000000LL, + 100000000000000LL, + 1000000000000000LL, + 10000000000000000LL, + 100000000000000000LL, + 1000000000000000000LL}; + +/// The DECIMAL columns: an unbounded signed varint per value in the DATA stream and the scale of +/// each value in the SECONDARY stream. The values are rescaled to the scale of the type. +class DecimalColumnReader : public ColumnReader +{ +public: + DecimalColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getPrecision() > MAX_PRECISION_128 || type.getScale() > MAX_PRECISION_128) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + value_stream = getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"); + scale_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::SECONDARY, "SECONDARY", "decimal"), + true, getRleVersion(stripe.getEncoding(column_id))); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + size_t skipped = 0; + while (skipped < num_values) + if (!(value_stream->readByte() & 0x80)) + ++skipped; + scale_decoder->skip(num_values); + return num_values; + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + auto & provider = positions.at(column_id); + value_stream->seek(provider); + scale_decoder->seek(provider); + } + +protected: + /// Reads the zigzag-encoded varint of up to 128 bits. + Int128 readInt128() + { + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + if (shift < 128) + value |= static_cast(byte & 0x7F) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + return static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + } + + /// The scale of each value is read from the file. The valid scales are from 0 to 38, the bound + /// also keeps the differences of the scales and the rescaling work small. + Int32 getValueScale(Int64 value_scale) const + { + if (value_scale < -Int64(MAX_PRECISION_128) || value_scale > Int64(MAX_PRECISION_128)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", value_scale, column_id); + return static_cast(value_scale); + } + + static void scaleInt128(Int128 & value, Int32 target_scale, Int32 current_scale) + { + while (target_scale > current_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, target_scale - current_scale); + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[adjust])); + current_scale += adjust; + } + while (current_scale > target_scale) + { + Int32 adjust = std::min(MAX_PRECISION_64, current_scale - target_scale); + value /= POWERS_OF_TEN[adjust]; + current_scale -= adjust; + } + } + + const Int32 precision; + Int32 scale; + std::unique_ptr value_stream; + std::unique_ptr scale_decoder; + PaddedPODArray scales; +}; + +class Decimal64ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int64 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt64(getValueScale(scales[i])); + } + } + +private: + Int64 readInt64(Int32 current_scale) + { + UInt64 encoded = readVarint(*value_stream); + Int64 value = static_cast((encoded >> 1) ^ (~(encoded & 1) + 1)); + if (scale > current_scale && static_cast(scale - current_scale) <= MAX_PRECISION_64) + value = static_cast(static_cast(value) * static_cast(POWERS_OF_TEN[scale - current_scale])); + else if (scale < current_scale && static_cast(current_scale - scale) <= MAX_PRECISION_64) + value /= POWERS_OF_TEN[current_scale - scale]; + else if (scale != current_scale) + throw Exception(ErrorCodes::INCORRECT_DATA, "Decimal scale {} is out of range in ORC column {}", current_scale, column_id); + return value; + } +}; + +class Decimal128ColumnReader final : public DecimalColumnReader +{ +public: + using DecimalColumnReader::DecimalColumnReader; + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + values[i] = readInt128(); + scaleInt128(values[i], scale, getValueScale(scales[i])); + } + } +}; + +/// The DECIMAL columns with the precision up to 18 in the files of the format version 1.9999 +/// (`UNSTABLE_PRE_2_0`): the unscaled values are signed RLEv2 integers in the DATA stream, +/// all with the scale of the type, and there is no SECONDARY stream. +class Decimal64V2ColumnReader final : public ColumnReader +{ +public: + Decimal64V2ColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , precision(static_cast(type.getPrecision())) + , scale(static_cast(type.getScale())) + { + if (type.getScale() > type.getPrecision()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid precision {} or scale {} of decimal ORC column {}", + type.getPrecision(), type.getScale(), column_id); + /// As in the reference implementation, RLEv2 is used regardless of the column encoding. + value_decoder = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "decimal"), true, RleVersion::V2); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + value_decoder->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & decimal_batch = typeid_cast(batch); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + value_decoder->next(decimal_batch.values.data(), num_values, batch.hasNulls ? batch.notNull.data() : nullptr); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + value_decoder->seek(positions.at(column_id)); + } + +private: + const Int32 precision; + const Int32 scale; + std::unique_ptr value_decoder; +}; + +/// The DECIMAL columns written by Hive 0.11, without the precision and the scale in the type. +/// As in the reference implementation, the values are read with the scale 6 and must have at most 38 digits. +class DecimalHive11ColumnReader final : public DecimalColumnReader +{ +public: + DecimalHive11ColumnReader(const Type & type, StripeStreams & stripe) + : DecimalColumnReader(type, stripe) + { + scale = 6; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & decimal_batch = typeid_cast(batch); + scales.resize(num_values); + scale_decoder->next(scales.data(), num_values, not_null); + decimal_batch.precision = precision; + decimal_batch.scale = scale; + decimal_batch.values.resize(num_values); + Int128 * values = decimal_batch.values.data(); + + static const Int128 max_value = Int128(10000000000000000000ULL) * Int128(10000000000000000000ULL) - 1; + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + bool overflow = false; + UInt128 value = 0; + UInt32 shift = 0; + while (true) + { + UInt8 byte = value_stream->readByte(); + UInt32 bits = byte & 0x7F; + if (shift > 128 || (shift == 126 && bits > 3)) + overflow = true; + if (shift < 128) + value |= static_cast(bits) << shift; + shift += 7; + if (!(byte & 0x80)) + break; + } + Int128 decoded = static_cast((value >> 1) ^ (UInt128(0) - (value & 1))); + if (!overflow) + { + scaleInt128(decoded, scale, getValueScale(scales[i])); + overflow = decoded > max_value || decoded < -max_value; + } + if (overflow) + throw Exception(ErrorCodes::INCORRECT_DATA, "Hive 0.11 decimal was more than 38 digits in ORC column {}", column_id); + values[i] = decoded; + } + } +}; + +class StructColumnReader final : public ColumnReader +{ +public: + StructColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + const auto & encoding = stripe.getEncoding(column_id); + if (encoding.kind != Proto::ColumnEncodingKind::DIRECT) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown encoding {} of ORC struct column {}", static_cast(encoding.kind), column_id); + const auto & selected = stripe.getSelectedColumns(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children.push_back(buildColumnReader(child, stripe)); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + for (auto & child : children) + child->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + for (auto & child : children) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + const char * not_null = batch.hasNulls ? batch.notNull.data() : nullptr; + auto & struct_batch = typeid_cast(batch); + for (size_t i = 0; i < children.size(); ++i) + { + if constexpr (encoded) + children[i]->nextEncoded(*struct_batch.fields[i], num_values, not_null); + else + children[i]->next(*struct_batch.fields[i], num_values, not_null); + } + } + + std::vector> children; +}; + +/// Reads the lengths of the lists or maps as the end offsets, returns the total number of the children. +UInt64 readListOffsets(IntRleDecoder & rle, ColumnPtr & result, size_t num_values, const char * not_null, UInt64 column_id) +{ + auto column = ColumnUInt64::create(num_values); + auto & offsets = column->getData(); + rle.next(offsets.data(), num_values, not_null); + UInt64 total = lengthsToEndOffsets(offsets.data(), num_values, column_id); + result = std::move(column); + return total; +} + +UInt64 sumLengths(IntRleDecoder & rle, size_t num_values, UInt64 column_id) +{ + static constexpr size_t BUFFER_SIZE = 1024; + Int64 buffer[BUFFER_SIZE]; + UInt64 total = 0; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + { + if (buffer[i] < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Negative length {} in ORC column {}", buffer[i], column_id); + total += static_cast(buffer[i]); + } + read += chunk; + } + return total; +} + +class ListColumnReader final : public ColumnReader +{ +public: + ListColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "list"), + false, getRleVersion(stripe.getEncoding(column_id))); + const Type & child_type = *type.getSubtype(0); + if (stripe.getSelectedColumns()[child_type.getColumnId()]) + child = buildColumnReader(child_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (child) + child->skip(sumLengths(*rle, num_values, column_id)); + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (child) + child->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & list_batch = typeid_cast(batch); + const char * not_null = list_batch.hasNulls ? list_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, list_batch.offsets, num_values, not_null, column_id); + if (child) + { + if constexpr (encoded) + child->nextEncoded(*list_batch.elements, total, nullptr); + else + child->next(*list_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr child; +}; + +class MapColumnReader final : public ColumnReader +{ +public: + MapColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + { + rle = createIntRleDecoder( + getRequiredStream(stripe, column_id, Proto::StreamKind::LENGTH, "LENGTH", "map"), + false, getRleVersion(stripe.getEncoding(column_id))); + const auto & selected = stripe.getSelectedColumns(); + const Type & key_type = *type.getSubtype(0); + if (selected[key_type.getColumnId()]) + key_reader = buildColumnReader(key_type, stripe); + const Type & value_type = *type.getSubtype(1); + if (selected[value_type.getColumnId()]) + value_reader = buildColumnReader(value_type, stripe); + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + if (key_reader || value_reader) + { + UInt64 total = sumLengths(*rle, num_values, column_id); + if (key_reader) + key_reader->skip(total); + if (value_reader) + value_reader->skip(total); + } + else + rle->skip(num_values); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle->seek(positions.at(column_id)); + if (key_reader) + key_reader->seekToRowGroup(positions); + if (value_reader) + value_reader->seekToRowGroup(positions); + } + +private: + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & map_batch = typeid_cast(batch); + const char * not_null = map_batch.hasNulls ? map_batch.notNull.data() : nullptr; + UInt64 total = readListOffsets(*rle, map_batch.offsets, num_values, not_null, column_id); + if (key_reader) + { + if constexpr (encoded) + key_reader->nextEncoded(*map_batch.keys, total, nullptr); + else + key_reader->next(*map_batch.keys, total, nullptr); + } + if (value_reader) + { + if constexpr (encoded) + value_reader->nextEncoded(*map_batch.elements, total, nullptr); + else + value_reader->next(*map_batch.elements, total, nullptr); + } + } + + std::unique_ptr rle; + std::unique_ptr key_reader; + std::unique_ptr value_reader; +}; + +class UnionColumnReader final : public ColumnReader +{ +public: + UnionColumnReader(const Type & type, StripeStreams & stripe) + : ColumnReader(type, stripe) + , rle(getRequiredStream(stripe, column_id, Proto::StreamKind::DATA, "DATA", "union")) + , num_children(type.getSubtypeCount()) + { + children.resize(num_children); + counts.resize(num_children); + const auto & selected = stripe.getSelectedColumns(); + for (size_t i = 0; i < num_children; ++i) + { + const Type & child = *type.getSubtype(i); + if (selected[child.getColumnId()]) + children[i] = buildColumnReader(child, stripe); + } + } + + size_t skip(size_t num_values) override + { + num_values = ColumnReader::skip(num_values); + std::fill(counts.begin(), counts.end(), 0); + static constexpr size_t BUFFER_SIZE = 1024; + char buffer[BUFFER_SIZE]; + size_t read = 0; + while (read < num_values) + { + size_t chunk = std::min(num_values - read, BUFFER_SIZE); + rle.next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + ++counts[checkedTag(static_cast(buffer[i]))]; + read += chunk; + } + for (size_t i = 0; i < num_children; ++i) + if (counts[i] && children[i]) + children[i]->skip(counts[i]); + return num_values; + } + + void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) override + { + nextImpl(batch, num_values, incoming_mask); + } + + void seekToRowGroup(std::unordered_map & positions) override + { + ColumnReader::seekToRowGroup(positions); + rle.seek(positions.at(column_id)); + for (auto & child : children) + if (child) + child->seekToRowGroup(positions); + } + +private: + size_t checkedTag(UInt8 tag) const + { + if (tag >= num_children) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid union tag {} for union with {} children in ORC column {}", static_cast(tag), num_children, column_id); + return tag; + } + + template + void nextImpl(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + ColumnReader::next(batch, num_values, incoming_mask); + auto & union_batch = typeid_cast(batch); + const char * not_null = union_batch.hasNulls ? union_batch.notNull.data() : nullptr; + union_batch.tags.resize(num_values); + union_batch.offsets.resize(num_values); + UInt8 * tags = union_batch.tags.data(); + UInt64 * offsets = union_batch.offsets.data(); + memset(tags, 0, num_values); + rle.next(reinterpret_cast(tags), num_values, not_null); + std::fill(counts.begin(), counts.end(), 0); + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + continue; + offsets[i] = counts[checkedTag(tags[i])]++; + } + for (size_t i = 0; i < num_children; ++i) + { + if (!children[i]) + continue; + if constexpr (encoded) + children[i]->nextEncoded(*union_batch.children[i], counts[i], nullptr); + else + children[i]->next(*union_batch.children[i], counts[i], nullptr); + } + } + + ByteRleDecoder rle; + const size_t num_children; + std::vector> children; + std::vector counts; +}; + +} + + +ColumnReader::ColumnReader(const Type & type, StripeStreams & stripe) + : column_id(type.getColumnId()) +{ + if (auto stream = stripe.getStream(column_id, Proto::StreamKind::PRESENT)) + not_null_decoder = std::make_unique(std::move(stream)); +} + +void ColumnReader::next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) +{ + batch.reset(num_values); + + if (not_null_decoder) + { + char * not_null = batch.notNull.data(); + not_null_decoder->next(not_null, num_values, incoming_mask); + batch.hasNulls = memchr(not_null, 0, num_values) != nullptr; + return; + } + if (incoming_mask) + { + batch.hasNulls = true; + memcpy(batch.notNull.data(), incoming_mask, num_values); + return; + } + batch.hasNulls = false; +} + +size_t ColumnReader::skip(size_t num_values) +{ + if (!not_null_decoder) + return num_values; + + static constexpr size_t BUFFER_SIZE = 32768; + char buffer[BUFFER_SIZE]; + size_t remaining = num_values; + while (remaining) + { + size_t chunk = std::min(remaining, BUFFER_SIZE); + not_null_decoder->next(buffer, chunk, nullptr); + for (size_t i = 0; i < chunk; ++i) + if (!buffer[i]) + --num_values; + remaining -= chunk; + } + return num_values; +} + +void ColumnReader::seekToRowGroup(std::unordered_map & positions) +{ + if (not_null_decoder) + { + auto it = positions.find(column_id); + if (it == positions.end()) + throw Exception(ErrorCodes::INCORRECT_DATA, "No row index for ORC column {}", column_id); + not_null_decoder->seek(it->second); + } +} + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, stripe); + case BYTE: + return std::make_unique(type, stripe); + case SHORT: + return std::make_unique>(type, stripe); + case INT: + return std::make_unique>(type, stripe); + case LONG: + case DATE: + return std::make_unique>(type, stripe); + case FLOAT: + return std::make_unique>(type, stripe); + case DOUBLE: + return std::make_unique>(type, stripe); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + switch (stripe.getEncoding(type.getColumnId()).kind) + { + case Proto::ColumnEncodingKind::DICTIONARY: + case Proto::ColumnEncodingKind::DICTIONARY_V2: + return std::make_unique(type, stripe); + case Proto::ColumnEncodingKind::DIRECT: + case Proto::ColumnEncodingKind::DIRECT_V2: + return std::make_unique(type, stripe); + } + break; + case TIMESTAMP: + return std::make_unique(type, stripe, false); + case TIMESTAMP_INSTANT: + return std::make_unique(type, stripe, true); + case DECIMAL: + if (type.getPrecision() == 0) + return std::make_unique(type, stripe); + if (type.getPrecision() <= MAX_PRECISION_64) + { + if (stripe.isDecimalAsLong()) + return std::make_unique(type, stripe); + return std::make_unique(type, stripe); + } + return std::make_unique(type, stripe); + case STRUCT: + return std::make_unique(type, stripe); + case LIST: + return std::make_unique(type, stripe); + case MAP: + return std::make_unique(type, stripe); + case UNION: + return std::make_unique(type, stripe); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Reading ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/ColumnReader.h b/src/Processors/Formats/Impl/ORC/ColumnReader.h new file mode 100644 index 000000000000..1abaedb6fff5 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/ColumnReader.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +/// Access to the streams of one stripe for the column readers. +class StripeStreams +{ +public: + virtual ~StripeStreams() = default; + + virtual const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const = 0; + /// Returns nullptr if the stripe does not have this stream. + virtual std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const = 0; + virtual const std::vector & getSelectedColumns() const = 0; + /// The time zones for TIMESTAMP (not TIMESTAMP_INSTANT) columns. + virtual const DateLUTImpl & getWriterTimezone() const = 0; + virtual const DateLUTImpl & getReaderTimezone() const = 0; + virtual UInt64 getNumberOfRows() const = 0; + /// Whether the file has the format version 1.9999 (`UNSTABLE_PRE_2_0` in the reference implementation), + /// where DECIMAL columns with the precision up to 18 are written as signed RLEv2 integers in the DATA stream + /// without the SECONDARY stream of scales. + virtual bool isDecimalAsLong() const = 0; +}; + +class ColumnReader +{ +public: + ColumnReader(const Type & type, StripeStreams & stripe); + virtual ~ColumnReader() = default; + + /// Reads the next `num_values` values into `batch`. `incoming_mask` is the mask of the + /// non-null values of the parent (or nullptr). + virtual void next(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask); + + /// Same, but the string columns with dictionary encoding fill `EncodedStringVectorBatch` + /// without decoding the dictionary. + virtual void nextEncoded(ColumnVectorBatch & batch, size_t num_values, const char * incoming_mask) + { + next(batch, num_values, incoming_mask); + } + + /// Skips `num_values` values, returns the number of the skipped non-null values. + virtual size_t skip(size_t num_values); + + /// Moves to the beginning of a row group, by the positions from the row indexes of the columns. + virtual void seekToRowGroup(std::unordered_map & positions); + +protected: + const UInt64 column_id; + std::unique_ptr not_null_decoder; +}; + +std::unique_ptr buildColumnReader(const Type & type, StripeStreams & stripe); + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.cpp b/src/Processors/Formats/Impl/ORC/Compression.cpp new file mode 100644 index 000000000000..cfacdc431ca8 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.cpp @@ -0,0 +1,437 @@ +#include + +#include + +#include +#include +#include +/// For `ZSTD_decompressBound`, which is not in the stable ABI of zstd. It is safe, as zstd is linked statically from contrib. +#define ZSTD_STATIC_LINKING_ONLY +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int CANNOT_COMPRESS; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +namespace +{ + +[[noreturn]] void throwMalformedLzo(size_t offset) +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed LZO-compressed data in ORC file at offset {}", offset); +} + +/// LZO1X decompressor, as written by the Hadoop codecs (and the ORC Java writer). A chunk can be a +/// concatenation of several LZO blocks, each terminated with the end-of-stream marker. +size_t decompressLzo(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + const UInt8 * input = reinterpret_cast(src); + const UInt8 * const input_begin = input; + const UInt8 * const input_end = input + src_size; + char * output = dst; + char * const output_end = dst + dst_capacity; + + auto offset = [&] { return static_cast(input - input_begin); }; + + auto read_byte = [&]() -> UInt32 + { + if (input >= input_end) + throwMalformedLzo(offset()); + return *input++; + }; + + /// A run of zero bytes extends a length by 255 each, then the next byte is added. + auto read_variable_length = [&](UInt32 base) -> size_t + { + size_t length = base; + UInt32 next = 0; + while ((next = read_byte()) == 0) + { + length += 0xFF; + if (length > dst_capacity) + throwMalformedLzo(offset()); + } + return length + next; + }; + + while (input < input_end) + { + bool first_command = true; + size_t last_literal_length = 0; + + while (true) + { + UInt32 command = read_byte(); + if (command == 0x11) + break; + + size_t match_length = 0; + size_t match_offset = 0; + size_t literal_length = 0; + + if ((command & 0xF0) == 0) + { + if (last_literal_length == 0) + { + /// A long run of literals. + literal_length = command & 0xF; + if (literal_length == 0) + literal_length = read_variable_length(0xF); + literal_length += 3; + } + else if (last_literal_length <= 3) + { + match_length = 3; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + match_offset |= 0x800; + literal_length = command & 0x3; + } + else + { + match_length = 2; + match_offset = (command & 0xC) >> 2; + match_offset |= read_byte() << 2; + literal_length = command & 0x3; + } + } + else if (first_command) + { + literal_length = command - 17; + } + else if ((command & 0xF0) == 0x10) + { + match_length = command & 0x7; + if (match_length == 0) + match_length = read_variable_length(0x7); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + match_offset |= (command & 0x8) ? 0x8000 : 0x4000; + --match_offset; + literal_length = trailer & 0x3; + } + else if ((command & 0xE0) == 0x20) + { + match_length = command & 0x1F; + if (match_length == 0) + match_length = read_variable_length(0x1F); + match_length += 2; + UInt32 trailer = read_byte(); + trailer |= read_byte() << 8; + match_offset = trailer >> 2; + literal_length = trailer & 0x3; + } + else if ((command & 0xC0) != 0) + { + match_length = ((command & 0xE0) >> 5) + 1; + match_offset = (command & 0x1C) >> 2; + match_offset |= read_byte() << 3; + literal_length = command & 0x3; + } + else + throwMalformedLzo(offset()); + + first_command = false; + + if (match_length != 0) + { + /// LZO encodes the match offset minus one. + ++match_offset; + if (match_offset > static_cast(output - dst) || match_length > static_cast(output_end - output)) + throwMalformedLzo(offset()); + const char * match = output - match_offset; + /// The source can overlap the destination, so copy byte by byte. + for (size_t i = 0; i < match_length; ++i) + output[i] = match[i]; + output += match_length; + } + + if (literal_length > static_cast(output_end - output) || literal_length > static_cast(input_end - input)) + throwMalformedLzo(offset()); + memcpy(output, input, literal_length); + output += literal_length; + input += literal_length; + last_literal_length = literal_length; + } + + /// The end-of-stream marker is 0x11 0x00 0x00. + if (input_end - input < 2 || input[0] != 0 || input[1] != 0) + throwMalformedLzo(offset()); + input += 2; + } + + return output - dst; +} + +size_t decompressZlib(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + z_stream stream{}; + if (inflateInit2(&stream, -15) != Z_OK) + throw Exception(ErrorCodes::INCORRECT_DATA, "Cannot initialize zlib decompression for ORC file"); + + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(dst); + stream.avail_out = static_cast(dst_capacity); + + int ret = inflate(&stream, Z_FINISH); + size_t result = dst_capacity - stream.avail_out; + inflateEnd(&stream); + + if (ret != Z_STREAM_END) + { + if (ret == Z_BUF_ERROR && stream.avail_out == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A zlib-compressed chunk of ORC file decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zlib-compressed data in ORC file (zlib error {})", ret); + } + return result; +} + +size_t decompressSnappy(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + if (uncompressed_size > dst_capacity) + throw Exception(ErrorCodes::INCORRECT_DATA, + "A snappy-compressed chunk of ORC file decompresses to {} bytes, more than the {} bytes allowed for the chunk", + uncompressed_size, dst_capacity); + if (!snappy::RawUncompress(src, src_size, dst)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + return uncompressed_size; +} + +size_t decompressLz4(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + if (src_size > static_cast(std::numeric_limits::max()) || dst_capacity > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "LZ4-compressed chunk of ORC file is too large"); + int res = LZ4_decompress_safe(src, dst, static_cast(src_size), static_cast(dst_capacity)); + if (res < 0) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed LZ4-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk", dst_capacity); + return static_cast(res); +} + +size_t decompressZstd(const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + size_t res = ZSTD_decompress(dst, dst_capacity, src, src_size); + if (ZSTD_isError(res)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed zstd-compressed data in ORC file, or it decompresses to more than the {} bytes allowed for the chunk: {}", + dst_capacity, ZSTD_getErrorName(res)); + return res; +} + + +class ZlibCompressor final : public Compressor +{ +public: + ZlibCompressor() + { + /// The level and the parameters are the same as in the C++ ORC library with its default + /// compression strategy, "speed". + if (deflateInit2(&stream, Z_BEST_SPEED + 1, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot initialize zlib compression for ORC"); + } + + ~ZlibCompressor() override { deflateEnd(&stream); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + if (deflateReset(&stream) != Z_OK) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot reset zlib compression for ORC"); + + size_t old_size = out.size(); + /// Allow only the output smaller than the input. + out.resize(old_size + src_size); + stream.next_in = reinterpret_cast(const_cast(src)); + stream.avail_in = static_cast(src_size); + stream.next_out = reinterpret_cast(out.data() + old_size); + stream.avail_out = static_cast(src_size); + + int ret = deflate(&stream, Z_FINISH); + if (ret == Z_STREAM_END && stream.avail_out > 0) + { + size_t compressed = src_size - stream.avail_out; + out.resize(old_size + compressed); + return compressed; + } + out.resize(old_size); + if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zlib compression failed with error {}", ret); + return 0; + } + +private: + z_stream stream{}; +}; + +class SnappyCompressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + out.resize(old_size + snappy::MaxCompressedLength(src_size)); + size_t compressed = 0; + snappy::RawCompress(src, src_size, out.data() + old_size, &compressed); + return finish(out, old_size, compressed, src_size); + } + + static size_t finish(std::string & out, size_t old_size, size_t compressed, size_t src_size) + { + if (compressed >= src_size) + { + out.resize(old_size); + return 0; + } + out.resize(old_size + compressed); + return compressed; + } +}; + +class Lz4Compressor final : public Compressor +{ +public: + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + int bound = LZ4_compressBound(static_cast(src_size)); + out.resize(old_size + bound); + int compressed = LZ4_compress_default(src, out.data() + old_size, static_cast(src_size), bound); + if (compressed <= 0) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "LZ4 compression failed"); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } +}; + +class ZstdCompressor final : public Compressor +{ +public: + ZstdCompressor() : context(ZSTD_createCCtx()) + { + if (!context) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "Cannot create zstd compression context"); + } + + ~ZstdCompressor() override { ZSTD_freeCCtx(context); } + + size_t compress(const char * src, size_t src_size, std::string & out) override + { + size_t old_size = out.size(); + size_t bound = ZSTD_compressBound(src_size); + out.resize(old_size + bound); + /// Level 1, as in the C++ ORC library with its default compression strategy, "speed". + size_t compressed = ZSTD_compressCCtx(context, out.data() + old_size, bound, src, src_size, 1); + if (ZSTD_isError(compressed)) + throw Exception(ErrorCodes::CANNOT_COMPRESS, "zstd compression failed: {}", ZSTD_getErrorName(compressed)); + return SnappyCompressor::finish(out, old_size, compressed, src_size); + } + +private: + ZSTD_CCtx * context; +}; + +} + + +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size) +{ + /// The ratios are the theoretical maximums of the formats, rounded up, so that valid chunks are never rejected. + /// The sizes stored in the chunks are only trusted below these bounds. + static constexpr size_t SLACK = 1024; + switch (kind) + { + case CompressionKind::NONE: + return src_size; + case CompressionKind::SNAPPY: + { + size_t uncompressed_size = 0; + if (!snappy::GetUncompressedLength(src, src_size, &uncompressed_size)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed snappy-compressed data in ORC file"); + /// A copy of 64 bytes takes at least 3 bytes. + return std::min(uncompressed_size, src_size * 22 + SLACK); + } + case CompressionKind::ZSTD: + { + /// Sums the content sizes of all frames, or 128 KiB per block when a frame omits its size, as in `ArrowIPC/BufferCompression.cpp`. + UInt64 bound = ZSTD_decompressBound(src, src_size); + if (bound == ZSTD_CONTENTSIZE_ERROR) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed zstd-compressed data in ORC file"); + /// A block of at most 128 KiB takes at least 4 bytes (an RLE block). + return std::min(bound, src_size * 32768 + SLACK); + } + /// A deflate match of 258 bytes takes at least 2 bits. + case CompressionKind::ZLIB: + return src_size * 1032 + SLACK; + /// Every byte of a match length extension adds at most 255 bytes. + case CompressionKind::LZ4: + case CompressionKind::LZO: + return src_size * 256 + SLACK; + default: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity) +{ + switch (kind) + { + case CompressionKind::ZLIB: return decompressZlib(src, src_size, dst, dst_capacity); + case CompressionKind::SNAPPY: return decompressSnappy(src, src_size, dst, dst_capacity); + case CompressionKind::LZO: return decompressLzo(src, src_size, dst, dst_capacity); + case CompressionKind::LZ4: return decompressLz4(src, src_size, dst, dst_capacity); + case CompressionKind::ZSTD: return decompressZstd(src, src_size, dst, dst_capacity); + case CompressionKind::NONE: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC compression {} is not supported", compressionKindToString(kind)); +} + +std::unique_ptr createCompressor(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return nullptr; + case CompressionKind::ZLIB: return std::make_unique(); + case CompressionKind::SNAPPY: return std::make_unique(); + case CompressionKind::LZ4: return std::make_unique(); + case CompressionKind::ZSTD: return std::make_unique(); + case CompressionKind::LZO: + case CompressionKind::BROTLI: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC with compression {} is not supported", compressionKindToString(kind)); +} + +String compressionKindToString(CompressionKind kind) +{ + switch (kind) + { + case CompressionKind::NONE: return "NONE"; + case CompressionKind::ZLIB: return "ZLIB"; + case CompressionKind::SNAPPY: return "SNAPPY"; + case CompressionKind::LZO: return "LZO"; + case CompressionKind::LZ4: return "LZ4"; + case CompressionKind::ZSTD: return "ZSTD"; + case CompressionKind::BROTLI: return "BROTLI"; + } + return "UNKNOWN(" + std::to_string(static_cast(kind)) + ")"; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Compression.h b/src/Processors/Formats/Impl/ORC/Compression.h new file mode 100644 index 000000000000..7e0ceddb72a7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Compression.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include +#include + +namespace DB::ORC +{ + +using Proto::CompressionKind; + +/// Every compressed chunk of an ORC stream is prefixed with a 3-byte little-endian header: +/// `(chunk_length << 1) | is_original`, where `is_original` means the chunk is stored as is. +static constexpr size_t COMPRESSION_HEADER_SIZE = 3; + +/// Decompresses one chunk into `dst`, which has room for `dst_capacity` bytes (the compression block +/// size of the file). Returns the decompressed size. Throws `INCORRECT_DATA` on malformed input, +/// including a chunk that decompresses to more than `dst_capacity` bytes. +size_t decompressChunk(CompressionKind kind, const char * src, size_t src_size, char * dst, size_t dst_capacity); + +/// An upper bound of the decompressed size of a chunk, from the maximum compression ratio of the codec +/// (and the size stored in the chunk), to avoid allocating the whole compression block for a small chunk. +size_t maxDecompressedSize(CompressionKind kind, const char * src, size_t src_size); + +/// Compresses chunks of an ORC stream. +class Compressor +{ +public: + virtual ~Compressor() = default; + + /// Appends the compressed representation of `src` to `out` and returns its size, + /// or appends nothing and returns 0 if it would not be smaller than the input. + virtual size_t compress(const char * src, size_t src_size, std::string & out) = 0; +}; + +/// Returns nullptr for `NONE`. +std::unique_ptr createCompressor(CompressionKind kind); + +String compressionKindToString(CompressionKind kind); + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.cpp b/src/Processors/Formats/Impl/ORC/Proto.cpp new file mode 100644 index 000000000000..19e504dfd365 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.cpp @@ -0,0 +1,944 @@ +#include + +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC::Proto +{ + +void WireReader::check(size_t n) const +{ + if (static_cast(end - pos) < n) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated protobuf message in ORC metadata"); +} + +UInt64 WireReader::readVarint() +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + check(1); + UInt8 byte = static_cast(*pos++); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC metadata"); +} + +UInt64 WireReader::readFixed64() +{ + check(8); + UInt64 v = 0; + memcpy(&v, pos, 8); + pos += 8; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +UInt32 WireReader::readFixed32() +{ + check(4); + UInt32 v = 0; + memcpy(&v, pos, 4); + pos += 4; + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + return v; +} + +double WireReader::readDouble() +{ + return std::bit_cast(readFixed64()); +} + +std::string_view WireReader::readBytes() +{ + UInt64 size = readVarint(); + check(size); + std::string_view res(pos, size); + pos += size; + return res; +} + +bool WireReader::nextField(UInt32 & field_number, WireType & wire_type) +{ + if (pos == end) + return false; + UInt64 key = readVarint(); + field_number = static_cast(key >> 3); + wire_type = static_cast(key & 7); + if (field_number == 0 || (key >> 3) > std::numeric_limits::max()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed field key in ORC metadata"); + return true; +} + +void WireReader::skip(WireType wire_type) +{ + switch (wire_type) + { + case VARINT: readVarint(); return; + case FIXED64: check(8); pos += 8; return; + case LENGTH_DELIMITED: readBytes(); return; + case FIXED32: check(4); pos += 4; return; + case START_GROUP: + case END_GROUP: + break; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Unsupported protobuf wire type {} in ORC metadata", static_cast(wire_type)); +} + +bool WireReader::readRepeatedVarint(WireType wire_type, std::vector & out) +{ + if (wire_type == LENGTH_DELIMITED) + { + WireReader packed(readBytes()); + while (packed.pos != packed.end) + out.push_back(packed.readVarint()); + return true; + } + if (wire_type == VARINT) + { + out.push_back(readVarint()); + return true; + } + return false; +} + + +void WireWriter::appendRawVarint(std::string & s, UInt64 value) +{ + while (value >= 0x80) + { + s.push_back(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + s.push_back(static_cast(value)); +} + +void WireWriter::writeVarint(UInt32 field, UInt64 value) +{ + writeKey(field, WireReader::VARINT); + appendRawVarint(out, value); +} + +void WireWriter::writeDouble(UInt32 field, double value) +{ + writeKey(field, WireReader::FIXED64); + UInt64 v = std::bit_cast(value); + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + out.append(reinterpret_cast(&v), 8); +} + +void WireWriter::writeBytes(UInt32 field, std::string_view value) +{ + writeKey(field, WireReader::LENGTH_DELIMITED); + appendRawVarint(out, value.size()); + out.append(value); +} + +void WireWriter::writePackedVarint(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + appendRawVarint(packed, v); + writeBytes(field, packed); +} + +void WireWriter::writePackedFixed64(UInt32 field, const std::vector & values) +{ + if (values.empty()) + return; + std::string packed; + for (UInt64 v : values) + { + if constexpr (std::endian::native == std::endian::big) + v = std::byteswap(v); + packed.append(reinterpret_cast(&v), 8); + } + writeBytes(field, packed); +} + + +namespace +{ + +using WireType = WireReader::WireType; + +/// A field with an unexpected wire type is an unknown field, which the Protocol Buffers rules +/// require to skip. It is detected before anything is read, and handled in `parseMessage`. +struct WireTypeMismatch : std::exception +{ +}; + +void expectWireType(WireType actual, WireType expected) +{ + if (actual != expected) + throw WireTypeMismatch{}; +} + +UInt64 readVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readVarint(); +} + +Int64 readSignedVarintField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + return r.readSignedVarint(); +} + +UInt32 readUInt32Field(WireReader & r, WireType t) +{ + /// Protobuf truncates the 64-bit varint for 32-bit fields. + return static_cast(readVarintField(r, t)); +} + +/// For `sint32` fields. +Int32 readSignedVarint32Field(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::VARINT); + UInt32 v = static_cast(r.readVarint()); + return static_cast((v >> 1) ^ (~(v & 1) + 1)); +} + +double readDoubleField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::FIXED64); + return r.readDouble(); +} + +std::string_view readBytesField(WireReader & r, WireType t) +{ + expectWireType(t, WireReader::LENGTH_DELIMITED); + return r.readBytes(); +} + +void checkCount(size_t count, size_t max_count, std::string_view what) +{ + if (count >= max_count) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many {} in ORC metadata, at most {} expected", what, max_count); +} + +template +void parseMessage(std::string_view data, F && handle_field) +{ + WireReader r(data); + UInt32 field = 0; + WireType type = WireReader::VARINT; + while (r.nextField(field, type)) + { + bool handled = false; + try + { + handled = handle_field(r, field, type); + } + catch (const WireTypeMismatch &) + { + handled = false; + } + if (!handled) + r.skip(type); + } +} + +IntegerStatistics parseIntegerStatistics(std::string_view data) +{ + IntegerStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +DoubleStatistics parseDoubleStatistics(std::string_view data) +{ + DoubleStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readDoubleField(r, type); return true; + case 2: res.maximum = readDoubleField(r, type); return true; + case 3: res.sum = readDoubleField(r, type); return true; + default: return false; + } + }); + return res; +} + +StringStatistics parseStringStatistics(std::string_view data) +{ + StringStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = readSignedVarintField(r, type); return true; + case 4: res.lower_bound = std::string(readBytesField(r, type)); return true; + case 5: res.upper_bound = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +BucketStatistics parseBucketStatistics(std::string_view data) +{ + BucketStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + return r.readRepeatedVarint(type, res.count); + }); + return res; +} + +DecimalStatistics parseDecimalStatistics(std::string_view data) +{ + DecimalStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = std::string(readBytesField(r, type)); return true; + case 2: res.maximum = std::string(readBytesField(r, type)); return true; + case 3: res.sum = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +DateStatistics parseDateStatistics(std::string_view data) +{ + DateStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarint32Field(r, type); return true; + case 2: res.maximum = readSignedVarint32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +TimestampStatistics parseTimestampStatistics(std::string_view data) +{ + TimestampStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.minimum = readSignedVarintField(r, type); return true; + case 2: res.maximum = readSignedVarintField(r, type); return true; + case 3: res.minimum_utc = readSignedVarintField(r, type); return true; + case 4: res.maximum_utc = readSignedVarintField(r, type); return true; + case 5: res.minimum_nanos = readVarintField(r, type); return true; + case 6: res.maximum_nanos = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +BinaryStatistics parseBinaryStatistics(std::string_view data) +{ + BinaryStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + res.sum = readSignedVarintField(r, type); + return true; + }); + return res; +} + +CollectionStatistics parseCollectionStatistics(std::string_view data) +{ + CollectionStatistics res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.min_children = readVarintField(r, type); return true; + case 2: res.max_children = readVarintField(r, type); return true; + case 3: res.total_children = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +Stream parseStream(std::string_view data) +{ + Stream res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: res.column = readUInt32Field(r, type); return true; + case 3: res.length = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +ColumnEncoding parseColumnEncoding(std::string_view data) +{ + ColumnEncoding res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: + { + UInt32 kind = readUInt32Field(r, type); + if (kind > static_cast(ColumnEncodingKind::DICTIONARY_V2)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC column encoding kind {}", kind); + res.kind = static_cast(kind); + return true; + } + case 2: res.dictionary_size = readUInt32Field(r, type); return true; + case 3: res.bloom_encoding = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +Type parseType(std::string_view data) +{ + Type res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.kind = readUInt32Field(r, type); return true; + case 2: return r.readRepeatedVarint(type, res.subtypes); + case 3: res.field_names.emplace_back(readBytesField(r, type)); return true; + case 4: res.maximum_length = readUInt32Field(r, type); return true; + case 5: res.precision = readUInt32Field(r, type); return true; + case 6: res.scale = readUInt32Field(r, type); return true; + case 7: + { + StringPair pair; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: pair.key = std::string(readBytesField(rr, t)); return true; + case 2: pair.value = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + res.attributes.push_back(std::move(pair)); + return true; + } + case 8: res.crs = std::string(readBytesField(r, type)); return true; + case 9: res.algorithm = readUInt32Field(r, type); return true; + default: return false; + } + }); + return res; +} + +StripeInformation parseStripeInformation(std::string_view data) +{ + StripeInformation res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.offset = readVarintField(r, type); return true; + case 2: res.index_length = readVarintField(r, type); return true; + case 3: res.data_length = readVarintField(r, type); return true; + case 4: res.footer_length = readVarintField(r, type); return true; + case 5: res.number_of_rows = readVarintField(r, type); return true; + default: return false; + } + }); + return res; +} + +UserMetadataItem parseUserMetadataItem(std::string_view data) +{ + UserMetadataItem res; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: res.name = std::string(readBytesField(r, type)); return true; + case 2: res.value = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + return res; +} + +std::string serializeIntegerStatistics(const IntegerStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + return out; +} + +std::string serializeDoubleStatistics(const DoubleStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeDouble(1, *s.minimum); + if (s.maximum) w.writeDouble(2, *s.maximum); + if (s.sum) w.writeDouble(3, *s.sum); + return out; +} + +std::string serializeStringStatistics(const StringStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeSignedVarint(3, *s.sum); + if (s.lower_bound) w.writeBytes(4, *s.lower_bound); + if (s.upper_bound) w.writeBytes(5, *s.upper_bound); + return out; +} + +std::string serializeDecimalStatistics(const DecimalStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeBytes(1, *s.minimum); + if (s.maximum) w.writeBytes(2, *s.maximum); + if (s.sum) w.writeBytes(3, *s.sum); + return out; +} + +std::string serializeDateStatistics(const DateStatistics & s) +{ + std::string out; + WireWriter w(out); + auto zigzag32 = [](Int32 v) { return static_cast((static_cast(v) << 1) ^ static_cast(v >> 31)); }; + if (s.minimum) w.writeVarint(1, zigzag32(*s.minimum)); + if (s.maximum) w.writeVarint(2, zigzag32(*s.maximum)); + return out; +} + +std::string serializeTimestampStatistics(const TimestampStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.minimum) w.writeSignedVarint(1, *s.minimum); + if (s.maximum) w.writeSignedVarint(2, *s.maximum); + if (s.minimum_utc) w.writeSignedVarint(3, *s.minimum_utc); + if (s.maximum_utc) w.writeSignedVarint(4, *s.maximum_utc); + /// `int32` fields: negative values are sign-extended to 64 bits. + if (s.minimum_nanos) w.writeVarint(5, *s.minimum_nanos); + if (s.maximum_nanos) w.writeVarint(6, *s.maximum_nanos); + return out; +} + +std::string serializeCollectionStatistics(const CollectionStatistics & s) +{ + std::string out; + WireWriter w(out); + if (s.min_children) w.writeVarint(1, *s.min_children); + if (s.max_children) w.writeVarint(2, *s.max_children); + if (s.total_children) w.writeVarint(3, *s.total_children); + return out; +} + +std::string serializeType(const Type & t) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, t.kind); + w.writePackedVarint(2, t.subtypes); + for (const auto & name : t.field_names) + w.writeBytes(3, name); + if (t.maximum_length) w.writeVarint(4, *t.maximum_length); + if (t.precision) w.writeVarint(5, *t.precision); + if (t.scale) w.writeVarint(6, *t.scale); + for (const auto & attr : t.attributes) + { + std::string pair; + WireWriter pw(pair); + pw.writeBytes(1, attr.key); + pw.writeBytes(2, attr.value); + w.writeBytes(7, pair); + } + if (t.crs) w.writeBytes(8, *t.crs); + if (t.algorithm) w.writeVarint(9, *t.algorithm); + return out; +} + +std::string serializeStripeInformation(const StripeInformation & s) +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, s.offset); + w.writeVarint(2, s.index_length); + w.writeVarint(3, s.data_length); + w.writeVarint(4, s.footer_length); + w.writeVarint(5, s.number_of_rows); + return out; +} + +} + + +void PostScript::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: footer_length = readVarintField(r, type); return true; + case 2: + { + UInt64 kind = readVarintField(r, type); + if (kind > static_cast(CompressionKind::BROTLI)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown ORC compression kind {}", kind); + compression = static_cast(kind); + return true; + } + case 3: compression_block_size = readVarintField(r, type); return true; + case 4: return r.readRepeatedVarint(type, version); + case 5: metadata_length = readVarintField(r, type); return true; + case 6: writer_version = readUInt32Field(r, type); return true; + case 8000: magic = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string PostScript::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, footer_length); + w.writeVarint(2, static_cast(compression)); + w.writeVarint(3, compression_block_size); + w.writePackedVarint(4, version); + w.writeVarint(5, metadata_length); + w.writeVarint(6, writer_version); + w.writeBytes(8000, magic); + return out; +} + +void ColumnStatistics::parse(std::string_view data) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: number_of_values = readVarintField(r, type); return true; + case 2: int_statistics = parseIntegerStatistics(readBytesField(r, type)); return true; + case 3: double_statistics = parseDoubleStatistics(readBytesField(r, type)); return true; + case 4: string_statistics = parseStringStatistics(readBytesField(r, type)); return true; + case 5: bucket_statistics = parseBucketStatistics(readBytesField(r, type)); return true; + case 6: decimal_statistics = parseDecimalStatistics(readBytesField(r, type)); return true; + case 7: date_statistics = parseDateStatistics(readBytesField(r, type)); return true; + case 8: binary_statistics = parseBinaryStatistics(readBytesField(r, type)); return true; + case 9: timestamp_statistics = parseTimestampStatistics(readBytesField(r, type)); return true; + case 10: has_null = readVarintField(r, type) != 0; return true; + case 11: bytes_on_disk = readVarintField(r, type); return true; + case 12: collection_statistics = parseCollectionStatistics(readBytesField(r, type)); return true; + default: return false; + } + }); +} + +std::string ColumnStatistics::serialize() const +{ + std::string out; + WireWriter w(out); + if (number_of_values) w.writeVarint(1, *number_of_values); + if (int_statistics) w.writeBytes(2, serializeIntegerStatistics(*int_statistics)); + if (double_statistics) w.writeBytes(3, serializeDoubleStatistics(*double_statistics)); + if (string_statistics) w.writeBytes(4, serializeStringStatistics(*string_statistics)); + if (bucket_statistics) + { + std::string bucket; + WireWriter(bucket).writePackedVarint(1, bucket_statistics->count); + w.writeBytes(5, bucket); + } + if (decimal_statistics) w.writeBytes(6, serializeDecimalStatistics(*decimal_statistics)); + if (date_statistics) w.writeBytes(7, serializeDateStatistics(*date_statistics)); + if (binary_statistics) + { + std::string binary; + if (binary_statistics->sum) + WireWriter(binary).writeSignedVarint(1, *binary_statistics->sum); + w.writeBytes(8, binary); + } + if (timestamp_statistics) w.writeBytes(9, serializeTimestampStatistics(*timestamp_statistics)); + if (has_null) w.writeVarint(10, *has_null); + if (bytes_on_disk) w.writeVarint(11, *bytes_on_disk); + if (collection_statistics) w.writeBytes(12, serializeCollectionStatistics(*collection_statistics)); + return out; +} + +void RowIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view entry_data = readBytesField(r, type); + checkCount(entry.size(), max_entries, "row index entries"); + auto & e = entry.emplace_back(); + parseMessage(entry_data, [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: return rr.readRepeatedVarint(t, e.positions); + case 2: e.statistics.emplace().parse(readBytesField(rr, t)); return true; + default: return false; + } + }); + return true; + }); +} + +std::string RowIndex::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & e : entry) + { + std::string entry_data; + WireWriter ew(entry_data); + ew.writePackedVarint(1, e.positions); + if (e.statistics) + ew.writeBytes(2, e.statistics->serialize()); + w.writeBytes(1, entry_data); + } + return out; +} + +void BloomFilterIndex::parse(std::string_view data, size_t max_entries) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + checkCount(bloom_filter.size(), max_entries, "bloom filters"); + BloomFilter bf; + parseMessage(readBytesField(r, type), [&](WireReader & rr, UInt32 f, WireType t) + { + switch (f) + { + case 1: bf.num_hash_functions = readUInt32Field(rr, t); return true; + case 2: + { + if (t == WireReader::LENGTH_DELIMITED) + { + /// Packed fixed64: a sequence of 8-byte little-endian values. + std::string_view bytes = rr.readBytes(); + if (bytes.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed bloom filter bitset in ORC file"); + WireReader packed(bytes); + for (size_t i = 0; i < bytes.size() / 8; ++i) + bf.bitset.push_back(packed.readFixed64()); + } + else + { + expectWireType(t, WireReader::FIXED64); + bf.bitset.push_back(rr.readFixed64()); + } + return true; + } + case 3: bf.utf8bitset = std::string(readBytesField(rr, t)); return true; + default: return false; + } + }); + bloom_filter.push_back(std::move(bf)); + return true; + }); +} + +void StripeFooter::parse(std::string_view data, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: streams.push_back(parseStream(readBytesField(r, type))); return true; + case 2: + { + std::string_view encoding_data = readBytesField(r, type); + checkCount(columns.size(), max_columns, "column encodings"); + columns.push_back(parseColumnEncoding(encoding_data)); + return true; + } + case 3: writer_timezone = std::string(readBytesField(r, type)); return true; + case 4: readBytesField(r, type); ++encryption_variants; return true; + default: return false; + } + }); +} + +std::string StripeFooter::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & s : streams) + { + std::string stream; + WireWriter sw(stream); + if (s.kind) + sw.writeVarint(1, *s.kind); + sw.writeVarint(2, s.column); + sw.writeVarint(3, s.length); + w.writeBytes(1, stream); + } + for (const auto & c : columns) + { + std::string encoding; + WireWriter ew(encoding); + ew.writeVarint(1, static_cast(c.kind)); + if (c.kind == ColumnEncodingKind::DICTIONARY || c.kind == ColumnEncodingKind::DICTIONARY_V2) + ew.writeVarint(2, c.dictionary_size); + w.writeBytes(2, encoding); + } + if (writer_timezone) + w.writeBytes(3, *writer_timezone); + return out; +} + +void Metadata::parse(std::string_view data, size_t max_stripes, size_t max_columns) +{ + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + if (field != 1) + return false; + std::string_view stripe_data = readBytesField(r, type); + checkCount(stripe_stats.size(), max_stripes, "stripe statistics"); + StripeStatistics stats; + parseMessage(stripe_data, [&](WireReader & rr, UInt32 f, WireType t) + { + if (f != 1) + return false; + std::string_view column_data = readBytesField(rr, t); + checkCount(stats.col_stats.size(), max_columns, "column statistics"); + stats.col_stats.emplace_back().parse(column_data); + return true; + }); + stripe_stats.push_back(std::move(stats)); + return true; + }); +} + +std::string Metadata::serialize() const +{ + std::string out; + WireWriter w(out); + for (const auto & stats : stripe_stats) + { + std::string stripe; + WireWriter sw(stripe); + for (const auto & col : stats.col_stats) + sw.writeBytes(1, col.serialize()); + w.writeBytes(1, stripe); + } + return out; +} + +void Footer::parse(std::string_view data) +{ + /// The statistics are parsed after the types, to limit their number by the number of columns. + std::vector statistics_data; + parseMessage(data, [&](WireReader & r, UInt32 field, WireType type) + { + switch (field) + { + case 1: header_length = readVarintField(r, type); return true; + case 2: content_length = readVarintField(r, type); return true; + case 3: stripes.push_back(parseStripeInformation(readBytesField(r, type))); return true; + case 4: types.push_back(parseType(readBytesField(r, type))); return true; + case 5: metadata.push_back(parseUserMetadataItem(readBytesField(r, type))); return true; + case 6: number_of_rows = readVarintField(r, type); return true; + case 7: statistics_data.push_back(readBytesField(r, type)); return true; + case 8: row_index_stride = readUInt32Field(r, type); return true; + case 9: writer = readUInt32Field(r, type); return true; + case 10: readBytesField(r, type); has_encryption = true; return true; + case 12: software_version = std::string(readBytesField(r, type)); return true; + default: return false; + } + }); + if (statistics_data.size() > types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many column statistics in ORC footer: {}, the file has {} columns", + statistics_data.size(), types.size()); + statistics.resize(statistics_data.size()); + for (size_t i = 0; i < statistics_data.size(); ++i) + statistics[i].parse(statistics_data[i]); +} + +std::string Footer::serialize() const +{ + std::string out; + WireWriter w(out); + w.writeVarint(1, header_length); + w.writeVarint(2, content_length); + for (const auto & s : stripes) + w.writeBytes(3, serializeStripeInformation(s)); + for (const auto & t : types) + w.writeBytes(4, serializeType(t)); + for (const auto & item : metadata) + { + std::string m; + WireWriter mw(m); + mw.writeBytes(1, item.name); + mw.writeBytes(2, item.value); + w.writeBytes(5, m); + } + w.writeVarint(6, number_of_rows); + for (const auto & s : statistics) + w.writeBytes(7, s.serialize()); + w.writeVarint(8, row_index_stride); + if (writer) + w.writeVarint(9, *writer); + if (software_version) + w.writeBytes(12, *software_version); + return out; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Proto.h b/src/Processors/Formats/Impl/ORC/Proto.h new file mode 100644 index 000000000000..999839f6ab5d --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Proto.h @@ -0,0 +1,343 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +/// Structures of the ORC file metadata, which is serialized with Protocol Buffers. +/// See `orc_proto.proto` in the ORC specification: https://orc.apache.org/specification/ORCv1/ +/// +/// Only the messages and the fields that are used by the reader and the writer are represented. +/// The parser skips the unknown fields, as required by the Protocol Buffers rules, so the files +/// written by newer writers can be read. + +namespace DB::ORC::Proto +{ + +/// Low-level reader of the Protocol Buffers wire format over a contiguous buffer. +/// Throws `INCORRECT_DATA` on a malformed or truncated message. +class WireReader +{ +public: + enum WireType : UInt8 + { + VARINT = 0, + FIXED64 = 1, + LENGTH_DELIMITED = 2, + START_GROUP = 3, + END_GROUP = 4, + FIXED32 = 5, + }; + + WireReader(const char * begin_, const char * end_) : pos(begin_), end(end_) {} + explicit WireReader(std::string_view data) : pos(data.data()), end(data.data() + data.size()) {} + + /// Reads the next field key. Returns false at the end of the message. + bool nextField(UInt32 & field_number, WireType & wire_type); + + UInt64 readVarint(); + Int64 readSignedVarint() { UInt64 v = readVarint(); return static_cast((v >> 1) ^ (~(v & 1) + 1)); } + UInt64 readFixed64(); + UInt32 readFixed32(); + double readDouble(); + std::string_view readBytes(); + + /// Skips a field of the given wire type. + void skip(WireType wire_type); + + /// Reads a scalar field that can be either packed or not packed. + /// Returns false (and reads nothing) if the wire type is not suitable. + [[nodiscard]] bool readRepeatedVarint(WireType wire_type, std::vector & out); + +private: + void check(size_t n) const; + + const char * pos; + const char * end; +}; + +/// Low-level writer of the Protocol Buffers wire format. +class WireWriter +{ +public: + explicit WireWriter(std::string & out_) : out(out_) {} + + void writeVarint(UInt32 field, UInt64 value); + void writeSignedVarint(UInt32 field, Int64 value) { writeVarint(field, (static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeDouble(UInt32 field, double value); + void writeBytes(UInt32 field, std::string_view value); + void writePackedVarint(UInt32 field, const std::vector & values); + void writePackedFixed64(UInt32 field, const std::vector & values); + + static void appendRawVarint(std::string & s, UInt64 value); + +private: + void writeKey(UInt32 field, UInt8 wire_type) { appendRawVarint(out, (static_cast(field) << 3) | wire_type); } + + std::string & out; +}; + + +enum class CompressionKind : UInt8 +{ + NONE = 0, + ZLIB = 1, + SNAPPY = 2, + LZO = 3, + LZ4 = 4, + ZSTD = 5, + BROTLI = 6, +}; + +struct PostScript +{ + UInt64 footer_length = 0; + CompressionKind compression = CompressionKind::NONE; + /// The default value in the specification. + UInt64 compression_block_size = 256 * 1024; + std::vector version; + UInt64 metadata_length = 0; + UInt32 writer_version = 0; + std::string magic; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct IntegerStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DoubleStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct StringStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; + std::optional lower_bound; + std::optional upper_bound; +}; + +struct BucketStatistics +{ + std::vector count; +}; + +struct DecimalStatistics +{ + std::optional minimum; + std::optional maximum; + std::optional sum; +}; + +struct DateStatistics +{ + std::optional minimum; + std::optional maximum; +}; + +struct TimestampStatistics +{ + /// In milliseconds, in the local time zone of the writer (deprecated). + std::optional minimum; + std::optional maximum; + /// In milliseconds since the epoch in UTC. + std::optional minimum_utc; + std::optional maximum_utc; + /// The sub-millisecond part of the nanoseconds plus one, if not zero. Unvalidated when read from a file. + std::optional minimum_nanos; + std::optional maximum_nanos; +}; + +struct BinaryStatistics +{ + std::optional sum; +}; + +struct CollectionStatistics +{ + std::optional min_children; + std::optional max_children; + std::optional total_children; +}; + +struct ColumnStatistics +{ + std::optional number_of_values; + std::optional int_statistics; + std::optional double_statistics; + std::optional string_statistics; + std::optional bucket_statistics; + std::optional decimal_statistics; + std::optional date_statistics; + std::optional binary_statistics; + std::optional timestamp_statistics; + std::optional has_null; + std::optional bytes_on_disk; + std::optional collection_statistics; + + void parse(std::string_view data); + std::string serialize() const; +}; + +struct RowIndexEntry +{ + std::vector positions; + std::optional statistics; +}; + +struct RowIndex +{ + std::vector entry; + + /// The limits of the number of the repeated objects keep a small malformed message from allocating much memory. + void parse(std::string_view data, size_t max_entries); + std::string serialize() const; +}; + +struct BloomFilter +{ + UInt32 num_hash_functions = 0; + std::vector bitset; + std::optional utf8bitset; +}; + +struct BloomFilterIndex +{ + std::vector bloom_filter; + + void parse(std::string_view data, size_t max_entries); +}; + +enum class StreamKind : UInt32 +{ + PRESENT = 0, + DATA = 1, + LENGTH = 2, + DICTIONARY_DATA = 3, + DICTIONARY_COUNT = 4, + SECONDARY = 5, + ROW_INDEX = 6, + BLOOM_FILTER = 7, + BLOOM_FILTER_UTF8 = 8, + ENCRYPTED_INDEX = 9, + ENCRYPTED_DATA = 10, + STRIPE_STATISTICS = 100, + FILE_STATISTICS = 101, +}; + +struct Stream +{ + std::optional kind; + UInt32 column = 0; + UInt64 length = 0; +}; + +enum class ColumnEncodingKind : UInt32 +{ + DIRECT = 0, + DICTIONARY = 1, + DIRECT_V2 = 2, + DICTIONARY_V2 = 3, +}; + +struct ColumnEncoding +{ + ColumnEncodingKind kind = ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; + /// 1 means the bloom filters use UTF-8 for the strings and UTC for the timestamps. + std::optional bloom_encoding; +}; + +struct StripeFooter +{ + std::vector streams; + std::vector columns; + std::optional writer_timezone; + /// Non-zero if the stripe has encrypted columns, which are not supported. + size_t encryption_variants = 0; + + void parse(std::string_view data, size_t max_columns); + std::string serialize() const; +}; + +struct StringPair +{ + std::string key; + std::string value; +}; + +struct Type +{ + UInt32 kind = 0; + std::vector subtypes; + std::vector field_names; + std::optional maximum_length; + std::optional precision; + std::optional scale; + std::vector attributes; + /// Only for GEOMETRY and GEOGRAPHY. + std::optional crs; + std::optional algorithm; +}; + +struct StripeInformation +{ + UInt64 offset = 0; + UInt64 index_length = 0; + UInt64 data_length = 0; + UInt64 footer_length = 0; + UInt64 number_of_rows = 0; +}; + +struct UserMetadataItem +{ + std::string name; + std::string value; +}; + +struct StripeStatistics +{ + std::vector col_stats; +}; + +struct Metadata +{ + std::vector stripe_stats; + + void parse(std::string_view data, size_t max_stripes, size_t max_columns); + std::string serialize() const; +}; + +struct Footer +{ + UInt64 header_length = 0; + UInt64 content_length = 0; + std::vector stripes; + std::vector types; + std::vector metadata; + UInt64 number_of_rows = 0; + std::vector statistics; + UInt32 row_index_stride = 0; + std::optional writer; + bool has_encryption = false; + std::optional software_version; + + void parse(std::string_view data); + std::string serialize() const; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.cpp b/src/Processors/Formats/Impl/ORC/RLE.cpp new file mode 100644 index 000000000000..7b9762e32de3 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.cpp @@ -0,0 +1,1129 @@ +#include + +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +namespace +{ + +inline Int64 unZigZag(UInt64 value) +{ + return static_cast((value >> 1) ^ (~(value & 1) + 1)); +} + +inline UInt64 zigZag(Int64 value) +{ + return (static_cast(value) << 1) ^ static_cast(value >> 63); +} + +/// The 5-bit codes of the bit widths in RLE v2. +constexpr UInt8 code_to_bit_width[32] = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30, 32, 40, 48, 56, 64}; + +/// The smallest bit width representable in RLE v2 that fits the given number of bits. +constexpr UInt8 closest_fixed_bits[65] = { + 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 26, 26, 28, 28, 30, 30, 32, 32, 40, 40, 40, 40, 40, 40, 40, 40, 48, 48, 48, + 48, 48, 48, 48, 48, 56, 56, 56, 56, 56, 56, 56, 56, 64, 64, 64, 64, 64, 64, 64, 64}; + +inline UInt32 decodeBitWidth(UInt32 code) +{ + return code_to_bit_width[code & 0x1F]; +} + +inline UInt32 getClosestFixedBits(UInt32 n) +{ + return n <= 64 ? closest_fixed_bits[n] : 64; +} + +inline UInt32 encodeBitWidth(UInt32 width) +{ + width = getClosestFixedBits(width); + if (width <= 24) + return width - 1; + switch (width) + { + case 26: return 24; + case 28: return 25; + case 30: return 26; + case 32: return 27; + case 40: return 28; + case 48: return 29; + case 56: return 30; + default: return 31; + } +} + +/// The number of bits required to represent the value, rounded to a representable bit width. +/// Negative values require 64 bits. +inline UInt32 findClosestNumBits(Int64 value) +{ + if (value < 0) + return 64; + UInt32 count = 64 - static_cast(std::countl_zero(static_cast(value))); + return getClosestFixedBits(count); +} + +} + + +UInt64 readVarint(InputByteStream & stream) +{ + UInt64 result = 0; + for (size_t shift = 0; shift < 64; shift += 7) + { + UInt8 byte = stream.readByte(); + result |= static_cast(byte & 0x7F) << shift; + if (!(byte & 0x80)) + return result; + } + throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed varint in ORC stream {}", stream.getName()); +} + +Int64 readSignedVarint(InputByteStream & stream) +{ + return unZigZag(readVarint(stream)); +} + + +void ByteRleDecoder::readHeader() +{ + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + value = static_cast(stream->readByte()); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } +} + +void ByteRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + if (not_null) + memset(data, 0, num_values); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + if (repeating) + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = value; + ++consumed; + } + } + } + else + { + memset(data + position, value, count); + consumed = count; + } + } + else + { + if (not_null) + { + for (size_t i = 0; i < count; ++i) + { + if (not_null[position + i]) + { + data[position + i] = static_cast(stream->readByte()); + ++consumed; + } + } + } + else + { + stream->readBytes(data + position, count); + consumed = count; + } + } + remaining_values -= consumed; + position += count; + } +} + +void ByteRleDecoder::skip(size_t num_values) +{ + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (!repeating) + stream->skipBytes(count); + } +} + +void ByteRleDecoder::seek(PositionProvider & positions) +{ + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); +} + + +void BooleanRleDecoder::next(char * data, size_t num_values, const char * not_null) +{ + for (size_t i = 0; i < num_values; ++i) + { + if (not_null && !not_null[i]) + { + /// The PRESENT stream of a child column is read with the mask of its parent, + /// and the masked positions must be null. + data[i] = 0; + continue; + } + if (remaining_bits == 0) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8; + } + --remaining_bits; + data[i] = (last_byte >> remaining_bits) & 1; + } +} + +void BooleanRleDecoder::skip(size_t num_values) +{ + if (num_values <= remaining_bits) + { + remaining_bits -= num_values; + return; + } + num_values -= remaining_bits; + byte_decoder.skip(num_values / 8); + if (num_values % 8) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - num_values % 8; + } + else + remaining_bits = 0; +} + +void BooleanRleDecoder::seek(PositionProvider & positions) +{ + byte_decoder.seek(positions); + UInt64 consumed = positions.next(); + remaining_bits = 0; + if (consumed > 8) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid seek position {} of a boolean stream in ORC file", consumed); + if (consumed) + { + char byte = 0; + byte_decoder.next(&byte, 1, nullptr); + last_byte = static_cast(byte); + remaining_bits = 8 - consumed; + } +} + + +namespace +{ + +class IntRleDecoderV1 final : public IntRleDecoder +{ +public: + IntRleDecoderV1(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (remaining_values == 0) + readHeader(); + + size_t count = std::min(num_values - position, remaining_values); + size_t consumed = 0; + for (size_t i = 0; i < count; ++i) + { + if (not_null && !not_null[position + i]) + continue; + if (repeating) + { + data[position + i] = static_cast(value); + value = static_cast(static_cast(value) + static_cast(delta)); + } + else + data[position + i] = static_cast(readValue()); + ++consumed; + } + remaining_values -= consumed; + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (remaining_values == 0) + readHeader(); + size_t count = std::min(num_values, remaining_values); + remaining_values -= count; + num_values -= count; + if (repeating) + value = static_cast(static_cast(value) + static_cast(delta) * count); + else + for (size_t i = 0; i < count; ++i) + readVarint(*stream); + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + remaining_values = 0; + skip(positions.next()); + } + +private: + Int64 readValue() + { + return is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + } + + void readHeader() + { + Int8 header = static_cast(stream->readByte()); + if (header >= 0) + { + repeating = true; + remaining_values = static_cast(header) + 3; + delta = static_cast(stream->readByte()); + value = readValue(); + } + else + { + repeating = false; + remaining_values = static_cast(-static_cast(header)); + } + } + + std::unique_ptr stream; + const bool is_signed; + size_t remaining_values = 0; + bool repeating = false; + Int64 value = 0; + Int64 delta = 0; +}; + + +class IntRleDecoderV2 final : public IntRleDecoder +{ +public: + IntRleDecoderV2(std::unique_ptr stream_, bool is_signed_) : stream(std::move(stream_)), is_signed(is_signed_) {} + + void next(Int64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(UInt64 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int32 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + void next(Int16 * data, size_t num_values, const char * not_null) override { nextImpl(data, num_values, not_null); } + + template + void nextImpl(T * data, size_t num_values, const char * not_null) + { + if (not_null) + memset(static_cast(data), 0, num_values * sizeof(T)); + size_t position = 0; + while (position < num_values) + { + if (not_null) + { + while (position < num_values && !not_null[position]) + ++position; + if (position == num_values) + return; + } + + if (run_read == run_length) + readRun(); + + size_t count = std::min(num_values - position, run_length - run_read); + if (not_null) + { + for (size_t i = position; i < position + count; ++i) + if (not_null[i]) + data[i] = static_cast(literals[run_read++]); + } + else if constexpr (sizeof(T) == sizeof(Int64)) + { + memcpy(static_cast(data + position), literals.data() + run_read, count * sizeof(Int64)); + run_read += count; + } + else + { + for (size_t i = 0; i < count; ++i) + data[position + i] = static_cast(literals[run_read + i]); + run_read += count; + } + position += count; + } + } + + void skip(size_t num_values) override + { + while (num_values) + { + if (run_read == run_length) + readRun(); + size_t count = std::min(num_values, run_length - run_read); + run_read += count; + num_values -= count; + } + } + + void seek(PositionProvider & positions) override + { + stream->seek(positions); + run_read = run_length = 0; + skip(positions.next()); + } + +private: + enum EncodingType : UInt8 + { + SHORT_REPEAT = 0, + DIRECT = 1, + PATCHED_BASE = 2, + DELTA = 3, + }; + + Int64 readLongBE(size_t num_bytes) + { + UInt64 result = 0; + for (size_t i = 0; i < num_bytes; ++i) + result = (result << 8) | stream->readByte(); + return static_cast(result); + } + + template + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count) + { + for (size_t i = 0; i < count; ++i, in += num_bytes) + { + UInt64 value = 0; + for (size_t j = 0; j < num_bytes; ++j) + value = (value << 8) | in[j]; + out[i] = static_cast(value); + } + } + + static void decodeBigEndian(const UInt8 * in, Int64 * out, size_t count, size_t num_bytes) + { + switch (num_bytes) + { + case 1: decodeBigEndian<1>(in, out, count); return; + case 2: decodeBigEndian<2>(in, out, count); return; + case 3: decodeBigEndian<3>(in, out, count); return; + case 4: decodeBigEndian<4>(in, out, count); return; + case 5: decodeBigEndian<5>(in, out, count); return; + case 6: decodeBigEndian<6>(in, out, count); return; + case 7: decodeBigEndian<7>(in, out, count); return; + default: decodeBigEndian<8>(in, out, count); return; + } + } + + /// The only bit widths that are not a multiple of 8 are at most 30. + template + static void decodeBitPacked(Int64 * out, size_t count, UInt32 bit_width, ReadByte && read_byte) + { + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + while (bits_in_buffer < bit_width) + { + buffer = (buffer << 8) | read_byte(); + bits_in_buffer += 8; + } + bits_in_buffer -= bit_width; + out[i] = static_cast((buffer >> bits_in_buffer) & mask); + } + } + + /// Reads `count` bit-packed values of `bit_width` bits, starting and ending at a byte boundary. + void readInts(Int64 * out, size_t count, UInt32 bit_width) + { + if (bit_width % 8 == 0) + { + const size_t num_bytes = bit_width / 8; + while (count) + { + /// Decode the values that are entirely in the current chunk directly from it. + size_t in_chunk = std::min(count, static_cast(stream->end - stream->pos) / num_bytes); + if (in_chunk == 0) + { + *out = readLongBE(num_bytes); + ++out; + --count; + continue; + } + decodeBigEndian(reinterpret_cast(stream->pos), out, in_chunk, num_bytes); + stream->pos += in_chunk * num_bytes; + out += in_chunk; + count -= in_chunk; + } + return; + } + + const size_t total_bytes = (count * bit_width + 7) / 8; + if (static_cast(stream->end - stream->pos) >= total_bytes) + { + const UInt8 * in = reinterpret_cast(stream->pos); + decodeBitPacked(out, count, bit_width, [&] { return *in++; }); + stream->pos += total_bytes; + } + else + { + decodeBitPacked(out, count, bit_width, [&] { return stream->readByte(); }); + } + } + + void readRun() + { + UInt8 first_byte = stream->readByte(); + auto encoding = static_cast(first_byte >> 6); + run_read = 0; + switch (encoding) + { + case SHORT_REPEAT: + { + size_t num_bytes = ((first_byte >> 3) & 0x07) + 1; + run_length = (first_byte & 0x07) + 3; + Int64 value = readLongBE(num_bytes); + if (is_signed) + value = unZigZag(static_cast(value)); + std::fill(literals.begin(), literals.begin() + run_length, value); + break; + } + case DIRECT: + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + readInts(literals.data(), run_length, bit_width); + if (is_signed) + for (size_t i = 0; i < run_length; ++i) + literals[i] = unZigZag(static_cast(literals[i])); + break; + } + case PATCHED_BASE: + readPatchedBase(first_byte); + break; + case DELTA: + readDelta(first_byte); + break; + } + } + + void readPatchedBase(UInt8 first_byte) + { + UInt32 bit_width = decodeBitWidth((first_byte >> 1) & 0x1F); + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + UInt8 third_byte = stream->readByte(); + size_t base_bytes = ((third_byte >> 5) & 0x07) + 1; + UInt32 patch_bit_width = decodeBitWidth(third_byte & 0x1F); + + UInt8 fourth_byte = stream->readByte(); + UInt32 patch_gap_width = ((fourth_byte >> 5) & 0x07) + 1; + size_t patch_list_length = fourth_byte & 0x1F; + if (patch_list_length == 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (empty patch list)", stream->getName()); + + Int64 base = readLongBE(base_bytes); + Int64 sign_mask = static_cast(1ULL << (base_bytes * 8 - 1)); + if (base & sign_mask) + { + base &= ~sign_mask; + base = -base; + } + + readInts(literals.data(), run_length, bit_width); + + if (patch_bit_width + patch_gap_width > 64) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Corrupt PATCHED_BASE encoded data in ORC stream {} (patch width + patch gap width > 64)", stream->getName()); + + Int64 patches[32]; + readInts(patches, patch_list_length, getClosestFixedBits(patch_bit_width + patch_gap_width)); + + const Int64 patch_mask = patch_bit_width >= 64 ? -1 : static_cast((1ULL << patch_bit_width) - 1); + size_t patch_index = 0; + Int64 gap = 0; + Int64 patch = 0; + + auto adjust_gap_and_patch = [&] + { + UInt64 current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + Int64 actual_gap = 0; + /// A gap of 255 with a zero patch means that the gap continues in the next entry. + while (current_gap == 255 && patch == 0) + { + actual_gap += 255; + ++patch_index; + if (patch_index >= patch_list_length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Corrupt PATCHED_BASE encoded data in ORC stream {} (unterminated gap)", stream->getName()); + current_gap = static_cast(patches[patch_index]) >> patch_bit_width; + patch = patches[patch_index] & patch_mask; + } + gap = actual_gap + static_cast(current_gap); + }; + + adjust_gap_and_patch(); + for (size_t i = 0; i < run_length; ++i) + { + if (static_cast(i) != gap) + { + literals[i] = static_cast(static_cast(literals[i]) + static_cast(base)); + } + else + { + UInt64 patched = static_cast(literals[i]) | (bit_width < 64 ? static_cast(patch) << bit_width : 0); + literals[i] = static_cast(static_cast(base) + patched); + ++patch_index; + if (patch_index < patch_list_length) + { + adjust_gap_and_patch(); + /// The next gap is relative to the current position. + gap += static_cast(i); + } + } + } + } + + void readDelta(UInt8 first_byte) + { + UInt32 code = (first_byte >> 1) & 0x1F; + UInt32 bit_width = code ? decodeBitWidth(code) : 0; + run_length = ((static_cast(first_byte & 0x01) << 8) | stream->readByte()) + 1; + + Int64 first_value = is_signed ? readSignedVarint(*stream) : static_cast(readVarint(*stream)); + literals[0] = first_value; + Int64 delta_base = readSignedVarint(*stream); + + if (bit_width == 0) + { + /// Fixed delta. + for (size_t i = 1; i < run_length; ++i) + literals[i] = static_cast(static_cast(literals[i - 1]) + static_cast(delta_base)); + return; + } + + if (run_length < 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal run length {} for delta encoding in ORC stream {}", run_length, stream->getName()); + + Int64 previous = static_cast(static_cast(first_value) + static_cast(delta_base)); + literals[1] = previous; + readInts(literals.data() + 2, run_length - 2, bit_width); + for (size_t i = 2; i < run_length; ++i) + { + if (delta_base < 0) + previous = static_cast(static_cast(previous) - static_cast(literals[i])); + else + previous = static_cast(static_cast(previous) + static_cast(literals[i])); + literals[i] = previous; + } + } + + std::unique_ptr stream; + const bool is_signed; + std::array literals{}; + size_t run_length = 0; + size_t run_read = 0; +}; + +} + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version) +{ + if (version == RleVersion::V1) + return std::make_unique(std::move(stream), is_signed); + return std::make_unique(std::move(stream), is_signed); +} + + +void ByteRleEncoder::writeValues() +{ + if (num_literals == 0) + return; + if (repeat) + { + stream.writeByte(static_cast(num_literals - MIN_REPEAT)); + stream.writeByte(static_cast(literals[0])); + } + else + { + stream.writeByte(static_cast(-static_cast(num_literals))); + stream.write(literals, num_literals); + } + repeat = false; + tail_run_length = 0; + num_literals = 0; +} + +void ByteRleEncoder::write(char value) +{ + if (num_literals == 0) + { + literals[num_literals++] = value; + tail_run_length = 1; + } + else if (repeat) + { + if (value == literals[0]) + { + ++num_literals; + if (num_literals == MAX_REPEAT_SIZE) + writeValues(); + } + else + { + writeValues(); + literals[num_literals++] = value; + tail_run_length = 1; + } + } + else + { + if (value == literals[num_literals - 1]) + ++tail_run_length; + else + tail_run_length = 1; + + if (tail_run_length == MIN_REPEAT) + { + if (num_literals + 1 == MIN_REPEAT) + { + repeat = true; + ++num_literals; + } + else + { + num_literals -= MIN_REPEAT - 1; + writeValues(); + literals[0] = value; + repeat = true; + num_literals = MIN_REPEAT; + } + } + else + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + writeValues(); + } + } +} + +void ByteRleEncoder::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void ByteRleEncoder::flush() +{ + writeValues(); +} + + +void BooleanRleEncoder::write(bool value) +{ + current = static_cast((current << 1) | (value ? 1 : 0)); + ++bits_in_current; + if (bits_in_current == 8) + { + byte_encoder.write(static_cast(current)); + current = 0; + bits_in_current = 0; + } +} + +void BooleanRleEncoder::recordPosition(std::vector & positions) const +{ + byte_encoder.recordPosition(positions); + positions.push_back(bits_in_current); +} + +void BooleanRleEncoder::flush() +{ + if (bits_in_current) + { + byte_encoder.write(static_cast(current << (8 - bits_in_current))); + current = 0; + bits_in_current = 0; + } + byte_encoder.flush(); +} + + +void IntRleEncoderV2::recordPosition(std::vector & positions) const +{ + stream.recordPosition(positions); + positions.push_back(num_literals); +} + +void IntRleEncoderV2::flush() +{ + size_t literal_start = 0; + size_t i = 0; + while (i < num_literals) + { + size_t j = i + 1; + while (j < num_literals && literals[j] == literals[i]) + ++j; + if (j - i >= 3) + { + if (literal_start < i) + encodeLiterals(literals + literal_start, i - literal_start); + encodeRepeat(literals[i], j - i); + literal_start = j; + } + i = j; + } + if (literal_start < num_literals) + encodeLiterals(literals + literal_start, num_literals - literal_start); + num_literals = 0; +} + +void IntRleEncoderV2::writeVarint(UInt64 value) +{ + while (value >= 0x80) + { + stream.writeByte(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + stream.writeByte(static_cast(value)); +} + +void IntRleEncoderV2::writeInts(const Int64 * values, size_t count, UInt32 bit_width) +{ + if (bit_width % 8 == 0) + { + size_t num_bytes = bit_width / 8; + for (size_t i = 0; i < count; ++i) + { + UInt64 v = static_cast(values[i]); + for (size_t b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(v >> ((b - 1) * 8))); + } + return; + } + + UInt64 buffer = 0; + UInt32 bits_in_buffer = 0; + const UInt64 mask = (1ULL << bit_width) - 1; + for (size_t i = 0; i < count; ++i) + { + buffer = (buffer << bit_width) | (static_cast(values[i]) & mask); + bits_in_buffer += bit_width; + while (bits_in_buffer >= 8) + { + bits_in_buffer -= 8; + stream.writeByte(static_cast(buffer >> bits_in_buffer)); + } + } + if (bits_in_buffer) + stream.writeByte(static_cast(buffer << (8 - bits_in_buffer))); +} + +void IntRleEncoderV2::encodeRepeat(Int64 value, size_t count) +{ + UInt64 encoded = is_signed ? zigZag(value) : static_cast(value); + if (count <= 10) + { + /// SHORT_REPEAT + UInt32 bits = findClosestNumBits(static_cast(encoded)); + UInt32 num_bytes = (bits + 7) / 8; + stream.writeByte(static_cast(((num_bytes - 1) << 3) | (count - 3))); + for (UInt32 b = num_bytes; b > 0; --b) + stream.writeByte(static_cast(encoded >> ((b - 1) * 8))); + return; + } + + /// DELTA with zero fixed delta. + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeVarint(encoded); + writeSignedVarint(0); +} + +void IntRleEncoderV2::writeDirect(const Int64 * values, size_t count) +{ + Int64 encoded[MAX_LITERAL_SIZE]; + UInt32 bit_width = 1; + for (size_t i = 0; i < count; ++i) + { + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + bit_width = std::max(bit_width, findClosestNumBits(encoded[i])); + } + size_t length = count - 1; + stream.writeByte(static_cast((1 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + writeInts(encoded, count, bit_width); +} + +namespace +{ + +/// The bit width that is enough for the given fraction `p` of the values (as in the reference implementation). +UInt32 percentileBits(const Int64 * values, size_t count, double p) +{ + UInt32 histogram[32] = {}; + for (size_t i = 0; i < count; ++i) + ++histogram[encodeBitWidth(findClosestNumBits(values[i]))]; + + Int64 per_len = static_cast(static_cast(count) * (1.0 - p)); + for (Int32 i = 31; i >= 0; --i) + { + per_len -= histogram[i]; + if (per_len < 0) + return decodeBitWidth(i); + } + return 0; +} + +} + +void IntRleEncoderV2::encodeLiterals(const Int64 * values, size_t count) +{ + if (count <= 3) + { + writeDirect(values, count); + return; + } + + Int64 min = values[0]; + Int64 max = values[0]; + bool is_increasing = true; + bool is_decreasing = true; + bool is_fixed_delta = true; + bool deltas_overflow = false; + Int64 initial_delta = 0; + if (__builtin_sub_overflow(values[1], values[0], &initial_delta)) + deltas_overflow = true; + + /// Absolute values of the deltas, starting from the second one. + Int64 abs_deltas[MAX_LITERAL_SIZE]; + UInt64 max_abs_delta = 0; + + for (size_t i = 1; i < count; ++i) + { + min = std::min(min, values[i]); + max = std::max(max, values[i]); + is_increasing &= values[i - 1] <= values[i]; + is_decreasing &= values[i - 1] >= values[i]; + + Int64 delta = 0; + if (__builtin_sub_overflow(values[i], values[i - 1], &delta)) + { + deltas_overflow = true; + is_fixed_delta = false; + continue; + } + is_fixed_delta &= (delta == initial_delta); + if (i > 1) + { + UInt64 abs_delta = delta < 0 ? (0 - static_cast(delta)) : static_cast(delta); + abs_deltas[i - 2] = static_cast(abs_delta); + max_abs_delta = std::max(max_abs_delta, abs_delta); + } + } + + Int64 range = 0; + if (__builtin_sub_overflow(max, min, &range)) + { + writeDirect(values, count); + return; + } + + if (!deltas_overflow && is_fixed_delta) + { + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + return; + } + + if (!deltas_overflow && initial_delta != 0 && (is_increasing || is_decreasing) + && max_abs_delta <= static_cast(std::numeric_limits::max())) + { + UInt32 bit_width = findClosestNumBits(static_cast(max_abs_delta)); + /// The bit width code 0 means a fixed delta, so the width 1 is not representable. + if (bit_width == 1) + bit_width = 2; + size_t length = count - 1; + stream.writeByte(static_cast((3 << 6) | (encodeBitWidth(bit_width) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + if (is_signed) + writeSignedVarint(values[0]); + else + writeVarint(static_cast(values[0])); + writeSignedVarint(initial_delta); + writeInts(abs_deltas, count - 2, bit_width); + return; + } + + /// DIRECT or PATCHED_BASE. + Int64 encoded[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + encoded[i] = is_signed ? static_cast(zigZag(values[i])) : values[i]; + + UInt32 bits_100p = percentileBits(encoded, count, 1.0); + UInt32 bits_90p = percentileBits(encoded, count, 0.9); + + static constexpr Int64 BASE_VALUE_LIMIT = 1LL << 56; + if (bits_100p - bits_90p <= 1 || min <= -BASE_VALUE_LIMIT || min >= BASE_VALUE_LIMIT) + { + writeDirect(values, count); + return; + } + + Int64 base_reduced[MAX_LITERAL_SIZE]; + for (size_t i = 0; i < count; ++i) + base_reduced[i] = values[i] - min; + + UInt32 br_bits_95p = percentileBits(base_reduced, count, 0.95); + UInt32 br_bits_100p = percentileBits(base_reduced, count, 1.0); + if (br_bits_100p == br_bits_95p) + { + writeDirect(values, count); + return; + } + + UInt32 patch_width = getClosestFixedBits(br_bits_100p - br_bits_95p); + if (patch_width == 64) + { + patch_width = 56; + br_bits_95p = 8; + } + const Int64 mask = static_cast((1ULL << br_bits_95p) - 1); + + size_t gaps[MAX_LITERAL_SIZE]; + Int64 patches[MAX_LITERAL_SIZE]; + size_t num_patches = 0; + size_t previous = 0; + size_t max_gap = 0; + for (size_t i = 0; i < count; ++i) + { + if (base_reduced[i] > mask) + { + size_t gap = i - previous; + max_gap = std::max(max_gap, gap); + previous = i; + gaps[num_patches] = gap; + patches[num_patches] = base_reduced[i] >> br_bits_95p; + ++num_patches; + base_reduced[i] &= mask; + } + } + + UInt32 patch_gap_width = (max_gap == 0) ? 1 : findClosestNumBits(static_cast(max_gap)); + patch_gap_width = std::min(patch_gap_width, 8u); + + Int64 patch_list[MAX_LITERAL_SIZE]; + size_t patch_list_length = 0; + for (size_t p = 0; p < num_patches; ++p) + { + size_t gap = gaps[p]; + while (gap > 255) + { + patch_list[patch_list_length++] = static_cast(255ULL << patch_width); + gap -= 255; + } + patch_list[patch_list_length++] = static_cast((static_cast(gap) << patch_width) | static_cast(patches[p])); + } + + /// The length of the patch list is stored in 5 bits. + if (patch_list_length > 31) + { + writeDirect(values, count); + return; + } + + bool is_negative = min < 0; + UInt64 base = is_negative ? static_cast(-min) : static_cast(min); + UInt32 base_width = findClosestNumBits(static_cast(base)) + 1; + UInt32 base_bytes = (base_width + 7) / 8; + if (is_negative) + base |= 1ULL << (base_bytes * 8 - 1); + + size_t length = count - 1; + stream.writeByte(static_cast((2 << 6) | (encodeBitWidth(br_bits_95p) << 1) | ((length >> 8) & 1))); + stream.writeByte(static_cast(length & 0xFF)); + stream.writeByte(static_cast(((base_bytes - 1) << 5) | encodeBitWidth(patch_width))); + stream.writeByte(static_cast(((patch_gap_width - 1) << 5) | patch_list_length)); + for (UInt32 b = base_bytes; b > 0; --b) + stream.writeByte(static_cast(base >> ((b - 1) * 8))); + writeInts(base_reduced, count, getClosestFixedBits(br_bits_95p)); + writeInts(patch_list, patch_list_length, getClosestFixedBits(patch_gap_width + patch_width)); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/RLE.h b/src/Processors/Formats/Impl/ORC/RLE.h new file mode 100644 index 000000000000..c5212bf5fbf6 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/RLE.h @@ -0,0 +1,151 @@ +#pragma once + +#include + +#include +#include + +/// Run-length encodings of ORC: https://orc.apache.org/specification/ORCv1/#run-length-encoding +/// +/// All decoders fill the positions where `not_null` is non-zero (or all positions if it is +/// nullptr), consuming one value from the stream for each of them; the other positions are set to zero. + +namespace DB::ORC +{ + +/// Byte run-length encoding, used for the bytes and for the booleans (packed into bytes). +class ByteRleDecoder +{ +public: + explicit ByteRleDecoder(std::unique_ptr stream_) : stream(std::move(stream_)) {} + + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + void readHeader(); + + std::unique_ptr stream; + size_t remaining_values = 0; + bool repeating = false; + char value = 0; +}; + +/// Booleans packed into bytes, most significant bit first, encoded with the byte run-length encoding. +class BooleanRleDecoder +{ +public: + explicit BooleanRleDecoder(std::unique_ptr stream_) : byte_decoder(std::move(stream_)) {} + + /// Writes 0 or 1. + void next(char * data, size_t num_values, const char * not_null); + void skip(size_t num_values); + void seek(PositionProvider & positions); + +private: + ByteRleDecoder byte_decoder; + size_t remaining_bits = 0; + UInt8 last_byte = 0; +}; + +/// Integer run-length encodings, version 1 and 2. +class IntRleDecoder +{ +public: + virtual ~IntRleDecoder() = default; + /// The values are converted to the type of the output, which can be narrower than the encoded values. + virtual void next(Int64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(UInt64 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int32 * data, size_t num_values, const char * not_null) = 0; + virtual void next(Int16 * data, size_t num_values, const char * not_null) = 0; + virtual void skip(size_t num_values) = 0; + virtual void seek(PositionProvider & positions) = 0; +}; + +enum class RleVersion : UInt8 +{ + V1, + V2, +}; + +std::unique_ptr createIntRleDecoder(std::unique_ptr stream, bool is_signed, RleVersion version); + +/// Reads a base 128 varint, as used by the DECIMAL columns. +UInt64 readVarint(InputByteStream & stream); +Int64 readSignedVarint(InputByteStream & stream); + + +class ByteRleEncoder +{ +public: + explicit ByteRleEncoder(OutputByteStream & stream_) : stream(stream_) {} + + void write(char value); + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + +private: + void writeValues(); + + static constexpr size_t MIN_REPEAT = 3; + static constexpr size_t MAX_LITERAL_SIZE = 128; + static constexpr size_t MAX_REPEAT_SIZE = 127 + MIN_REPEAT; + + OutputByteStream & stream; + char literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; + size_t tail_run_length = 0; + bool repeat = false; +}; + +class BooleanRleEncoder +{ +public: + explicit BooleanRleEncoder(OutputByteStream & stream_) : byte_encoder(stream_) {} + + void write(bool value); + void recordPosition(std::vector & positions) const; + void flush(); + +private: + ByteRleEncoder byte_encoder; + UInt8 current = 0; + size_t bits_in_current = 0; +}; + +/// Integer run-length encoding, version 2. +class IntRleEncoderV2 +{ +public: + IntRleEncoderV2(OutputByteStream & stream_, bool is_signed_) : stream(stream_), is_signed(is_signed_) {} + + void write(Int64 value) + { + literals[num_literals++] = value; + if (num_literals == MAX_LITERAL_SIZE) + flush(); + } + + void recordPosition(std::vector & positions) const; + /// Writes out the buffered values. + void flush(); + + static constexpr size_t MAX_LITERAL_SIZE = 512; + +private: + void encodeLiterals(const Int64 * values, size_t count); + void encodeRepeat(Int64 value, size_t count); + void writeDirect(const Int64 * values, size_t count); + void writeVarint(UInt64 value); + void writeSignedVarint(Int64 value) { writeVarint((static_cast(value) << 1) ^ static_cast(value >> 63)); } + void writeInts(const Int64 * values, size_t count, UInt32 bit_width); + + OutputByteStream & stream; + const bool is_signed; + Int64 literals[MAX_LITERAL_SIZE]{}; + size_t num_literals = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.cpp b/src/Processors/Formats/Impl/ORC/Reader.cpp new file mode 100644 index 000000000000..76c6a432d1b0 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.cpp @@ -0,0 +1,842 @@ +#include + +#include +#include +#include +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int NOT_IMPLEMENTED; +} +} + +namespace DB::ORC +{ + +std::future InputStream::readAsync(void * buf, UInt64 length, UInt64 offset) +{ + read(buf, length, offset); + std::promise promise; + promise.set_value(); + return promise.get_future(); +} + + +Reader::Reader(std::unique_ptr stream_, const ReaderOptions & options_) + : stream(std::move(stream_)), options(options_) +{ + readTail(); +} + +Reader::~Reader() +{ + /// The background reads write into the buffers of the cache. + for (auto & range : cache) + if (!range.ready && range.future.valid()) + range.future.wait(); +} + +void Reader::readTail() +{ + const UInt64 file_size = stream->getLength(); + /// The header "ORC" and at least the length of the postscript. + if (file_size < 4) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {} is too small ({} bytes)", stream->getName(), file_size); + + static constexpr UInt64 DIRECTORY_SIZE_GUESS = 16 * 1024; + UInt64 tail_size = std::min(file_size, DIRECTORY_SIZE_GUESS); + std::string tail(tail_size, '\0'); + stream->read(tail.data(), tail_size, file_size - tail_size); + + postscript_length = static_cast(tail.back()); + if (postscript_length + 1 > tail_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid postscript length {} in ORC file {}", postscript_length, stream->getName()); + + postscript.parse(std::string_view(tail).substr(tail_size - 1 - postscript_length, postscript_length)); + + if (postscript.magic != "ORC") + { + /// Very old files do not have the magic in the postscript, but they have it at the beginning. + char header[3]; + stream->read(header, 3, 0); + if (memcmp(header, "ORC", 3) != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not an ORC file: {}", stream->getName()); + } + + if (postscript.compression != CompressionKind::NONE) + { + if (postscript.compression_block_size == 0 || postscript.compression_block_size > (1ULL << 30)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid compression block size {} in ORC file {}", postscript.compression_block_size, stream->getName()); + if (postscript.compression == CompressionKind::BROTLI) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "BROTLI compression in ORC files is not supported"); + } + + UInt64 tail_length = 0; + if (__builtin_add_overflow(postscript.footer_length, postscript.metadata_length, &tail_length) + || __builtin_add_overflow(tail_length, postscript_length + 1, &tail_length) + || tail_length > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Invalid footer length {} and metadata length {} in ORC file {} of size {}", + postscript.footer_length, postscript.metadata_length, stream->getName(), file_size); + + if (tail_length > tail_size) + { + tail.resize(tail_length); + tail_size = tail_length; + stream->read(tail.data(), tail_size, file_size - tail_size); + } + + std::string_view footer_data = std::string_view(tail).substr(tail_size - 1 - postscript_length - postscript.footer_length, postscript.footer_length); + footer.parse(decompress(footer_data, "footer")); + + if (footer.has_encryption) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + + schema = Type::fromProto(footer.types); + + /// Validate the stripes once, so that the sums of their offsets and lengths cannot overflow later. + if (footer.stripes.size() > static_cast(std::numeric_limits::max())) + throw Exception(ErrorCodes::INCORRECT_DATA, "Too many stripes {} in ORC file {}", footer.stripes.size(), stream->getName()); + for (size_t i = 0; i < footer.stripes.size(); ++i) + { + const auto & stripe = footer.stripes[i]; + UInt64 stripe_end = 0; + if (common::addOverflow(stripe.offset, stripe.index_length, stripe_end) + || common::addOverflow(stripe_end, stripe.data_length, stripe_end) + || common::addOverflow(stripe_end, stripe.footer_length, stripe_end) + || stripe_end > file_size) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + i, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, file_size); + } + + std::string_view metadata_data = std::string_view(tail).substr( + tail_size - 1 - postscript_length - postscript.footer_length - postscript.metadata_length, postscript.metadata_length); + if (!metadata_data.empty()) + metadata.emplace().parse(decompress(metadata_data, "metadata"), footer.stripes.size(), footer.types.size()); + else + metadata.emplace(); +} + +const Proto::Metadata & Reader::getMetadata() +{ + return *metadata; +} + +std::string Reader::decompress(std::string_view data, const std::string & name) const +{ + if (postscript.compression == CompressionKind::NONE) + return std::string(data); + + std::string result; + InputByteStream in(data, postscript.compression, postscript.compression_block_size, name); + while (in.nextChunk()) + result.append(in.pos, in.end); + return result; +} + +Proto::StripeFooter Reader::readStripeFooter(size_t stripe_index) +{ + const auto & stripe = getStripe(stripe_index); + UInt64 offset = stripe.offset + stripe.index_length + stripe.data_length; + UInt64 end = 0; + if (__builtin_add_overflow(offset, stripe.footer_length, &end) || end > stream->getLength() || offset < stripe.offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stripe information at stripe index {} in ORC file {}: offset={}, indexLength={}, dataLength={}, footerLength={}, fileLength={}", + stripe_index, stream->getName(), stripe.offset, stripe.index_length, stripe.data_length, stripe.footer_length, stream->getLength()); + + auto slices = readRanges({{offset, stripe.footer_length}}); + Proto::StripeFooter result; + result.parse(decompress(slices[0].data, "stripe footer"), footer.types.size()); + if (result.encryption_variants) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Encrypted ORC files are not supported"); + return result; +} + +std::vector> Reader::getStripeRanges( + size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const +{ + const auto & stripe = getStripe(stripe_index); + std::vector> ranges; + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + for (const auto & s : stripe_footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream at offset {} of length {} in stripe {} of ORC file {}", offset, s.length, stripe_index, stream->getName()); + if (s.kind && s.column < selected.size() && selected[s.column] && s.length) + ranges.emplace_back(offset, s.length); + offset = stream_end; + } + return ranges; +} + +std::vector Reader::readRanges(const std::vector> & ranges) +{ + std::vector result(ranges.size()); + + std::vector order(ranges.size()); + for (size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return ranges[a].first < ranges[b].first; }); + + size_t i = 0; + while (i < order.size()) + { + UInt64 begin = ranges[order[i]].first; + UInt64 end = begin + ranges[order[i]].second; + size_t j = i + 1; + while (j < order.size()) + { + UInt64 next_begin = ranges[order[j]].first; + UInt64 next_end = next_begin + ranges[order[j]].second; + UInt64 new_end = std::max(end, next_end); + if (next_begin > end && next_begin - end > options.hole_size_limit) + break; + if (new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + std::shared_ptr> holder; + const char * base = nullptr; + UInt64 base_offset = begin; + { + std::lock_guard lock(cache_mutex); + for (auto & cached : cache) + { + if (cached.offset <= begin && end <= cached.offset + cached.length) + { + if (!cached.ready) + { + cached.ready = true; + cached.future.get(); + } + holder = cached.buffer; + base = cached.buffer->data(); + base_offset = cached.offset; + break; + } + } + } + + if (!holder) + { + if (end > stream->getLength()) + throw Exception(ErrorCodes::INCORRECT_DATA, "A range at {} of length {} goes beyond the end of ORC file {}", begin, end - begin, stream->getName()); + auto buffer = std::make_shared>(end - begin); + if (end > begin) + stream->read(buffer->data(), end - begin, begin); + base = buffer->data(); + holder = std::move(buffer); + } + + for (size_t k = i; k < j; ++k) + { + const auto & range = ranges[order[k]]; + result[order[k]] = Slice{holder, std::string_view(base + (range.first - base_offset), range.second)}; + } + i = j; + } + return result; +} + +void Reader::preBuffer(const std::vector & stripes, const std::vector & include_types) +{ + auto selected = selectColumnsByTypeIds(*schema, include_types); + for (UInt32 stripe_index : stripes) + { + const auto & stripe = getStripe(stripe_index); + auto stripe_footer = readStripeFooter(stripe_index); + auto ranges = getStripeRanges(stripe_index, stripe_footer, selected); + ranges.emplace_back(stripe.offset + stripe.index_length + stripe.data_length, stripe.footer_length); + std::sort(ranges.begin(), ranges.end()); + + size_t i = 0; + while (i < ranges.size()) + { + UInt64 begin = ranges[i].first; + UInt64 end = begin + ranges[i].second; + size_t j = i + 1; + while (j < ranges.size()) + { + UInt64 next_begin = ranges[j].first; + UInt64 new_end = std::max(end, next_begin + ranges[j].second); + if ((next_begin > end && next_begin - end > options.hole_size_limit) || new_end - begin > options.range_size_limit) + break; + end = new_end; + ++j; + } + + auto buffer = std::make_shared>(end - begin); + { + /// The entry must be owned by the cache before the background read starts, so that + /// the destructor waits for the read even if an exception is thrown in between. + std::lock_guard lock(cache_mutex); + auto & cached = cache.emplace_back(CachedRange{.offset = begin, .length = end - begin, .buffer = std::move(buffer), .future = {}}); + try + { + cached.future = stream->readAsync(cached.buffer->data(), end - begin, begin); + } + catch (...) + { + /// Nothing has been scheduled, so the entry can be removed safely. + cache.pop_back(); + throw; + } + } + i = j; + } + } +} + +void Reader::releaseBuffer(UInt64 boundary) +{ + std::lock_guard lock(cache_mutex); + for (auto it = cache.begin(); it != cache.end();) + { + if (it->offset + it->length <= boundary) + { + /// The buffer can be destroyed only after the background read finishes. The data has + /// not been used, so an error of reading it does not matter. + if (!it->ready && it->future.valid()) + it->future.wait(); + it = cache.erase(it); + } + else + ++it; + } +} + +std::unique_ptr Reader::createRowReader(const RowReaderOptions & row_options) +{ + return std::make_unique(*this, row_options); +} + + +class RowReader::StripeStreamsImpl final : public StripeStreams +{ +public: + StripeStreamsImpl( + Reader & reader_, + size_t stripe_index_, + Proto::StripeFooter footer_, + const std::vector & selected_columns_, + const DateLUTImpl & writer_timezone_, + const DateLUTImpl & reader_timezone_) + : reader(reader_) + , stripe_index(stripe_index_) + , footer(std::move(footer_)) + , selected_columns(selected_columns_) + , writer_timezone(writer_timezone_) + , reader_timezone(reader_timezone_) + { + const auto & stripe = reader.getStripe(stripe_index); + UInt64 offset = stripe.offset; + const UInt64 data_end = stripe.offset + stripe.index_length + stripe.data_length; + + for (const auto & s : footer.streams) + { + /// Every stream is checked: the offsets of the following streams depend on its length. + UInt64 stream_end = 0; + if (common::addOverflow(offset, s.length, stream_end) || stream_end > data_end) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: streamOffset={}, streamLength={}, stripeOffset={}, stripeIndexLength={}, stripeDataLength={}", + stripe_index, offset, s.length, stripe.offset, stripe.index_length, stripe.data_length); + if (s.kind && s.column < selected_columns.size() && selected_columns[s.column]) + { + /// Use the first stream if there are several of the same kind, as the reference implementation. + stream_ranges.try_emplace({static_cast(s.column), *s.kind}, offset, s.length); + } + else if (s.kind && s.column >= selected_columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Malformed stream meta in stripe {} of ORC file: column {} is out of range, the file has {} columns", + stripe_index, s.column, selected_columns.size()); + offset = stream_end; + } + } + + static bool isIndexStream(UInt32 kind) + { + return kind == static_cast(Proto::StreamKind::ROW_INDEX) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER) + || kind == static_cast(Proto::StreamKind::BLOOM_FILTER_UTF8); + } + + /// Reads the streams into memory at once, only the index streams or all of them. The streams + /// that are not read are loaded on demand by `getStream`. + void loadStreams(bool only_index) + { + std::vector> ranges; + std::vector> keys; + for (const auto & [key, range] : stream_ranges) + { + if (streams.contains(key) || (only_index && !isIndexStream(key.second))) + continue; + keys.push_back(key); + ranges.push_back(range); + } + + auto new_slices = reader.readRanges(ranges); + for (size_t i = 0; i < keys.size(); ++i) + streams.emplace(keys[i], new_slices[i].data); + slices.insert(slices.end(), std::make_move_iterator(new_slices.begin()), std::make_move_iterator(new_slices.end())); + } + + const Proto::ColumnEncoding & getEncoding(UInt64 column_id) const override + { + if (column_id >= footer.columns.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC stripe {} has no encoding for column {}, it has {} column encodings", stripe_index, column_id, footer.columns.size()); + return footer.columns[column_id]; + } + + std::unique_ptr getStream(UInt64 column_id, Proto::StreamKind kind) const override + { + std::pair key{column_id, static_cast(kind)}; + auto name = fmt::format("column {} kind {} in stripe {}", column_id, static_cast(kind), stripe_index); + if (auto it = streams.find(key); it != streams.end()) + return std::make_unique(it->second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + + auto it = stream_ranges.find(key); + if (it == stream_ranges.end()) + return nullptr; + auto loader = [&file_reader = reader, stream_offset = it->second.first](UInt64 offset, UInt64 length) + { + auto loaded = file_reader.readRanges({{stream_offset + offset, length}}); + return LoadedRange{std::move(loaded[0].holder), loaded[0].data}; + }; + return std::make_unique( + std::move(loader), it->second.second, reader.getCompression(), reader.getCompressionBlockSize(), std::move(name)); + } + + std::optional getStreamData(UInt64 column_id, Proto::StreamKind kind) const + { + auto it = streams.find({column_id, static_cast(kind)}); + if (it == streams.end()) + return {}; + return it->second; + } + + const std::vector & getSelectedColumns() const override { return selected_columns; } + const DateLUTImpl & getWriterTimezone() const override { return writer_timezone; } + const DateLUTImpl & getReaderTimezone() const override { return reader_timezone; } + UInt64 getNumberOfRows() const override { return reader.getStripe(stripe_index).number_of_rows; } + bool isDecimalAsLong() const override + { + const auto & version = reader.getPostScript().version; + return version.size() == 2 && version[0] == 1 && version[1] == 9999; + } + + const Proto::StripeFooter & getFooter() const { return footer; } + +private: + Reader & reader; + size_t stripe_index; + Proto::StripeFooter footer; + const std::vector & selected_columns; + const DateLUTImpl & writer_timezone; + const DateLUTImpl & reader_timezone; + /// The offset in the file and the length of each selected stream. + std::map, std::pair> stream_ranges; + /// The streams read into memory. + std::vector slices; + std::map, std::string_view> streams; +}; + + +RowReader::RowReader(Reader & reader_, const RowReaderOptions & options_) + : reader(reader_) + , options(options_) + , reader_timezone(DateLUT::instance(options.timezone_name)) +{ + const Type & schema = reader.getType(); + if (options.include_types) + selected_columns = selectColumnsByTypeIds(schema, *options.include_types); + else + selected_columns.assign(schema.getMaximumColumnId() + 1, true); + selected_type = Type::buildSelectedType(schema, selected_columns); + + UInt64 range_end = options.range_offset + std::min(options.range_length, std::numeric_limits::max() - options.range_offset); + const auto & stripes = reader.getFooter().stripes; + current_stripe = stripes.size(); + last_stripe = 0; + for (size_t i = 0; i < stripes.size(); ++i) + { + if (stripes[i].offset >= options.range_offset && stripes[i].offset < range_end) + { + current_stripe = std::min(current_stripe, i); + last_stripe = std::max(last_stripe, i + 1); + } + } + if (current_stripe >= last_stripe) + current_stripe = last_stripe = 0; + + /// The search argument can be applied only if there are row indexes. + if (reader.getFooter().row_index_stride == 0) + options.search_argument.reset(); +} + +RowReader::~RowReader() = default; + +std::unique_ptr RowReader::createRowBatch() const +{ + return ORC::createRowBatch(*selected_type, options.enable_lazy_decoding); +} + +bool Reader::hasBadBloomFilters() const +{ + /// Same as in the reference implementation. Only the C++ writer (id 1) of some old releases wrote bad bloom filters. + if (footer.writer.value_or(0) != 1) + return false; + /// `software_version` is written since 1.5.13, 1.6.11 and 1.7.0, and the C++ writer supports bloom filters since 1.6.0, + /// so the files of the C++ writer without `software_version` have bad bloom filters. + if (!footer.software_version) + return true; + /// Strip the suffix of snapshot versions, like 1.6.12-SNAPSHOT. + std::string_view version = *footer.software_version; + version = version.substr(0, version.find('-')); + static constexpr std::string_view bad_versions[] = { + "1.6.0", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.6.7", "1.6.8", "1.6.9", "1.6.10", "1.6.11", "1.7.0"}; + return std::find(std::begin(bad_versions), std::end(bad_versions), version) != std::end(bad_versions); +} + +const DateLUTImpl & RowReader::getWriterTimezone(const Proto::StripeFooter & stripe_footer) const +{ + if (stripe_footer.writer_timezone) + return DateLUT::instance(*stripe_footer.writer_timezone); + /// The reference implementation uses the local time zone of the reader if the file does not specify it. + return DateLUT::serverTimezoneInstance(); +} + +bool RowReader::evaluateStatistics(const std::vector & stats) const +{ + const auto & leaves = options.search_argument->getLeaves(); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + UInt32 writer_version = reader.getPostScript().writer_version; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + if (column < stats.size()) + values[i] = leaves[i].evaluate(writer_version, stats[column], nullptr); + } + return isNeeded(options.search_argument->evaluate(values)); +} + +UInt64 RowReader::numberOfRowGroups() const +{ + const UInt64 stride = reader.getFooter().row_index_stride; + return rows_in_current_stripe / stride + (rows_in_current_stripe % stride != 0); +} + +void RowReader::loadStripeIndex() +{ + row_indexes.clear(); + bloom_filters.clear(); + /// One extra entry is accepted from lenient writers. + const UInt64 max_entries = std::min(numberOfRowGroups(), std::numeric_limits::max() - 1) + 1; + const bool use_bloom_filters = !reader.hasBadBloomFilters(); + const auto & stripe_footer = stripe_streams->getFooter(); + for (const auto & s : stripe_footer.streams) + { + if (!s.kind || s.column >= selected_columns.size() || !selected_columns[s.column]) + continue; + auto kind = static_cast(*s.kind); + if (kind == Proto::StreamKind::ROW_INDEX) + { + if (row_indexes.contains(s.column)) + continue; + auto data = stripe_streams->getStreamData(s.column, kind); + row_indexes[s.column].parse(reader.decompress(data.value_or(std::string_view{}), "row index"), max_entries); + } + else if (kind == Proto::StreamKind::BLOOM_FILTER_UTF8 && use_bloom_filters) + { + if (bloom_filters.contains(s.column)) + continue; + const auto & encoding = stripe_streams->getEncoding(s.column); + Proto::BloomFilterIndex index; + auto data = stripe_streams->getStreamData(s.column, kind); + index.parse(reader.decompress(data.value_or(std::string_view{}), "bloom filter"), max_entries); + auto & filters = bloom_filters[s.column]; + for (const auto & bf : index.bloom_filter) + { + /// Only the bloom filters with the UTF-8 strings and UTC timestamps can be used. + if (encoding.bloom_encoding.value_or(0) == 1 && bf.num_hash_functions && bf.utf8bitset) + filters.push_back(std::make_shared(bf)); + else + filters.push_back(nullptr); + } + } + } +} + +void RowReader::pickRowGroups() +{ + const UInt64 stride = reader.getFooter().row_index_stride; + const UInt64 groups = numberOfRowGroups(); + const auto & leaves = options.search_argument->getLeaves(); + + /// The number of the row groups comes from the file. Check it against the row indexes, which are already + /// read, before allocating memory for it. + bool has_leaf_index = false; + for (const auto & leaf : leaves) + { + auto it = row_indexes.find(leaf.getColumnId()); + if (it == row_indexes.end()) + continue; + has_leaf_index = true; + if (it->second.entry.size() < groups) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + it->first, it->second.entry.size(), groups, current_stripe); + } + + if (!has_leaf_index) + { + /// Without the row indexes all row groups are read. + next_skipped_rows.clear(); + return; + } + + next_skipped_rows.assign(groups, 0); + std::vector values(leaves.size(), TruthValue::YES_NO_NULL); + const UInt32 writer_version = reader.getPostScript().writer_version; + const Proto::ColumnStatistics empty_statistics; + + UInt64 next_skipped_group = groups; + for (UInt64 group = groups; group > 0;) + { + --group; + for (size_t i = 0; i < leaves.size(); ++i) + { + UInt64 column = leaves[i].getColumnId(); + auto it = row_indexes.find(column); + if (it == row_indexes.end()) + { + values[i] = TruthValue::YES_NO_NULL; + continue; + } + if (group >= it->second.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, less than the {} row groups of stripe {}", + column, it->second.entry.size(), groups, current_stripe); + const auto & entry = it->second.entry[group]; + const BloomFilter * bloom_filter = nullptr; + if (auto bf = bloom_filters.find(column); bf != bloom_filters.end() && group < bf->second.size()) + bloom_filter = bf->second[group].get(); + values[i] = leaves[i].evaluate(writer_version, entry.statistics ? *entry.statistics : empty_statistics, bloom_filter); + } + + bool needed = isNeeded(options.search_argument->evaluate(values)); + if (!needed) + { + next_skipped_rows[group] = 0; + next_skipped_group = group; + } + else + next_skipped_rows[group] = (next_skipped_group == groups) ? rows_in_current_stripe : next_skipped_group * stride; + } +} + +UInt64 RowReader::advanceToNextRowGroup(UInt64 current_row) const +{ + const UInt64 groups = next_skipped_rows.size(); + if (groups == 0) + return std::min(current_row, rows_in_current_stripe); + + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return rows_in_current_stripe; + if (next_skipped_rows[group] != 0) + return current_row; + while (group < groups && next_skipped_rows[group] == 0) + ++group; + if (group < groups) + return group * stride; + return rows_in_current_stripe; +} + +UInt64 RowReader::computeBatchSize(UInt64 requested, UInt64 current_row) const +{ + UInt64 end_row = rows_in_current_stripe; + const UInt64 groups = next_skipped_rows.size(); + if (groups > 0) + { + const UInt64 stride = reader.getFooter().row_index_stride; + UInt64 group = current_row / stride; + if (group >= groups) + return 0; + UInt64 next_skipped_row = next_skipped_rows[group]; + if (next_skipped_row == 0) + return 0; + end_row = next_skipped_row; + } + return std::min(requested, end_row - current_row); +} + +void RowReader::seekToRowGroup(size_t row_group) +{ + std::unordered_map positions; + for (const auto & [column, index] : row_indexes) + { + if (row_group >= index.entry.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The row index of ORC column {} has {} entries, the row group {} is requested", column, index.entry.size(), row_group); + positions.emplace(column, PositionProvider(index.entry[row_group].positions)); + } + column_reader->seekToRowGroup(positions); +} + +void RowReader::startNextStripe() +{ + column_reader.reset(); + stripe_streams.reset(); + row_indexes.clear(); + bloom_filters.clear(); + next_skipped_rows.clear(); + + const auto & search_argument = options.search_argument; + const auto & footer = reader.getFooter(); + + if (search_argument && !file_statistics_evaluated) + { + file_statistics_result = footer.statistics.empty() || evaluateStatistics(footer.statistics); + file_statistics_evaluated = true; + } + if (search_argument && !file_statistics_result) + { + current_stripe = last_stripe; + return; + } + + do + { + const auto & stripe = footer.stripes[current_stripe]; + rows_in_current_stripe = stripe.number_of_rows; + + bool is_stripe_needed = true; + const auto & stripe_statistics = reader.getMetadata().stripe_stats; + if (search_argument && stripe_statistics.size() == footer.stripes.size()) + { + const auto & stats = stripe_statistics[current_stripe].col_stats; + is_stripe_needed = stats.empty() || evaluateStatistics(stats); + } + + if (is_stripe_needed) + { + auto stripe_footer = reader.readStripeFooter(current_stripe); + const DateLUTImpl & writer_timezone = getWriterTimezone(stripe_footer); + stripe_streams = std::make_unique( + reader, current_stripe, std::move(stripe_footer), selected_columns, writer_timezone, reader_timezone); + if (!search_argument) + stripe_streams->loadStreams(/* only_index */ false); + + if (search_argument) + { + stripe_streams->loadStreams(/* only_index */ true); + loadStripeIndex(); + pickRowGroups(); + bool has_selected = next_skipped_rows.empty(); + for (UInt64 group = current_row_in_stripe / footer.row_index_stride; !has_selected && group < next_skipped_rows.size(); ++group) + has_selected = next_skipped_rows[group] != 0; + if (has_selected) + { + /// If some row groups are skipped, the data is loaded on demand, only around the + /// selected row groups. Otherwise the whole stripe is read at once. + bool has_skipped = std::find(next_skipped_rows.begin(), next_skipped_rows.end(), 0) != next_skipped_rows.end(); + if (!has_skipped) + stripe_streams->loadStreams(/* only_index */ false); + break; + } + is_stripe_needed = false; + stripe_streams.reset(); + } + } + + if (!is_stripe_needed) + { + ++current_stripe; + current_row_in_stripe = 0; + } + } while (search_argument && current_stripe < last_stripe); + + if (current_stripe >= last_stripe) + return; + + column_reader = buildColumnReader(reader.getType(), *stripe_streams); + + if (search_argument) + { + current_row_in_stripe = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe > 0) + seekToRowGroup(current_row_in_stripe / footer.row_index_stride); + } +} + +bool RowReader::next(ColumnVectorBatch & batch, size_t max_rows) +{ + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + if (current_row_in_stripe == 0) + startNextStripe(); + + if (current_stripe >= last_stripe) + { + batch.numElements = 0; + return false; + } + + UInt64 rows_to_read = std::min(max_rows, rows_in_current_stripe - current_row_in_stripe); + if (options.search_argument && rows_to_read > 0) + rows_to_read = computeBatchSize(rows_to_read, current_row_in_stripe); + + batch.numElements = rows_to_read; + if (rows_to_read == 0) + { + current_stripe = last_stripe; + return false; + } + + if (options.enable_lazy_decoding) + column_reader->nextEncoded(batch, rows_to_read, nullptr); + else + column_reader->next(batch, rows_to_read, nullptr); + + current_row_in_stripe += rows_to_read; + + if (options.search_argument) + { + UInt64 next_row = advanceToNextRowGroup(current_row_in_stripe); + if (current_row_in_stripe != next_row) + { + current_row_in_stripe = next_row; + if (current_row_in_stripe < rows_in_current_stripe) + seekToRowGroup(current_row_in_stripe / reader.getFooter().row_index_stride); + } + } + + if (current_row_in_stripe >= rows_in_current_stripe) + { + ++current_stripe; + current_row_in_stripe = 0; + } + return true; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Reader.h b/src/Processors/Formats/Impl/ORC/Reader.h new file mode 100644 index 000000000000..981ab8c5c799 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Reader.h @@ -0,0 +1,188 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/// The reader of the ORC files: https://orc.apache.org/specification/ORCv1/ + +namespace DB::ORC +{ + +/// Random access to the file. +class InputStream +{ +public: + virtual ~InputStream() = default; + + virtual UInt64 getLength() const = 0; + /// Reads exactly `length` bytes at `offset`. Must be thread-safe if `readAsync` is used. + virtual void read(void * buf, UInt64 length, UInt64 offset) = 0; + /// Reads in the background. The default implementation reads synchronously. + virtual std::future readAsync(void * buf, UInt64 length, UInt64 offset); + virtual const std::string & getName() const = 0; +}; + +struct ReaderOptions +{ + /// Two ranges are read with one request if the gap between them is at most this size... + UInt64 hole_size_limit = 8192; + /// ... and the combined range is at most this size. + UInt64 range_size_limit = 32 * 1024 * 1024; +}; + +struct RowReaderOptions +{ + /// The ids of the columns to read, with the same semantics as in the reference implementation + /// (see `selectColumnsByTypeIds`). If not set, all columns are read. + std::optional> include_types; + /// Read only the stripes that start in `[range_offset, range_offset + range_length)`. + UInt64 range_offset = 0; + UInt64 range_length = std::numeric_limits::max(); + /// For the dictionary-encoded string columns, fill `EncodedStringVectorBatch`. + bool enable_lazy_decoding = false; + /// The time zone to show the values of the TIMESTAMP (not TIMESTAMP_INSTANT) columns in. + std::string timezone_name = "GMT"; + std::shared_ptr search_argument; +}; + +class RowReader; + +class Reader +{ +public: + Reader(std::unique_ptr stream_, const ReaderOptions & options_); + ~Reader(); + + const Type & getType() const { return *schema; } + UInt64 getNumberOfRows() const { return footer.number_of_rows; } + UInt64 getNumberOfStripes() const { return footer.stripes.size(); } + const Proto::StripeInformation & getStripe(size_t index) const { return footer.stripes.at(index); } + static UInt64 getStripeLength(const Proto::StripeInformation & stripe) { return stripe.index_length + stripe.data_length + stripe.footer_length; } + + const Proto::Footer & getFooter() const { return footer; } + const Proto::PostScript & getPostScript() const { return postscript; } + CompressionKind getCompression() const { return postscript.compression; } + /// Whether the bloom filters of the file were written by a version of the C++ writer + /// that hashed the integers incorrectly (ORC-1024), so they must not be used. + bool hasBadBloomFilters() const; + UInt64 getCompressionBlockSize() const { return postscript.compression_block_size; } + + /// The statistics of the whole file, one per column. + const std::vector & getStatistics() const { return footer.statistics; } + /// The statistics of the stripes, read on the first call. Can be empty. + const Proto::Metadata & getMetadata(); + + /// Reads the stripe footer. Not thread-safe. + Proto::StripeFooter readStripeFooter(size_t stripe_index); + + std::unique_ptr createRowReader(const RowReaderOptions & options); + + /// Starts reading the data of the selected columns of the stripes in the background. + void preBuffer(const std::vector & stripes, const std::vector & include_types); + /// Releases the prefetched data that ends before `boundary`. + void releaseBuffer(UInt64 boundary); + + /// A piece of the file in memory. + struct Slice + { + std::shared_ptr> holder; + std::string_view data; + }; + + /// Reads the ranges `(offset, length)` of the file, from the prefetched data if possible. + /// The adjacent ranges are coalesced according to the options. + std::vector readRanges(const std::vector> & ranges); + + /// Decompresses a whole metadata stream (a footer, an index). + std::string decompress(std::string_view data, const std::string & name) const; + +private: + void readTail(); + + struct CachedRange + { + UInt64 offset; + UInt64 length; + std::shared_ptr> buffer; + std::future future; + bool ready = false; + }; + + /// Returns the ranges of the streams of the selected columns in the stripe, and the stripe footer. + std::vector> getStripeRanges(size_t stripe_index, const Proto::StripeFooter & stripe_footer, const std::vector & selected) const; + + std::unique_ptr stream; + ReaderOptions options; + Proto::PostScript postscript; + UInt64 postscript_length = 0; + Proto::Footer footer; + std::optional metadata; + std::unique_ptr schema; + + std::mutex cache_mutex; + std::list cache; +}; + +/// Reads the rows of the selected stripes and columns in batches. +class RowReader +{ +public: + RowReader(Reader & reader_, const RowReaderOptions & options_); + ~RowReader(); + + std::unique_ptr createRowBatch() const; + + /// Fills the batch with the next rows, at most `max_rows`. Returns false at the end. + bool next(ColumnVectorBatch & batch, size_t max_rows); + + /// The type of the file with only the selected columns. The batches have this structure. + const Type & getSelectedType() const { return *selected_type; } + +private: + class StripeStreamsImpl; + + void startNextStripe(); + void loadStripeIndex(); + UInt64 numberOfRowGroups() const; + void pickRowGroups(); + void seekToRowGroup(size_t row_group); + UInt64 advanceToNextRowGroup(UInt64 current_row) const; + UInt64 computeBatchSize(UInt64 requested, UInt64 current_row) const; + bool evaluateStatistics(const std::vector & stats) const; + const DateLUTImpl & getWriterTimezone(const Proto::StripeFooter & stripe_footer) const; + + Reader & reader; + RowReaderOptions options; + std::vector selected_columns; + std::unique_ptr selected_type; + const DateLUTImpl & reader_timezone; + + UInt64 current_stripe = 0; + UInt64 last_stripe = 0; + UInt64 rows_in_current_stripe = 0; + UInt64 current_row_in_stripe = 0; + bool file_statistics_evaluated = false; + bool file_statistics_result = true; + + std::unique_ptr stripe_streams; + std::unique_ptr column_reader; + + /// For the predicate pushdown, by the column id. + std::unordered_map row_indexes; + std::unordered_map>> bloom_filters; + /// For each row group of the current stripe: zero if it is skipped, otherwise the row (in the + /// stripe) of the next skipped row group or the number of rows in the stripe. + std::vector next_skipped_rows; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.cpp b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp new file mode 100644 index 000000000000..e0543230c614 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp @@ -0,0 +1,1075 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +TruthValue operator||(TruthValue left, TruthValue right) +{ + if (right == TruthValue::YES || left == TruthValue::YES) + return TruthValue::YES; + if (right == TruthValue::YES_NULL || left == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + if (right == TruthValue::NO) + return left; + if (left == TruthValue::NO) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::NO_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::NO_NULL) + return TruthValue::IS_NULL; + return TruthValue::YES_NULL; + } + if (left == TruthValue::NO_NULL && right == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator&&(TruthValue left, TruthValue right) +{ + if (right == TruthValue::NO || left == TruthValue::NO) + return TruthValue::NO; + if (right == TruthValue::NO_NULL || left == TruthValue::NO_NULL) + return TruthValue::NO_NULL; + if (right == TruthValue::YES) + return left; + if (left == TruthValue::YES) + return right; + if (left == TruthValue::IS_NULL) + { + if (right == TruthValue::YES_NULL || right == TruthValue::IS_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (right == TruthValue::IS_NULL) + { + if (left == TruthValue::YES_NULL) + return TruthValue::IS_NULL; + return TruthValue::NO_NULL; + } + if (left == TruthValue::YES_NULL && right == TruthValue::YES_NULL) + return TruthValue::YES_NULL; + return TruthValue::YES_NO_NULL; +} + +TruthValue operator!(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: return TruthValue::YES; + case TruthValue::YES: return TruthValue::NO; + case TruthValue::IS_NULL: + case TruthValue::YES_NO: + case TruthValue::YES_NO_NULL: + return value; + case TruthValue::NO_NULL: return TruthValue::YES_NULL; + case TruthValue::YES_NULL: return TruthValue::NO_NULL; + } + return value; +} + +bool isNeeded(TruthValue value) +{ + switch (value) + { + case TruthValue::NO: + case TruthValue::IS_NULL: + case TruthValue::NO_NULL: + return false; + default: + return true; + } +} + + +bool Literal::Decimal::parse(std::string_view s) +{ + bool negative = false; + size_t i = 0; + if (i < s.size() && (s[i] == '-' || s[i] == '+')) + { + negative = s[i] == '-'; + ++i; + } + Int256 result = 0; + bool has_digits = false; + bool has_point = false; + Int32 result_scale = 0; + for (; i < s.size(); ++i) + { + char c = s[i]; + if (c == '.' && !has_point) + { + has_point = true; + continue; + } + if (c < '0' || c > '9') + return false; + has_digits = true; + result = result * 10 + (c - '0'); + if (has_point) + ++result_scale; + /// More than 38 digits do not fit into the 128-bit value. + if (result > Int256(std::numeric_limits::max())) + return false; + } + if (!has_digits) + return false; + value = static_cast(negative ? -result : result); + scale = result_scale; + return true; +} + +std::string Literal::Decimal::toString() const +{ + bool negative = value < 0; + std::string digits = DB::toString(negative ? -Int256(value) : Int256(value)); + std::string result; + if (scale <= 0) + result = digits; + else + { + if (digits.size() <= static_cast(scale)) + digits = std::string(scale - digits.size() + 1, '0') + digits; + result = digits.substr(0, digits.size() - scale) + "." + digits.substr(digits.size() - scale); + size_t last = result.find_last_not_of('0'); + if (result[last] == '.') + result.resize(last); + else + result.resize(last + 1); + } + return negative ? "-" + result : result; +} + +namespace +{ + +int compareDecimals(const Literal::Decimal & a, const Literal::Decimal & b) +{ + Int256 left = a.value; + Int256 right = b.value; + for (Int32 s = a.scale; s < b.scale; ++s) + left *= 10; + for (Int32 s = b.scale; s < a.scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +} + +Literal::Literal(bool value) : type(PredicateDataType::BOOLEAN), int_value(value) {} +Literal::Literal(Int64 value) : type(PredicateDataType::LONG), int_value(value) {} +Literal::Literal(double value) : type(PredicateDataType::FLOAT), float_value(value) {} +Literal::Literal(const char * data, size_t size) : type(PredicateDataType::STRING), string_value(data, size) {} + +Literal::Literal(PredicateDataType type_, Int64 value) : type(type_), int_value(value) +{ + if (type != PredicateDataType::DATE) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Only DATE literals can be created from a type and an integer"); +} + +Literal::Literal(Int64 second, Int32 nanos) : type(PredicateDataType::TIMESTAMP), timestamp_value{second, nanos} {} + +Literal::Literal(Int128 value, Int32 /*precision*/, Int32 scale) : type(PredicateDataType::DECIMAL), decimal_value{value, scale} {} + + +namespace +{ + +/// Where a point is relative to the range [min, max]. +enum class Location : UInt8 +{ + BEFORE, + MIN, + MIDDLE, + MAX, + AFTER, +}; + +template +Location compareToRange(const T & point, const T & min, const T & max, Less less, Equal equal) +{ + if (less(point, min)) + return Location::BEFORE; + if (equal(point, min)) + return Location::MIN; + if (less(max, point)) + return Location::AFTER; + if (equal(point, max)) + return Location::MAX; + return Location::MIDDLE; +} + +template +TruthValue evaluatePredicateRange( + PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null, Less less, Equal equal) +{ + auto loc_of = [&](const T & v) { return compareToRange(v, min_value, max_value, less, equal); }; + bool min_equals_max = equal(min_value, max_value); + + switch (op) + { + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::AFTER) + return TruthValue::NO; + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + auto loc = loc_of(values.at(0)); + if (min_equals_max && loc == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE || loc == Location::MIN) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::LESS_THAN_EQUALS: + { + auto loc = loc_of(values.at(0)); + if (loc == Location::AFTER || loc == Location::MAX || (loc == Location::MIN && min_equals_max)) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IN: + { + if (min_equals_max) + { + for (const auto & value : values) + if (loc_of(value) == Location::MIN) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + for (const auto & value : values) + { + auto loc = loc_of(value); + if (loc == Location::MIN || loc == Location::MIDDLE || loc == Location::MAX) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + } + case PredicateLeaf::Operator::BETWEEN: + { + if (values.empty()) + return TruthValue::YES_NO; + auto loc = loc_of(values.at(0)); + if (loc == Location::BEFORE || loc == Location::MIN) + { + auto loc2 = loc_of(values.at(1)); + if (loc2 == Location::AFTER || loc2 == Location::MAX) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + if (loc2 == Location::BEFORE) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + if (loc == Location::AFTER) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; +} + +template +TruthValue evaluateRange(PredicateLeaf::Operator op, const std::vector & values, const T & min_value, const T & max_value, bool has_null) +{ + return evaluatePredicateRange(op, values, min_value, max_value, has_null, + [](const T & a, const T & b) { return a < b; }, + [](const T & a, const T & b) { return a == b; }); +} + +TruthValue evaluateBoolPredicate(PredicateLeaf::Operator op, const std::vector & literals, const Proto::ColumnStatistics & stats) +{ + bool has_null = stats.has_null.value_or(false); + if (!stats.bucket_statistics || stats.bucket_statistics->count.empty()) + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + + UInt64 true_count = stats.bucket_statistics->count[0]; + UInt64 false_count = stats.number_of_values.value_or(0) - true_count; + switch (op) + { + case PredicateLeaf::Operator::IS_NULL: + return has_null ? TruthValue::YES_NO : TruthValue::NO; + case PredicateLeaf::Operator::NULL_SAFE_EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return TruthValue::NO; + if (false_count == 0) + return TruthValue::YES; + } + else + { + if (false_count == 0) + return TruthValue::NO; + if (true_count == 0) + return TruthValue::YES; + } + return TruthValue::YES_NO; + } + case PredicateLeaf::Operator::EQUALS: + { + if (literals.at(0).getBool()) + { + if (true_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (false_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + else + { + if (false_count == 0) + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (true_count == 0) + return has_null ? TruthValue::YES_NULL : TruthValue::YES; + } + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +template +std::vector literalsTo(const std::vector & literals, Get get) +{ + std::vector result; + for (const auto & literal : literals) + if (!literal.isNull()) + result.push_back(get(literal)); + return result; +} + +/// From the reference implementation: the writer version that fixed the timestamp statistics. +constexpr UInt32 WRITER_VERSION_ORC_135 = 6; + +} + +TruthValue PredicateLeaf::evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const +{ + TruthValue result = TruthValue::YES_NO_NULL; + bool has_null = stats.has_null.value_or(false); + + switch (type) + { + case PredicateDataType::LONG: + { + if (stats.int_statistics && stats.int_statistics->minimum && stats.int_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getLong(); }), + *stats.int_statistics->minimum, *stats.int_statistics->maximum, has_null); + break; + } + case PredicateDataType::FLOAT: + { + if (stats.double_statistics && stats.double_statistics->minimum && stats.double_statistics->maximum) + { + if (!std::isfinite(stats.double_statistics->sum.value_or(0))) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + else + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getFloat(); }), + *stats.double_statistics->minimum, *stats.double_statistics->maximum, has_null); + } + break; + } + case PredicateDataType::STRING: + { + if (stats.string_statistics && stats.string_statistics->minimum && stats.string_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getString(); }), + *stats.string_statistics->minimum, *stats.string_statistics->maximum, has_null); + break; + } + case PredicateDataType::DATE: + { + if (stats.date_statistics && stats.date_statistics->minimum && stats.date_statistics->maximum) + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getDate(); }), + static_cast(*stats.date_statistics->minimum), static_cast(*stats.date_statistics->maximum), has_null); + break; + } + case PredicateDataType::TIMESTAMP: + { + const auto & ts = stats.timestamp_statistics; + /// The stored nanoseconds are the sub-millisecond part plus one; malformed ones disable the pruning. + auto valid_nanos = [](const std::optional & nanos) { return !nanos || (*nanos >= 1 && *nanos <= 1'000'000); }; + if (ts && ts->minimum_utc && ts->maximum_utc && valid_nanos(ts->minimum_nanos) && valid_nanos(ts->maximum_nanos)) + { + Int32 min_nanos = ts->minimum_nanos ? static_cast(*ts->minimum_nanos) - 1 : 0; + Int32 max_nanos = ts->maximum_nanos ? static_cast(*ts->maximum_nanos) - 1 : 999999; + /// The milliseconds are rounded down, so the nanoseconds are not negative, as in the literals. + auto to_timestamp = [](Int64 millis, Int32 nanos) + { + Int64 second = millis / 1000; + Int64 rest = millis % 1000; + if (rest < 0) + { + rest += 1000; + --second; + } + return Literal::Timestamp{second, static_cast(rest * 1000000) + nanos}; + }; + Literal::Timestamp min = to_timestamp(*ts->minimum_utc, min_nanos); + Literal::Timestamp max = to_timestamp(*ts->maximum_utc, max_nanos); + result = evaluateRange(op, literalsTo(literals, [](const Literal & l) { return l.getTimestamp(); }), + min, max, has_null); + } + break; + } + case PredicateDataType::DECIMAL: + { + const auto & ds = stats.decimal_statistics; + if (ds && ds->minimum && ds->maximum) + { + Literal::Decimal min; + Literal::Decimal max; + if (min.parse(*ds->minimum) && max.parse(*ds->maximum)) + result = evaluatePredicateRange(op, + literalsTo(literals, [](const Literal & l) { return l.getDecimal(); }), + min, max, has_null, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) < 0; }, + [](const Literal::Decimal & a, const Literal::Decimal & b) { return compareDecimals(a, b) == 0; }); + } + break; + } + case PredicateDataType::BOOLEAN: + { + if (stats.bucket_statistics) + result = evaluateBoolPredicate(op, literals, stats); + break; + } + } + + /// Respect a null literal for IN. + if (op == Operator::IN && has_null) + for (const auto & literal : literals) + if (literal.isNull()) + return TruthValue::YES_NO_NULL; + + return result; +} + +namespace +{ + +TruthValue checkInBloomFilter(PredicateDataType type, const Literal & literal, const BloomFilter & bf, bool has_null) +{ + TruthValue result = has_null ? TruthValue::NO_NULL : TruthValue::NO; + if (literal.isNull()) + result = has_null ? TruthValue::YES_NO_NULL : TruthValue::NO; + else + { + bool found = true; + switch (type) + { + case PredicateDataType::LONG: found = bf.testLong(literal.getLong()); break; + case PredicateDataType::FLOAT: found = bf.testDouble(literal.getFloat()); break; + case PredicateDataType::STRING: found = bf.testBytes(literal.getString().data(), literal.getString().size()); break; + case PredicateDataType::DECIMAL: + { + std::string s = literal.getDecimal().toString(); + found = bf.testBytes(s.data(), s.size()); + break; + } + case PredicateDataType::TIMESTAMP: + { + /// The writers round the negative milliseconds differently: the Java one down, the C++ one toward zero. + const auto timestamp = literal.getTimestamp(); + const Int64 millis_down = timestamp.getMillis(); + const bool has_fraction = timestamp.second < 0 && timestamp.nanos % 1000000 != 0; + found = bf.testLong(millis_down) || (has_fraction && bf.testLong(millis_down + 1)); + break; + } + case PredicateDataType::DATE: found = bf.testLong(literal.getDate()); break; + case PredicateDataType::BOOLEAN: found = true; break; + } + if (found) + result = TruthValue::YES_NO_NULL; + } + + if (result == TruthValue::YES_NO_NULL && !has_null) + result = TruthValue::YES_NO; + return result; +} + +} + +TruthValue PredicateLeaf::evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const +{ + switch (op) + { + case Operator::NULL_SAFE_EQUALS: + /// Null-safe equals does not return the `*_NULL` variants. + return checkInBloomFilter(type, literals.front(), bloom_filter, false); + case Operator::EQUALS: + return checkInBloomFilter(type, literals.front(), bloom_filter, has_null); + case Operator::IN: + for (const auto & literal : literals) + { + TruthValue result = checkInBloomFilter(type, literal, bloom_filter, has_null); + if (result == TruthValue::YES_NO_NULL || result == TruthValue::YES_NO) + return result; + } + return has_null ? TruthValue::NO_NULL : TruthValue::NO; + default: + return has_null ? TruthValue::YES_NO_NULL : TruthValue::YES_NO; + } +} + +TruthValue PredicateLeaf::evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const +{ + /// The files written before ORC-135 store the timestamps in the local time zone of the writer. + if (type == PredicateDataType::TIMESTAMP && writer_version < WRITER_VERSION_ORC_135) + return TruthValue::YES_NO_NULL; + + /// The files written by some writers do not have the `has_null` field. + if (!stats.has_null) + return TruthValue::YES_NO_NULL; + + bool has_null = *stats.has_null; + bool all_null = has_null && stats.number_of_values.value_or(0) == 0; + if (op == Operator::IS_NULL || ((op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS) && literals.at(0).isNull())) + return all_null ? TruthValue::YES : (has_null ? TruthValue::YES_NO : TruthValue::NO); + if (all_null) + return TruthValue::IS_NULL; + + TruthValue result = evaluatePredicateMinMax(stats); + if (bloom_filter && result != TruthValue::NO_NULL && result != TruthValue::NO + && (op == Operator::EQUALS || op == Operator::NULL_SAFE_EQUALS || op == Operator::IN)) + return evaluatePredicateBloomFilter(*bloom_filter, has_null); + return result; +} + + +class ExpressionTree +{ +public: + enum class Operator : UInt8 + { + OR, + AND, + NOT, + LEAF, + CONSTANT, + }; + + explicit ExpressionTree(Operator op_) : op(op_) {} + explicit ExpressionTree(TruthValue constant_) : op(Operator::CONSTANT), constant(constant_) {} + explicit ExpressionTree(size_t leaf_) : op(Operator::LEAF), leaf(leaf_) {} + ExpressionTree(Operator op_, std::vector children_) : op(op_), children(std::move(children_)) {} + + TruthValue evaluate(const std::vector & leaves) const + { + switch (op) + { + case Operator::OR: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && !isNeeded(result); ++i) + result = children[i]->evaluate(leaves) || result; + return result; + } + case Operator::AND: + { + TruthValue result = children.at(0)->evaluate(leaves); + for (size_t i = 1; i < children.size() && isNeeded(result); ++i) + result = children[i]->evaluate(leaves) && result; + return result; + } + case Operator::NOT: + return !children.at(0)->evaluate(leaves); + case Operator::LEAF: + return leaves.at(leaf); + case Operator::CONSTANT: + return constant; + } + return TruthValue::YES_NO_NULL; + } + + Operator op; + TruthValue constant = TruthValue::YES_NO_NULL; + size_t leaf = 0; + std::vector children; +}; + + +SearchArgument::SearchArgument(ExpressionTreePtr root_, std::vector leaves_) + : root(std::move(root_)), leaves(std::move(leaves_)) +{ +} + +TruthValue SearchArgument::evaluate(const std::vector & leaf_values) const +{ + return root ? root->evaluate(leaf_values) : TruthValue::YES_NO_NULL; +} + + +namespace +{ + +using Op = ExpressionTree::Operator; + +/// Pushes the negations down to the leaves and removes the double negations. +ExpressionTreePtr pushDownNot(ExpressionTreePtr root) +{ + if (root->op == Op::NOT) + { + ExpressionTreePtr child = root->children.at(0); + switch (child->op) + { + case Op::NOT: + return pushDownNot(child->children.at(0)); + case Op::CONSTANT: + return std::make_shared(!child->constant); + case Op::AND: + case Op::OR: + { + auto result = std::make_shared(child->op == Op::AND ? Op::OR : Op::AND); + for (const auto & kid : child->children) + result->children.push_back(pushDownNot(std::make_shared(Op::NOT, std::vector{kid}))); + return result; + } + case Op::LEAF: + break; + } + } + else + { + for (auto & kid : root->children) + kid = pushDownNot(kid); + } + return root; +} + +/// Removes the MAYBE (YES_NO_NULL) constants: they are dropped from AND and they replace OR. +ExpressionTreePtr foldMaybe(ExpressionTreePtr expr) +{ + for (auto & kid : expr->children) + { + ExpressionTreePtr child = foldMaybe(kid); + if (child->op == Op::CONSTANT && child->constant == TruthValue::YES_NO_NULL) + { + if (expr->op == Op::AND) + kid = nullptr; + else if (expr->op == Op::OR) + return child; + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Got a maybe as a child of a NOT in ORC search argument"); + } + else + kid = child; + } + + if (!expr->children.empty()) + { + std::erase(expr->children, nullptr); + if (expr->children.empty()) + return std::make_shared(TruthValue::YES_NO_NULL); + } + return expr; +} + +/// Converts multi-level ANDs and ORs into single level ones. +ExpressionTreePtr flatten(ExpressionTreePtr root) +{ + std::vector nodes; + for (auto & kid : root->children) + { + ExpressionTreePtr child = flatten(kid); + if (child->op == root->op && child->op != Op::NOT) + nodes.insert(nodes.end(), child->children.begin(), child->children.end()); + else + nodes.push_back(child); + } + root->children = std::move(nodes); + if ((root->op == Op::OR || root->op == Op::AND) && root->children.size() == 1) + return root->children[0]; + return root; +} + +ExpressionTreePtr copyTree(const ExpressionTreePtr & node) +{ + auto result = std::make_shared(*node); + return result; +} + +void generateAllCombinations( + std::vector & result, const std::vector & and_list, size_t and_index, const std::vector & non_and_list) +{ + const auto & kids = and_list[and_index]->children; + if (result.empty()) + { + for (const auto & kid : kids) + { + auto node = std::make_shared(Op::OR); + for (const auto & non_and : non_and_list) + node->children.push_back(copyTree(non_and)); + node->children.push_back(kid); + result.push_back(node); + } + } + else + { + std::vector work = std::move(result); + result.clear(); + for (const auto & kid : kids) + { + for (const auto & node : work) + { + auto copy = copyTree(node); + copy->children.push_back(kid); + result.push_back(copy); + } + } + } + if (and_index + 1 < and_list.size()) + generateAllCombinations(result, and_list, and_index + 1, non_and_list); +} + +constexpr size_t CNF_COMBINATIONS_THRESHOLD = 256; + +/// Converts the expression into the conjunctive normal form, if it is not too large. +ExpressionTreePtr convertToCNF(ExpressionTreePtr root) +{ + for (auto & kid : root->children) + kid = convertToCNF(kid); + + if (root->op != Op::OR) + return root; + + std::vector non_and_list; + std::vector and_list; + for (const auto & child : root->children) + { + if (child->op == Op::AND) + and_list.push_back(child); + else if (child->op == Op::OR) + non_and_list.insert(non_and_list.end(), child->children.begin(), child->children.end()); + else + non_and_list.push_back(child); + } + + if (and_list.empty()) + return root; + + size_t num_combinations = 1; + for (const auto & node : and_list) + { + num_combinations *= node->children.size(); + if (num_combinations > CNF_COMBINATIONS_THRESHOLD) + return std::make_shared(TruthValue::YES_NO_NULL); + } + + auto result = std::make_shared(Op::AND); + generateAllCombinations(result->children, and_list, 0, non_and_list); + return result; +} + +void collectUsedLeaves(const ExpressionTreePtr & node, std::vector & reorder, size_t & next) +{ + if (node->op == Op::LEAF) + { + if (reorder[node->leaf] == std::numeric_limits::max()) + reorder[node->leaf] = next++; + return; + } + for (const auto & kid : node->children) + collectUsedLeaves(kid, reorder, next); +} + +/// The trees can share nodes after the CNF conversion, so rewrite every leaf node exactly once. +void rewriteLeaves(const ExpressionTreePtr & root, const std::vector & reorder) +{ + std::unordered_set leaves; + std::deque nodes{root.get()}; + while (!nodes.empty()) + { + ExpressionTree * node = nodes.front(); + nodes.pop_front(); + if (node->op == Op::LEAF) + leaves.insert(node); + else + for (const auto & kid : node->children) + nodes.push_back(kid.get()); + } + for (auto * leaf : leaves) + leaf->leaf = reorder[leaf->leaf]; +} + +} + + +SearchArgumentBuilder::SearchArgumentBuilder() +{ + root = std::make_shared(Op::AND); + stack.push_back(root); +} + +SearchArgumentBuilder & SearchArgumentBuilder::start(UInt8 op) +{ + auto node = std::make_shared(static_cast(op)); + stack.back()->children.push_back(node); + stack.push_back(node); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::startOr() { return start(static_cast(Op::OR)); } +SearchArgumentBuilder & SearchArgumentBuilder::startAnd() { return start(static_cast(Op::AND)); } +SearchArgumentBuilder & SearchArgumentBuilder::startNot() { return start(static_cast(Op::NOT)); } + +SearchArgumentBuilder & SearchArgumentBuilder::end() +{ + auto current = stack.back(); + stack.pop_back(); + if (stack.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unbalanced end() in ORC search argument builder"); + if (current->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an expression with no children in ORC search argument builder"); + if (current->op == Op::NOT && current->children.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "A NOT expression must have exactly one child in ORC search argument builder"); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::literal(TruthValue value) +{ + stack.back()->children.push_back(std::make_shared(value)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::addLeaf(PredicateLeaf leaf) +{ + size_t index = leaves.size(); + leaves.push_back(std::move(leaf)); + stack.back()->children.push_back(std::make_shared(index)); + return *this; +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThan(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::LESS_THAN_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::equals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::NULL_SAFE_EQUALS, type, column_id, {std::move(value)})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::in(UInt64 column_id, PredicateDataType type, const std::vector & values) +{ + if (values.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create an IN expression with no arguments in ORC search argument builder"); + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IN, type, column_id, values)); +} + +SearchArgumentBuilder & SearchArgumentBuilder::isNull(UInt64 column_id, PredicateDataType type) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::IS_NULL, type, column_id, {})); +} + +SearchArgumentBuilder & SearchArgumentBuilder::between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper) +{ + return addLeaf(PredicateLeaf(PredicateLeaf::Operator::BETWEEN, type, column_id, {std::move(lower), std::move(upper)})); +} + +std::unique_ptr SearchArgumentBuilder::build() +{ + if (stack.size() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to end {} operations in ORC search argument builder", stack.size() - 1); + if (root->children.empty()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Empty ORC search argument"); + + root = pushDownNot(root); + root = foldMaybe(root); + root = flatten(root); + root = convertToCNF(root); + root = flatten(root); + + std::vector reorder(leaves.size(), std::numeric_limits::max()); + size_t num_used = 0; + collectUsedLeaves(root, reorder, num_used); + rewriteLeaves(root, reorder); + + std::vector used_leaves; + used_leaves.reserve(num_used); + std::vector by_new_index(num_used); + for (size_t i = 0; i < leaves.size(); ++i) + if (reorder[i] != std::numeric_limits::max()) + by_new_index[reorder[i]] = &leaves[i]; + for (const auto * leaf : by_new_index) + used_leaves.push_back(*leaf); + + return std::make_unique(root, std::move(used_leaves)); +} + + +namespace +{ + +constexpr UInt32 MURMUR3_DEFAULT_SEED = 104729; + +inline UInt64 rotl64(UInt64 x, int r) +{ + return (x << r) | (x >> (64 - r)); +} + +inline UInt64 fmix64(UInt64 value) +{ + value ^= (value >> 33); + value *= 0xff51afd7ed558ccdULL; + value ^= (value >> 33); + value *= 0xc4ceb9fe1a85ec53ULL; + value ^= (value >> 33); + return value; +} + +/// The 64-bit variant of Murmur3 used by ORC (the lower half of the 128-bit hash with one state). +UInt64 murmur3Hash64(const UInt8 * data, size_t size) +{ + UInt64 h = MURMUR3_DEFAULT_SEED; + const UInt64 c1 = 0x87c37b91114253d5ULL; + const UInt64 c2 = 0x4cf5ad432745937fULL; + size_t blocks = size >> 3; + for (size_t i = 0; i < blocks; ++i) + { + UInt64 k = 0; + memcpy(&k, data + i * 8, 8); + if constexpr (std::endian::native == std::endian::big) + k = std::byteswap(k); + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + h = rotl64(h, 27); + h = h * 5 + 0x52dce729; + } + + UInt64 k = 0; + size_t idx = blocks << 3; + size_t tail = size - idx; + for (size_t i = tail; i > 0; --i) + k ^= static_cast(data[idx + i - 1]) << ((i - 1) * 8); + if (tail) + { + k *= c1; + k = rotl64(k, 31); + k *= c2; + h ^= k; + } + + h ^= static_cast(size); + return fmix64(h); +} + +/// Thomas Wang's 64-bit integer hash, as in the reference implementation. +Int64 getLongHash(Int64 key) +{ + UInt64 k = static_cast(key); + k = (~k) + (k << 21); + k = k ^ static_cast(static_cast(k) >> 24); + k = (k + (k << 3)) + (k << 8); + k = k ^ static_cast(static_cast(k) >> 14); + k = (k + (k << 2)) + (k << 4); + k = k ^ static_cast(static_cast(k) >> 28); + k = k + (k << 31); + return static_cast(k); +} + +} + +BloomFilter::BloomFilter(const Proto::BloomFilter & proto) : num_hash_functions(proto.num_hash_functions) +{ + /// The writers use a few hash functions (the optimal number for the false positive probability), + /// a huge number from a corrupt file would make every probe extremely slow. + static constexpr UInt32 MAX_HASH_FUNCTIONS = 256; + if (num_hash_functions == 0 || num_hash_functions > MAX_HASH_FUNCTIONS) + throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid number of hash functions {} of a bloom filter in ORC file, must be from 1 to {}", + num_hash_functions, MAX_HASH_FUNCTIONS); + const std::string & bitset = proto.utf8bitset.value(); + if (bitset.empty() || bitset.size() % 8 != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "The size of a bloom filter in ORC file must be a positive multiple of 8 bytes"); + bits.resize(bitset.size() / 8); + memcpy(bits.data(), bitset.data(), bitset.size()); + if constexpr (std::endian::native == std::endian::big) + for (auto & word : bits) + word = std::byteswap(word); +} + +bool BloomFilter::testHash(Int64 hash) const +{ + Int32 hash1 = static_cast(hash & 0xffffffff); + Int32 hash2 = static_cast(static_cast(hash) >> 32); + UInt64 num_bits = bits.size() * 64; + for (UInt32 i = 1; i <= num_hash_functions; ++i) + { + Int32 combined = static_cast(static_cast(hash1) + i * static_cast(hash2)); + if (combined < 0) + combined = ~combined; + UInt64 pos = static_cast(combined) % num_bits; + if (!(bits[pos >> 6] & (1ULL << (pos % 64)))) + return false; + } + return true; +} + +bool BloomFilter::testLong(Int64 value) const +{ + return testHash(getLongHash(value)); +} + +bool BloomFilter::testDouble(double value) const +{ + return testLong(std::bit_cast(value)); +} + +bool BloomFilter::testBytes(const char * data, size_t size) const +{ + return testHash(static_cast(murmur3Hash64(reinterpret_cast(data), size))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.h b/src/Processors/Formats/Impl/ORC/SearchArgument.h new file mode 100644 index 000000000000..da19904275e7 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/SearchArgument.h @@ -0,0 +1,198 @@ +#pragma once + +#include + +#include +#include +#include + +/// Predicates for skipping stripes and row groups by the column statistics and the bloom filters. +/// The semantics (the truth values, the normalization of the expression, the evaluation of each +/// predicate against the statistics) are the same as in the reference implementation. + +namespace DB::ORC +{ + +/// The possible outcomes of a predicate over a set of rows: whether any row can satisfy it (YES), +/// fail it (NO), or evaluate it to NULL. +enum class TruthValue : UInt8 +{ + YES, + NO, + IS_NULL, + YES_NULL, + NO_NULL, + YES_NO, + YES_NO_NULL, +}; + +TruthValue operator||(TruthValue left, TruthValue right); +TruthValue operator&&(TruthValue left, TruthValue right); +TruthValue operator!(TruthValue value); +/// Whether the rows have to be read. +bool isNeeded(TruthValue value); + +enum class PredicateDataType : UInt8 +{ + LONG, + FLOAT, + STRING, + DATE, + DECIMAL, + TIMESTAMP, + BOOLEAN, +}; + +class Literal +{ +public: + struct Timestamp + { + Int64 second = 0; + Int32 nanos = 0; + + /// Rounded down, as the nanoseconds are not negative. + Int64 getMillis() const { return second * 1000 + nanos / 1000000; } + auto operator<=>(const Timestamp &) const = default; + }; + + struct Decimal + { + Int128 value = 0; + Int32 scale = 0; + + /// Parses a decimal number like `-123.45`. Returns false if it is malformed. + bool parse(std::string_view s); + /// Without the trailing zeros in the fraction, as in the bloom filters. + std::string toString() const; + }; + + explicit Literal(bool value); + explicit Literal(Int64 value); + explicit Literal(double value); + Literal(const char * data, size_t size); + /// Only for DATE: the number of days since the epoch. + Literal(PredicateDataType type, Int64 value); + /// TIMESTAMP: the seconds since the epoch in UTC and the nanoseconds. + Literal(Int64 second, Int32 nanos); + Literal(Int128 value, Int32 precision, Int32 scale); + + PredicateDataType getType() const { return type; } + bool isNull() const { return is_null; } + + bool getBool() const { return int_value != 0; } + Int64 getLong() const { return int_value; } + Int64 getDate() const { return int_value; } + double getFloat() const { return float_value; } + const std::string & getString() const { return string_value; } + Timestamp getTimestamp() const { return timestamp_value; } + Decimal getDecimal() const { return decimal_value; } + +private: + PredicateDataType type; + bool is_null = false; + Int64 int_value = 0; + double float_value = 0; + std::string string_value; + Timestamp timestamp_value; + Decimal decimal_value; +}; + +class BloomFilter; + +class PredicateLeaf +{ +public: + enum class Operator : UInt8 + { + EQUALS, + NULL_SAFE_EQUALS, + LESS_THAN, + LESS_THAN_EQUALS, + IN, + BETWEEN, + IS_NULL, + }; + + PredicateLeaf(Operator op_, PredicateDataType type_, UInt64 column_id_, std::vector literals_) + : op(op_), type(type_), column_id(column_id_), literals(std::move(literals_)) {} + + UInt64 getColumnId() const { return column_id; } + + /// `writer_version` is from the postscript of the file. `bloom_filter` can be nullptr. + TruthValue evaluate(UInt32 writer_version, const Proto::ColumnStatistics & stats, const BloomFilter * bloom_filter) const; + +private: + TruthValue evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const; + TruthValue evaluatePredicateBloomFilter(const BloomFilter & bloom_filter, bool has_null) const; + + Operator op; + PredicateDataType type; + UInt64 column_id; + std::vector literals; +}; + +class ExpressionTree; +using ExpressionTreePtr = std::shared_ptr; + +class SearchArgument +{ +public: + SearchArgument(ExpressionTreePtr root_, std::vector leaves_); + + const std::vector & getLeaves() const { return leaves; } + TruthValue evaluate(const std::vector & leaf_values) const; + +private: + ExpressionTreePtr root; + std::vector leaves; +}; + +class SearchArgumentBuilder +{ +public: + SearchArgumentBuilder(); + + SearchArgumentBuilder & startOr(); + SearchArgumentBuilder & startAnd(); + SearchArgumentBuilder & startNot(); + SearchArgumentBuilder & end(); + + SearchArgumentBuilder & literal(TruthValue value); + SearchArgumentBuilder & lessThan(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & lessThanEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & equals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & nullSafeEquals(UInt64 column_id, PredicateDataType type, Literal value); + SearchArgumentBuilder & in(UInt64 column_id, PredicateDataType type, const std::vector & values); + SearchArgumentBuilder & isNull(UInt64 column_id, PredicateDataType type); + SearchArgumentBuilder & between(UInt64 column_id, PredicateDataType type, Literal lower, Literal upper); + + std::unique_ptr build(); + +private: + SearchArgumentBuilder & start(UInt8 op); + SearchArgumentBuilder & addLeaf(PredicateLeaf leaf); + + std::vector stack; + ExpressionTreePtr root; + std::vector leaves; +}; + +/// A bloom filter of a row group (or a stripe), from the BLOOM_FILTER_UTF8 stream. +class BloomFilter +{ +public: + explicit BloomFilter(const Proto::BloomFilter & proto); + + bool testLong(Int64 value) const; + bool testDouble(double value) const; + bool testBytes(const char * data, size_t size) const; + +private: + bool testHash(Int64 hash) const; + + UInt32 num_hash_functions; + std::vector bits; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.cpp b/src/Processors/Formats/Impl/ORC/Statistics.cpp new file mode 100644 index 000000000000..0b1b4c86cd9b --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.cpp @@ -0,0 +1,462 @@ +#include +#include + +#include + +#include + + +namespace DB::ORC +{ + +namespace +{ + +int compareDecimals(Int128 a, Int32 a_scale, Int128 b, Int32 b_scale) +{ + Int256 left = a; + Int256 right = b; + for (Int32 s = a_scale; s < b_scale; ++s) + left *= 10; + for (Int32 s = b_scale; s < a_scale; ++s) + right *= 10; + return left < right ? -1 : (left == right ? 0 : 1); +} + +std::string decimalToString(Int128 value, Int32 scale) +{ + return Literal::Decimal{value, scale}.toString(); +} + +} + +void StatisticsBuilder::updateInteger(Int64 value) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + if (has_int_sum && __builtin_add_overflow(int_sum, value, &int_sum)) + has_int_sum = false; +} + +void StatisticsBuilder::updateDouble(double value) +{ + if (!has_minimum) + { + has_minimum = true; + double_minimum = double_maximum = value; + } + else + { + double_minimum = std::min(double_minimum, value); + double_maximum = std::max(double_maximum, value); + } + double_sum += value; +} + +void StatisticsBuilder::updateString(std::string_view value) +{ + if (!has_minimum) + { + has_minimum = true; + string_minimum = value; + string_maximum = value; + } + else + { + if (value < std::string_view(string_minimum)) + string_minimum = value; + if (value > std::string_view(string_maximum)) + string_maximum = value; + } + total_length += value.size(); +} + +void StatisticsBuilder::updateBinary(size_t length) +{ + total_length += length; +} + +void StatisticsBuilder::updateBoolean(bool value) +{ + if (value) + ++true_count; +} + +void StatisticsBuilder::updateDate(Int32 value) +{ + updateInteger(value); +} + +void StatisticsBuilder::updateDecimal(Int128 value, Int32 scale) +{ + if (!has_minimum) + { + has_minimum = true; + decimal_minimum = decimal_maximum = value; + decimal_minimum_scale = decimal_maximum_scale = scale; + } + else + { + if (compareDecimals(value, scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = value; + decimal_minimum_scale = scale; + } + if (compareDecimals(value, scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = value; + decimal_maximum_scale = scale; + } + } + + if (has_decimal_sum) + { + Int256 sum = decimal_sum; + Int256 addend = value; + Int32 result_scale = std::max(decimal_sum_scale, scale); + for (Int32 s = decimal_sum_scale; s < result_scale; ++s) + sum *= 10; + for (Int32 s = scale; s < result_scale; ++s) + addend *= 10; + sum += addend; + if (sum > Int256(std::numeric_limits::max()) || sum < Int256(std::numeric_limits::min())) + has_decimal_sum = false; + else + { + decimal_sum = static_cast(sum); + decimal_sum_scale = result_scale; + } + } +} + +void StatisticsBuilder::updateTimestamp(Int64 millis, Int32 nanos) +{ + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = millis; + minimum_nanos = maximum_nanos = nanos; + return; + } + if (millis <= int_minimum) + { + if (millis < int_minimum || nanos < minimum_nanos) + minimum_nanos = nanos; + int_minimum = millis; + } + if (millis >= int_maximum) + { + if (millis > int_maximum || nanos > maximum_nanos) + maximum_nanos = nanos; + int_maximum = millis; + } +} + +void StatisticsBuilder::updateCollection(UInt64 children) +{ + Int64 value = static_cast(children); + if (!has_minimum) + { + has_minimum = true; + int_minimum = int_maximum = value; + } + else + { + int_minimum = std::min(int_minimum, value); + int_maximum = std::max(int_maximum, value); + } + total_children += children; +} + +void StatisticsBuilder::merge(const StatisticsBuilder & other) +{ + number_of_values += other.number_of_values; + has_null |= other.has_null; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + case DATE: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + has_int_sum = has_int_sum && other.has_int_sum; + if (has_int_sum && __builtin_add_overflow(int_sum, other.int_sum, &int_sum)) + has_int_sum = false; + break; + case FLOAT: + case DOUBLE: + if (other.has_minimum) + { + if (!has_minimum) + { + double_minimum = other.double_minimum; + double_maximum = other.double_maximum; + } + else + { + double_minimum = std::min(double_minimum, other.double_minimum); + double_maximum = std::max(double_maximum, other.double_maximum); + } + has_minimum = true; + } + double_sum += other.double_sum; + break; + case STRING: + case CHAR: + case VARCHAR: + if (other.has_minimum) + { + if (!has_minimum) + { + string_minimum = other.string_minimum; + string_maximum = other.string_maximum; + } + else + { + if (other.string_minimum < string_minimum) + string_minimum = other.string_minimum; + if (other.string_maximum > string_maximum) + string_maximum = other.string_maximum; + } + has_minimum = true; + } + total_length += other.total_length; + break; + case BINARY: + total_length += other.total_length; + break; + case BOOLEAN: + true_count += other.true_count; + break; + case DECIMAL: + if (other.has_minimum) + { + if (!has_minimum) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + else + { + if (compareDecimals(other.decimal_minimum, other.decimal_minimum_scale, decimal_minimum, decimal_minimum_scale) < 0) + { + decimal_minimum = other.decimal_minimum; + decimal_minimum_scale = other.decimal_minimum_scale; + } + if (compareDecimals(other.decimal_maximum, other.decimal_maximum_scale, decimal_maximum, decimal_maximum_scale) > 0) + { + decimal_maximum = other.decimal_maximum; + decimal_maximum_scale = other.decimal_maximum_scale; + } + } + has_minimum = true; + } + has_decimal_sum = has_decimal_sum && other.has_decimal_sum; + if (has_decimal_sum) + { + /// Reuse the update of the sum without touching the minimum and the maximum. + bool saved_has_minimum = has_minimum; + Int128 saved_min = decimal_minimum; + Int32 saved_min_scale = decimal_minimum_scale; + Int128 saved_max = decimal_maximum; + Int32 saved_max_scale = decimal_maximum_scale; + updateDecimal(other.decimal_sum, other.decimal_sum_scale); + has_minimum = saved_has_minimum; + decimal_minimum = saved_min; + decimal_minimum_scale = saved_min_scale; + decimal_maximum = saved_max; + decimal_maximum_scale = saved_max_scale; + } + break; + case TIMESTAMP: + case TIMESTAMP_INSTANT: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + minimum_nanos = other.minimum_nanos; + maximum_nanos = other.maximum_nanos; + has_minimum = true; + } + else + { + if (other.int_minimum <= int_minimum) + { + if (other.int_minimum < int_minimum || other.minimum_nanos < minimum_nanos) + minimum_nanos = other.minimum_nanos; + int_minimum = other.int_minimum; + } + if (other.int_maximum >= int_maximum) + { + if (other.int_maximum > int_maximum || other.maximum_nanos > maximum_nanos) + maximum_nanos = other.maximum_nanos; + int_maximum = other.int_maximum; + } + } + } + break; + case LIST: + case MAP: + if (other.has_minimum) + { + if (!has_minimum) + { + int_minimum = other.int_minimum; + int_maximum = other.int_maximum; + } + else + { + int_minimum = std::min(int_minimum, other.int_minimum); + int_maximum = std::max(int_maximum, other.int_maximum); + } + has_minimum = true; + } + total_children += other.total_children; + break; + default: + break; + } +} + +void StatisticsBuilder::reset() +{ + *this = StatisticsBuilder(kind); +} + +Proto::ColumnStatistics StatisticsBuilder::toProto() const +{ + Proto::ColumnStatistics res; + res.has_null = has_null; + res.number_of_values = number_of_values; + + switch (kind) + { + case BYTE: + case SHORT: + case INT: + case LONG: + { + auto & stats = res.int_statistics.emplace(); + if (has_minimum) + { + stats.minimum = int_minimum; + stats.maximum = int_maximum; + } + if (has_int_sum) + stats.sum = int_sum; + break; + } + case DATE: + { + auto & stats = res.date_statistics.emplace(); + if (has_minimum) + { + stats.minimum = static_cast(int_minimum); + stats.maximum = static_cast(int_maximum); + } + break; + } + case FLOAT: + case DOUBLE: + { + auto & stats = res.double_statistics.emplace(); + if (has_minimum) + { + stats.minimum = double_minimum; + stats.maximum = double_maximum; + } + stats.sum = double_sum; + break; + } + case STRING: + case CHAR: + case VARCHAR: + { + auto & stats = res.string_statistics.emplace(); + if (has_minimum) + { + stats.minimum = string_minimum; + stats.maximum = string_maximum; + } + stats.sum = static_cast(total_length); + break; + } + case BINARY: + res.binary_statistics.emplace().sum = static_cast(total_length); + break; + case BOOLEAN: + res.bucket_statistics.emplace().count.push_back(true_count); + break; + case DECIMAL: + { + auto & stats = res.decimal_statistics.emplace(); + if (has_minimum) + { + stats.minimum = decimalToString(decimal_minimum, decimal_minimum_scale); + stats.maximum = decimalToString(decimal_maximum, decimal_maximum_scale); + } + if (has_decimal_sum) + stats.sum = decimalToString(decimal_sum, decimal_sum_scale); + break; + } + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + auto & stats = res.timestamp_statistics.emplace(); + if (has_minimum) + { + stats.minimum_utc = int_minimum; + stats.maximum_utc = int_maximum; + if (minimum_nanos != 0) + stats.minimum_nanos = static_cast(minimum_nanos) + 1; + if (maximum_nanos != 999999) + stats.maximum_nanos = static_cast(maximum_nanos) + 1; + } + break; + } + case LIST: + case MAP: + { + auto & stats = res.collection_statistics.emplace(); + if (has_minimum) + { + stats.min_children = static_cast(int_minimum); + stats.max_children = static_cast(int_maximum); + } + stats.total_children = total_children; + break; + } + default: + break; + } + return res; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Statistics.h b/src/Processors/Formats/Impl/ORC/Statistics.h new file mode 100644 index 000000000000..c00c00e07b94 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Statistics.h @@ -0,0 +1,71 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// Accumulates the statistics of a column for a row group, a stripe or the whole file, +/// in the same way as the reference implementation. +class StatisticsBuilder +{ +public: + explicit StatisticsBuilder(TypeKind kind_) : kind(kind_) {} + + void increase(UInt64 count) { number_of_values += count; } + void setHasNull() { has_null = true; } + + void updateInteger(Int64 value); + void updateDouble(double value); + void updateString(std::string_view value); + void updateBinary(size_t length); + void updateBoolean(bool value); + void updateDate(Int32 value); + void updateDecimal(Int128 value, Int32 scale); + /// `millis` since the epoch in UTC, `nanos` is the sub-millisecond part. + void updateTimestamp(Int64 millis, Int32 nanos); + void updateCollection(UInt64 children); + + void merge(const StatisticsBuilder & other); + void reset(); + + Proto::ColumnStatistics toProto() const; + +private: + TypeKind kind; + UInt64 number_of_values = 0; + bool has_null = false; + bool has_minimum = false; + + Int64 int_minimum = 0; + Int64 int_maximum = 0; + Int64 int_sum = 0; + bool has_int_sum = true; + + double double_minimum = 0; + double double_maximum = 0; + double double_sum = 0; + + std::string string_minimum; + std::string string_maximum; + UInt64 total_length = 0; + + UInt64 true_count = 0; + + Int128 decimal_minimum = 0; + Int32 decimal_minimum_scale = 0; + Int128 decimal_maximum = 0; + Int32 decimal_maximum_scale = 0; + Int128 decimal_sum = 0; + Int32 decimal_sum_scale = 0; + bool has_decimal_sum = true; + + Int32 minimum_nanos = 0; + Int32 maximum_nanos = 999999; + + UInt64 total_children = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.cpp b/src/Processors/Formats/Impl/ORC/Stream.cpp new file mode 100644 index 000000000000..275e75915dca --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.cpp @@ -0,0 +1,248 @@ +#include + +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +UInt64 PositionProvider::next() +{ + if (index >= positions.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Not enough positions in a row index entry of ORC file"); + return positions[index++]; +} + + +InputByteStream::InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_) + : data(data_), length(data_.size()), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +InputByteStream::InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_) + : length(length_), loader(std::move(loader_)), compression(compression_), block_size(block_size_), name(std::move(name_)) +{ +} + +std::string_view InputByteStream::getRange(UInt64 offset, UInt64 size) +{ + if (!loader) + return data.substr(offset, size); + + if (offset < window_offset || offset + size > window_offset + data.size()) + { + UInt64 load_size = std::min(length - offset, std::max(size, LAZY_READ_SIZE)); + auto range = loader(offset, load_size); + if (range.data.size() != load_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Loaded {} bytes instead of {} from ORC stream {}", range.data.size(), load_size, name); + window_holder = std::move(range.holder); + data = range.data; + window_offset = offset; + } + return data.substr(offset - window_offset, size); +} + +bool InputByteStream::nextChunk() +{ + while (next_chunk_offset < length) + { + if (compression == CompressionKind::NONE) + { + UInt64 size = length - next_chunk_offset; + if (loader) + size = std::min(size, LAZY_READ_SIZE); + pos = getRange(next_chunk_offset, size).data(); + end = pos + size; + next_chunk_offset += size; + return true; + } + + if (length - next_chunk_offset < COMPRESSION_HEADER_SIZE) + throw Exception(ErrorCodes::INCORRECT_DATA, "Truncated compression chunk header in ORC stream {}", name); + + const UInt8 * header = reinterpret_cast(getRange(next_chunk_offset, COMPRESSION_HEADER_SIZE).data()); + UInt32 header_value = header[0] | (header[1] << 8) | (header[2] << 16); + bool is_original = header_value & 1; + size_t chunk_length = header_value >> 1; + size_t chunk_offset = next_chunk_offset + COMPRESSION_HEADER_SIZE; + + if (chunk_length > length - chunk_offset) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Compression chunk of size {} at offset {} goes beyond the end of ORC stream {} of size {}", + chunk_length, next_chunk_offset, name, length); + + next_chunk_offset = chunk_offset + chunk_length; + const char * chunk = getRange(chunk_offset, chunk_length).data(); + + if (is_original) + { + pos = chunk; + end = chunk + chunk_length; + } + else + { + /// The chunk length is at most 8 MiB, so the bound does not overflow. + size_t capacity = std::min(block_size, maxDecompressedSize(compression, chunk, chunk_length)); + if (decompressed.size() < capacity) + decompressed.resize(capacity); + size_t size = decompressChunk(compression, chunk, chunk_length, decompressed.data(), capacity); + pos = decompressed.data(); + end = decompressed.data() + size; + } + + if (pos != end) + return true; + } + + pos = end = nullptr; + return false; +} + +void InputByteStream::readBytes(char * to, size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + memcpy(to, pos, count); + pos += count; + to += count; + n -= count; + } +} + +void InputByteStream::skipBytes(size_t n) +{ + while (n) + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + size_t count = std::min(n, static_cast(end - pos)); + pos += count; + n -= count; + } +} + +void InputByteStream::seek(PositionProvider & positions) +{ + if (compression == CompressionKind::NONE) + { + UInt64 offset = positions.next(); + if (offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", offset, name, length); + next_chunk_offset = offset; + pos = end = nullptr; + nextChunk(); + return; + } + + UInt64 chunk_offset = positions.next(); + UInt64 uncompressed_offset = positions.next(); + if (chunk_offset > length) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {} of size {}", chunk_offset, name, length); + + next_chunk_offset = chunk_offset; + pos = end = nullptr; + if (!nextChunk()) + { + if (uncompressed_offset != 0) + throw Exception(ErrorCodes::INCORRECT_DATA, "Seek position {} is beyond the end of ORC stream {}", uncompressed_offset, name); + return; + } + + if (uncompressed_offset > static_cast(end - pos)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Seek position {} is beyond the end of the compression chunk of size {} in ORC stream {}", + uncompressed_offset, end - pos, name); + pos += uncompressed_offset; +} + +void InputByteStream::throwUnexpectedEnd() const +{ + throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected end of ORC stream {}", name); +} + + +OutputByteStream::OutputByteStream(Compressor * compressor_, size_t block_size_) + : compressor(compressor_), block_size(block_size_) +{ + buffer.reserve(std::min(block_size, 64 * 1024)); +} + +void OutputByteStream::write(const char * data, size_t size) +{ + while (size) + { + if (buffer.size() == block_size) + flushChunk(); + size_t count = std::min(size, block_size - buffer.size()); + buffer.append(data, count); + data += count; + size -= count; + } +} + +void OutputByteStream::recordPosition(std::vector & positions) const +{ + if (compressor) + { + positions.push_back(output.size()); + positions.push_back(buffer.size()); + } + else + positions.push_back(output.size() + buffer.size()); +} + +void OutputByteStream::flushChunk() +{ + if (buffer.empty()) + return; + + if (!compressor) + { + output.append(buffer); + buffer.clear(); + return; + } + + size_t header_offset = output.size(); + output.append(COMPRESSION_HEADER_SIZE, '\0'); + size_t compressed_size = compressor->compress(buffer.data(), buffer.size(), output); + + UInt32 header_value = 0; + if (compressed_size) + header_value = static_cast(compressed_size << 1); + else + { + output.append(buffer); + header_value = static_cast((buffer.size() << 1) | 1); + } + + output[header_offset] = static_cast(header_value & 0xFF); + output[header_offset + 1] = static_cast((header_value >> 8) & 0xFF); + output[header_offset + 2] = static_cast((header_value >> 16) & 0xFF); + buffer.clear(); +} + +size_t OutputByteStream::finish() +{ + flushChunk(); + return output.size(); +} + +void OutputByteStream::reset() +{ + buffer.clear(); + output.clear(); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Stream.h b/src/Processors/Formats/Impl/ORC/Stream.h new file mode 100644 index 000000000000..44d209d38321 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Stream.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace DB::ORC +{ + +/// A sequence of positions from a row index entry, consumed by the streams and the decoders of a +/// column in their order. +class PositionProvider +{ +public: + explicit PositionProvider(const std::vector & positions_) : positions(positions_) {} + UInt64 next(); + +private: + const std::vector & positions; + size_t index = 0; +}; + +/// A piece of a stream loaded from the file. `data` is valid while `holder` is alive. +struct LoadedRange +{ + std::shared_ptr holder; + std::string_view data; +}; + +/// Loads the range `(offset, length)` of a stream from the file. +using RangeLoader = std::function; + +/// A stream of an ORC column, such as PRESENT or DATA, decompressed chunk by chunk. The decoders +/// read from the buffer `[pos, end)` of the current chunk directly. +class InputByteStream +{ +public: + /// The whole stream in memory. `data` must outlive the stream. + InputByteStream(std::string_view data_, CompressionKind compression_, size_t block_size_, std::string name_); + /// The stream of `length_` bytes is loaded from the file on demand, by `loader_`, a window of + /// at least `LAZY_READ_SIZE` bytes at a time. Used when only some row groups are read. + InputByteStream(RangeLoader loader_, UInt64 length_, CompressionKind compression_, size_t block_size_, std::string name_); + + static constexpr size_t LAZY_READ_SIZE = 1024 * 1024; + + /// Loads the next chunk. Returns false at the end of the stream. + bool nextChunk(); + + bool eof() + { + return pos == end && !nextChunk(); + } + + UInt8 readByte() + { + if (pos == end && !nextChunk()) + throwUnexpectedEnd(); + return static_cast(*pos++); + } + + void readBytes(char * to, size_t n); + void skipBytes(size_t n); + + /// Moves to the position from the row index: one value (the byte offset) for an uncompressed + /// stream, two values (the offset of the compressed chunk and the offset in its decompressed + /// data) for a compressed one. + void seek(PositionProvider & positions); + + [[noreturn]] void throwUnexpectedEnd() const; + + const std::string & getName() const { return name; } + + const char * pos = nullptr; + const char * end = nullptr; + +private: + /// Returns the range `[offset, offset + length)` of the stream. It is valid until the next call. + std::string_view getRange(UInt64 offset, UInt64 length); + + /// The stream in memory, or the currently loaded window of a lazily loaded stream. + std::string_view data; + UInt64 length; + RangeLoader loader; + /// For a lazily loaded stream: the offset of `data` in the stream, and its owner. + UInt64 window_offset = 0; + std::shared_ptr window_holder; + + CompressionKind compression; + size_t block_size; + std::string name; + + /// The offset of the next chunk to read in `data`. + size_t next_chunk_offset = 0; + PODArray decompressed; +}; + +/// Accumulates a stream of an ORC column, compressing it chunk by chunk. +class OutputByteStream +{ +public: + /// `compressor` can be nullptr, which means no compression. + OutputByteStream(Compressor * compressor_, size_t block_size_); + + void writeByte(UInt8 byte) + { + if (buffer.size() == block_size) + flushChunk(); + buffer.push_back(static_cast(byte)); + } + + void write(const char * data, size_t size); + + /// Appends the current position to `positions`, in the format that `InputByteStream::seek` expects. + void recordPosition(std::vector & positions) const; + + /// Finishes the stream and returns its size in bytes. + size_t finish(); + + const std::string & getOutput() const { return output; } + + /// Clears the stream to start a new stripe. + void reset(); + + size_t estimateSize() const { return output.size() + buffer.size(); } + +private: + void flushChunk(); + + Compressor * compressor; + size_t block_size; + std::string buffer; + std::string output; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.cpp b/src/Processors/Formats/Impl/ORC/Timezone.cpp new file mode 100644 index 000000000000..33a1574507d2 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.cpp @@ -0,0 +1,87 @@ +#include + +#include +#include + +#include + +/// The embedded time zone files, see `DateLUTImpl.cpp`. +std::string_view getTimeZone(const char * name); /// NOLINT(misc-use-internal-linkage) + +namespace DB +{ +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +TimezoneOffset::TimezoneOffset(const DateLUTImpl & lut_) + : lut(lut_) +{ + const std::string & name = lut.getTimeZone(); + const std::string_view file = getTimeZone(name.c_str()); + /// `Fixed/UTC±HH:MM:SS` zones have no file. On this branch `DateLUT` also loads zones that are not embedded + /// (`libc:` names, the host database), so keep the offsets of `DateLUTImpl` for all of them. + if (file.empty()) + return; + + /// Raw records, as `cctz::time_zone::next_transition` skips no-op ones (Europe/Lisbon has one in 1884). + static constexpr size_t header_size = 44; + size_t pos = 0; + auto check = [&](size_t size) + { + if (size > file.size() - pos) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + }; + auto read_count = [&](size_t index) { return unalignedLoadBigEndian(file.data() + pos + 20 + index * 4); }; + + check(header_size); + if (!file.starts_with("TZif")) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + size_t time_size = 4; + /// Version 2 and later repeat the data with 64-bit times after the 32-bit section. + if (file[4] != '\0') + { + const size_t v1_size = read_count(3) * 5 + read_count(4) * 6 + read_count(5) + read_count(2) * 8 + read_count(1) + read_count(0); + check(header_size + v1_size); + pos += header_size + v1_size; + check(header_size); + time_size = 8; + } + const size_t time_count = read_count(3); + const size_t type_count = read_count(4); + pos += header_size; + check(time_count * (time_size + 1) + type_count * 6); + if (time_count == 0) + return; + + const char * times = file.data() + pos; + const auto * type_indices = reinterpret_cast(times + time_count * time_size); + const char * types = times + time_count * (time_size + 1); + auto type_record = [&](size_t type) + { + if (type >= type_count) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Malformed time zone file for {}", name); + return types + type * 6; + }; + + first_transition = time_size == 8 ? unalignedLoadBigEndian(times) : unalignedLoadBigEndian(times); + /// The oldest standard time, or the first type if all of them are daylight saving time. + const char * ancient = type_record(0); + for (size_t i = 0; i < time_count; ++i) + { + const char * record = type_record(type_indices[i]); + if (record[4] == 0) + { + ancient = record; + break; + } + } + ancient_offset = unalignedLoadBigEndian(ancient); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Timezone.h b/src/Processors/Formats/Impl/ORC/Timezone.h new file mode 100644 index 000000000000..8a7dbd7361fd --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Timezone.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include + +namespace DB::ORC +{ + +/// The UTC offset as in the reference implementation: before the first transition record it is the oldest +/// standard time, not the local mean time (Asia/Shanghai +08:00, not +08:05:43). Shared by reader and writer. +class TimezoneOffset +{ +public: + explicit TimezoneOffset(const DateLUTImpl & lut_); + + Int64 operator()(Int64 t) const { return t < first_transition ? ancient_offset : lut.timezoneOffset(t); } + +private: + const DateLUTImpl & lut; + Int64 first_transition = std::numeric_limits::min(); + Int64 ancient_offset = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.cpp b/src/Processors/Formats/Impl/ORC/Type.cpp new file mode 100644 index 000000000000..b716b8c9ccb1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.cpp @@ -0,0 +1,380 @@ +#include + +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int INCORRECT_DATA; + extern const int UNKNOWN_TYPE; + extern const int LOGICAL_ERROR; +} +} + +namespace DB::ORC +{ + +namespace +{ + +bool isUnquotedFieldName(const std::string & name) +{ + for (char c : name) + if (!isalnum(static_cast(c)) && c != '_') + return false; + return true; +} + +std::string algorithmToString(UInt32 algorithm) +{ + switch (algorithm) + { + case 0: return "spherical"; + case 1: return "vincenty"; + case 2: return "thomas"; + case 3: return "andoyer"; + case 4: return "karney"; + default: return std::to_string(algorithm); + } +} + +/// The same limit as in the reference implementation. +constexpr size_t MAX_TYPE_NESTING_DEPTH = 2000; + +std::unique_ptr convertType(const std::vector & types, UInt64 index, UInt64 & next_id, size_t depth) +{ + checkStackSize(); + + if (depth > MAX_TYPE_NESTING_DEPTH) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: type nesting depth exceeds the limit of {}", MAX_TYPE_NESTING_DEPTH); + + /// The types are listed in pre-order and the column id of each type is its index in the list. + if (index != next_id || index >= types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: the types are not a tree listed in pre-order (type {} is referenced at position {})", + index, next_id); + ++next_id; + + const auto & proto = types[index]; + if (proto.kind > GEOGRAPHY) + throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown ORC type kind {}", proto.kind); + + auto kind = static_cast(proto.kind); + auto result = std::make_unique(kind); + + switch (kind) + { + case LIST: + if (proto.subtypes.size() != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC LIST type that doesn't contain one subtype"); + break; + case MAP: + if (proto.subtypes.size() != 2) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC MAP type that doesn't contain two subtypes"); + break; + case UNION: + if (proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type that doesn't contain any subtypes"); + /// The tags of a union are bytes. + if (proto.subtypes.size() > 256) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC UNION type with {} subtypes, more than 256", proto.subtypes.size()); + break; + case STRUCT: + if (proto.subtypes.size() > proto.field_names.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC STRUCT type that contains less field names than subtypes"); + break; + default: + if (!proto.subtypes.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "Illegal ORC type {} with subtypes", proto.kind); + break; + } + + if (kind == CHAR || kind == VARCHAR) + result->setMaximumLength(proto.maximum_length.value_or(0)); + if (kind == DECIMAL) + result->setPrecisionAndScale(proto.precision.value_or(0), proto.scale.value_or(0)); + if (kind == GEOMETRY || kind == GEOGRAPHY) + result->setGeospatial(proto.crs.value_or("OGC:CRS84"), proto.algorithm.value_or(0)); + + for (size_t i = 0; i < proto.subtypes.size(); ++i) + { + auto child = convertType(types, proto.subtypes[i], next_id, depth + 1); + if (kind == STRUCT) + result->addStructField(proto.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + + for (const auto & attribute : proto.attributes) + result->setAttribute(attribute.key, attribute.value); + + return result; +} + +void selectChildren(std::vector & selected, const Type & type) +{ + for (UInt64 c = type.getColumnId(); c <= type.getMaximumColumnId(); ++c) + selected[c] = true; +} + +bool selectParents(std::vector & selected, const Type & type) +{ + size_t id = type.getColumnId(); + bool result = selected[id]; + size_t num_selected_subtypes = 0; + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + { + if (selectParents(selected, *type.getSubtype(c))) + { + result = true; + ++num_selected_subtypes; + } + } + selected[id] = result; + + /// The branches of a union are either all selected or all not selected. + if (type.getKind() == UNION && result && num_selected_subtypes > 0 && num_selected_subtypes < type.getSubtypeCount()) + for (UInt64 c = 0; c < type.getSubtypeCount(); ++c) + selectChildren(selected, *type.getSubtype(c)); + + return result; +} + +} + + +std::string Type::toString() const +{ + switch (kind) + { + case BOOLEAN: return "boolean"; + case BYTE: return "tinyint"; + case SHORT: return "smallint"; + case INT: return "int"; + case LONG: return "bigint"; + case FLOAT: return "float"; + case DOUBLE: return "double"; + case STRING: return "string"; + case BINARY: return "binary"; + case TIMESTAMP: return "timestamp"; + case TIMESTAMP_INSTANT: return "timestamp with local time zone"; + case LIST: return "array<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + ">"; + case MAP: + return "map<" + (subtypes.empty() ? std::string("void") : subtypes[0]->toString()) + "," + + (subtypes.size() < 2 ? std::string("void") : subtypes[1]->toString()) + ">"; + case STRUCT: + { + std::string result = "struct<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + if (isUnquotedFieldName(field_names[i])) + result += field_names[i]; + else + { + result += "`"; + for (char c : field_names[i]) + { + if (c == '`') + result += "``"; + else + result += c; + } + result += "`"; + } + result += ":"; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case UNION: + { + std::string result = "uniontype<"; + for (size_t i = 0; i < subtypes.size(); ++i) + { + if (i != 0) + result += ","; + result += subtypes[i]->toString(); + } + result += ">"; + return result; + } + case DECIMAL: return "decimal(" + std::to_string(precision) + "," + std::to_string(scale) + ")"; + case DATE: return "date"; + case VARCHAR: return "varchar(" + std::to_string(maximum_length) + ")"; + case CHAR: return "char(" + std::to_string(maximum_length) + ")"; + case GEOMETRY: return "geometry(" + crs + ")"; + case GEOGRAPHY: return "geography(" + crs + "," + algorithmToString(algorithm) + ")"; + } + return "unknown"; +} + +Type * Type::addStructField(const std::string & name, std::unique_ptr field) +{ + field_names.push_back(name); + return addChild(std::move(field)); +} + +Type * Type::addChild(std::unique_ptr child) +{ + subtypes.push_back(std::move(child)); + return subtypes.back().get(); +} + +UInt64 Type::assignIds(UInt64 start) +{ + column_id = start; + UInt64 next = start + 1; + for (auto & subtype : subtypes) + next = subtype->assignIds(next); + maximum_column_id = next - 1; + return next; +} + +void Type::toProto(std::vector & out) const +{ + size_t index = out.size(); + if (index != column_id) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type ids are not assigned in pre-order"); + out.emplace_back(); + { + auto & proto = out.back(); + proto.kind = kind; + for (const auto & subtype : subtypes) + proto.subtypes.push_back(subtype->getColumnId()); + proto.field_names = field_names; + if (kind == CHAR || kind == VARCHAR) + proto.maximum_length = static_cast(maximum_length); + if (kind == DECIMAL) + { + proto.precision = static_cast(precision); + proto.scale = static_cast(scale); + } + for (const auto & [key, value] : attributes) + proto.attributes.push_back({key, value}); + } + /// `out` may be reallocated by the recursive calls, so do not keep the reference. + for (const auto & subtype : subtypes) + subtype->toProto(out); +} + +std::unique_ptr Type::createPrimitiveType(TypeKind kind) +{ + return std::make_unique(kind); +} + +std::unique_ptr Type::createCharType(TypeKind kind, UInt64 maximum_length) +{ + auto result = std::make_unique(kind); + result->maximum_length = maximum_length; + return result; +} + +std::unique_ptr Type::createDecimalType(UInt64 precision, UInt64 scale) +{ + auto result = std::make_unique(DECIMAL); + result->precision = precision; + result->scale = scale; + return result; +} + +std::unique_ptr Type::createStructType() +{ + return std::make_unique(STRUCT); +} + +std::unique_ptr Type::createListType(std::unique_ptr element) +{ + auto result = std::make_unique(LIST); + result->addChild(std::move(element)); + return result; +} + +std::unique_ptr Type::createMapType(std::unique_ptr key, std::unique_ptr value) +{ + auto result = std::make_unique(MAP); + result->addChild(std::move(key)); + result->addChild(std::move(value)); + return result; +} + +std::unique_ptr Type::createUnionType() +{ + return std::make_unique(UNION); +} + +std::unique_ptr Type::fromProto(const std::vector & types) +{ + if (types.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC file footer is corrupt: it has no types"); + UInt64 next_id = 0; + auto root = convertType(types, 0, next_id, 0); + if (next_id != types.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "ORC file footer is corrupt: {} of {} types are not reachable from the root type", types.size() - next_id, types.size()); + root->assignIds(0); + return root; +} + +std::unique_ptr Type::buildSelectedType(const Type & type, const std::vector & selected) +{ + if (!selected.at(type.column_id)) + return nullptr; + + auto result = std::make_unique(type.kind); + result->maximum_length = type.maximum_length; + result->precision = type.precision; + result->scale = type.scale; + result->crs = type.crs; + result->algorithm = type.algorithm; + result->attributes = type.attributes; + result->column_id = type.column_id; + result->maximum_column_id = type.maximum_column_id; + + for (size_t i = 0; i < type.subtypes.size(); ++i) + { + auto child = buildSelectedType(*type.subtypes[i], selected); + if (!child) + continue; + if (type.kind == STRUCT) + result->addStructField(type.field_names[i], std::move(child)); + else + result->addChild(std::move(child)); + } + return result; +} + +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids) +{ + std::vector selected(root.getMaximumColumnId() + 1, false); + + /// Find the types by ids with a walk over the tree. + std::vector by_id(selected.size()); + std::vector stack{&root}; + while (!stack.empty()) + { + const Type * type = stack.back(); + stack.pop_back(); + by_id[type->getColumnId()] = type; + for (UInt64 i = 0; i < type->getSubtypeCount(); ++i) + stack.push_back(type->getSubtype(i)); + } + + for (UInt64 id : type_ids) + { + if (id >= selected.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid ORC type id {} selected out of {}", id, selected.size()); + selectChildren(selected, *by_id[id]); + } + + selectParents(selected, root); + selected[0] = true; + return selected; +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Type.h b/src/Processors/Formats/Impl/ORC/Type.h new file mode 100644 index 000000000000..9a30f4455076 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Type.h @@ -0,0 +1,114 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace DB::ORC +{ + +enum TypeKind : UInt32 +{ + BOOLEAN = 0, + BYTE = 1, + SHORT = 2, + INT = 3, + LONG = 4, + FLOAT = 5, + DOUBLE = 6, + STRING = 7, + BINARY = 8, + TIMESTAMP = 9, + LIST = 10, + MAP = 11, + STRUCT = 12, + UNION = 13, + DECIMAL = 14, + DATE = 15, + VARCHAR = 16, + CHAR = 17, + TIMESTAMP_INSTANT = 18, + GEOMETRY = 19, + GEOGRAPHY = 20, +}; + +/// A node of the type tree of an ORC file. Every node is a column of the file; the column ids are +/// assigned in pre-order, so the subtree of a column `c` occupies the ids `[c, c.getMaximumColumnId()]`. +class Type +{ +public: + explicit Type(TypeKind kind_) : kind(kind_) {} + + TypeKind getKind() const { return kind; } + UInt64 getColumnId() const { return column_id; } + UInt64 getMaximumColumnId() const { return maximum_column_id; } + UInt64 getSubtypeCount() const { return subtypes.size(); } + const Type * getSubtype(UInt64 i) const { return subtypes.at(i).get(); } + /// Only for STRUCT. + const std::string & getFieldName(UInt64 i) const { return field_names.at(i); } + /// Only for CHAR and VARCHAR. + UInt64 getMaximumLength() const { return maximum_length; } + /// Only for DECIMAL. + UInt64 getPrecision() const { return precision; } + UInt64 getScale() const { return scale; } + + bool hasAttributeKey(const std::string & key) const { return attributes.contains(key); } + const std::string & getAttributeValue(const std::string & key) const { return attributes.at(key); } + void setAttribute(const std::string & key, const std::string & value) { attributes[key] = value; } + const std::map & getAttributes() const { return attributes; } + + /// The type name in the same format as in the reference implementation (Hive type names). + std::string toString() const; + + void setMaximumLength(UInt64 value) { maximum_length = value; } + void setPrecisionAndScale(UInt64 precision_, UInt64 scale_) { precision = precision_; scale = scale_; } + void setGeospatial(std::string crs_, UInt32 algorithm_) { crs = std::move(crs_); algorithm = algorithm_; } + + Type * addStructField(const std::string & name, std::unique_ptr field); + Type * addChild(std::unique_ptr child); + + /// Assigns the column ids in pre-order, starting from `start`. Returns the next free id. + UInt64 assignIds(UInt64 start); + + /// Appends the types of this subtree to `out` in pre-order. The ids must be assigned. + void toProto(std::vector & out) const; + + static std::unique_ptr createPrimitiveType(TypeKind kind); + static std::unique_ptr createCharType(TypeKind kind, UInt64 maximum_length); + static std::unique_ptr createDecimalType(UInt64 precision, UInt64 scale); + static std::unique_ptr createStructType(); + static std::unique_ptr createListType(std::unique_ptr element); + static std::unique_ptr createMapType(std::unique_ptr key, std::unique_ptr value); + static std::unique_ptr createUnionType(); + + /// Builds the type tree from the types in the file footer. Throws `INCORRECT_DATA` if they do + /// not form a tree with the ids in pre-order. + static std::unique_ptr fromProto(const std::vector & types); + + /// Builds a copy of the tree with only the selected columns (by id). The parent of every + /// selected column must also be selected. Returns nullptr if the root is not selected. + static std::unique_ptr buildSelectedType(const Type & type, const std::vector & selected); + +private: + TypeKind kind; + UInt64 column_id = 0; + UInt64 maximum_column_id = 0; + std::vector> subtypes; + std::vector field_names; + UInt64 maximum_length = 0; + UInt64 precision = 0; + UInt64 scale = 0; + std::string crs; + UInt32 algorithm = 0; + std::map attributes; +}; + +/// The column selection with the same semantics as in the reference implementation: +/// selecting a column selects its whole subtree, and then all parents of the selected columns +/// are selected. If only some branches of a UNION are selected, all its branches are selected. +std::vector selectColumnsByTypeIds(const Type & root, const std::vector & type_ids); + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.cpp b/src/Processors/Formats/Impl/ORC/Vector.cpp new file mode 100644 index 000000000000..ce7b5cdac8de --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int NOT_IMPLEMENTED; + extern const int INCORRECT_DATA; +} +} + +namespace DB::ORC +{ + +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values) +{ + const size_t dictionary_size = dictionary.size(); + const auto & dictionary_offsets = dictionary.getOffsets(); + const auto & dictionary_chars = dictionary.getChars(); + + auto result = ColumnString::create(); + auto & chars = result->getChars(); + auto & offsets = result->getOffsets(); + offsets.resize(num_values); + + size_t total = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + Int64 entry = index[i]; + if (entry < 0 || static_cast(entry) >= dictionary_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "ORC dictionary index {} at row {} is out of range [0, {})", entry, i, dictionary_size); + total += dictionary_offsets[entry] - dictionary_offsets[entry - 1]; + } + offsets[i] = total; + } + + chars.resize(total); + UInt8 * out = chars.data(); + for (size_t i = 0; i < num_values; ++i) + { + if (!not_null || not_null[i]) + { + size_t begin = dictionary_offsets[index[i] - 1]; + size_t size = dictionary_offsets[index[i]] - begin; + memcpy(out, dictionary_chars.data() + begin, size); + out += size; + } + } + return result; +} + +ColumnPtr getStringColumn(const StringVectorBatch & batch) +{ + if (!batch.isEncoded) + return batch.column; + + const auto & encoded = typeid_cast(batch); + return decodeDictionary( + assert_cast(*encoded.dictionary->column), + encoded.index.data(), + batch.hasNulls ? batch.notNull.data() : nullptr, + batch.numElements); +} + +std::unique_ptr createRowBatch(const Type & type, bool encoded) +{ + checkStackSize(); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(); + case BYTE: + return std::make_unique(); + case SHORT: + return std::make_unique(); + case INT: + return std::make_unique(); + case LONG: + case DATE: + return std::make_unique(); + case FLOAT: + return std::make_unique(); + case DOUBLE: + return std::make_unique(); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + case GEOMETRY: + case GEOGRAPHY: + if (encoded) + return std::make_unique(); + return std::make_unique(); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + return std::make_unique(); + case STRUCT: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addField(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case LIST: + { + auto result = std::make_unique(); + if (type.getSubtypeCount()) + result->elements = createRowBatch(*type.getSubtype(0), encoded); + return result; + } + case MAP: + { + auto result = std::make_unique(); + if (type.getSubtypeCount() > 0) + result->keys = createRowBatch(*type.getSubtype(0), encoded); + if (type.getSubtypeCount() > 1) + result->elements = createRowBatch(*type.getSubtype(1), encoded); + return result; + } + case UNION: + { + auto result = std::make_unique(); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + result->addChild(createRowBatch(*type.getSubtype(i), encoded)); + return result; + } + case DECIMAL: + if (type.getPrecision() == 0 || type.getPrecision() > 18) + return std::make_unique(); + return std::make_unique(); + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ORC type {} is not supported", type.toString()); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Vector.h b/src/Processors/Formats/Impl/ORC/Vector.h new file mode 100644 index 000000000000..1e44a80a61d1 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Vector.h @@ -0,0 +1,174 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +/// Batches of column values filled by the reader. The values of the primitive types are decoded +/// directly into ClickHouse columns, which the conversion to the requested types takes without +/// copying. The structure follows the reference implementation: a batch has the null mask of its +/// values, and the batches of the compound types have the batches of their children. + +namespace DB::ORC +{ + +struct ColumnVectorBatch +{ + ColumnVectorBatch() = default; + virtual ~ColumnVectorBatch() = default; + + ColumnVectorBatch(const ColumnVectorBatch &) = delete; + ColumnVectorBatch & operator=(const ColumnVectorBatch &) = delete; + + /// Prepares the batch for `num_values` values. + void reset(size_t num_values) + { + numElements = num_values; + notNull.resize(num_values); + } + + size_t numElements = 0; + /// Non-zero for the non-null values, valid only if `hasNulls`. + PaddedPODArray notNull; + bool hasNulls = false; + /// For string batches read with lazy dictionary decoding. + bool isEncoded = false; +}; + +/// The values of a primitive type in a ClickHouse column (`ColumnVector` of `T`). The null values are zeros. +template +struct NumericVectorBatch : public ColumnVectorBatch +{ + using Container = PaddedPODArray; + + /// Creates a new column for the next values: the previous column can be still referenced. + Container & prepareColumn(size_t num_values) + { + auto new_column = ColumnVector::create(num_values); + auto & data = new_column->getData(); + column = std::move(new_column); + return data; + } + + const Container & getData() const { return assert_cast &>(*column).getData(); } + + ColumnPtr column; +}; + +/// BOOLEAN: 0 or 1. +using BoolVectorBatch = NumericVectorBatch; +using ByteVectorBatch = NumericVectorBatch; +using ShortVectorBatch = NumericVectorBatch; +using IntVectorBatch = NumericVectorBatch; +/// LONG and DATE (days since the epoch, not narrowed, so that the range can be checked). +using LongVectorBatch = NumericVectorBatch; +using FloatVectorBatch = NumericVectorBatch; +using DoubleVectorBatch = NumericVectorBatch; + +/// The values in a `ColumnString`. The null values are empty strings. +struct StringVectorBatch : public ColumnVectorBatch +{ + ColumnPtr column; +}; + +struct StringDictionary +{ + /// The entries of the dictionary. + ColumnPtr column; +}; + +/// A string batch with the dictionary indices, without decoding the values. `column` is not set. +struct EncodedStringVectorBatch : public StringVectorBatch +{ + std::shared_ptr dictionary; + PaddedPODArray index; +}; + +/// Builds a `ColumnString` from the dictionary entries by the indices (the null values are empty strings). +/// Throws `INCORRECT_DATA` if an index is out of range. +ColumnPtr decodeDictionary(const ColumnString & dictionary, const Int64 * index, const char * not_null, size_t num_values); + +/// Returns the values of a string batch as a `ColumnString`, decoding the dictionary for an encoded batch. +ColumnPtr getStringColumn(const StringVectorBatch & batch); + +struct StructVectorBatch : public ColumnVectorBatch +{ + void addField(std::unique_ptr field) + { + fields.push_back(field.get()); + owned_fields.push_back(std::move(field)); + } + + std::vector fields; + +private: + std::vector> owned_fields; +}; + +/// LIST and MAP: the end offsets of the values in the children, as in `ColumnArray`. +struct ListVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr elements; +}; + +struct MapVectorBatch : public ColumnVectorBatch +{ + /// `ColumnArray::ColumnOffsets`. + ColumnPtr offsets; + std::unique_ptr keys; + std::unique_ptr elements; +}; + +struct UnionVectorBatch : public ColumnVectorBatch +{ + void addChild(std::unique_ptr child) + { + children.push_back(child.get()); + owned_children.push_back(std::move(child)); + } + + /// The branch of each value. + PaddedPODArray tags; + /// The position of each value in its branch. + PaddedPODArray offsets; + std::vector children; + +private: + std::vector> owned_children; +}; + +/// For DECIMAL with the precision at most 18. +struct Decimal64VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +/// For DECIMAL with the precision above 18 or unspecified (zero). +struct Decimal128VectorBatch : public ColumnVectorBatch +{ + Int32 precision = 0; + Int32 scale = 0; + PaddedPODArray values; +}; + +struct TimestampVectorBatch : public ColumnVectorBatch +{ + /// Seconds since the epoch in UTC. + PaddedPODArray data; + PaddedPODArray nanoseconds; +}; + +/// Creates a batch tree matching the type. With `encoded`, the string columns get +/// `EncodedStringVectorBatch`, which the reader fills without decoding the dictionaries. +std::unique_ptr createRowBatch(const Type & type, bool encoded = false); + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.cpp b/src/Processors/Formats/Impl/ORC/Writer.cpp new file mode 100644 index 000000000000..cfab65634955 --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.cpp @@ -0,0 +1,1493 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +namespace DB +{ +namespace ErrorCodes +{ + extern const int BAD_ARGUMENTS; + extern const int LOGICAL_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE; +} +} + +namespace DB::ORC +{ + +struct WriterContext +{ + Compressor * compressor = nullptr; + size_t block_size = 0; + bool enable_index = false; + double dictionary_key_size_threshold = 0; + std::optional timezone_offset; + bool timezone_is_utc = true; + /// 2015-01-01 00:00:00 in the time zone of the writer, as seconds since the epoch. + Int64 epoch_offset = 0; +}; + +namespace +{ + +struct StreamData +{ + Proto::StreamKind kind; + UInt32 column; + std::string data; +}; + +std::string compressWhole(const WriterContext & context, const std::string & data) +{ + OutputByteStream stream(context.compressor, context.block_size); + stream.write(data.data(), data.size()); + stream.finish(); + return stream.getOutput(); +} + +} + +class ColumnWriter +{ +public: + ColumnWriter(const Type & type, WriterContext & context_) + : column_id(type.getColumnId()) + , context(context_) + , present_stream(context.compressor, context.block_size) + , present_encoder(present_stream) + , index_statistics(type.getKind()) + , stripe_statistics(type.getKind()) + , file_statistics(type.getKind()) + { + } + + virtual ~ColumnWriter() = default; + + /// Must be called by the most derived constructor, after the streams are created. + void init() + { + if (context.enable_index) + recordPositions(); + } + + /// Adds the values `[offset, offset + num_values)` of `column`, which is not `Nullable`. + /// `null_map` (1 for a null) and `parent_null_map` (1 for a null in the parent struct, for which + /// no value is written at all) are for these values only, so they start at the first value. + virtual void add(const IColumn & /*column*/, const UInt8 * null_map, size_t /*offset*/, size_t num_values, const UInt8 * parent_null_map) + { + addPresent(null_map, num_values, parent_null_map); + } + + /// Writes the PRESENT stream for the values. + void addPresent(const UInt8 * null_map, size_t num_values, const UInt8 * parent_null_map) + { + for (size_t i = 0; i < num_values; ++i) + { + if (parent_null_map && parent_null_map[i]) + continue; + present_encoder.write(!null_map || !null_map[i]); + } + if (null_map) + { + for (size_t i = 0; i < num_values && !has_null_value; ++i) + if (null_map[i]) + has_null_value = true; + } + } + + virtual void createRowIndexEntry() + { + entries.push_back(Entry{std::move(current_present_positions), std::move(current_data_positions), index_statistics.toProto()}); + current_present_positions.clear(); + current_data_positions.clear(); + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + recordPositions(); + } + + virtual void mergeRowGroupStatsIntoStripeStats() + { + stripe_statistics.merge(index_statistics); + index_statistics.reset(); + } + + /// Encodes the deferred data of the stripe. + virtual void finalizeStripe() {} + + virtual void writeIndex(std::vector & streams) + { + Proto::RowIndex index; + for (const auto & entry : entries) + { + auto & proto_entry = index.entry.emplace_back(); + /// The positions of the PRESENT stream are written only if the stream is written. + if (has_null_value) + proto_entry.positions = entry.present_positions; + proto_entry.positions.insert(proto_entry.positions.end(), entry.data_positions.begin(), entry.data_positions.end()); + proto_entry.statistics = entry.statistics; + } + streams.push_back({Proto::StreamKind::ROW_INDEX, static_cast(column_id), compressWhole(context, index.serialize())}); + } + + virtual void flush(std::vector & streams) + { + present_encoder.flush(); + present_stream.finish(); + if (has_null_value) + streams.push_back({Proto::StreamKind::PRESENT, static_cast(column_id), present_stream.getOutput()}); + } + + virtual void getColumnEncodings(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + + virtual void getStripeStatistics(std::vector & stats) const + { + stats.push_back(stripe_statistics.toProto()); + } + + virtual void getFileStatistics(std::vector & stats) const + { + stats.push_back(file_statistics.toProto()); + } + + virtual void mergeStripeStatsIntoFileStats() + { + file_statistics.merge(stripe_statistics); + stripe_statistics.reset(); + } + + virtual size_t estimateSize() const + { + return present_stream.estimateSize(); + } + + /// Starts a new stripe. + virtual void reset() + { + present_stream.reset(); + has_null_value = false; + entries.clear(); + current_present_positions.clear(); + current_data_positions.clear(); + resetStreams(); + if (context.enable_index) + recordPositions(); + } + +protected: + /// Appends the positions of the data streams, in the order the reader seeks them. + virtual void recordDataPositions(std::vector & positions) = 0; + /// Clears the data streams for a new stripe. + virtual void resetStreams() = 0; + + /// The number of the non-null values, also updates the statistics with the count. + size_t countValues(const UInt8 * null_map, size_t num_values) + { + size_t count = num_values; + if (null_map) + { + count = 0; + for (size_t i = 0; i < num_values; ++i) + count += !null_map[i]; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + return count; + } + + struct Entry + { + std::vector present_positions; + std::vector data_positions; + Proto::ColumnStatistics statistics; + }; + + const UInt64 column_id; + WriterContext & context; + OutputByteStream present_stream; + BooleanRleEncoder present_encoder; + bool has_null_value = false; + StatisticsBuilder index_statistics; + StatisticsBuilder stripe_statistics; + StatisticsBuilder file_statistics; + std::vector entries; + +private: + void recordPositions() + { + present_encoder.recordPosition(current_present_positions); + recordDataPositions(current_data_positions); + } + + std::vector current_present_positions; + std::vector current_data_positions; +}; + +namespace +{ + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type, WriterContext & context); + +/// Adds the values of a column that can be `Nullable`. The values that are null in the parent +/// (`outer_null_map`, for the fields of a struct) are null as well. +void addColumn( + ColumnWriter & writer, const IColumn & column, const UInt8 * outer_null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) +{ + if (const auto * nullable = typeid_cast(&column)) + { + const UInt8 * null_map = nullable->getNullMapData().data() + offset; + if (!outer_null_map) + { + writer.add(nullable->getNestedColumn(), null_map, offset, num_values, parent_null_map); + return; + } + PaddedPODArray merged(num_values); + for (size_t i = 0; i < num_values; ++i) + merged[i] = null_map[i] | outer_null_map[i]; + writer.add(nullable->getNestedColumn(), merged.data(), offset, num_values, parent_null_map); + return; + } + writer.add(column, outer_null_map, offset, num_values, parent_null_map); +} + +/// The raw values of a column with fixed-size values. +template +const T * getRawValues(const IColumn & column) +{ + auto raw = column.getRawData(); + if (column.sizeOfValueIfFixed() != sizeof(T)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} with values of size {} for ORC (expected {})", + column.getName(), column.sizeOfValueIfFixed(), sizeof(T)); + return reinterpret_cast(raw.data()); +} + +/// The value of the integer column (of any width up to 8 bytes) as a signed number of the same width, +/// as ORC does not have unsigned types. +Int64 readSignedValue(const char * data, size_t width, size_t row) +{ + switch (width) + { + case 1: return unalignedLoad(data + row); + case 2: return unalignedLoad(data + row * 2); + case 4: return unalignedLoad(data + row * 4); + default: return unalignedLoad(data + row * 8); + } +} + +/// The writers that have children call the same methods for them. +class CompoundColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void createRowIndexEntry() override + { + ColumnWriter::createRowIndexEntry(); + for (auto & child : children) + child->createRowIndexEntry(); + } + + void mergeRowGroupStatsIntoStripeStats() override + { + ColumnWriter::mergeRowGroupStatsIntoStripeStats(); + for (auto & child : children) + child->mergeRowGroupStatsIntoStripeStats(); + } + + void finalizeStripe() override + { + for (auto & child : children) + child->finalizeStripe(); + } + + void writeIndex(std::vector & streams) override + { + ColumnWriter::writeIndex(streams); + for (auto & child : children) + child->writeIndex(streams); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + flushOwnStreams(streams); + for (auto & child : children) + child->flush(streams); + } + + void getColumnEncodings(std::vector & encodings) const override + { + getOwnColumnEncoding(encodings); + for (const auto & child : children) + child->getColumnEncodings(encodings); + } + + void getStripeStatistics(std::vector & stats) const override + { + ColumnWriter::getStripeStatistics(stats); + for (const auto & child : children) + child->getStripeStatistics(stats); + } + + void getFileStatistics(std::vector & stats) const override + { + ColumnWriter::getFileStatistics(stats); + for (const auto & child : children) + child->getFileStatistics(stats); + } + + void mergeStripeStatsIntoFileStats() override + { + ColumnWriter::mergeStripeStatsIntoFileStats(); + for (auto & child : children) + child->mergeStripeStatsIntoFileStats(); + } + + size_t estimateSize() const override + { + size_t size = ColumnWriter::estimateSize() + estimateOwnSize(); + for (const auto & child : children) + size += child->estimateSize(); + return size; + } + + void reset() override + { + ColumnWriter::reset(); + for (auto & child : children) + (*child).reset(); + } + +protected: + virtual void flushOwnStreams(std::vector &) {} + virtual void getOwnColumnEncoding(std::vector & encodings) const + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT, 0, {}}); + } + virtual size_t estimateOwnSize() const { return 0; } + + std::vector> children; +}; + +class StructColumnWriter final : public CompoundColumnWriter +{ +public: + StructColumnWriter(const Type & type, const DataTypes & field_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + { + if (field_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC struct {} has {} fields, the ClickHouse type has {}", + type.toString(), type.getSubtypeCount(), field_types.size()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), field_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & tuple = assert_cast(column); + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The fields of the null values are null, and they are not written. + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], tuple.getColumn(i), null_map, offset, num_values, null_map); + countValues(null_map, num_values); + } + + /// Adds the rows of the root struct, which are the columns of the file. + void addRoot(const Columns & columns, size_t offset, size_t num_values) + { + if (columns.size() != children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Expected {} columns for ORC, got {}", children.size(), columns.size()); + addPresent(nullptr, num_values, nullptr); + for (size_t i = 0; i < children.size(); ++i) + addColumn(*children[i], *columns[i], nullptr, offset, num_values, nullptr); + countValues(nullptr, num_values); + } + +protected: + void recordDataPositions(std::vector &) override {} + void resetStreams() override {} +}; + +template +class CollectionColumnWriter final : public CompoundColumnWriter +{ +public: + CollectionColumnWriter(const Type & type, const DataTypes & child_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , length_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + { + if (child_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC type {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), child_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const ColumnArray & array = is_map ? assert_cast(column).getNestedColumn() : assert_cast(column); + /// The offsets of `ColumnArray` are the end offsets, and the one before the first is zero. + const auto & offsets = array.getOffsets(); + + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + + UInt64 element_offset = offsets[static_cast(offset) - 1]; + UInt64 total_elements = offsets[offset + num_values - 1] - element_offset; + + if constexpr (is_map) + { + const auto & key_value = assert_cast(array.getData()); + addColumn(*children[0], key_value.getColumn(0), nullptr, element_offset, total_elements, nullptr); + addColumn(*children[1], key_value.getColumn(1), nullptr, element_offset, total_elements, nullptr); + } + else + { + addColumn(*children[0], array.getData(), nullptr, element_offset, total_elements, nullptr); + } + + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + UInt64 length = offsets[row] - offsets[static_cast(row) - 1]; + length_encoder.write(static_cast(length)); + index_statistics.updateCollection(length); + ++count; + } + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + length_encoder.recordPosition(positions); + } + + void resetStreams() override + { + length_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + + void getOwnColumnEncoding(std::vector & encodings) const override + { + encodings.push_back({Proto::ColumnEncodingKind::DIRECT_V2, 0, {}}); + } + + size_t estimateOwnSize() const override { return length_stream.estimateSize(); } + +private: + OutputByteStream length_stream; + IntRleEncoderV2 length_encoder; +}; + +class UnionColumnWriter final : public CompoundColumnWriter +{ +public: + /// The branches of the union are in the same order as the variants of the `Variant` type, + /// so the global discriminator of a value is its tag. + UnionColumnWriter(const Type & type, const DataTypes & variant_types, WriterContext & context_) + : CompoundColumnWriter(type, context_) + , tag_stream(context.compressor, context.block_size) + , tag_encoder(tag_stream) + { + if (variant_types.size() != type.getSubtypeCount()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC union {} does not match the ClickHouse type", type.toString()); + for (UInt64 i = 0; i < type.getSubtypeCount(); ++i) + children.push_back(buildColumnWriter(*type.getSubtype(i), variant_types[i], context)); + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + const auto & variant = assert_cast(column); + + /// A `NULL` of `Variant` is a null value of the union. + PaddedPODArray union_null_map(num_values); + bool has_nulls = false; + for (size_t i = 0; i < num_values; ++i) + { + union_null_map[i] = (null_map && null_map[i]) || variant.globalDiscriminatorAt(offset + i) == ColumnVariant::NULL_DISCRIMINATOR; + has_nulls |= union_null_map[i]; + } + const UInt8 * union_nulls = has_nulls ? union_null_map.data() : nullptr; + + ColumnWriter::add(column, union_nulls, offset, num_values, parent_null_map); + + std::vector child_offset(children.size(), -1); + std::vector child_length(children.size(), 0); + size_t count = 0; + for (size_t i = 0; i < num_values; ++i) + { + if (union_nulls && union_nulls[i]) + continue; + size_t row = offset + i; + auto tag = variant.globalDiscriminatorAt(row); + if (tag >= children.size()) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid union tag {} for union with {} children", static_cast(tag), children.size()); + if (child_offset[tag] == -1) + child_offset[tag] = static_cast(variant.offsetAt(row)); + ++child_length[tag]; + tag_encoder.write(static_cast(tag)); + ++count; + } + + /// The values of each branch are consecutive in its column. + for (size_t i = 0; i < children.size(); ++i) + if (child_length[i]) + addColumn(*children[i], variant.getVariantByGlobalDiscriminator(i), nullptr, static_cast(child_offset[i]), child_length[i], nullptr); + + index_statistics.increase(count); + if (count < num_values) + index_statistics.setHasNull(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + tag_encoder.recordPosition(positions); + } + + void resetStreams() override + { + tag_stream.reset(); + } + + void flushOwnStreams(std::vector & streams) override + { + tag_encoder.flush(); + tag_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), tag_stream.getOutput()}); + } + + size_t estimateOwnSize() const override { return tag_stream.estimateSize(); } + +private: + OutputByteStream tag_stream; + ByteRleEncoder tag_encoder; +}; + + +/// The writers of the primitive columns. +class PrimitiveColumnWriter : public ColumnWriter +{ +public: + using ColumnWriter::ColumnWriter; + + void getColumnEncodings(std::vector & encodings) const override + { + encodings.push_back({encoding_kind, dictionary_size, {}}); + } + +protected: + Proto::ColumnEncodingKind encoding_kind = Proto::ColumnEncodingKind::DIRECT; + UInt32 dictionary_size = 0; +}; + +class BooleanColumnWriter final : public PrimitiveColumnWriter +{ +public: + BooleanColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const UInt8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(data[i] != 0); + index_statistics.updateBoolean(data[i] != 0); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + BooleanRleEncoder encoder; +}; + +class ByteColumnWriter final : public PrimitiveColumnWriter +{ +public: + ByteColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width. + const Int8 * data = getRawValues(column) + offset; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + encoder.write(static_cast(data[i])); + index_statistics.updateInteger(data[i]); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + ByteRleEncoder encoder; +}; + +/// SHORT, INT, LONG and DATE. +class IntegerColumnWriter final : public PrimitiveColumnWriter +{ +public: + IntegerColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + , encoder(data_stream, true) + , is_date(type.getKind() == DATE) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// The unsigned values are written as signed ones of the same width (except `Date`). + const size_t width = column.sizeOfValueIfFixed(); + if (width != 2 && width != 4 && width != 8) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC integer", column.getName()); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + /// `Date` is the unsigned number of days (up to 2149), which must not wrap around + /// to the negative ones after 2059. `Date32` is signed, as the other integers. + Int64 value = (is_date && width == 2) + ? unalignedLoad(data + (offset + i) * sizeof(UInt16)) + : readSignedValue(data, width, offset + i); + encoder.write(value); + if (is_date) + index_statistics.updateDate(static_cast(value)); + else + index_statistics.updateInteger(value); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + encoder.flush(); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { encoder.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; + IntRleEncoderV2 encoder; + const bool is_date; +}; + +template +class FloatingColumnWriter final : public PrimitiveColumnWriter +{ +public: + FloatingColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , data_stream(context.compressor, context.block_size) + { + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const ItemType * data = getRawValues(column) + offset; + if (!null_map && std::endian::native == std::endian::little) + { + data_stream.write(reinterpret_cast(data), num_values * sizeof(ItemType)); + for (size_t i = 0; i < num_values; ++i) + index_statistics.updateDouble(static_cast(data[i])); + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + ItemType value = data[i]; + if constexpr (std::endian::native == std::endian::big) + value = std::bit_cast(std::byteswap(std::bit_cast>(value))); + data_stream.write(reinterpret_cast(&value), sizeof(value)); + index_statistics.updateDouble(static_cast(data[i])); + } + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + } + + size_t estimateSize() const override { return ColumnWriter::estimateSize() + data_stream.estimateSize(); } + +protected: + void recordDataPositions(std::vector & positions) override { data_stream.recordPosition(positions); } + void resetStreams() override { data_stream.reset(); } + +private: + OutputByteStream data_stream; +}; + +/// STRING, VARCHAR, CHAR and BINARY. The values of a stripe are kept in memory and encoded at the +/// end of the stripe, either directly or with a dictionary. +class StringColumnWriter final : public PrimitiveColumnWriter +{ +public: + StringColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , is_binary(type.getKind() == BINARY) + , data_stream(context.compressor, context.block_size) + , length_stream(context.compressor, context.block_size) + , dictionary_data_stream(context.compressor, context.block_size) + , length_encoder(length_stream, false) + , index_encoder(data_stream, false) + { + /// The binary columns never use dictionaries, as in the reference implementation. + if (is_binary || context.dictionary_key_size_threshold <= 0) + use_dictionary = false; + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `String`, or the raw bytes of the values of fixed size (`FixedString`, `IPv6`, big integers). + auto add_value = [&](std::string_view value) + { + blob.append(value); + value_ends.push_back(blob.size()); + if (is_binary) + index_statistics.updateBinary(value.size()); + else + index_statistics.updateString(value); + }; + + if (const auto * strings = typeid_cast(&column)) + { + const auto & offsets = strings->getOffsets(); + const auto * chars = reinterpret_cast(strings->getChars().data()); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + add_value(std::string_view(chars + offsets[row - 1], offsets[row] - offsets[row - 1])); + } + } + else + { + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + add_value(column.getDataAt(offset + i)); + } + } + countValues(null_map, num_values); + } + + void createRowIndexEntry() override + { + if (!use_dictionary) + decideDictionary(); + ColumnWriter::createRowIndexEntry(); + } + + void finalizeStripe() override + { + if (!use_dictionary) + decideDictionary(); + + /// The start of the group without an entry is not needed. + group_starts.resize(entries.size()); + + if (*use_dictionary) + encodeWithDictionary(); + else + encodeDirect(); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + if (*use_dictionary) + { + index_encoder.flush(); + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + dictionary_data_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::DICTIONARY_DATA, static_cast(column_id), dictionary_data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + else + { + data_stream.finish(); + length_encoder.flush(); + length_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), data_stream.getOutput()}); + streams.push_back({Proto::StreamKind::LENGTH, static_cast(column_id), length_stream.getOutput()}); + } + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + blob.size() + value_ends.size() * sizeof(UInt64); + } + +protected: + void recordDataPositions(std::vector &) override + { + /// The positions are known only after the encoding, at the end of the stripe. + group_starts.push_back(value_ends.size()); + } + + void resetStreams() override + { + data_stream.reset(); + length_stream.reset(); + dictionary_data_stream.reset(); + blob.clear(); + value_ends.clear(); + group_starts.clear(); + dictionary_size = 0; + } + +private: + std::string_view getValue(size_t i) const + { + size_t begin = i ? value_ends[i - 1] : 0; + return std::string_view(blob.data() + begin, value_ends[i] - begin); + } + + /// The decision is made once for the file, by the values of the first row group (or the first + /// stripe without the row index), as in the reference implementation. + void decideDictionary() + { + std::unordered_set distinct; + for (size_t i = 0; i < value_ends.size(); ++i) + distinct.insert(getValue(i)); + /// Compare as doubles: the threshold is user-provided and the product may not fit in `size_t`. + use_dictionary = static_cast(distinct.size()) <= static_cast(value_ends.size()) * context.dictionary_key_size_threshold; + } + + void encodeDirect() + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + auto & positions = entries[group].data_positions; + data_stream.recordPosition(positions); + length_encoder.recordPosition(positions); + ++group; + } + if (i == value_ends.size()) + break; + auto value = getValue(i); + data_stream.write(value.data(), value.size()); + length_encoder.write(static_cast(value.size())); + } + } + + void encodeWithDictionary() + { + encoding_kind = Proto::ColumnEncodingKind::DICTIONARY_V2; + + /// The dictionary is sorted, as in the reference implementation. + std::unordered_map index_of; + std::vector keys; + for (size_t i = 0; i < value_ends.size(); ++i) + { + auto value = getValue(i); + if (index_of.emplace(value, 0).second) + keys.push_back(value); + } + std::sort(keys.begin(), keys.end()); + for (size_t i = 0; i < keys.size(); ++i) + index_of[keys[i]] = static_cast(i); + dictionary_size = static_cast(keys.size()); + + size_t group = 0; + for (size_t i = 0; i <= value_ends.size(); ++i) + { + while (group < group_starts.size() && group_starts[group] == i) + { + index_encoder.recordPosition(entries[group].data_positions); + ++group; + } + if (i == value_ends.size()) + break; + index_encoder.write(index_of[getValue(i)]); + } + + for (const auto & key : keys) + { + dictionary_data_stream.write(key.data(), key.size()); + length_encoder.write(static_cast(key.size())); + } + } + + const bool is_binary; + std::optional use_dictionary; + OutputByteStream data_stream; + OutputByteStream length_stream; + OutputByteStream dictionary_data_stream; + IntRleEncoderV2 length_encoder; + IntRleEncoderV2 index_encoder; + + std::string blob; + std::vector value_ends; + /// The index of the first value of each row group. + std::vector group_starts; +}; + +class TimestampColumnWriter final : public PrimitiveColumnWriter +{ +public: + /// `scale` is of `DateTime64`, or nullopt for `DateTime` (`UInt32` seconds). + TimestampColumnWriter(const Type & type, std::optional scale_, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(scale_) + , seconds_stream(context.compressor, context.block_size) + , nanos_stream(context.compressor, context.block_size) + , seconds_encoder(seconds_stream, true) + , nanos_encoder(nanos_stream, false) + , is_utc(type.getKind() == TIMESTAMP_INSTANT || context.timezone_is_utc) + , epoch_offset(type.getKind() == TIMESTAMP_INSTANT ? 1420070400 : context.epoch_offset) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + const char * data = column.getRawData().data(); + const Int64 multiplier = scale ? common::exp10_i64(static_cast(*scale)) : 1; + const Int64 nanos_multiplier = scale ? common::exp10_i64(9 - static_cast(*scale)) : 0; + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + Int64 secs = 0; + Int64 nano = 0; + if (scale) + { + /// For the values before the epoch, the nanoseconds are negative (as in the Arrow ORC adapter). + Int64 value = unalignedLoad(data + (offset + i) * sizeof(Int64)); + secs = value / multiplier; + nano = (value % multiplier) * nanos_multiplier; + } + else + { + secs = unalignedLoad(data + (offset + i) * sizeof(UInt32)); + nano = 0; + } + + /// The statistics have the milliseconds rounded down and the rest of the nanoseconds, which is not negative. + Int64 nano_millis = nano / 1000000; + Int64 nano_rest = nano % 1000000; + if (nano_rest < 0) + { + nano_rest += 1000000; + --nano_millis; + } + Int64 utc_seconds = secs; + Int64 millis = 0; + Int64 encoded_seconds = 0; + if ((!is_utc && common::addOverflow(secs, (*context.timezone_offset)(secs), utc_seconds)) + || common::mulOverflow(utc_seconds, Int64{1000}, millis) + || common::addOverflow(millis, nano_millis, millis) + || common::subOverflow(secs + (secs < 0 && nano > 999999), epoch_offset, encoded_seconds)) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, + "Timestamp (seconds={}, nanoseconds={}) in ORC column {} is out of the range supported by the ORC format", secs, nano, column_id); + index_statistics.updateTimestamp(millis, static_cast(nano_rest)); + + seconds_encoder.write(encoded_seconds); + nanos_encoder.write(formatNanos(nano)); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + seconds_encoder.flush(); + seconds_stream.finish(); + nanos_encoder.flush(); + nanos_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), seconds_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), nanos_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + seconds_stream.estimateSize() + nanos_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + seconds_encoder.recordPosition(positions); + nanos_encoder.recordPosition(positions); + } + + void resetStreams() override + { + seconds_stream.reset(); + nanos_stream.reset(); + } + +private: + /// The trailing zeros are removed and their number is kept in the lowest 3 bits. + static Int64 formatNanos(Int64 nanos) + { + if (nanos == 0) + return 0; + if (nanos % 100 != 0) + return nanos << 3; + nanos /= 100; + Int64 trailing_zeros = 1; + while (nanos % 10 == 0 && trailing_zeros < 7) + { + nanos /= 10; + ++trailing_zeros; + } + return (nanos << 3) | trailing_zeros; + } + + const std::optional scale; + OutputByteStream seconds_stream; + OutputByteStream nanos_stream; + IntRleEncoderV2 seconds_encoder; + IntRleEncoderV2 nanos_encoder; + const bool is_utc; + const Int64 epoch_offset; +}; + +class DecimalColumnWriter final : public PrimitiveColumnWriter +{ +public: + DecimalColumnWriter(const Type & type, WriterContext & context_) + : PrimitiveColumnWriter(type, context_) + , scale(static_cast(type.getScale())) + , value_stream(context.compressor, context.block_size) + , scale_stream(context.compressor, context.block_size) + , scale_encoder(scale_stream, true) + { + encoding_kind = Proto::ColumnEncodingKind::DIRECT_V2; + init(); + } + + void add(const IColumn & column, const UInt8 * null_map, size_t offset, size_t num_values, const UInt8 * parent_null_map) override + { + ColumnWriter::add(column, null_map, offset, num_values, parent_null_map); + /// `Decimal32`, `Decimal64` or `Decimal128`. + const size_t width = column.sizeOfValueIfFixed(); + const char * data = column.getRawData().data(); + for (size_t i = 0; i < num_values; ++i) + { + if (null_map && null_map[i]) + continue; + size_t row = offset + i; + Int128 value; + if (width == 16) + value = unalignedLoad(data + row * 16); + else if (width == 8) + value = unalignedLoad(data + row * 8); + else if (width == 4) + value = unalignedLoad(data + row * 4); + else + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected column {} for ORC decimal", column.getName()); + + /// Zigzag-encoded base 128 varint. + UInt128 encoded = (static_cast(value) << 1) ^ static_cast(value >> 127); + while (encoded >= 0x80) + { + char byte = static_cast(static_cast(encoded & 0x7F) | 0x80); + value_stream.write(&byte, 1); + encoded >>= 7; + } + char last = static_cast(static_cast(encoded)); + value_stream.write(&last, 1); + + scale_encoder.write(scale); + index_statistics.updateDecimal(value, scale); + } + countValues(null_map, num_values); + } + + void flush(std::vector & streams) override + { + ColumnWriter::flush(streams); + value_stream.finish(); + scale_encoder.flush(); + scale_stream.finish(); + streams.push_back({Proto::StreamKind::DATA, static_cast(column_id), value_stream.getOutput()}); + streams.push_back({Proto::StreamKind::SECONDARY, static_cast(column_id), scale_stream.getOutput()}); + } + + size_t estimateSize() const override + { + return ColumnWriter::estimateSize() + value_stream.estimateSize() + scale_stream.estimateSize(); + } + +protected: + void recordDataPositions(std::vector & positions) override + { + value_stream.recordPosition(positions); + scale_encoder.recordPosition(positions); + } + + void resetStreams() override + { + value_stream.reset(); + scale_stream.reset(); + } + +private: + const Int32 scale; + OutputByteStream value_stream; + OutputByteStream scale_stream; + IntRleEncoderV2 scale_encoder; +}; + +std::unique_ptr buildColumnWriter(const Type & type, const DataTypePtr & data_type_with_nulls, WriterContext & context) +{ + checkStackSize(); + + /// The nulls are handled by `addColumn`. + DataTypePtr data_type = removeNullable(data_type_with_nulls); + + switch (type.getKind()) + { + case BOOLEAN: + return std::make_unique(type, context); + case BYTE: + return std::make_unique(type, context); + case SHORT: + case INT: + case LONG: + case DATE: + return std::make_unique(type, context); + case FLOAT: + return std::make_unique>(type, context); + case DOUBLE: + return std::make_unique>(type, context); + case STRING: + case BINARY: + case CHAR: + case VARCHAR: + return std::make_unique(type, context); + case TIMESTAMP: + case TIMESTAMP_INSTANT: + { + std::optional scale; + if (const auto * datetime64 = typeid_cast(data_type.get())) + scale = datetime64->getScale(); + return std::make_unique(type, scale, context); + } + case DECIMAL: + return std::make_unique(type, context); + case STRUCT: + return std::make_unique(type, assert_cast(*data_type).getElements(), context); + case LIST: + return std::make_unique>( + type, DataTypes{assert_cast(*data_type).getNestedType()}, context); + case MAP: + { + const auto & map_type = assert_cast(*data_type); + return std::make_unique>(type, DataTypes{map_type.getKeyType(), map_type.getValueType()}, context); + } + case UNION: + return std::make_unique(type, assert_cast(*data_type).getVariants(), context); + case GEOMETRY: + case GEOGRAPHY: + break; + } + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Writing ORC type {} is not supported", type.toString()); +} + +} + + +Writer::Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_) + : out(out_), options(options_) +{ + if (options.compression_block_size == 0 || options.compression_block_size >= (1ULL << 23)) + throw Exception(ErrorCodes::BAD_ARGUMENTS, + "The ORC compression block size must be positive and less than 8 MiB, got {}", options.compression_block_size); + + schema = Type::buildSelectedType(schema_, std::vector(schema_.getMaximumColumnId() + 1, true)); + schema->assignIds(0); + + compressor = createCompressor(options.compression); + + context = std::make_unique(); + context->compressor = compressor.get(); + context->block_size = options.compression_block_size; + context->enable_index = options.row_index_stride > 0; + context->dictionary_key_size_threshold = options.dictionary_key_size_threshold; + context->timezone_offset.emplace(DateLUT::instance(options.timezone_name)); + context->timezone_is_utc = options.timezone_name == "GMT" || options.timezone_name == "UTC"; + static constexpr Int64 UTC_2015_01_01 = 1420070400; + context->epoch_offset = UTC_2015_01_01 - (*context->timezone_offset)(UTC_2015_01_01); + + if (schema->getKind() != STRUCT) + throw Exception(ErrorCodes::LOGICAL_ERROR, "The root type of ORC file must be a struct"); + column_writer = std::make_unique(*schema, column_types, *context); + + write("ORC"); + footer.header_length = current_offset; + footer.row_index_stride = static_cast(options.row_index_stride); + /// The identifier of the C++ writer of the reference implementation, which this writer follows. + footer.writer = 1; + footer.software_version = "ClickHouse"; + schema->toProto(footer.types); +} + +Writer::~Writer() = default; + +void Writer::write(const std::string & data) +{ + out.write(data.data(), data.size()); + current_offset += data.size(); +} + +void Writer::add(const Columns & columns, size_t num_rows) +{ + auto & root = typeid_cast(*column_writer); + + if (context->enable_index) + { + size_t position = 0; + while (position < num_rows) + { + size_t chunk = std::min(num_rows - position, options.row_index_stride - index_rows); + root.addRoot(columns, position, chunk); + position += chunk; + index_rows += chunk; + stripe_rows += chunk; + if (index_rows >= options.row_index_stride) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + } + } + else + { + stripe_rows += num_rows; + root.addRoot(columns, 0, num_rows); + } + + if (column_writer->estimateSize() >= options.stripe_size) + writeStripe(); +} + +void Writer::writeStripe() +{ + if (context->enable_index && index_rows != 0) + { + column_writer->createRowIndexEntry(); + index_rows = 0; + } + else + column_writer->mergeRowGroupStatsIntoStripeStats(); + + column_writer->finalizeStripe(); + + std::vector index_streams; + std::vector data_streams; + if (context->enable_index) + column_writer->writeIndex(index_streams); + column_writer->flush(data_streams); + + Proto::StripeFooter stripe_footer; + UInt64 index_length = 0; + UInt64 data_length = 0; + for (const auto & s : index_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + index_length += s.data.size(); + } + for (const auto & s : data_streams) + { + stripe_footer.streams.push_back({static_cast(s.kind), s.column, s.data.size()}); + data_length += s.data.size(); + } + column_writer->getColumnEncodings(stripe_footer.columns); + stripe_footer.writer_timezone = options.timezone_name; + + auto & stripe_statistics = metadata.stripe_stats.emplace_back(); + column_writer->getStripeStatistics(stripe_statistics.col_stats); + column_writer->mergeStripeStatsIntoFileStats(); + + Proto::StripeInformation stripe; + stripe.offset = current_offset; + + for (const auto & s : index_streams) + write(s.data); + for (const auto & s : data_streams) + write(s.data); + + std::string footer_data = compressWhole(*context, stripe_footer.serialize()); + write(footer_data); + + stripe.index_length = index_length; + stripe.data_length = data_length; + stripe.footer_length = footer_data.size(); + stripe.number_of_rows = stripe_rows; + footer.stripes.push_back(stripe); + + total_rows += stripe_rows; + stripe_rows = 0; + index_rows = 0; + (*column_writer).reset(); +} + +void Writer::close() +{ + if (stripe_rows > 0) + writeStripe(); + + Proto::PostScript postscript; + + /// The content length covers only the stripes, not the metadata section with the stripe statistics. + footer.content_length = current_offset - footer.header_length; + + std::string metadata_data = compressWhole(*context, metadata.serialize()); + write(metadata_data); + postscript.metadata_length = metadata_data.size(); + + footer.number_of_rows = total_rows; + footer.statistics.clear(); + column_writer->getFileStatistics(footer.statistics); + std::string footer_data = compressWhole(*context, footer.serialize()); + write(footer_data); + + postscript.footer_length = footer_data.size(); + postscript.compression = options.compression; + postscript.compression_block_size = options.compression_block_size; + postscript.version = {0, 12}; + /// ORC-135: the timestamp statistics are in UTC. + postscript.writer_version = 6; + postscript.magic = "ORC"; + std::string postscript_data = postscript.serialize(); + if (postscript_data.size() > 255) + throw Exception(ErrorCodes::LOGICAL_ERROR, "ORC postscript is too large: {} bytes", postscript_data.size()); + write(postscript_data); + write(std::string(1, static_cast(postscript_data.size()))); +} + +} diff --git a/src/Processors/Formats/Impl/ORC/Writer.h b/src/Processors/Formats/Impl/ORC/Writer.h new file mode 100644 index 000000000000..111c20ac0fab --- /dev/null +++ b/src/Processors/Formats/Impl/ORC/Writer.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +class DateLUTImpl; + +namespace DB::ORC +{ + +class OutputStream +{ +public: + virtual ~OutputStream() = default; + virtual void write(const void * buf, size_t length) = 0; +}; + +struct WriterOptions +{ + CompressionKind compression = CompressionKind::ZSTD; + UInt64 compression_block_size = 256 * 1024; + /// The number of rows between the row index entries; 0 means no row index. + UInt64 row_index_stride = 10000; + /// Use the dictionary encoding for a string column if the number of distinct values in the + /// first row group is at most this fraction of the number of values. 0 disables the dictionaries. + double dictionary_key_size_threshold = 0.0; + /// The time zone of the writer, which is written into the stripe footers. + std::string timezone_name = "GMT"; + /// A stripe is written when the estimated size of its data reaches this size. + UInt64 stripe_size = 64 * 1024 * 1024; +}; + +class ColumnWriter; +struct WriterContext; + +class Writer +{ +public: + /// `column_types` are the ClickHouse types (without `LowCardinality`) of the columns of the file, + /// which are the fields of `schema` (a struct). The values are converted as follows: + /// the unsigned integers are written as the signed ones of the same width (but `Date` as is); + /// `DateTime` and `DateTime64` as TIMESTAMP; `FixedString`, `IPv6` and the big integers + /// as their raw bytes; `Variant` as UNION with the branches in the order of its variants. + Writer(const Type & schema_, const DataTypes & column_types, OutputStream & out_, const WriterOptions & options_); + ~Writer(); + + /// Adds the rows of the columns (in the order of the fields of the schema). + void add(const Columns & columns, size_t num_rows); + + /// Writes the remaining data and the file footer. + void close(); + +private: + void writeStripe(); + void write(const std::string & data); + + std::unique_ptr schema; + OutputStream & out; + WriterOptions options; + std::unique_ptr compressor; + std::unique_ptr context; + std::unique_ptr column_writer; + + Proto::Footer footer; + Proto::Metadata metadata; + UInt64 current_offset = 0; + UInt64 stripe_rows = 0; + UInt64 index_rows = 0; + UInt64 total_rows = 0; +}; + +} diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp deleted file mode 100644 index 95d9cd537d74..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp +++ /dev/null @@ -1,276 +0,0 @@ -#include -#include - -#if USE_ORC -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -namespace DB -{ - -namespace ErrorCodes -{ - extern const int BAD_ARGUMENTS; - extern const int CANNOT_READ_ALL_DATA; -} - -ORCBlockInputFormat::ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_) - : IInputFormat(std::move(header_), &in_) - , block_missing_values(getPort().getHeader().columns()) - , format_settings(format_settings_) - , skip_stripes(format_settings.orc.skip_stripes) -{ -} - -Chunk ORCBlockInputFormat::read() -{ - block_missing_values.clear(); - - if (!file_reader) - prepareReader(); - - if (is_stopped) - return {}; - - for (; stripe_current < stripe_total && skip_stripes.contains(stripe_current); ++stripe_current) - ; - - if (stripe_current >= stripe_total) - return {}; - - if (need_only_count) - return getChunkForCount(file_reader->GetRawORCReader()->getStripe(stripe_current++)->getNumberOfRows()); - - auto batch_result = file_reader->ReadStripe(stripe_current, include_indices); - if (!batch_result.ok()) - throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Failed to create batch reader: {}", batch_result.status().ToString()); - - auto batch = batch_result.ValueOrDie(); - if (!batch) - return {}; - - /// Validate validity bitmaps before building the table: Table::FromRecordBatches computes - /// each column's null_count, and Arrow derives an unknown FieldNode null_count by scanning - /// the bitmap over the declared length, which reads out of bounds on a truncated bitmap. - ArrowColumnToCHColumn::checkRecordBatchValidityBitmaps(*batch); - - auto table_result = arrow::Table::FromRecordBatches({batch}); - if (!table_result.ok()) - throw Exception( - ErrorCodes::CANNOT_READ_ALL_DATA, "Error while reading batch of ORC data: {}", table_result.status().ToString()); - - /// We should extract the number of rows directly from the stripe, because in case when - /// record batch contains 0 columns (for example if we requested only columns that - /// are not presented in data) the number of rows in record batch will be 0. - size_t num_rows = file_reader->GetRawORCReader()->getStripe(stripe_current)->getNumberOfRows(); - - const auto & table = table_result.ValueOrDie(); - if (!table || !num_rows) - return {}; - - approx_bytes_read_for_chunk = file_reader->GetRawORCReader()->getStripe(stripe_current)->getDataLength(); - ++stripe_current; - - /// If defaults_for_omitted_fields is true, calculate the default values from default expression for omitted fields. - /// Otherwise fill the missing columns with zero values of its type. - BlockMissingValues * block_missing_values_ptr = format_settings.defaults_for_omitted_fields ? &block_missing_values : nullptr; - std::shared_ptr metadata; - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueOrDie(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected error while reading parquet metadata {}", status.status().message()); - - return arrow_column_to_ch_column->arrowTableToCHChunk(table, num_rows, metadata, block_missing_values_ptr); -} - -void ORCBlockInputFormat::resetParser() -{ - IInputFormat::resetParser(); - - file_reader.reset(); - include_indices.clear(); - block_missing_values.clear(); -} - -const BlockMissingValues * ORCBlockInputFormat::getMissingValues() const -{ - return &block_missing_values; -} - - -static void getFileReaderAndSchema( - ReadBuffer & in, - std::unique_ptr & file_reader, - std::shared_ptr & schema, - const FormatSettings & format_settings, - std::atomic & is_stopped) -{ - auto arrow_file = asArrowFile(in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES); - if (is_stopped) - return; - - auto result = arrow::adapters::orc::ORCFileReader::Open(arrow_file, ArrowMemoryPool::instance()); - if (!result.ok()) - throw Exception::createDeprecated(result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - file_reader = std::move(result).ValueOrDie(); - - auto read_schema_result = file_reader->ReadSchema(); - if (!read_schema_result.ok()) - throw Exception::createDeprecated(read_schema_result.status().ToString(), ErrorCodes::BAD_ARGUMENTS); - schema = std::move(read_schema_result).ValueOrDie(); -} - -void ORCBlockInputFormat::prepareReader() -{ - std::shared_ptr schema; - getFileReaderAndSchema(*in, file_reader, schema, format_settings, is_stopped); - if (is_stopped) - return; - - stripe_total = static_cast(file_reader->NumberOfStripes()); - stripe_current = 0; - - arrow_column_to_ch_column = std::make_unique( - getPort().getHeader(), - "ORC", - format_settings, - std::nullopt, - std::nullopt, - format_settings.orc.allow_missing_columns, - format_settings.null_as_default, - format_settings.date_time_overflow_behavior, - format_settings.parquet.allow_geoparquet_parser, - format_settings.orc.case_insensitive_column_matching); - - const bool ignore_case = format_settings.orc.case_insensitive_column_matching; - std::unordered_set nested_table_names = Nested::getAllTableNames(getPort().getHeader(), ignore_case); - for (int i = 0; i < schema->num_fields(); ++i) - { - const auto & name = schema->field(i)->name(); - if (getPort().getHeader().has(name, ignore_case) || nested_table_names.contains(ignore_case ? boost::to_lower_copy(name) : name)) - include_indices.push_back(i); - } -} - -ORCSchemaReader::ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_) - : ISchemaReader(in_), format_settings(format_settings_) -{ -} - -void ORCSchemaReader::initializeIfNeeded() -{ - if (file_reader) - return; - - std::atomic is_stopped = 0; - getFileReaderAndSchema(in, file_reader, schema, format_settings, is_stopped); - - if (auto status = file_reader->ReadMetadata(); status.ok()) - metadata = status.ValueUnsafe(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Error while reading incorrect metadata of ORC {}", status.status().message()); -} - -NamesAndTypesList ORCSchemaReader::readSchema() -{ - initializeIfNeeded(); - - auto header = ArrowColumnToCHColumn::arrowSchemaToCHHeader( - *schema, - metadata, - "ORC", - format_settings, - format_settings.orc.skip_columns_with_unsupported_types_in_schema_inference, - format_settings.schema_inference_make_columns_nullable != 0, - false, - format_settings.parquet.allow_geoparquet_parser); - if (format_settings.schema_inference_make_columns_nullable == 1) - return getNamesAndRecursivelyNullableTypes(header, format_settings); - return header.getNamesAndTypesList(); -} - -std::optional ORCSchemaReader::readNumberOrRows() -{ - initializeIfNeeded(); - return file_reader->NumberOfRows(); -} - -void registerInputFormatORC(FormatFactory & factory) -{ - factory.registerRandomAccessInputFormat( - "ORC", - [](ReadBuffer & buf, - const Block & sample, - const FormatSettings & settings, - const ReadSettings & read_settings, - bool is_remote_fs, - FormatParserSharedResourcesPtr, - FormatFilterInfoPtr format_filter_info) - { - InputFormatPtr res; - if (settings.orc.use_fast_decoder) - { - const bool has_file_size = isBufferWithFileSize(buf); - auto * seekable_in = dynamic_cast(&buf); - const bool use_prefetch = is_remote_fs && read_settings.remote_fs_prefetch && has_file_size && seekable_in - && seekable_in->checkIfActuallySeekable() && seekable_in->supportsReadAt() && settings.seekable_read; - const size_t min_bytes_for_seek = use_prefetch ? read_settings.remote_read_min_bytes_for_seek : 0; - res = std::make_shared( - buf, std::make_shared(sample), settings, use_prefetch, min_bytes_for_seek, format_filter_info); - } - else - res = std::make_shared(buf, std::make_shared(sample), settings); - - return res; - }); - factory.markFormatSupportsSubsetOfColumns("ORC"); -} - -void registerORCSchemaReader(FormatFactory & factory) -{ - factory.registerSchemaReader( - "ORC", - [](ReadBuffer & buf, const FormatSettings & settings) - { - SchemaReaderPtr res; - if (settings.orc.use_fast_decoder) - res = std::make_shared(buf, settings); - else - res = std::make_shared(buf, settings); - - return res; - } - ); - - factory.registerAdditionalInfoForSchemaCacheGetter("ORC", [](const FormatSettings & settings) - { - return fmt::format("schema_inference_make_columns_nullable={}", settings.schema_inference_make_columns_nullable); - }); -} - -} -#else - -namespace DB -{ - class FormatFactory; - void registerInputFormatORC(FormatFactory &) - { - } - - void registerORCSchemaReader(FormatFactory &) - { - } -} - -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.h b/src/Processors/Formats/Impl/ORCBlockInputFormat.h deleted file mode 100644 index 622a6276c344..000000000000 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once -#include "config.h" -#if USE_ORC - -#include -#include -#include -#include - -#include - -namespace arrow::adapters::orc -{ - class ORCFileReader; -} - -namespace DB -{ - -class ArrowColumnToCHColumn; - -class ORCBlockInputFormat : public IInputFormat -{ -public: - ORCBlockInputFormat(ReadBuffer & in_, SharedHeader header_, const FormatSettings & format_settings_); - - String getName() const override { return "ORCBlockInputFormat"; } - - void resetParser() override; - - const BlockMissingValues * getMissingValues() const override; - - size_t getApproxBytesReadForChunk() const override { return approx_bytes_read_for_chunk; } - -protected: - Chunk read() override; - - void onCancel() noexcept override - { - is_stopped = 1; - } - -private: - void prepareReader(); - - // TODO: check that this class implements every part of its parent - - std::unique_ptr file_reader; - - std::unique_ptr arrow_column_to_ch_column; - - // indices of columns to read from ORC file - std::vector include_indices; - - BlockMissingValues block_missing_values; - size_t approx_bytes_read_for_chunk = 0; - - const FormatSettings format_settings; - const std::unordered_set & skip_stripes; - - int stripe_total = 0; - int stripe_current = 0; - - std::atomic is_stopped{0}; -}; - -class ORCSchemaReader : public ISchemaReader -{ -public: - ORCSchemaReader(ReadBuffer & in_, const FormatSettings & format_settings_); - - NamesAndTypesList readSchema() override; - std::optional readNumberOrRows() override; - -private: - void initializeIfNeeded(); - - std::unique_ptr file_reader; - std::shared_ptr metadata; - std::shared_ptr schema; - const FormatSettings format_settings; -}; - -} -#endif diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp index b9f8bd463152..acf3371b9249 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp @@ -1,5 +1,9 @@ #include +#include + +#include + #if USE_ORC #include @@ -11,6 +15,7 @@ #include #include #include +#include #include #include @@ -20,8 +25,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -38,495 +45,257 @@ namespace ErrorCodes namespace { -orc::CompressionKind getORCCompression(FormatSettings::ORCCompression method) +ORC::CompressionKind getORCCompression(FormatSettings::ORCCompression method) { if (method == FormatSettings::ORCCompression::NONE) - return orc::CompressionKind::CompressionKind_NONE; + return ORC::CompressionKind::NONE; #if USE_SNAPPY if (method == FormatSettings::ORCCompression::SNAPPY) - return orc::CompressionKind::CompressionKind_SNAPPY; + return ORC::CompressionKind::SNAPPY; #endif if (method == FormatSettings::ORCCompression::ZSTD) - return orc::CompressionKind::CompressionKind_ZSTD; + return ORC::CompressionKind::ZSTD; if (method == FormatSettings::ORCCompression::LZ4) - return orc::CompressionKind::CompressionKind_LZ4; + return ORC::CompressionKind::LZ4; if (method == FormatSettings::ORCCompression::ZLIB) - return orc::CompressionKind::CompressionKind_ZLIB; + return ORC::CompressionKind::ZLIB; throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported compression method"); } -} - -ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} - -uint64_t ORCOutputStream::getLength() const +/// Two ORC types get the same key exactly when `parseORCType` (NativeORCBlockInputFormat.cpp) reads +/// them back as the same ClickHouse type: `BINARY` and `STRING` both read as `String`, and a nested +/// `UNION` reads as a `Variant`, which sorts its branches, while ORC keeps them positional. +/// A field name is length-prefixed so a name containing `:` or `,` cannot forge another key. +String orcTypeDedupKey(const ORC::Type & type) { - return out.count(); + const auto kind = type.getKind(); + if (kind == ORC::TypeKind::BINARY || kind == ORC::TypeKind::STRING) + return "string"; + if (kind == ORC::TypeKind::DECIMAL) + return fmt::format("decimal({},{})", type.getPrecision(), type.getScale()); + + std::vector children; + for (size_t i = 0; i < type.getSubtypeCount(); ++i) + { + auto child = orcTypeDedupKey(*type.getSubtype(i)); + if (kind == ORC::TypeKind::STRUCT) + child = fmt::format("{}:{}:{}", type.getFieldName(i).size(), type.getFieldName(i), child); + children.push_back(std::move(child)); + } + if (kind == ORC::TypeKind::UNION) + std::sort(children.begin(), children.end()); + /// Every remaining kind the writer emits is a parameterless primitive mapping to a distinct + /// ClickHouse type, so for those the kind alone is the key and there are no children. + return fmt::format("{}<{}>", static_cast(kind), fmt::join(children, ",")); } -uint64_t ORCOutputStream::getNaturalWriteSize() const -{ - out.nextIfAtEnd(); - return out.available(); } +ORCOutputStream::ORCOutputStream(WriteBuffer & out_) : out(out_) {} + void ORCOutputStream::write(const void* buf, size_t length) { out.write(static_cast(buf), length); } -ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_) +ORCBlockOutputFormat::ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_) : IOutputFormat(header_, out_) , format_settings{format_settings_} , output_stream(out_) + , column_mapper(std::move(column_mapper_)) { for (const auto & type : header_->getDataTypes()) data_types.push_back(recursiveRemoveLowCardinality(type)); } -std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type) +std::unique_ptr ORCBlockOutputFormat::getORCType(const DataTypePtr & type, const String & column_path) { - switch (type->getTypeId()) + /// Nullable(T) maps to the same ORC node as T; only the Iceberg `required` flag differs. + bool required = !type->isNullable(); + const DataTypePtr unwrapped = removeNullable(type); + + std::unique_ptr result; + switch (unwrapped->getTypeId()) { case TypeIndex::UInt8: { - if (isBool(type)) - return orc::createPrimitiveType(orc::TypeKind::BOOLEAN); - return orc::createPrimitiveType(orc::TypeKind::BYTE); + if (isBool(unwrapped)) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BOOLEAN); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum8: [[fallthrough]]; case TypeIndex::Int8: { - return orc::createPrimitiveType(orc::TypeKind::BYTE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BYTE); + break; } case TypeIndex::Enum16: [[fallthrough]]; case TypeIndex::UInt16: [[fallthrough]]; case TypeIndex::Int16: { - return orc::createPrimitiveType(orc::TypeKind::SHORT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::SHORT); + break; } case TypeIndex::UInt32: [[fallthrough]]; case TypeIndex::IPv4: [[fallthrough]]; case TypeIndex::Int32: { - return orc::createPrimitiveType(orc::TypeKind::INT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::INT); + break; } case TypeIndex::UInt64: [[fallthrough]]; case TypeIndex::Int64: { - return orc::createPrimitiveType(orc::TypeKind::LONG); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::LONG); + break; } case TypeIndex::Float32: { - return orc::createPrimitiveType(orc::TypeKind::FLOAT); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::FLOAT); + break; } case TypeIndex::Float64: { - return orc::createPrimitiveType(orc::TypeKind::DOUBLE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DOUBLE); + break; } case TypeIndex::Date32: [[fallthrough]]; case TypeIndex::Date: { - return orc::createPrimitiveType(orc::TypeKind::DATE); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::DATE); + break; } case TypeIndex::DateTime: [[fallthrough]]; case TypeIndex::DateTime64: { - return orc::createPrimitiveType(orc::TypeKind::TIMESTAMP); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::TIMESTAMP); + break; } case TypeIndex::Int128: [[fallthrough]]; case TypeIndex::UInt128: [[fallthrough]]; case TypeIndex::Int256: [[fallthrough]]; case TypeIndex::UInt256: [[fallthrough]]; case TypeIndex::Decimal256: - return orc::createPrimitiveType(orc::TypeKind::BINARY); - case TypeIndex::FixedString: [[fallthrough]]; - case TypeIndex::String: - { - if (format_settings.orc.output_string_as_string) - return orc::createPrimitiveType(orc::TypeKind::STRING); - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::IPv6: - { - return orc::createPrimitiveType(orc::TypeKind::BINARY); - } - case TypeIndex::Nullable: - { - return getORCType(removeNullable(type)); - } - case TypeIndex::Array: - { - const auto * array_type = assert_cast(type.get()); - return orc::createListType(getORCType(array_type->getNestedType())); - } - case TypeIndex::Decimal32: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal64: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Decimal128: - { - const auto * decimal_type = assert_cast *>(type.get()); - return orc::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); - } - case TypeIndex::Tuple: - { - const auto * tuple_type = assert_cast(type.get()); - const auto & nested_names = tuple_type->getElementNames(); - const auto & nested_types = tuple_type->getElements(); - auto struct_type = orc::createStructType(); - for (size_t i = 0; i < nested_types.size(); ++i) - struct_type->addStructField(nested_names[i], getORCType(nested_types[i])); - return struct_type; - } - case TypeIndex::Map: - { - const auto * map_type = assert_cast(type.get()); - return orc::createMapType( - getORCType(map_type->getKeyType()), - getORCType(map_type->getValueType()) - ); - } - default: - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); - } - } -} - -template -void ORCBlockOutputFormat::writeNumbers( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - NumberVectorBatch & number_orc_column = dynamic_cast(orc_column); - const auto & number_column = assert_cast &>(column); - - number_orc_column.data.resize(number_column.size()); - for (size_t i = 0; i != number_column.size(); ++i) - number_orc_column.data[i] = convert(number_column.getElement(i)); -} - -template -void ORCBlockOutputFormat::writeDecimals( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * /*null_bytemap*/, - ConvertFunc convert) -{ - DecimalVectorBatch & decimal_orc_column = dynamic_cast(orc_column); - const auto & decimal_column = assert_cast &>(column); - const auto * decimal_type = assert_cast *>(type.get()); - decimal_orc_column.precision = decimal_type->getPrecision(); - decimal_orc_column.scale = decimal_type->getScale(); - decimal_orc_column.resize(decimal_column.size()); - - decimal_orc_column.values.resize(decimal_column.size()); - for (size_t i = 0; i != decimal_column.size(); ++i) - decimal_orc_column.values[i] = convert(decimal_column.getElement(i).value); -} - -template -void ORCBlockOutputFormat::writeStrings( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * null_bytemap) -{ - orc::StringVectorBatch & string_orc_column = dynamic_cast(orc_column); - const auto & string_column = assert_cast(column); - - string_orc_column.data.resize(string_column.size()); - string_orc_column.length.resize(string_column.size()); - for (size_t i = 0; i != string_column.size(); ++i) - { - const std::string_view string = string_column.getDataAt(i); - string_orc_column.data[i] = (null_bytemap && (*null_bytemap)[i]) ? nullptr : const_cast(string.data()); - string_orc_column.length[i] = string.size(); - } -} - -template -void ORCBlockOutputFormat::writeDateTimes( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - const PaddedPODArray * /*null_bytemap*/, - GetSecondsFunc get_seconds, - GetNanosecondsFunc get_nanoseconds) -{ - orc::TimestampVectorBatch & timestamp_orc_column = dynamic_cast(orc_column); - const auto & timestamp_column = assert_cast(column); - - timestamp_orc_column.data.resize(timestamp_column.size()); - timestamp_orc_column.nanoseconds.resize(timestamp_column.size()); - for (size_t i = 0; i != timestamp_column.size(); ++i) - { - timestamp_orc_column.data[i] = static_cast(get_seconds(timestamp_column.getElement(i))); - timestamp_orc_column.nanoseconds[i] = static_cast(get_nanoseconds(timestamp_column.getElement(i))); - } -} - -void ORCBlockOutputFormat::writeColumn( - orc::ColumnVectorBatch & orc_column, - const IColumn & column, - DataTypePtr & type, - const PaddedPODArray * null_bytemap) -{ - size_t rows = column.size(); - orc_column.resize(rows); - orc_column.numElements = rows; - - /// Calculate orc_column.hasNulls - if (null_bytemap) - orc_column.hasNulls = !memoryIsZero(null_bytemap->data(), 0, null_bytemap->size()); - else - orc_column.hasNulls = false; - - /// Fill orc_column.notNull - if (orc_column.hasNulls) - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = !(*null_bytemap)[i]; - } - else - { - for (size_t i = 0; i < rows; ++i) - orc_column.notNull[i] = 1; - } - - /// ORC doesn't have unsigned types, so cast everything to signed and sign-extend to Int64 to - /// make the ORC library calculate min and max correctly. - switch (type->getTypeId()) - { - case TypeIndex::Enum8: [[fallthrough]]; - case TypeIndex::Int8: - { - /// Note: Explicit cast to avoid clang-tidy error: 'signed char' to 'long' conversion; consider casting to 'unsigned char' first. - writeNumbers(orc_column, column, null_bytemap, [](const Int8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::UInt8: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt8 & value){ return Int64(Int8(value)); }); - break; - } - case TypeIndex::Enum16: [[fallthrough]]; - case TypeIndex::Int16: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int16 & value){ return value; }); - break; - } - case TypeIndex::Date: [[fallthrough]]; - case TypeIndex::UInt16: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt16 & value){ return Int64(Int16(value)); }); - break; - } - case TypeIndex::Date32: [[fallthrough]]; - case TypeIndex::Int32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int32 & value){ return value; }); - break; - } - case TypeIndex::UInt32: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt32 & value){ return Int64(Int32(value)); }); - break; - } - case TypeIndex::IPv4: - { - writeNumbers(orc_column, column, null_bytemap, [](const IPv4 & value){ return Int64(Int32(value.toUnderType())); }); - break; - } - case TypeIndex::Int64: - { - writeNumbers(orc_column, column, null_bytemap, [](const Int64 & value){ return value; }); - break; - } - case TypeIndex::UInt64: - { - writeNumbers(orc_column, column, null_bytemap, [](const UInt64 & value){ return value; }); - break; - } - case TypeIndex::Int128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt128: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Int256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::UInt256: - { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::Float32: - { - writeNumbers(orc_column, column, null_bytemap, [](const Float32 & value){ return value; }); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; - } - case TypeIndex::Float64: + case TypeIndex::String: { - writeNumbers(orc_column, column, null_bytemap, [](const Float64 & value){ return value; }); + bool force_string = format_settings.orc.output_string_as_string; + result = ORC::Type::createPrimitiveType(force_string ? ORC::TypeKind::STRING : ORC::TypeKind::BINARY); break; } case TypeIndex::FixedString: { - writeStrings(orc_column, column, null_bytemap); - break; - } - case TypeIndex::String: - { - writeStrings(orc_column, column, null_bytemap); + /// Iceberg `fixed[L]` (FixedString) must stay ORC `binary`, so for Iceberg writes + /// force `binary` regardless of the setting; keep the setting-driven choice otherwise. + if (format_settings.orc.output_string_as_string && !column_mapper) + result = ORC::Type::createPrimitiveType(ORC::TypeKind::STRING); + else + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } case TypeIndex::IPv6: { - writeStrings(orc_column, column, null_bytemap); + result = ORC::Type::createPrimitiveType(ORC::TypeKind::BINARY); break; } - case TypeIndex::DateTime: + case TypeIndex::Array: { - writeDateTimes( - orc_column, - column, null_bytemap, - [](UInt32 value){ return value; }, - [](UInt32){ return 0; }); + const auto * array_type = assert_cast(unwrapped.get()); + result = ORC::Type::createListType(getORCType(array_type->getNestedType(), Nested::concatenateName(column_path, "element"))); break; } - case TypeIndex::DateTime64: + case TypeIndex::Decimal32: { - const auto * timestamp_type = assert_cast(type.get()); - UInt32 scale = timestamp_type->getScale(); - writeDateTimes( - orc_column, - column, - null_bytemap, - [scale](Int64 value) { return value / Int64(std::pow(10, scale)); }, - [scale](Int64 value) { return (value % Int64(std::pow(10, scale))) * Int64(std::pow(10, 9 - scale)); }); - break; - } - case TypeIndex::Decimal32: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int32 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal64: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int64 value){ return value; }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } case TypeIndex::Decimal128: { - writeDecimals( - orc_column, - column, - type, - null_bytemap, - [](Int128 value){ return orc::Int128(static_cast(value >> 64), static_cast((value << 64) >> 64)); }); + const auto * decimal_type = assert_cast *>(unwrapped.get()); + result = ORC::Type::createDecimalType(decimal_type->getPrecision(), decimal_type->getScale()); break; } - case TypeIndex::Decimal256: + case TypeIndex::Tuple: { - writeStrings>(orc_column, column, null_bytemap); + const auto * tuple_type = assert_cast(unwrapped.get()); + const auto & nested_names = tuple_type->getElementNames(); + const auto & nested_types = tuple_type->getElements(); + auto struct_type = ORC::Type::createStructType(); + for (size_t i = 0; i < nested_types.size(); ++i) + struct_type->addStructField(nested_names[i], getORCType(nested_types[i], Nested::concatenateName(column_path, nested_names[i]))); + result = std::move(struct_type); break; } - case TypeIndex::Nullable: + case TypeIndex::Map: { - chassert(!null_bytemap); - const auto & nullable_column = assert_cast(column); - const PaddedPODArray & new_null_bytemap = assert_cast &>(*nullable_column.getNullMapColumnPtr()).getData(); - auto nested_type = removeNullable(type); - writeColumn(orc_column, nullable_column.getNestedColumn(), nested_type, &new_null_bytemap); + const auto * map_type = assert_cast(unwrapped.get()); + result = ORC::Type::createMapType( + getORCType(map_type->getKeyType(), Nested::concatenateName(column_path, "key")), + getORCType(map_type->getValueType(), Nested::concatenateName(column_path, "value")) + ); break; } - case TypeIndex::Array: - { - orc::ListVectorBatch & list_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column); - auto nested_type = assert_cast(*type).getNestedType(); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - list_orc_column.offsets.resize(column_size + 1); - - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - list_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - list_orc_column.offsets[i + 1] = offsets[i]; - - orc::ColumnVectorBatch & nested_orc_column = *list_orc_column.elements; - writeColumn(nested_orc_column, list_column.getData(), nested_type, nullptr); + case TypeIndex::Variant: + { + const auto & variant_type = assert_cast(*unwrapped); + auto union_type = ORC::Type::createUnionType(); + /// ORC keeps one physical stream per union branch and identifies a branch only by its + /// ORC type, so two variants that map to the same ORC type (e.g. `Int32` and `UInt32`, + /// both ORC `int`) would produce a union with duplicate branches, which the reader + /// rejects. Branches whose ORC types merely read back as one ClickHouse type collide the + /// same way, so they are keyed by `orcTypeDedupKey` rather than by the ORC type itself. + std::unordered_map> variant_by_orc_type; + /// A union child is addressed by its type name, the way a `Variant` subcolumn is + /// (`v.Int32`). Iceberg has no union type, so no field id is expected to be found there. + for (const auto & nested_type : variant_type.getVariants()) + { + auto child_type = getORCType(nested_type, Nested::concatenateName(column_path, nested_type->getName())); + auto [it, inserted] = variant_by_orc_type.emplace( + orcTypeDedupKey(*child_type), std::pair{nested_type->getName(), child_type->toString()}); + if (!inserted) + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Type {} is not supported for ORC output format: variant {} is written as ORC type '{}' and variant {} as " + "'{}', which are read back as the same type, and ORC unions with duplicate branch types cannot be read back", + unwrapped->getName(), it->second.first, it->second.second, nested_type->getName(), child_type->toString()); + union_type->addChild(std::move(child_type)); + } + result = std::move(union_type); break; } - case TypeIndex::Tuple: + default: { - orc::StructVectorBatch & struct_orc_column = dynamic_cast(orc_column); - const auto & tuple_column = assert_cast(column); - auto nested_types = assert_cast(type.get())->getElements(); - for (size_t i = 0; i != tuple_column.tupleSize(); ++i) - writeColumn(*struct_orc_column.fields[i], tuple_column.getColumn(i), nested_types[i], nullptr); - break; + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", unwrapped->getName()); } - case TypeIndex::Map: - { - orc::MapVectorBatch & map_orc_column = dynamic_cast(orc_column); - const auto & list_column = assert_cast(column).getNestedColumn(); - const auto & map_type = assert_cast(*type); - const ColumnArray::Offsets & offsets = list_column.getOffsets(); - - size_t column_size = list_column.size(); - - map_orc_column.offsets.resize(column_size + 1); - /// The length of list i in ListVectorBatch is offsets[i+1] - offsets[i]. - map_orc_column.offsets[0] = 0; - for (size_t i = 0; i != column_size; ++i) - map_orc_column.offsets[i + 1] = offsets[i]; - - const auto nested_columns = assert_cast(list_column.getDataPtr().get())->getColumns(); - - orc::ColumnVectorBatch & keys_orc_column = *map_orc_column.keys; - auto key_type = map_type.getKeyType(); - writeColumn(keys_orc_column, *nested_columns[0], key_type, nullptr); + } - orc::ColumnVectorBatch & values_orc_column = *map_orc_column.elements; - auto value_type = map_type.getValueType(); - writeColumn(values_orc_column, *nested_columns[1], value_type, nullptr); - break; + /// Attach Iceberg field-id attributes so spec-compliant readers project columns by id. + if (column_mapper) + { + const auto & encoding = column_mapper->getStorageColumnEncoding(); + if (auto it = encoding.find(column_path); it != encoding.end()) + { + result->setAttribute("iceberg.id", std::to_string(it->second)); + result->setAttribute("iceberg.required", required ? "true" : "false"); } - default: - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Type {} is not supported for ORC output format", type->getName()); } + + return result; } void ORCBlockOutputFormat::consume(Chunk chunk) @@ -534,21 +303,13 @@ void ORCBlockOutputFormat::consume(Chunk chunk) if (!writer) prepareWriter(); - size_t columns_num = chunk.getNumColumns(); size_t rows_num = chunk.getNumRows(); - - std::unique_ptr batch = writer->createRowBatch(chunk.getNumRows()); - orc::StructVectorBatch & root = dynamic_cast(*batch); - auto columns = chunk.detachColumns(); for (auto & column : columns) column = recursiveRemoveLowCardinality(column); - for (size_t i = 0; i != columns_num; ++i) - writeColumn(*root.fields[i], *columns[i], data_types[i], nullptr); - - root.numElements = rows_num; - writer->add(*batch); + /// The values are encoded directly from the columns. + writer->add(columns, rows_num); } void ORCBlockOutputFormat::finalizeImpl() @@ -567,19 +328,22 @@ void ORCBlockOutputFormat::resetFormatterImpl() void ORCBlockOutputFormat::prepareWriter() { const Block & header = getPort(PortKind::Main).getHeader(); - schema = orc::createStructType(); - options.setMemoryPool(&getORCMemoryPool()); - options.setCompression(getORCCompression(format_settings.orc.output_compression_method)); - options.setRowIndexStride(format_settings.orc.output_row_index_stride); - options.setDictionaryKeySizeThreshold(format_settings.orc.output_dictionary_key_size_threshold); - options.setCompressionBlockSize(format_settings.orc.output_compression_block_size); - options.setTimezoneName(format_settings.orc.writer_time_zone_name); + schema = ORC::Type::createStructType(); + options.compression = getORCCompression(format_settings.orc.output_compression_method); + options.row_index_stride = format_settings.orc.output_row_index_stride; + options.dictionary_key_size_threshold = format_settings.orc.output_dictionary_key_size_threshold; + options.compression_block_size = format_settings.orc.output_compression_block_size; + options.timezone_name = format_settings.orc.writer_time_zone_name; size_t columns_count = header.columns(); for (size_t i = 0; i != columns_count; ++i) - schema->addStructField(header.safeGetByPosition(i).name, getORCType(recursiveRemoveLowCardinality(data_types[i]))); - writer = orc::createWriter(*schema, &output_stream, options); + { + const auto & column_name = header.safeGetByPosition(i).name; + schema->addStructField(column_name, getORCType(recursiveRemoveLowCardinality(data_types[i]), column_name)); + } + writer = std::make_unique(*schema, data_types, output_stream, options); } +void registerOutputFormatORC(FormatFactory & factory); void registerOutputFormatORC(FormatFactory & factory) { factory.registerOutputFormat("ORC", []( @@ -603,6 +367,7 @@ void registerOutputFormatORC(FormatFactory & factory) namespace DB { class FormatFactory; + void registerOutputFormatORC(FormatFactory &); void registerOutputFormatORC(FormatFactory &) { } diff --git a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h index 0e47f7333d9d..5c9ebc4da420 100644 --- a/src/Processors/Formats/Impl/ORCBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ORCBlockOutputFormat.h @@ -7,7 +7,8 @@ #include #include #include -#include +#include +#include namespace DB @@ -19,29 +20,22 @@ using DataTypes = std::vector; class WriteBuffer; -/// orc::Writer writes only in orc::OutputStream -class ORCOutputStream : public orc::OutputStream +class ORCOutputStream : public ORC::OutputStream { public: explicit ORCOutputStream(WriteBuffer & out_); - uint64_t getLength() const override; - uint64_t getNaturalWriteSize() const override; void write(const void * buf, size_t length) override; - void close() override {} - const std::string& getName() const override { return name; } - private: WriteBuffer & out; - std::string name = "ORCOutputStream"; }; -class ORCBlockOutputFormat : public IOutputFormat +class ORCBlockOutputFormat final : public IOutputFormat { public: - ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_); + ORCBlockOutputFormat(WriteBuffer & out_, SharedHeader header_, const FormatSettings & format_settings_, ColumnMapperPtr column_mapper_ = nullptr); String getName() const override { return "ORCBlockOutputFormat"; } @@ -50,37 +44,20 @@ class ORCBlockOutputFormat : public IOutputFormat void finalizeImpl() override; void resetFormatterImpl() override; - std::unique_ptr getORCType(const DataTypePtr & type); - - /// ConvertFunc is needed for type UInt8, because firstly UInt8 (char8_t) must be - /// converted to unsigned char (bugprone-signed-char-misuse in clang). - template - void writeNumbers(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, ConvertFunc convert); - - /// ConvertFunc is needed to convert ClickHouse Int128 to ORC Int128. - template - void writeDecimals(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, - const PaddedPODArray * null_bytemap, ConvertFunc convert); - - template - void writeStrings(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap); - - /// ORC column TimestampVectorBatch stores only seconds and nanoseconds, - /// GetSecondsFunc and GetNanosecondsFunc are needed to extract them from DateTime type. - template - void writeDateTimes(orc::ColumnVectorBatch & orc_column, const IColumn & column, const PaddedPODArray * null_bytemap, - GetSecondsFunc get_seconds, GetNanosecondsFunc get_nanoseconds); - - void writeColumn(orc::ColumnVectorBatch & orc_column, const IColumn & column, DataTypePtr & type, const PaddedPODArray * null_bytemap); + /// For Iceberg writes, attaches the field-id `iceberg.id` type attribute so readers project + /// by id. `column_path` is the dotted name (`t.x`, `arr.element`) used to look the id up. + std::unique_ptr getORCType(const DataTypePtr & type, const String & column_path); void prepareWriter(); const FormatSettings format_settings; ORCOutputStream output_stream; DataTypes data_types; - std::unique_ptr writer; - std::unique_ptr schema; - orc::WriterOptions options; + std::unique_ptr writer; + std::unique_ptr schema; + ORC::WriterOptions options; + /// Non-null only for Iceberg writes; maps dotted column name -> Iceberg field-id. + ColumnMapperPtr column_mapper; }; } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.cpp b/src/Processors/Formats/Impl/Parquet/Decoding.cpp index 840abe3265b2..e52e24dce6a8 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.cpp +++ b/src/Processors/Formats/Impl/Parquet/Decoding.cpp @@ -1676,6 +1676,8 @@ Int96Converter::Int96Converter() void Int96Converter::convertColumn(std::span data, size_t num_values, IColumn & col) const { + const bool saturate = overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Saturate; + std::span to_span = col.insertRawUninitialized(num_values); Int64 * to = reinterpret_cast(to_span.data()); for (size_t i = 0; i < num_values; ++i) @@ -1700,16 +1702,17 @@ void Int96Converter::convertColumn(std::span data, size_t num_values /// This interpretation is consistent with the arrow reader code (DecodeInt96Timestamp in /// arrow/cpp/src/parquet/types.h) and with a test file written by spark /// (tests/queries/0_stateless/02998_native_parquet_reader.sh). - bool overflow = false; - Int64 x; - overflow |= common::subOverflow(julian_day, static_cast(2440588l), x); // unix day number - overflow |= common::mulOverflow(x, day_nanos, x); // unix nanoseconds - overflow |= common::addOverflow(x, nanos, x); - - if (overflow) - throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); - to[i] = x; + /// julian_day comes from Int32, so neither the subtraction nor the product can overflow Int128. + const Int128 total = Int128(julian_day - 2440588l) * day_nanos + nanos; + if (total < std::numeric_limits::min() || total > std::numeric_limits::max()) + { + if (!saturate) + throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "INT96 timestamp out of range: julian day {}, time of day {} ns", julian_day, nanos); + to[i] = julian_day < 2440588l ? std::numeric_limits::min() : std::numeric_limits::max(); + } + else + to[i] = static_cast(total); } } diff --git a/src/Processors/Formats/Impl/Parquet/Decoding.h b/src/Processors/Formats/Impl/Parquet/Decoding.h index 05f6ef6a2e02..266176171e45 100644 --- a/src/Processors/Formats/Impl/Parquet/Decoding.h +++ b/src/Processors/Formats/Impl/Parquet/Decoding.h @@ -298,6 +298,9 @@ extern template struct BigEndianDecimalStringConverter; struct Int96Converter : public FixedSizeConverter { + /// A value that does not fit into Int64 nanoseconds is clamped to the `DateTime64(9)` range with Saturate, otherwise throws. + FormatSettings::DateTimeOverflowBehavior overflow_behavior = FormatSettings::DateTimeOverflowBehavior::Ignore; + Int96Converter(); void convertColumn(std::span data, size_t num_values, IColumn & col) const override; diff --git a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp index 8053f644407c..b1633c13f7e2 100644 --- a/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp +++ b/src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp @@ -1258,7 +1258,9 @@ void SchemaConverter::processPrimitiveColumn( case parq::Type::INT96: { out_inferred_type = std::make_shared(9, "UTC"); - out_decoder.fixed_size_converter = std::make_shared(); + auto converter = std::make_shared(); + converter->overflow_behavior = options.format.date_time_overflow_behavior; + out_decoder.fixed_size_converter = std::move(converter); /// (Leaving allow_stats == false because INT96 sort order is undefined.) return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp index 3e938fddea10..317478590c98 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp @@ -6,21 +6,17 @@ #include #include +#include #include #include +#include + #include #include #include -namespace CurrentMetrics -{ - extern const Metric ParquetEncoderThreads; - extern const Metric ParquetEncoderThreadsActive; - extern const Metric ParquetEncoderThreadsScheduled; -} - namespace DB { @@ -87,11 +83,10 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Custom parquet encoder doesn't support parquet versions < 2.6. Use output_format_parquet_use_custom_encoder = 0."); if (format_settings.parquet.parallel_encoding && format_settings.max_threads > 1) - pool = std::make_unique( - CurrentMetrics::ParquetEncoderThreads, - CurrentMetrics::ParquetEncoderThreadsActive, - CurrentMetrics::ParquetEncoderThreadsScheduled, - format_settings.max_threads); + { + getParquetEncoderThreadPool().initializeWithDefaultSettingsIfNotInitialized(); + pool = &getParquetEncoderThreadPool().get(); + } using C = FormatSettings::ParquetCompression; switch (format_settings.parquet.output_compression_method) @@ -130,10 +125,14 @@ ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, SharedHea ParquetBlockOutputFormat::~ParquetBlockOutputFormat() { if (pool) - { - is_stopped = true; - pool->wait(); - } + stopThreads(); +} + +void ParquetBlockOutputFormat::stopThreads() +{ + is_stopped = true; + std::unique_lock lock(mutex); + condvar.wait(lock, [this] { return threads_running == 0; }); } void ParquetBlockOutputFormat::consume(Chunk chunk) @@ -279,8 +278,7 @@ void ParquetBlockOutputFormat::resetFormatterImpl() { if (pool) { - is_stopped = true; - pool->wait(); + stopThreads(); is_stopped = false; } @@ -497,17 +495,16 @@ void ParquetBlockOutputFormat::startMoreThreadsIfNeeded(const std::unique_locktrySchedule(job)) break; + ++threads_running; } } } -void ParquetBlockOutputFormat::threadFunction() +void ParquetBlockOutputFormat::threadFunction(ThreadGroupPtr & thread_group) { + std::optional switcher; + switcher.emplace(thread_group, ThreadName::PARQUET_ENCODER); + std::unique_lock lock(mutex); while (true) @@ -540,7 +541,12 @@ void ParquetBlockOutputFormat::threadFunction() { /// The check and the decrement need to be in the same critical section, to make sure /// we never get stuck with tasks but no threads. + /// Leave the query's thread group before stopThreads() can see the decrement. + switcher.reset(); + thread_group.reset(); --threads_running; + if (threads_running == 0) + condvar.notify_all(); return; } diff --git a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h index f22447850e82..b553a00ba391 100644 --- a/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h +++ b/src/Processors/Formats/Impl/ParquetBlockOutputFormat.h @@ -28,6 +28,9 @@ namespace DB class CHColumnToArrowColumn; +class ThreadGroup; +using ThreadGroupPtr = std::shared_ptr; + class ParquetBlockOutputFormat : public IOutputFormat { public: @@ -118,8 +121,9 @@ class ParquetBlockOutputFormat : public IOutputFormat void writeRowGroupInOneThread(Chunk chunk); void writeRowGroupInParallel(std::vector chunks); - void threadFunction(); + void threadFunction(ThreadGroupPtr & thread_group); void startMoreThreadsIfNeeded(const std::unique_lock & lock); + void stopThreads(); /// Called in single-threaded fashion. Writes to the file. void reapCompletedRowGroups(std::unique_lock & lock); @@ -140,13 +144,15 @@ class ParquetBlockOutputFormat : public IOutputFormat size_t base_offset = 0; // initial out.count(), just for assert std::mutex mutex; - std::condition_variable condvar; // wakes up consume() - std::unique_ptr pool; + std::condition_variable condvar; // wakes up consume() and stopThreads() + /// Shared by all Parquet writers of the process (`getParquetEncoderThreadPool`). + ThreadPool * pool = nullptr; std::atomic_bool is_stopped{false}; std::exception_ptr background_exception = nullptr; /// Invariant: if there's at least one task then there's at least one thread. + /// Counts the jobs scheduled on `pool` until they exit, queued ones included. size_t threads_running = 0; std::atomic bytes_in_flight{0}; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 5e9a4bfd7565..119112f9838a 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -56,9 +56,16 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat( format_filter_info = std::make_shared(); } -void ParquetV3BlockInputFormat::initializeIfNeeded() +void ParquetV3BlockInputFormat::prefetch() { - if (!reader) + if (need_only_count) + return; + readFileFooterIfNeeded(); +} + +void ParquetV3BlockInputFormat::readFileFooterIfNeeded() +{ + if (!reader && !reader_with_footer) { format_filter_info->initKeyConditionOnce(getPort().getHeader()); parser_shared_resources->initOnce([&] @@ -87,11 +94,24 @@ void ParquetV3BlockInputFormat::initializeIfNeeded() parser_shared_resources->opaque = ext; }); + auto new_reader = std::make_unique(); + new_reader->reader.prefetcher.init(in, read_options, parser_shared_resources); + new_reader->reader.file_metadata = getFileMetadata(new_reader->reader.prefetcher); + + std::lock_guard lock(reader_mutex); + reader_with_footer = std::move(new_reader); + } +} + +void ParquetV3BlockInputFormat::initializeIfNeeded() +{ + if (!reader) + { + readFileFooterIfNeeded(); + { std::lock_guard lock(reader_mutex); - reader.emplace(); - reader->reader.prefetcher.init(in, read_options, parser_shared_resources); - reader->reader.file_metadata = getFileMetadata(reader->reader.prefetcher); + reader = std::move(reader_with_footer); reader->reader.init(read_options, getPort().getHeader(), format_filter_info); reader->init(parser_shared_resources, buckets_to_read ? std::optional(buckets_to_read->row_group_ids) : std::nullopt); } @@ -169,6 +189,7 @@ void ParquetV3BlockInputFormat::resetReadBuffer() std::lock_guard lock(reader_mutex); if (reader) reader->shutdownTasks(); + reader_with_footer.reset(); } IInputFormat::resetReadBuffer(); } @@ -178,6 +199,7 @@ void ParquetV3BlockInputFormat::resetParser() { std::lock_guard lock(reader_mutex); reader.reset(); + reader_with_footer.reset(); } previous_block_missing_values.clear(); IInputFormat::resetParser(); diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h index a66ea4d97c2e..892771da231f 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h @@ -43,6 +43,8 @@ class ParquetV3BlockInputFormat : public IInputFormat private: Chunk read() override; + void prefetch() override; + void onCancel() noexcept override; const FormatSettings format_settings; @@ -52,17 +54,20 @@ class ParquetV3BlockInputFormat : public IInputFormat ParquetMetadataCachePtr metadata_cache; const std::optional object_with_metadata; - /// (This mutex is not important. It protects `reader.emplace` in a weird case where onCancel() + /// (This mutex is not important. It protects setting `reader` in a weird case where onCancel() /// may be called in parallel with first read(). ReadManager itself is thread safe for that, - /// but initializing vs checking the std::optional would race without this mutex.) + /// but initializing vs checking the pointer would race without this mutex.) std::mutex reader_mutex; - std::optional reader; + std::unique_ptr reader; + /// Has the file footer, but is not initialized: initializing it starts reading and decoding the column chunks. + std::unique_ptr reader_with_footer; bool reported_count = false; // if need_only_count BlockMissingValues previous_block_missing_values; size_t previous_approx_bytes_read_for_chunk = 0; + void readFileFooterIfNeeded(); void initializeIfNeeded(); std::shared_ptr buckets_to_read; diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp index a2c57cf0ed3a..48d880484d33 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include #include #include @@ -10,14 +12,24 @@ namespace DB RawBLOBRowOutputFormat::RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_) + SharedHeader header_, + const FormatSettings & format_settings_) : IRowOutputFormat(header_, out_) + , format_settings(format_settings_) { } -void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization &, size_t row_num) +void RawBLOBRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) { + /// `getDataAt` of `ColumnAggregateFunction` returns the bytes of the pointer to the state, not the state itself. + /// Write the serialized state, the same as its conversion to `String`. + if (typeid_cast(&column)) + { + serialization.serializeBinary(column, row_num, out, format_settings); + return; + } + if (!column.isNullAt(row_num)) { auto value = column.getDataAt(row_num); @@ -31,10 +43,10 @@ void registerOutputFormatRawBLOB(FormatFactory & factory) factory.registerOutputFormat("RawBLOB", []( WriteBuffer & buf, const Block & sample, - const FormatSettings &, + const FormatSettings & settings, FormatFilterInfoPtr /*format_filter_info*/) { - return std::make_shared(buf, std::make_shared(sample)); + return std::make_shared(buf, std::make_shared(sample), settings); }); } diff --git a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h index e2afa209faaa..9418d3c33028 100644 --- a/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h +++ b/src/Processors/Formats/Impl/RawBLOBRowOutputFormat.h @@ -1,5 +1,6 @@ #pragma once +#include #include @@ -28,12 +29,15 @@ class RawBLOBRowOutputFormat final : public IRowOutputFormat public: RawBLOBRowOutputFormat( WriteBuffer & out_, - SharedHeader header_); + SharedHeader header_, + const FormatSettings & format_settings_); String getName() const override { return "RawBLOBRowOutputFormat"; } private: - void writeField(const IColumn & column, const ISerialization &, size_t row_num) override; + void writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) override; + + const FormatSettings format_settings; }; } diff --git a/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp b/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp index c7ab86e4056c..328efe3b04ae 100644 --- a/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp +++ b/src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp @@ -863,6 +863,10 @@ QueryPlan::Node chooseJoinOrder(QueryGraphBuilder query_graph_builder, QueryPlan QueryGraph query_graph; query_graph.relation_stats = std::move(query_graph_builder.relation_stats); query_graph.edges = std::move(query_graph_builder.join_edges); + BitSet null_supplying_relations; + for (const auto & [relation, restriction] : query_graph_builder.join_kinds) + if (restriction.second != JoinKind::Inner) + null_supplying_relations.set(relation); query_graph.join_kinds = std::move(query_graph_builder.join_kinds); query_graph.pinned = std::move(query_graph_builder.pinned); @@ -1031,11 +1035,13 @@ QueryPlan::Node chooseJoinOrder(QueryGraphBuilder query_graph_builder, QueryPlan /// input pos -> new input node std::unordered_map current_step_type_changes; - for (auto rel_id : {left_rels.getSingleBit(), right_rels.getSingleBit()}) + /// NULL padding applies where the relation is joined alone; other type changes only after all predicates on original columns. + const bool is_last_step = entry_idx + 1 == sequence.size(); + for (const auto & [relation, new_inputs] : query_graph_builder.type_changes) { - if (!rel_id.has_value()) + const bool joined_alone = left_rels.getSingleBit() == relation || right_rels.getSingleBit() == relation; + if (!(null_supplying_relations.test(relation) ? joined_alone : is_last_step)) continue; - const auto & new_inputs = query_graph_builder.type_changes[rel_id.value()]; for (const auto * new_input : new_inputs) { const auto * input_node = trackInputColumn(new_input); diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp index 8fd5aba82710..005d5379243a 100644 --- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp +++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp @@ -49,7 +49,6 @@ #include #include #include -#include #include #include #include @@ -520,9 +519,7 @@ Pipe ReadFromMergeTree::readFromPoolParallelReplicas( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); pipes.emplace_back(std::move(source)); @@ -631,9 +628,7 @@ Pipe ReadFromMergeTree::readFromPool( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); auto source = std::make_shared(std::move(processor), data.getLogName()); @@ -750,9 +745,7 @@ Pipe ReadFromMergeTree::readInOrder( index_read_tasks, actions_settings, reader_settings, - index_build_context, - LazyMaterializingRowsPtr{}, - &storage_snapshot->metadata->getColumns()); + index_build_context); processor->addPartLevelToChunk(isQueryWithFinal()); diff --git a/src/Processors/Transforms/AddingDefaultsTransform.cpp b/src/Processors/Transforms/AddingDefaultsTransform.cpp index 9e0fe0f5c260..9650df7204bb 100644 --- a/src/Processors/Transforms/AddingDefaultsTransform.cpp +++ b/src/Processors/Transforms/AddingDefaultsTransform.cpp @@ -157,7 +157,8 @@ void AddingDefaultsTransform::transform(Chunk & chunk) return; const auto * block_missing_values = input_format.getMissingValues(); - if (!block_missing_values) + /// `BlockMissingValues::empty` is also true when the mask holds no columns at all, where the lookups below would be out of range. + if (!block_missing_values || block_missing_values->empty()) return; const auto & header = getOutputPort().getHeader(); diff --git a/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp new file mode 100644 index 000000000000..89e4391079a6 --- /dev/null +++ b/src/Processors/tests/gtest_ch_column_to_arrow_column_record_batch_split.cpp @@ -0,0 +1,127 @@ +#include "config.h" + +#if USE_ARROW || USE_PARQUET + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/// Arrow offsets its `Utf8`, `Binary` and `List` buffers with 32-bit integers, so a chunk holding more +/// than that becomes several record batches, each covering a row range. A range not starting at row 0 has +/// to rebase those offsets against the row before it. Reaching the real limit needs more than 2 GiB of +/// data, so these tests lower it. +/// +/// `CHColumnToArrowColumn` is the Apache Arrow library writer, used by the `Arrow` output format, +/// `ArrowFlight`, `StorageArrowFlight` and Delta Lake writes. + +namespace DB +{ + +namespace +{ + +constexpr size_t NUM_ROWS = 8; +constexpr size_t VALUE_SIZE = 16; + +std::string valueAt(size_t row) +{ + return std::string(VALUE_SIZE, static_cast('a' + row)); +} + +CHColumnToArrowColumn::Settings settingsWithLimit(UInt64 max_record_batch_bytes) +{ + CHColumnToArrowColumn::Settings settings; + settings.output_string_as_string = true; + settings.output_max_record_batch_bytes = max_record_batch_bytes; + return settings; +} + +std::shared_ptr convertToArrow(const DataTypePtr & type, MutableColumnPtr column, UInt64 max_record_batch_bytes) +{ + ColumnsWithTypeAndName header_columns{ColumnWithTypeAndName(type->createColumn(), type, "t")}; + + Columns columns; + columns.emplace_back(std::move(column)); + + std::vector chunks; + chunks.emplace_back(std::move(columns), NUM_ROWS); + + CHColumnToArrowColumn converter(header_columns, "Arrow", settingsWithLimit(max_record_batch_bytes)); + std::shared_ptr arrow_table; + converter.chChunkToArrowTable(arrow_table, chunks, 1); + return arrow_table; +} + +} + +TEST(CHColumnToArrowColumn, StringSplitAcrossRecordBatches) +{ + auto type = std::make_shared(); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(valueAt(row)); + + /// Two values per batch, so most batches start past row 0. + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & array = assert_cast(*chunked.chunk(chunk_i)); + /// Every batch addresses its own values from zero. + ASSERT_EQ(array.value_offset(0), 0); + for (int64_t i = 0; i < array.length(); ++i, ++row) + ASSERT_EQ(array.GetString(i), valueAt(row)); + } + ASSERT_EQ(row, NUM_ROWS); +} + +TEST(CHColumnToArrowColumn, ArraySplitAcrossRecordBatches) +{ + auto type = std::make_shared(std::make_shared()); + auto column = type->createColumn(); + for (size_t row = 0; row < NUM_ROWS; ++row) + column->insert(Array{Field(valueAt(row)), Field(valueAt(row))}); + + auto table = convertToArrow(type, std::move(column), 2 * VALUE_SIZE); + + const auto & chunked = *table->column(0); + ASSERT_GT(chunked.num_chunks(), 1); + ASSERT_EQ(chunked.length(), static_cast(NUM_ROWS)); + + size_t row = 0; + for (int chunk_i = 0; chunk_i < chunked.num_chunks(); ++chunk_i) + { + const auto & list = assert_cast(*chunked.chunk(chunk_i)); + ASSERT_EQ(list.value_offset(0), 0); + for (int64_t i = 0; i < list.length(); ++i, ++row) + { + /// `value_slice` returns a new array by value: keep it alive while it is inspected. + const auto values_holder = list.value_slice(i); + const auto & values = assert_cast(*values_holder); + ASSERT_EQ(values.length(), 2); + ASSERT_EQ(values.GetString(0), valueAt(row)); + ASSERT_EQ(values.GetString(1), valueAt(row)); + } + } + ASSERT_EQ(row, NUM_ROWS); +} + +} + +#endif diff --git a/src/Server/HTTP/ReadHeaders.cpp b/src/Server/HTTP/ReadHeaders.cpp index 142b47a8d6d2..4a5ef642b68b 100644 --- a/src/Server/HTTP/ReadHeaders.cpp +++ b/src/Server/HTTP/ReadHeaders.cpp @@ -87,7 +87,12 @@ void readHeaders( skipToNextLineOrEOF(in); Poco::trimRightInPlace(value); - headers.add(name, Poco::Net::MessageHeader::decodeWord(value)); + std::string decoded_value = Poco::Net::MessageHeader::decodeWord(value); + /// RFC 2047 decoding can produce bytes that are forbidden in a field value (RFC 9110, section 5.5), + /// e.g. `=0D=0A` would become a line break that splits the header when it is written out again. + if (decoded_value.find_first_of(std::string_view("\r\n\0", 3)) != std::string::npos) + throw Poco::Net::MessageException(fmt::format("Value of field \"{}\" contains CR, LF or NUL", name)); + headers.add(name, decoded_value); ++fields; } } diff --git a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp index f17e4f25ce44..d93ae95ec67b 100644 --- a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp +++ b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp @@ -59,6 +59,7 @@ namespace ErrorCodes extern const int WRONG_PASSWORD; extern const int REQUIRED_PASSWORD; extern const int AUTHENTICATION_FAILED; + extern const int REQUIRED_SECOND_FACTOR; extern const int SET_NON_GRANTED_ROLE; extern const int HTTP_LENGTH_REQUIRED; @@ -76,7 +77,8 @@ Poco::Net::HTTPResponse::HTTPStatus exceptionCodeToHTTPStatus(int exception_code return HTTPResponse::HTTP_UNAUTHORIZED; } if (exception_code == ErrorCodes::UNKNOWN_USER || exception_code == ErrorCodes::WRONG_PASSWORD - || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE) + || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE + || exception_code == ErrorCodes::REQUIRED_SECOND_FACTOR) { return HTTPResponse::HTTP_FORBIDDEN; } diff --git a/src/Server/PostgreSQLHandler.cpp b/src/Server/PostgreSQLHandler.cpp index c8e2fe902361..c49afe8df5cd 100644 --- a/src/Server/PostgreSQLHandler.cpp +++ b/src/Server/PostgreSQLHandler.cpp @@ -678,8 +678,8 @@ void PostgreSQLHandler::cancelRequest() inline std::unique_ptr PostgreSQLHandler::receiveStartupMessage(int payload_size) { /// The declared size is read from the wire before any authentication, and the message is read - /// into memory in full, so it has to be bounded. PostgreSQL uses the same limit. - static constexpr Int32 max_startup_message_size = 10000; + /// into memory in full, so it has to be bounded (`max_unauthenticated_message_size`). + static constexpr Int32 max_startup_message_size = PostgreSQLProtocol::Messaging::max_unauthenticated_message_size; std::unique_ptr message; try diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index 1d7b6d09bf16..92be0d801fac 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2525,8 +2525,10 @@ bool TCPHandler::processData(QueryState & state, bool scalar) if (scalar) { - /// Scalar value - state.query_context->addScalar(temporary_id.table_name, block); + /// Scalar value received from the client over the wire. It must not be trusted as a + /// server-computed scalar-subquery result (see Context::addClientScalar): otherwise a client + /// could name it with a row policy's scalar-subquery hash and forge the policy's result. + state.query_context->addClientScalar(temporary_id.table_name, block); } else if (!state.need_receive_data_for_insert && !state.need_receive_data_for_input) { diff --git a/src/Storages/AlterCommands.cpp b/src/Storages/AlterCommands.cpp index b1661cffc376..c026d44cb772 100644 --- a/src/Storages/AlterCommands.cpp +++ b/src/Storages/AlterCommands.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -1314,6 +1315,33 @@ bool AlterCommands::hasVectorSimilarityIndex(const StorageInMemoryMetadata & met return false; } +NameSet AlterCommands::getAddedIndexNames(const IndicesDescription & existing) const +{ + NameSet present; + for (const auto & index : existing) + present.insert(index.name); + + NameSet added; + for (const AlterCommand & command : *this) + { + if (command.ignore) + continue; + + if (command.type == AlterCommand::ADD_INDEX) + { + /// Otherwise `AlterCommand::apply` either skips it, with `IF NOT EXISTS`, or throws. + if (present.insert(command.index_name).second) + added.insert(command.index_name); + } + else if (command.type == AlterCommand::DROP_INDEX && !command.partition && !command.clear) + { + present.erase(command.index_name); + added.erase(command.index_name); + } + } + return added; +} + void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context) const { if (!prepared) @@ -1371,6 +1399,16 @@ void AlterCommands::apply(StorageInMemoryMetadata & metadata, ContextPtr context } } + /// Only the declared ones, and only now: the rebuild above resolves them against the schema every + /// command produced, which is what gets stored. Existing indices stay unauthorised on purpose. + const NameSet declared_indices = getAddedIndexNames(metadata.secondary_indices); + + for (const auto & index : metadata_copy.secondary_indices) + { + if (declared_indices.contains(index.name)) + checkTextIndexPreAndPostProcessorPermissions(index, context); + } + /// Changes in columns may lead to changes in projections ProjectionsDescription new_projections; for (const auto & projection : metadata_copy.projections) diff --git a/src/Storages/AlterCommands.h b/src/Storages/AlterCommands.h index 22a9253baa10..82501af8dd29 100644 --- a/src/Storages/AlterCommands.h +++ b/src/Storages/AlterCommands.h @@ -219,6 +219,9 @@ class AlterCommands : public std::vector /// Commands have to be prepared before apply. void apply(StorageInMemoryMetadata & metadata, ContextPtr context) const; + /// Indices the commands actually add: `ADD INDEX IF NOT EXISTS` of an existing name adds nothing. + NameSet getAddedIndexNames(const IndicesDescription & existing) const; + /// At least one command modify settings or comments. bool hasNonReplicatedAlterCommand() const; diff --git a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp index 7b54bd1a72fc..d2b3e89891d2 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertBatch.cpp @@ -21,6 +21,7 @@ #include #include +#include #include namespace CurrentMetrics @@ -217,6 +218,11 @@ bool DistributedAsyncInsertBatch::recoverBatch() } files.erase(files.begin(), first_existing_file); + /// The batch is sent with the `ClientInfo` of its first file. Older servers could put files of different + /// users (or originating hosts) into one batch, so a restored batch of mixed identities must not be resent + /// as a whole: it is dropped, and its files are batched again by identity like any other pending files. + std::optional> batch_identity; + /// A missing file inside the surviving suffix cannot be recovered safely. for (const auto & file : files) { @@ -228,13 +234,25 @@ bool DistributedAsyncInsertBatch::recoverBatch() try { - ReadBufferFromFile header_buffer(files.back()); + ReadBufferFromFile header_buffer(file); const DistributedAsyncInsertHeader & header = DistributedAsyncInsertHeader::read(header_buffer, parent.log); if (header.rows) { total_rows += header.rows; total_bytes += header.bytes; } + + auto identity = getRemoteAuthenticationIdentity(header.client_info); + if (!batch_identity) + { + batch_identity = std::move(identity); + } + else if (identity != *batch_identity) + { + LOG_WARNING(parent.log, "File {} has a different user or originating host than the first file of the batch, " + "the files of the batch will be sent in new batches", file); + return false; + } } catch (Exception & e) { diff --git a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp index 172028d48813..c94608ea330d 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp @@ -494,8 +494,11 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader bool operator==(const BatchHeader & other) const { + /// The whole batch is sent with the `ClientInfo` of its first file, so files that the shard would + /// authenticate differently must never be merged into one batch. return std::tie(settings, query, client_info.query_kind) == std::tie(other.settings, other.query, other.client_info.query_kind) && + getRemoteAuthenticationIdentity(client_info) == getRemoteAuthenticationIdentity(other.client_info) && blocksHaveEqualStructure(header, other.header); } @@ -505,6 +508,9 @@ struct DistributedAsyncInsertDirectoryQueue::BatchHeader { SipHash hash_state; hash_state.update(batch_header.query.data(), batch_header.query.size()); + const auto [initial_user, initial_host] = getRemoteAuthenticationIdentity(batch_header.client_info); + hash_state.update(initial_user.data(), initial_user.size()); + hash_state.update(initial_host.data(), initial_host.size()); batch_header.header.updateHash(hash_state); return hash_state.get64(); } diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp index e14d376583c7..ef6564f896e7 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.cpp @@ -68,6 +68,14 @@ void writeAndConvert(RemoteInserter & remote, const DistributedAsyncInsertHeader } } +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info) +{ + String initial_host; + if (client_info.initial_address) + initial_host = client_info.initial_address->host().toString(); + return {client_info.initial_user, initial_host}; +} + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h index 202d9ff6fff8..3cc335c169f9 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertHelpers.h +++ b/src/Storages/Distributed/DistributedAsyncInsertHelpers.h @@ -1,12 +1,16 @@ #pragma once #include +#include + +#include namespace DB { struct DistributedAsyncInsertHeader; +class ClientInfo; class ReadBufferFromFile; class RemoteInserter; @@ -23,6 +27,11 @@ class RemoteInserter; /// and mark batch as broken. bool isDistributedSendBroken(int code, bool remote_error); +/// The identity the shard authenticates a queued insert as (with the interserver ``): `initial_user` +/// and the host of `initial_address`, which is checked against the allowed hosts of that user. +/// A batch is sent with the `ClientInfo` of its first file, so all files of a batch must have the same identity. +std::pair getRemoteAuthenticationIdentity(const ClientInfo & client_info); + void writeRemoteConvert( const DistributedAsyncInsertHeader & distributed_header, RemoteInserter & remote, diff --git a/src/Storages/Distributed/DistributedSink.cpp b/src/Storages/Distributed/DistributedSink.cpp index dc3fa7f31036..b0d05d4d5ebb 100644 --- a/src/Storages/Distributed/DistributedSink.cpp +++ b/src/Storages/Distributed/DistributedSink.cpp @@ -864,17 +864,21 @@ void DistributedSink::writeToShard(const Cluster::ShardInfo & shard_info, const writeStringBinary(query_string, header_buf); context->getSettingsRef().write(header_buf); - if (OpenTelemetry::CurrentContext().isTraceEnabled()) { - // if the distributed tracing is enabled, use the trace context in current thread as parent of next span auto client_info = context->getClientInfo(); - client_info.client_trace_context = OpenTelemetry::CurrentContext(); + // if the distributed tracing is enabled, use the trace context in current thread as parent of next span + if (OpenTelemetry::CurrentContext().isTraceEnabled()) + client_info.client_trace_context = OpenTelemetry::CurrentContext(); + /// Background contexts (e.g. the ones of `Kafka` / `RabbitMQ` streaming into views) have + /// `query_kind = NO_QUERY`, for which `ClientInfo::write` stores nothing but the kind. The + /// replayed insert would then reach the shard with an empty `initial_user`, which a shard + /// accepting the interserver `` executes with full access, losing the identity + /// (e.g. the definer of a `SQL SECURITY DEFINER` view) that the query is bound to. + /// `RemoteInserter` sends the insert as a secondary query anyway, so persist it as such. + if (client_info.query_kind == ClientInfo::QueryKind::NO_QUERY) + client_info.query_kind = ClientInfo::QueryKind::SECONDARY_QUERY; client_info.write(header_buf, DBMS_TCP_PROTOCOL_VERSION); } - else - { - context->getClientInfo().write(header_buf, DBMS_TCP_PROTOCOL_VERSION); - } writeVarUInt(block.rows(), header_buf); writeVarUInt(block.bytes(), header_buf); diff --git a/src/Storages/Hive/HiveFile.cpp b/src/Storages/Hive/HiveFile.cpp index 18c9bf27a6f6..f2c467937ddb 100644 --- a/src/Storages/Hive/HiveFile.cpp +++ b/src/Storages/Hive/HiveFile.cpp @@ -8,12 +8,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -33,31 +33,16 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } -#define THROW_ARROW_NOT_OK(status) \ - do \ - { \ - if (const ::arrow::Status & _s = (status); !_s.ok()) \ - throw Exception::createDeprecated(_s.ToString(), ErrorCodes::BAD_ARGUMENTS); \ - } while (false) - - -template -Range createRangeFromOrcStatistics(const StatisticsType * stats) +template +Range createRangeFromOrcStatistics(const std::optional & minimum, const std::optional & maximum) { /// Null values or NaN/Inf values of double type. - if (stats->hasMinimum() && stats->hasMaximum()) - { - return Range(FieldType(stats->getMinimum()), true, FieldType(stats->getMaximum()), true); - } - if (stats->hasMinimum()) - { - return Range::createLeftBounded(FieldType(stats->getMinimum()), true); - } - if (stats->hasMaximum()) - { - return Range::createRightBounded(FieldType(stats->getMaximum()), true); - } - + if (minimum && maximum) + return Range(FieldType(*minimum), true, FieldType(*maximum), true); + if (minimum) + return Range::createLeftBounded(FieldType(*minimum), true); + if (maximum) + return Range::createRightBounded(FieldType(*maximum), true); return Range::createWholeUniverseWithoutNull(); } @@ -116,48 +101,40 @@ void IHiveFile::loadSplitMinMaxIndexes() split_minmax_idxes_loaded = true; } -Range HiveORCFile::buildRange(const orc::ColumnStatistics * col_stats) +Range HiveORCFile::buildRange(const ORC::Proto::ColumnStatistics * col_stats) { - if (!col_stats || col_stats->hasNull()) + /// A missing `has_null` means that the column may contain nulls. + if (!col_stats || col_stats->has_null.value_or(true)) return Range::createWholeUniverseWithoutNull(); - if (const auto * int_stats = dynamic_cast(col_stats)) + if (const auto & int_stats = col_stats->int_statistics) + return createRangeFromOrcStatistics(int_stats->minimum, int_stats->maximum); + if (const auto & double_stats = col_stats->double_statistics) + return createRangeFromOrcStatistics(double_stats->minimum, double_stats->maximum); + if (const auto & string_stats = col_stats->string_statistics) + return createRangeFromOrcStatistics(string_stats->minimum, string_stats->maximum); + if (const auto & bool_stats = col_stats->bucket_statistics) { - return createRangeFromOrcStatistics(int_stats); - } - if (const auto * double_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(double_stats); - } - if (const auto * string_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(string_stats); - } - if (const auto * bool_stats = dynamic_cast(col_stats)) - { - auto false_cnt = bool_stats->getFalseCount(); - auto true_cnt = bool_stats->getTrueCount(); + if (bool_stats->count.empty()) + return Range::createWholeUniverseWithoutNull(); + UInt64 true_cnt = bool_stats->count[0]; + UInt64 false_cnt = col_stats->number_of_values.value_or(0) - true_cnt; if (false_cnt && true_cnt) - { return Range(UInt8(0), true, UInt8(1), true); - } if (false_cnt) - { return Range::createLeftBounded(UInt8(0), true); - } if (true_cnt) - { return Range::createRightBounded(UInt8(1), true); - } - } - else if (const auto * timestamp_stats = dynamic_cast(col_stats)) - { - return createRangeFromOrcStatistics(timestamp_stats); + return Range::createWholeUniverseWithoutNull(); } - else if (const auto * date_stats = dynamic_cast(col_stats)) + if (const auto & timestamp_stats = col_stats->timestamp_statistics) { - return createRangeFromOrcStatistics(date_stats); + /// The deprecated `minimum` and `maximum` are in the local time zone of the writer, which is + /// unknown for the statistics of the whole file, so only the UTC bounds are usable. + return createRangeFromOrcStatistics(timestamp_stats->minimum_utc, timestamp_stats->maximum_utc); } + if (const auto & date_stats = col_stats->date_statistics) + return createRangeFromOrcStatistics(date_stats->minimum, date_stats->maximum); return Range::createWholeUniverseWithoutNull(); } @@ -166,14 +143,12 @@ void HiveORCFile::prepareReader() in = std::make_unique(namenode_url, path, getContext()->getGlobalContext()->getConfigRef(), getContext()->getReadSettings()); auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; - auto result = arrow::adapters::orc::ORCFileReader::Open(asArrowFile(*in, format_settings, is_stopped, "ORC", ORC_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(result.status()); - reader = std::move(result).ValueOrDie(); + reader = createORCReader(asORCInputStream(*in, format_settings, /*use_prefetch=*/false, is_stopped), ORC::ReaderOptions{}); } void HiveORCFile::prepareColumnMapping() { - const orc::Type & type = reader->GetRawORCReader()->getType(); + const ORC::Type & type = reader->getType(); size_t count = type.getSubtypeCount(); for (size_t pos = 0; pos < count; pos++) { @@ -190,7 +165,7 @@ bool HiveORCFile::useFileMinMaxIndex() const } -std::unique_ptr HiveORCFile::buildMinMaxIndex(const orc::Statistics * statistics) +std::unique_ptr HiveORCFile::buildMinMaxIndex(const std::vector * statistics) { if (!statistics) return nullptr; @@ -213,7 +188,7 @@ std::unique_ptr HiveORCFile::buildMinMaxIndex(c { size_t pos = it->second; /// Attention: column statistics start from 1. 0 has special purpose. - const orc::ColumnStatistics * col_stats = statistics->getColumnStatistics(static_cast(pos + 1)); + const ORC::Proto::ColumnStatistics * col_stats = pos + 1 < statistics->size() ? &(*statistics)[pos + 1] : nullptr; idx->hyperrectangle[i] = buildRange(col_stats); } ++i; @@ -230,8 +205,7 @@ void HiveORCFile::loadFileMinMaxIndexImpl() prepareColumnMapping(); } - auto statistics = reader->GetRawORCReader()->getStatistics(); - file_minmax_idx = buildMinMaxIndex(statistics.get()); + file_minmax_idx = buildMinMaxIndex(&reader->getStatistics()); } bool HiveORCFile::useSplitMinMaxIndex() const @@ -248,9 +222,10 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); auto stripe_num = raw_reader->getNumberOfStripes(); - auto stripe_stats_num = raw_reader->getNumberOfStripeStatistics(); + const auto & stripe_statistics = raw_reader->getMetadata().stripe_stats; + auto stripe_stats_num = stripe_statistics.size(); if (stripe_num != stripe_stats_num) throw Exception(ErrorCodes::BAD_ARGUMENTS, "orc file:{} has different strip num {} and strip statistics num {}", path, stripe_num, stripe_stats_num); @@ -258,8 +233,7 @@ void HiveORCFile::loadSplitMinMaxIndexesImpl() split_minmax_idxes.resize(stripe_num); for (size_t i = 0; i < stripe_num; ++i) { - auto stripe_stats = raw_reader->getStripeStatistics(i); - split_minmax_idxes[i] = buildMinMaxIndex(stripe_stats.get()); + split_minmax_idxes[i] = buildMinMaxIndex(&stripe_statistics[i].col_stats); } } @@ -271,7 +245,7 @@ std::optional HiveORCFile::getRowsImpl() prepareColumnMapping(); } - auto * raw_reader = reader->GetRawORCReader(); + auto * raw_reader = reader.get(); return raw_reader->getNumberOfRows(); } @@ -286,7 +260,8 @@ void HiveParquetFile::prepareReader() auto format_settings = getFormatSettings(getContext()); std::atomic is_stopped{0}; auto open_file_res = parquet::arrow::OpenFile(asArrowFile(*in, format_settings, is_stopped, "Parquet", PARQUET_MAGIC_BYTES), ArrowMemoryPool::instance()); - THROW_ARROW_NOT_OK(open_file_res.status()); + if (!open_file_res.ok()) + throw Exception::createDeprecated(open_file_res.status().ToString(), ErrorCodes::BAD_ARGUMENTS); reader = *std::move(open_file_res); } diff --git a/src/Storages/Hive/HiveFile.h b/src/Storages/Hive/HiveFile.h index 611302693b1d..50d9e0cbc6c2 100644 --- a/src/Storages/Hive/HiveFile.h +++ b/src/Storages/Hive/HiveFile.h @@ -5,9 +5,10 @@ #include #include +#include #include -#include +#include #include #include @@ -217,18 +218,18 @@ class HiveORCFile : public IHiveFile bool useSplitMinMaxIndex() const override; private: - static Range buildRange(const orc::ColumnStatistics * col_stats); + static Range buildRange(const ORC::Proto::ColumnStatistics * col_stats); void loadFileMinMaxIndexImpl() override; void loadSplitMinMaxIndexesImpl() override; - std::unique_ptr buildMinMaxIndex(const orc::Statistics * statistics); + std::unique_ptr buildMinMaxIndex(const std::vector * statistics); void prepareReader(); void prepareColumnMapping(); std::optional getRowsImpl() override; std::unique_ptr in; - std::unique_ptr reader; + std::unique_ptr reader; std::map orc_column_positions; }; diff --git a/src/Storages/Hive/StorageHive.cpp b/src/Storages/Hive/StorageHive.cpp index fccccb7c7fca..15e23429c5ad 100644 --- a/src/Storages/Hive/StorageHive.cpp +++ b/src/Storages/Hive/StorageHive.cpp @@ -608,6 +608,10 @@ HiveFiles StorageHive::collectHiveFilesFromPartition( throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, "Partition value size not match, expect {}, but got {}", partition_names.size(), partition.values.size()); + if (!partition_key_expr) + throw Exception(ErrorCodes::INVALID_PARTITION_VALUE, + "Hive metastore returned a partition for table {}.{}, but the table has no partition key", hive_database, hive_table); + /// Join partition values in CSV format WriteBufferFromOwnString wb; for (size_t i = 0; i < partition.values.size(); ++i) diff --git a/src/Storages/IStorage.h b/src/Storages/IStorage.h index 8c58fa27b6a5..e10d484de8b3 100644 --- a/src/Storages/IStorage.h +++ b/src/Storages/IStorage.h @@ -167,6 +167,9 @@ class IStorage : public std::enable_shared_from_this, public TypePromo virtual bool supportsSubcolumns() const { return false; } /// Returns true if storage supports optimizations of functions by reading subcolumns. virtual bool supportsOptimizationToSubcolumns() const { return supportsSubcolumns(); } + /// Returns true if the storage writes `Map` columns with the bucketed serialization, where a single key + /// can be read without reading the whole column. Gates the `m['key']` -> `m.key_` rewrite. + virtual bool hasBucketedMapSerialization() const { return false; } /// Returns true if the storage supports transactions for SELECT, INSERT and ALTER queries. /// Storage may throw an exception later if some query kind is not fully supported. diff --git a/src/Storages/IndicesDescription.cpp b/src/Storages/IndicesDescription.cpp index 9d716df4428b..6bdb804cd4c6 100644 --- a/src/Storages/IndicesDescription.cpp +++ b/src/Storages/IndicesDescription.cpp @@ -1,12 +1,20 @@ #include #include +#include #include +#include #include +#include +#include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -25,6 +33,122 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; } +namespace +{ + +/// Calls `fn` with the value of each `preprocessor` / `postprocessor` argument of a text index. +template +void forEachTransformArgument(const ASTPtr & arguments, F && fn) +{ + for (const auto & child : arguments->children) + { + auto * func = child->as(); + if (!func || func->name != "equals" || !func->arguments || func->arguments->children.size() != 2) + continue; + + const auto * key = func->arguments->children[0]->as(); + if (key && (key->name() == "preprocessor" || key->name() == "postprocessor")) + fn(func->arguments->children[1]); + } +} + +/// Resolving a name runs the function's `create`, where `checkAccess` lives. Names only: building the +/// expression would report its type errors from here, not from the validator. +/// +/// A transform is analysed under the global context, so reading a table or a dictionary during analysis +/// would happen with full access. Such access depends on the arguments, not the function name, so +/// authorizing names cannot cover it, and these constructs are refused. Only here, where a user declares +/// the index: metadata stored by an older version must still load and stay alterable. +void checkFunctionsAsUser(const ASTPtr & ast, const ContextPtr & context) +{ + if (ast->as() || ast->as() || ast->as() || ast->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, "A text index transform expression must not contain subqueries or table references"); + + if (const auto * function = ast->as()) + { + if (functionIsInOrGlobalInOperator(function->name) && function->arguments && function->arguments->children.size() == 2) + { + const auto & set = function->arguments->children[1]; + if (set->as() || set->as()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not use a table or a set as the right side of `{}`", function->name); + } + + /// Only the name, which for `dictGet` and the like does not touch the dictionary; analysis would. + if (auto resolver = FunctionFactory::instance().tryGet(function->name, context); resolver && !resolver->isDeterministic()) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "A text index transform expression must not contain non-deterministic functions. Got `{}`", function->name); + } + + for (const auto & child : ast->children) + checkFunctionsAsUser(child, context); +} + +void checkTransformPermissions(const ASTPtr & arguments, const ContextPtr & context) +{ + forEachTransformArgument(arguments, [&](ASTPtr & argument) + { + auto expression = argument->clone(); + /// Inlines SQL UDF bodies, as `TreeRewriter` does, so a function used only inside one is seen. + if (!UserDefinedSQLFunctionFactory::instance().empty()) + UserDefinedSQLFunctionVisitor::visit(expression, context); + + checkFunctionsAsUser(expression, context); + }); +} + +} + +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context) +{ + if (index.type == TEXT_INDEX_NAME && index.arguments) + checkTransformPermissions(index.arguments, context); +} + +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index) +{ + if (index.type != TEXT_INDEX_NAME || !index.arguments) + return false; + + bool found = false; + forEachTransformArgument(index.arguments, [&](ASTPtr &) { found = true; }); + return found; +} + +[[noreturn]] static void throwTransformNeedsInitiatorUser() +{ + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "A text index preprocessor or postprocessor is authorized on the host the query is submitted to, and the " + "other hosts resolve it against their own schema without that user. Let every host run the query as the " + "initiating user instead: enable the server setting distributed_ddl_use_initial_user_and_roles on every " + "host, and set distributed_ddl_entry_format_version to at least {}", + DDLLogEntry::INITIATOR_USER_VERSION); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration) +{ + if (hasTextIndexPreOrPostProcessor(declaration)) + throwTransformNeedsInitiatorUser(); +} + +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index) +{ + if (hasTextIndexPreOrPostProcessor(index)) + throwTransformNeedsInitiatorUser(); +} + +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration) +{ + const auto * type = declaration.getType() ? declaration.getType()->as() : nullptr; + if (!type || Poco::toLower(type->name) != TEXT_INDEX_NAME || !type->arguments) + return false; + + bool found = false; + forEachTransformArgument(type->arguments, [&](ASTPtr &) { found = true; }); + return found; +} + IndexDescription::IndexDescription(const IndexDescription & other) : definition_ast(other.definition_ast ? other.definition_ast->clone() : nullptr) , expression_list_ast(other.expression_list_ast ? other.expression_list_ast->clone() : nullptr) diff --git a/src/Storages/IndicesDescription.h b/src/Storages/IndicesDescription.h index 207e3c76b154..5d1daf8affaa 100644 --- a/src/Storages/IndicesDescription.h +++ b/src/Storages/IndicesDescription.h @@ -16,6 +16,7 @@ namespace DB class ExpressionActions; using ExpressionActionsPtr = std::shared_ptr; +class ASTIndexDeclaration; /// Description of non-primary index for Storage struct IndexDescription @@ -86,6 +87,20 @@ struct IndexDescription bool isSimpleSingleColumnIndex() const; }; +/// Checks that the functions referenced by the text index preprocessor and postprocessor expressions +/// may run with the permissions of `context`, and that they read no table, set or dictionary. Call only +/// where a user declares an index, on the node they submitted it to; elsewhere these resolve under the +/// global context, and stored metadata is not re-checked. +void checkTextIndexPreAndPostProcessorPermissions(const IndexDescription & index, const ContextPtr & context); + +/// Refuses a transform when the other hosts of an `ON CLUSTER` query do not run it as the initiator. +void rejectTextIndexTransformWithoutInitiatorUser(const ASTIndexDeclaration & declaration); +void rejectTextIndexTransformWithoutInitiatorUser(const IndexDescription & index); + +/// Whether the declaration is a text index with a `preprocessor` or a `postprocessor` argument. +bool hasTextIndexPreOrPostProcessor(const ASTIndexDeclaration & declaration); +bool hasTextIndexPreOrPostProcessor(const IndexDescription & index); + /// All secondary indices in storage struct IndicesDescription : public std::vector, IHints<> { diff --git a/src/Storages/MergeTree/KeyCondition.cpp b/src/Storages/MergeTree/KeyCondition.cpp index 2d6ff22b1111..1fb619b3cdc4 100644 --- a/src/Storages/MergeTree/KeyCondition.cpp +++ b/src/Storages/MergeTree/KeyCondition.cpp @@ -3775,6 +3775,11 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( DataTypePtr current_type, bool single_point) { + /// A bound where `isNull()` holds stands in for NULL or for an infinity, and is left untransformed below, + /// so no transformed value would remain to compare against an atom in the function's result domain. + if (single_point && (key_range.left.isNull() || key_range.right.isNull())) + return {}; + for (const auto & func : functions) { /// We check the monotonicity of each function on a specific range. @@ -3791,17 +3796,21 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( /// If we apply function to open interval, we can get empty intervals in result. /// E.g. for ('2020-01-03', '2020-01-20') after applying 'toYYYYMM' we will get ('202001', '202001'). /// To avoid this we make range left and right included. - /// Any function that treats NULL specially is not monotonic. - /// Thus we can safely use isNull() as an -Inf/+Inf indicator here. + /// A NULL bound is an -inf/+inf stand-in and is left as is. A function that returns NULL for a non-NULL + /// argument leaves a bound with no position in the `Range` order, so the range cannot be analyzed. if (!key_range.left.isNull()) { key_range.left = applyFunction(func, current_type, key_range.left); + if (key_range.left.isNull()) + return {}; key_range.left_included = true; } if (!key_range.right.isNull()) { key_range.right = applyFunction(func, current_type, key_range.right); + if (key_range.right.isNull()) + return {}; key_range.right_included = true; } diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp index 5b0543026617..b0cf4a2bb646 100644 --- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp +++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp @@ -540,8 +540,7 @@ MergeTreeReadTaskColumns getReadTaskColumns( index_read_tasks, actions_settings, reader_settings.enable_multiple_prewhere_read_steps, - reader_settings.force_short_circuit_execution, - &storage_snapshot->metadata->getColumns()); + reader_settings.force_short_circuit_execution); for (const auto & step : prewhere_actions.steps) add_step(*step); diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index fd61defc239a..7c8f71bd5502 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -293,6 +293,7 @@ namespace MergeTreeSetting extern const MergeTreeSettingsMergeTreeStringSerializationVersion string_serialization_version; extern const MergeTreeSettingsMergeTreeNullableSerializationVersion nullable_serialization_version; extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version; + extern const MergeTreeSettingsMergeTreeMapSerializationVersion map_serialization_version_for_zero_level_parts; extern const MergeTreeSettingsUInt32 min_level_for_wide_part; extern const MergeTreeSettingsBool propagate_types_serialization_versions_to_nested_types; } @@ -894,6 +895,14 @@ bool MergeTreeData::supportsFinal() const || merging_params.mode == MergingParams::VersionedCollapsing; } +bool MergeTreeData::hasBucketedMapSerialization() const +{ + /// Inserted parts use the zero-level setting, merged parts the other one. + auto settings = getSettings(); + return (*settings)[MergeTreeSetting::map_serialization_version] == MergeTreeMapSerializationVersion::WITH_BUCKETS + || (*settings)[MergeTreeSetting::map_serialization_version_for_zero_level_parts] == MergeTreeMapSerializationVersion::WITH_BUCKETS; +} + static void checkKeyExpression(const ExpressionActions & expr, const Block & sample_block, const String & key_name, bool allow_nullable_key) { if (expr.hasArrayJoin()) @@ -10134,7 +10143,7 @@ QueryPipeline MergeTreeData::updateLightweightImpl(const MutationCommands & comm if (it != commands.end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Got unexpected command with type {} in lightweight update", it->type); - LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.toString(false)); + LOG_DEBUG(log, "Executing lightweight update with commands: {}", commands.ast(false)->formatForLogging()); MutationCommands commands_to_run; const auto & system_columns = getPatchPartSystemColumns(); @@ -10665,6 +10674,16 @@ StorageSnapshotPtr MergeTreeData::getStorageSnapshot(const StorageMetadataPtr & return cache->emplace(this, createStorageSnapshot(metadata_snapshot, query_context, false)).first->second; } +void MergeTreeData::discardSharedStorageSnapshot(const ContextPtr & query_context) const +{ + auto query_metadata_cache = query_context->getQueryMetadataCache(); + if (!query_metadata_cache) + return; + + auto [cache, lock] = query_metadata_cache->getStorageSnapshotCache(); + cache->erase(this); +} + StorageSnapshotPtr MergeTreeData::getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const { diff --git a/src/Storages/MergeTree/MergeTreeData.h b/src/Storages/MergeTree/MergeTreeData.h index 24c347de459d..c19156cfd60f 100644 --- a/src/Storages/MergeTree/MergeTreeData.h +++ b/src/Storages/MergeTree/MergeTreeData.h @@ -548,6 +548,8 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; + bool supportsTTL() const override { return true; } bool supportsColumnsWithDynamicStructure() const override { return true; } @@ -648,6 +650,11 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr /// The same as above but does not hold vector of data parts. StorageSnapshotPtr getStorageSnapshotWithoutData(const StorageMetadataPtr & metadata_snapshot, ContextPtr query_context) const override; + /// Removes the snapshot of this table from the query-scoped snapshot cache of + /// `enable_shared_storage_snapshot_in_query`, so that the next `getStorageSnapshot` in the query + /// takes a fresh one. Holders of the removed snapshot keep it. + void discardSharedStorageSnapshot(const ContextPtr & query_context) const; + /// Load the set of data parts from disk. Call once - immediately after the object is created. void loadDataParts(bool skip_sanity_checks, std::optional> expected_parts); diff --git a/src/Storages/MergeTree/MergeTreeDataWriter.cpp b/src/Storages/MergeTree/MergeTreeDataWriter.cpp index 0eda0376f9db..94aa1b21eb17 100644 --- a/src/Storages/MergeTree/MergeTreeDataWriter.cpp +++ b/src/Storages/MergeTree/MergeTreeDataWriter.cpp @@ -514,6 +514,11 @@ Block MergeTreeDataWriter::mergeBlock( span.addAttribute("clickhouse.rows", block_size); span.addAttribute("clickhouse.columns", header->columns()); + /// The block can lose all its rows before this point, e.g. when insert deduplication removes + /// duplicate rows of a materialized view block. Merging algorithms do not expect an empty input. + if (block_size == 0) + return *header; + auto get_merging_algorithm = [&]() -> std::shared_ptr { switch (merging_params.mode) diff --git a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp index 8d0538e64453..1964c89f521f 100644 --- a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace DB @@ -28,6 +29,7 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int CORRUPTED_DATA; extern const int ILLEGAL_COLUMN; extern const int INCORRECT_QUERY; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; @@ -87,9 +89,22 @@ void MergeTreeIndexGranuleBloomFilter::deserializeBinary(ReadBuffer & istr, Merg throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown index version {}.", version); readVarUInt(total_rows, istr); + if (total_rows == 0) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Bloom filter index granule has zero rows"); - static size_t atom_size = 8; - size_t bytes_size = (bits_per_row * total_rows + atom_size - 1) / atom_size; + static constexpr size_t atom_size = 8; + size_t bits_size = 0; + if (common::mulOverflow(bits_per_row, total_rows, bits_size) + || common::addOverflow(bits_size, atom_size - 1, bits_size)) + { + throw Exception( + ErrorCodes::CORRUPTED_DATA, + "Bloom filter index granule size overflows for {} rows and {} bits per row", + total_rows, + bits_per_row); + } + + size_t bytes_size = bits_size / atom_size; size_t read_size = bytes_size; for (auto & filter : bloom_filters) { diff --git a/src/Storages/MergeTree/MergeTreeIndexSet.cpp b/src/Storages/MergeTree/MergeTreeIndexSet.cpp index 91ea8793399b..61443eea6299 100644 --- a/src/Storages/MergeTree/MergeTreeIndexSet.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexSet.cpp @@ -572,6 +572,21 @@ const ActionsDAG::Node & MergeTreeIndexConditionSet::traverseDAG(const ActionsDA { auto bit_wrapper_function = FunctionFactory::instance().get("__bitWrapperFunc", context); result_node = &result_dag.addFunction(bit_wrapper_function, {atom_node_ptr}, {}); + + /// A NULL atom value yields a NULL from `__bitWrapperFunc` rather than a BoolMask. + /// That NULL propagates through `__bitBoolMaskAnd`/`Or` and wrongly prunes a granule + /// the atom does not exclude. Map a NULL mask to `UNKNOWN_FIELD` (can be true or false). + if (isNullableOrLowCardinalityNullable(result_node->result_type)) + { + ColumnWithTypeAndName unknown_field_column_with_type; + unknown_field_column_with_type.name = calculateConstantActionNodeName(UNKNOWN_FIELD); + unknown_field_column_with_type.type = std::make_shared(); + unknown_field_column_with_type.column = unknown_field_column_with_type.type->createColumnConst(1, UNKNOWN_FIELD); + const auto & unknown_node = result_dag.addColumn(unknown_field_column_with_type); + + auto if_null_function = FunctionFactory::instance().get("ifNull", context); + result_node = &result_dag.addFunction(if_null_function, {result_node, &unknown_node}, {}); + } } else { diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp index db7da52fdaf7..a4e9b9a702a5 100644 --- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp +++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp @@ -1596,6 +1596,14 @@ void MergeTreeRangeReader::executePrewhereActionsAndFilterColumns(ReadResult & r /// Columns might be projected out. We need to store them here so that default columns can be evaluated later. Block additional_columns = block; + /// Carry over columns projected out at earlier steps: they may be needed + /// to evaluate defaults of columns missing in the part. + for (const auto & col : result.additional_columns) + { + if (!additional_columns.has(col.name)) + additional_columns.insert(col); + } + if (prewhere_info->actions) { const String dummy_column = addDummyColumnWithRowCount(block, result.num_rows); diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp index 147e7778daad..f20a455b4f2b 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp @@ -132,8 +132,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_, - LazyMaterializingRowsPtr lazy_materializing_rows_, - const ColumnsDescription * columns_) + LazyMaterializingRowsPtr lazy_materializing_rows_) : pool(std::move(pool_)) , algorithm(std::move(algorithm_)) , row_level_filter(row_level_filter_) @@ -145,8 +144,7 @@ MergeTreeSelectProcessor::MergeTreeSelectProcessor( index_read_tasks_, actions_settings, reader_settings_.enable_multiple_prewhere_read_steps, - reader_settings_.force_short_circuit_execution, - columns_)) + reader_settings_.force_short_circuit_execution)) , reader_settings(reader_settings_) , result_header(transformHeader(pool->getHeader(), row_level_filter, prewhere_info)) , merge_tree_index_build_context(std::move(merge_tree_index_build_context_)) @@ -174,8 +172,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { PrewhereExprInfo prewhere_actions; @@ -208,7 +205,7 @@ PrewhereExprInfo MergeTreeSelectProcessor::getPrewhereActions( } if (prewhere_info && - (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution, columns))) + (!enable_multiple_prewhere_read_steps || !tryBuildPrewhereSteps(prewhere_info, actions_settings, prewhere_actions, force_short_circuit_execution))) { PrewhereExprStep prewhere_step { diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.h b/src/Storages/MergeTree/MergeTreeSelectProcessor.h index b044ff67fc1f..5909f164ed45 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.h +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.h @@ -108,8 +108,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const ExpressionActionsSettings & actions_settings_, const MergeTreeReaderSettings & reader_settings_, MergeTreeIndexBuildContextPtr merge_tree_index_build_context_ = {}, - LazyMaterializingRowsPtr lazy_materializing_rows_ = {}, - const ColumnsDescription * columns_ = nullptr); + LazyMaterializingRowsPtr lazy_materializing_rows_ = {}); String getName() const; @@ -138,8 +137,7 @@ class MergeTreeSelectProcessor : private boost::noncopyable const IndexReadTasks & index_read_tasks, const ExpressionActionsSettings & actions_settings, bool enable_multiple_prewhere_read_steps, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); void addPartLevelToChunk(bool add_part_level_) { add_part_level = add_part_level_; } diff --git a/src/Storages/MergeTree/MergeTreeSettings.cpp b/src/Storages/MergeTree/MergeTreeSettings.cpp index d6317adfe555..edb023a8c897 100644 --- a/src/Storages/MergeTree/MergeTreeSettings.cpp +++ b/src/Storages/MergeTree/MergeTreeSettings.cpp @@ -1171,7 +1171,7 @@ namespace ErrorCodes in the Keeper, the cache will update as soon as possible, so that we are able to filter the duplicated inserts in the memory. )", 0) \ - DECLARE(UInt64, max_replicated_logs_to_keep, 1000, R"( + DECLARE(NonZeroUInt64, max_replicated_logs_to_keep, 1000, R"( How many records may be in the ClickHouse Keeper log if there is inactive replica. An inactive replica becomes lost when when this number exceed. diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp index 52c20d4ee7d8..abf6b4c90f7e 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp @@ -1,8 +1,5 @@ #include -#include -#include - namespace DB { @@ -22,29 +19,10 @@ namespace struct NodeInfo { NameSet required_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column are placed into one step. - NameSet required_storage_columns; }; -/// Resolves a column name to its storage (physical) name. -/// For subcolumns like `map.key_k0`, returns `map`. -/// For regular columns, returns the name unchanged. -String resolveStorageColumnName(const String & column_name, const ColumnsDescription * columns) -{ - if (columns) - { - if (auto col = columns->tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, column_name)) - return col->getNameInStorage(); - } - return column_name; -} - /// Fills the list of required columns for a node in the DAG. -void fillRequiredColumns( - const ActionsDAG::Node * node, - std::unordered_map & nodes_info, - const ColumnsDescription * columns) +void fillRequiredColumns(const ActionsDAG::Node * node, std::unordered_map & nodes_info) { if (nodes_info.contains(node)) return; @@ -54,16 +32,14 @@ void fillRequiredColumns( if (node->type == ActionsDAG::ActionType::INPUT) { node_info.required_columns.insert(node->result_name); - node_info.required_storage_columns.insert(resolveStorageColumnName(node->result_name, columns)); return; } for (const auto & child : node->children) { - fillRequiredColumns(child, nodes_info, columns); + fillRequiredColumns(child, nodes_info); const auto & child_info = nodes_info[child]; node_info.required_columns.insert(child_info.required_columns.begin(), child_info.required_columns.end()); - node_info.required_storage_columns.insert(child_info.required_storage_columns.begin(), child_info.required_storage_columns.end()); } } @@ -226,8 +202,7 @@ bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns) + bool force_short_circuit_execution) { if (!prewhere_info) return true; @@ -243,37 +218,21 @@ bool tryBuildPrewhereSteps( std::unordered_map nodes_info; for (const auto & node : condition_nodes) { - fillRequiredColumns(node, nodes_info, columns); + fillRequiredColumns(node, nodes_info); } /// 3. Sort condition nodes by the number of columns used in them and the overall size of those columns /// TODO: not sorting for now because the conditions are already sorted by Where Optimizer - /// 4. Group adjacent conditions that read from the same set of physical storage columns into a single step. - /// Conditions on subcolumns of the same column (e.g. `map.key_k0` and `map.key_k1`) are placed into one group - /// when they appear next to each other in the condition list. - /// - /// Only adjacent conditions are merged to preserve the user's explicit PREWHERE evaluation order. - /// Non-adjacent conditions on the same storage column are kept in separate steps even though this - /// may cause redundant reads, because the user may have intentionally interleaved a guard predicate - /// (e.g. `PREWHERE tags['safe'] != '' AND value > 0 AND toUInt64(tags['unsafe']) > 0` — the - /// `value > 0` step must filter rows before evaluating the potentially-throwing conversion). - /// - /// For the WHERE-to-PREWHERE path this is not a problem: `MergeTreeWhereOptimizer` already groups - /// conditions by their physical storage columns, so subcolumns of the same column arrive here adjacent. + /// 4. Group conditions with the same set of columns into a single read/compute step std::vector> condition_groups; for (const auto & node : condition_nodes) { const auto & node_info = nodes_info[node]; - if (!condition_groups.empty() - && nodes_info[condition_groups.back().front()].required_storage_columns == node_info.required_storage_columns) - { - condition_groups.back().push_back(node); - } + if (!condition_groups.empty() && nodes_info[condition_groups.back().back()].required_columns == node_info.required_columns) + condition_groups.back().push_back(node); /// Add to the last group else - { - condition_groups.push_back({node}); - } + condition_groups.push_back({node}); /// Start new group } /// 5. Build DAGs for each step diff --git a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h index 4d3845a7e048..833e6f506992 100644 --- a/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h +++ b/src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.h @@ -13,13 +13,10 @@ namespace DB { -class ColumnsDescription; - bool tryBuildPrewhereSteps( PrewhereInfoPtr prewhere_info, const ExpressionActionsSettings & actions_settings, PrewhereExprInfo & prewhere, - bool force_short_circuit_execution, - const ColumnsDescription * columns = nullptr); + bool force_short_circuit_execution); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index dbfc28547453..39df2ecbc8ef 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -338,17 +338,6 @@ void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const RPNBuilderTree cond.columns_size = getColumnsSize(cond.table_columns); - /// Resolve each column to its physical storage name so that subcolumns - /// of the same column (e.g. `map.key_k0`, `map.key_k1`) share one group. - const auto & storage_columns_description = storage_metadata->getColumns(); - for (const auto & col : cond.table_columns) - { - if (auto resolved = storage_columns_description.tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, col)) - cond.table_storage_columns.insert(resolved->getNameInStorage()); - else - cond.table_storage_columns.insert(col); - } - cond.viable = !has_invalid_column /// Condition depend on some column. Constant expressions are not moved. @@ -495,20 +484,17 @@ std::optional MergeTreeWhereOptimizer:: } }; - /// Move condition and all other conditions that depend on the same set of physical storage columns. - /// Grouping by storage columns (rather than the exact column set) keeps subcolumns of the - /// same column (e.g. `map.key_k0` and `map.key_k1`) in one group, so they are moved to - /// PREWHERE together and arrive adjacent for the prewhere-splitting step. + /// Move condition and all other conditions depend on the same set of columns. auto move_condition = [&](Conditions::iterator cond_it) { move_to_prewhere_conditions(cond_it); total_size_of_moved_conditions += cond_it->columns_size; total_number_of_moved_columns += cond_it->table_columns.size(); - /// Move all other viable conditions that depend on the same set of storage columns. + /// Move all other viable conditions that depend on the same set of columns. for (auto jt = where_conditions.begin(); jt != where_conditions.end();) { - if (jt->viable && jt->table_storage_columns == cond_it->table_storage_columns) + if (jt->viable && jt->columns_size == cond_it->columns_size && jt->table_columns == cond_it->table_columns) { move_to_prewhere_conditions(jt++); } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h index bf2b97b3640d..b0a8bfdb2173 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.h +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.h @@ -69,10 +69,6 @@ class MergeTreeWhereOptimizer : private boost::noncopyable UInt64 columns_size = 0; NameSet table_columns; - /// Column names resolved to their physical storage names (subcolumn suffix stripped). - /// Used for grouping: conditions on subcolumns of the same storage column - /// (e.g. `map.key_k0` and `map.key_k1`) are grouped and moved to PREWHERE together. - NameSet table_storage_columns; /// Can condition be moved to prewhere? bool viable = false; diff --git a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp index 3f8edc6d4cc1..c94d1390bf19 100644 --- a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp +++ b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp @@ -144,7 +144,7 @@ ReplicatedMergeMutateTaskBase::PrepareResult MutateFromLogEntryTask::prepare() Strings mutation_ids; commands = std::make_shared(storage.queue.getMutationCommands(source_part, new_part_info.mutation, mutation_ids)); LOG_TRACE(log, "Mutating part {} with mutation commands from {} mutations ({}): {}", - entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->toString(true)); + entry.new_part_name, commands->size(), fmt::join(mutation_ids, ", "), commands->ast(true)->formatForLogging()); /// mutation_ids can be empty here. mutation_ids_for_log = mutation_ids; diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index 3735c427cffc..a2490c3ec29e 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -12,7 +12,7 @@ namespace MergeTreeSetting { extern const MergeTreeSettingsUInt64 finished_mutations_to_keep; extern const MergeTreeSettingsSeconds lock_acquire_timeout_for_background_operations; - extern const MergeTreeSettingsUInt64 max_replicated_logs_to_keep; + extern const MergeTreeSettingsNonZeroUInt64 max_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 min_replicated_logs_to_keep; extern const MergeTreeSettingsUInt64 replicated_deduplication_window; extern const MergeTreeSettingsUInt64 replicated_deduplication_window_for_async_inserts; diff --git a/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp new file mode 100644 index 000000000000..007d155521ef --- /dev/null +++ b/src/Storages/MergeTree/tests/gtest_merge_tree_index_bloom_filter.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include +#include + +#include + +using namespace DB; + +namespace DB::ErrorCodes +{ + extern const int CORRUPTED_DATA; +} + +namespace +{ + +String encodeRowCount(size_t row_count) +{ + WriteBufferFromOwnString out; + writeVarUInt(row_count, out); + return out.str(); +} + +void expectCorruptedRowCount(size_t bits_per_row, size_t row_count) +{ + MergeTreeIndexGranuleBloomFilter granule(bits_per_row, 3, 1); + String encoded = encodeRowCount(row_count); + ReadBufferFromString in(encoded); + + try + { + granule.deserializeBinary(in, 1); + FAIL() << "Expected a corrupted Bloom-filter granule to be rejected"; + } + catch (const Exception & exception) + { + EXPECT_EQ(exception.code(), ErrorCodes::CORRUPTED_DATA); + } +} + +} + +TEST(MergeTreeIndexBloomFilterTest, DeserializesValidGranule) +{ + String encoded = encodeRowCount(1); + encoded.append(sizeof(BloomFilter::UnderType), '\0'); + + MergeTreeIndexGranuleBloomFilter granule(12, 3, 1); + ReadBufferFromString in(encoded); + + EXPECT_NO_THROW(granule.deserializeBinary(in, 1)); + EXPECT_FALSE(granule.empty()); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsZeroRowGranule) +{ + expectCorruptedRowCount(12, 0); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsFilterSizeOverflow) +{ + constexpr size_t bits_per_row = 12; + constexpr size_t overflowing_rows = std::numeric_limits::max() / bits_per_row + 1; + expectCorruptedRowCount(bits_per_row, overflowing_rows); +} + +TEST(MergeTreeIndexBloomFilterTest, RejectsRoundedFilterSizeOverflow) +{ + expectCorruptedRowCount(1, std::numeric_limits::max()); +} diff --git a/src/Storages/ObjectStorage/Azure/Configuration.cpp b/src/Storages/ObjectStorage/Azure/Configuration.cpp index 574921743d36..03767ddf2d66 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.cpp +++ b/src/Storages/ObjectStorage/Azure/Configuration.cpp @@ -44,7 +44,6 @@ namespace ErrorCodes { extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; - extern const int LOGICAL_ERROR; } const std::unordered_set required_configuration_keys = { @@ -69,7 +68,7 @@ const std::unordered_set optional_configuration_keys = { void StorageAzureConfiguration::check(ContextPtr context) { - auto url = Poco::URI(connection_params.getConnectionURL()); + auto url = Poco::URI(connection_params.getConnectionURLWithoutQuery()); context->getGlobalContext()->getRemoteHostFilter().checkURL(url); StorageObjectStorageConfiguration::check(context); } @@ -163,9 +162,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url if (pos_container != std::string::npos) { - String container_blob_path = connection_url.substr(pos_container+5); - connection_url = connection_url.substr(0,pos_container+4); - container_name = connection_url.substr(pos_container+4); + size_t host_end = pos_container + suffix.size(); + String container_blob_path = host_end < connection_url.size() ? connection_url.substr(host_end + 1) : ""; + connection_url.resize(host_end); auto pos_blob_path = container_blob_path.find('/'); if (pos_blob_path != std::string::npos) @@ -185,9 +184,9 @@ void AzureStorageParsedArguments::fillBlobsFromURLCommon(String & connection_url auto pos_net = connection_url.find(suffix); if (pos_slash == std::string::npos || pos_at == std::string::npos|| pos_dot == std::string::npos || pos_net == std::string::npos - || pos_at-pos_slash-3 <= 0 || pos_dot-pos_at-1 <= 0) + || pos_at <= pos_slash + 3 || pos_dot <= pos_at + 1) { - throw Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect url format for a abfss url {}", connection_url); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Incorrect url format for a abfss url {}", connection_url); } auto container_name_abfss = connection_url.substr(pos_slash+3, pos_at-pos_slash-3); auto name = connection_url.substr(pos_at+1, pos_dot-pos_at-1); diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 3a346c1d28f2..08aa8818f4a3 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -106,7 +106,7 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration void setPaths(const Paths & paths) override { blobs_paths = paths; } String getNamespace() const override { return connection_params.getContainer(); } - String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURL()) / connection_params.getContainer(); } + String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURLWithoutQuery()) / connection_params.getContainer(); } StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; void check(ContextPtr context) override; diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp index e7b956fd20c6..28c9ba764fd3 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp @@ -51,6 +51,7 @@ try } metadata = manifest_file_reader->metadata(); + bytes_read = buffer->count(); parsed_column = std::move(columns[0]); parsed_column_data_type = std::dynamic_pointer_cast(data_type); parsed_manifest_file_entries.resize(parsed_column->size()); diff --git a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h index 2cf4c8a61d61..997c587f1880 100644 --- a/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h +++ b/src/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h @@ -45,6 +45,8 @@ class AvroForIcebergDeserializer std::map> metadata; + size_t bytes_read = 0; + /// Shared mutex to protect mutable cache members for thread safety mutable SharedMutex cache_mutex; @@ -71,6 +73,9 @@ class AvroForIcebergDeserializer size_t rows() const; + /// The constructor consumes the whole file, so this is its size on storage. + size_t bytesRead() const { return bytes_read; } + /// Allow to access avro paths like "a.b.c" bool hasPath(const std::string & path) const; DB::TypeIndex getTypeForPath(const std::string & path) const; diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp index 3e9dd4058b3f..cac54224ac17 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp @@ -90,6 +90,30 @@ Field parseFieldFromString(const String & value, DB::DataTypePtr data_type) namespace DeltaLake { +namespace +{ + +/// A data file with the size its `add` action records. +struct DataObjectInfo : public DB::ObjectInfo +{ + DataObjectInfo(std::string path_, int64_t size_) + : DB::ObjectInfo(DB::RelativePathWithMetadata(std::move(path_))) + , size(size_) + { + } + + std::optional getFileSizeHint() const override + { + if (size > 0) + return static_cast(size); + return std::nullopt; + } + + const int64_t size; +}; + +} + class TableSnapshot::Iterator final : public DB::IObjectIterator { private: @@ -120,7 +144,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator const TableSchema & table_schema_, const DB::NameToNameMap & physical_names_map_, const DB::Names & partition_columns_, - DB::ObjectStoragePtr object_storage_, const DB::ActionsDAG * filter_, DB::IDataLakeMetadata::FileProgressCallback callback_, size_t list_batch_size_, @@ -135,7 +158,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator , read_schema(read_schema_) , expression_schema(table_schema_) , partition_columns(partition_columns_) - , object_storage(object_storage_) , callback(callback_) , list_batch_size(list_batch_size_) , log(log_) @@ -437,13 +459,9 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator } parseDVHandle(*scan_item, object); - object->setObjectMetadata(object_storage->getObjectMetadata(object->getPath(), /*with_tags=*/ false)); if (callback) - { - chassert(object->getObjectMetadata()); - callback(DB::FileProgress(0, object->getObjectMetadata()->size_bytes)); - } + callback(DB::FileProgress(0, object->getFileSizeHint().value_or(0))); return object; } } @@ -597,7 +615,7 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator std::string full_path = DB::resolvePathInsideTable( context->getDataPath(), DB::unescapeForFileName(KernelUtils::fromDeltaString(path))); - auto object = std::make_shared(DB::RelativePathWithMetadata(std::move(full_path))); + auto object = std::make_shared(std::move(full_path), size); object->data_lake_metadata.emplace(); LOG_TEST( @@ -641,7 +659,6 @@ class TableSnapshot::Iterator final : public DB::IObjectIterator DB::NamesAndTypesList read_schema; DB::NamesAndTypesList expression_schema; DB::Names partition_columns; - const DB::ObjectStoragePtr object_storage; const DB::IDataLakeMetadata::FileProgressCallback callback; const size_t list_batch_size; const LoggerPtr log; @@ -966,7 +983,6 @@ DB::ObjectIterator TableSnapshot::iterate( schema->table_schema, schema->physical_names_map, schema->partition_columns, - object_storage, filter_dag, callback, list_batch_size, diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp index 94c263c0e7e7..dc22ef8c5954 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLake/WriteTransaction.cpp @@ -45,18 +45,13 @@ UInt64 getCurrentTime() return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } -void exportTable( - std::shared_ptr table, +void exportRecordBatch( + const arrow::RecordBatch & batch, ffi::FFI_ArrowArray & array, ffi::FFI_ArrowSchema & schema) { - auto batch = table->CombineChunksToBatch(); - if (!batch.ok()) - throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, - "Failed to create chunks batch: {}", batch.status().ToString()); - arrow::Status status = arrow::ExportRecordBatch( - **batch, + batch, reinterpret_cast(&array), reinterpret_cast(&schema)); @@ -230,30 +225,61 @@ void WriteTransaction::commit(const std::vector & files) LOG_TEST(log, "Will commit {} files", files.size()); auto write_metadata = getWriteMetadata(files, log); - ffi::FFI_ArrowArray array; - ffi::FFI_ArrowSchema schema; - SCOPE_EXIT({ - if (schema.release) - schema.release(&schema); - }); - exportTable(write_metadata, array, schema); - - KernelEngineData engine_data; - try + /// Metadata too large for one Arrow record batch comes back as several table chunks. Recombining them + /// would hit the same 32-bit offset limit, so each record batch is added to the transaction on its own. + /// `TableBatchReader` yields nothing for an empty table, which still has to reach the kernel as before. + arrow::RecordBatchVector batches; + if (write_metadata->num_rows() == 0) { - /// Takes ownership of `array` (but not`schema`) if successfully called. - engine_data = DeltaLake::KernelUtils::unwrapResult( - ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), - "get_engine_data"); + auto empty_batch = arrow::RecordBatch::MakeEmpty(write_metadata->schema()); + if (!empty_batch.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to create an empty record batch: {}", empty_batch.status().ToString()); + batches.push_back(*std::move(empty_batch)); } - catch (...) + else { - if (array.release) - array.release(&array); - throw; + arrow::TableBatchReader batch_reader(*write_metadata); + while (true) + { + std::shared_ptr batch; + arrow::Status read_status = batch_reader.ReadNext(&batch); + if (!read_status.ok()) + throw DB::Exception(DB::ErrorCodes::UNKNOWN_EXCEPTION, + "Failed to read a record batch: {}", read_status.ToString()); + if (!batch) + break; + batches.push_back(std::move(batch)); + } } - ffi::add_files(transaction.get(), engine_data.release()); + for (const auto & batch : batches) + { + ffi::FFI_ArrowArray array{}; + ffi::FFI_ArrowSchema schema{}; + SCOPE_EXIT({ + if (schema.release) + schema.release(&schema); + }); + exportRecordBatch(*batch, array, schema); + + KernelEngineData engine_data; + try + { + /// Takes ownership of `array` (but not`schema`) if successfully called. + engine_data = DeltaLake::KernelUtils::unwrapResult( + ffi::get_engine_data(array, &schema, &KernelUtils::allocateError), + "get_engine_data"); + } + catch (...) + { + if (array.release) + array.release(&array); + throw; + } + + ffi::add_files(transaction.get(), engine_data.release()); + } auto version = DeltaLake::KernelUtils::unwrapResult(ffi::commit(transaction.release(), engine.get()), "commit"); LOG_TEST(log, "Commit version: {}", version); diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp index c0072e3e576b..74fcc2accefb 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp @@ -182,8 +182,7 @@ std::optional SingleThreadIcebergKeysIterator::ne persistent_components, local_context, log, - mle.manifest_file_path, - mle.manifest_file_byte_size); + mle.manifest_file_path); current_manifest_file_iterator = Iceberg::ManifestFileIterator::create( manifest_file_cacheable_part.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h index 44309f94e60a..63479720f676 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h @@ -74,7 +74,7 @@ struct IcebergMetadataFilesCacheCell : private boost::noncopyable /// - manifest list consists of cache keys which will retrieve the manifest file from cache [file_path --> ManifestFileCacheKeys] /// - manifest file [file_path --> Iceberg::ManifestFileCacheableInfo] std::variant cached_element; - Int64 memory_bytes; + size_t memory_bytes; explicit IcebergMetadataFilesCacheCell(String && metadata_json_str) : cached_element(std::move(metadata_json_str)) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp index e8226dadcd76..fd279ca1936a 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp @@ -74,6 +74,9 @@ void MultipleFileWriter::finalize() output_format->finalize(); buffer->finalize(); total_bytes += buffer->count(); + + /// A finished format can still hold resources: a Parquet one keeps its idle encoder threads. + release(); } void MultipleFileWriter::release() diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp index 5039abab707a..859b46f2b219 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp @@ -259,6 +259,8 @@ static std::optional writeDataFiles( delete_data_writers[partition_key]->finalize(); delete_data_write_buffers[partition_key]->finalize(); delete_data_result[partition_key].total_bytes = static_cast(delete_data_write_buffers[partition_key]->count()); + delete_data_writers[partition_key].reset(); + delete_data_write_buffers[partition_key].reset(); } } @@ -317,6 +319,8 @@ static std::optional writeDataFiles( update_data_writers[partition_key]->finalize(); update_data_write_buffers[partition_key]->finalize(); update_data_result[partition_key].total_bytes = static_cast(update_data_write_buffers[partition_key]->count()); + update_data_writers[partition_key].reset(); + update_data_write_buffers[partition_key].reset(); } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp index b65109e9f697..d342906b3302 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp @@ -69,8 +69,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size) + const String & filename) { auto log_level = local_context->getSettingsRef()[Setting::iceberg_metadata_log_level].value; @@ -90,7 +89,8 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( auto manifest_file_deserializer = std::make_unique( std::move(buffer), filename, getFormatSettings(local_context)); - return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), bytes_size}; + const size_t manifest_file_bytes = manifest_file_deserializer->bytesRead(); + return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), manifest_file_bytes}; }; if (use_iceberg_metadata_cache && persistent_table_components.table_uuid.has_value()) @@ -115,8 +115,7 @@ Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesH persistent_table_components, local_context, log, - cache_key.manifest_file_path, - static_cast(cache_key.manifest_file_byte_size)); + cache_key.manifest_file_path); auto iterator = Iceberg::ManifestFileIterator::create( cacheable_info.deserializer, diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h index ac5a7f7bc06e..5df057a2bb49 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h @@ -28,8 +28,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const PersistentTableComponents & persistent_table_components, ContextPtr local_context, LoggerPtr log, - const String & filename, - size_t bytes_size); + const String & filename); /// Creates a fully initialized ManifestFileIterator from a cache key. /// All entries are drained so that aggregate methods (e.g. getRowsCountInAllFilesExcludingDeleted) diff --git a/src/Storages/ObjectStorage/IObjectIterator.h b/src/Storages/ObjectStorage/IObjectIterator.h index 83c645e915fd..1b191139ce67 100644 --- a/src/Storages/ObjectStorage/IObjectIterator.h +++ b/src/Storages/ObjectStorage/IObjectIterator.h @@ -41,6 +41,7 @@ struct ObjectInfo virtual size_t fileSizeInArchive() const { throw Exception(ErrorCodes::LOGICAL_ERROR, "Not an archive"); } virtual std::string getPathOrPathToArchiveIfArchive() const; virtual std::optional getFileFormat() const { return std::nullopt; } + virtual std::optional getFileSizeHint() const { return std::nullopt; } std::optional getObjectMetadata() const { return relative_path_with_metadata.metadata; } void setObjectMetadata(const ObjectMetadata & metadata) { relative_path_with_metadata.metadata = metadata; } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp index 2acdbf6da675..1d4de8b623cd 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp @@ -95,6 +95,15 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + String getObjectStorageHash(const IObjectStorage & object_storage) + { + const String description = object_storage.getDescription(); + return sipHash128String(description.substr(0, description.find('?')) + '\0' + object_storage.getObjectsNamespace()); + } +} + StorageObjectStorageSource::StorageObjectStorageSource( String name_, ObjectStoragePtr object_storage_, @@ -536,7 +545,7 @@ void StorageObjectStorageSource::addNumRowsToCache(const ObjectInfo & object_inf schema_cache.addNumRows(cache_key, num_rows); } -StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader() +StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader(bool prefetch_input_format) { return createReader( 0, @@ -551,7 +560,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade max_block_size, parser_shared_resources, format_filter_info, - need_only_count); + need_only_count, + prefetch_input_format); } StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReader( @@ -567,7 +577,8 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count) + bool need_only_count, + bool prefetch_input_format) { ObjectInfoPtr object_info; auto query_settings = configuration->getQuerySettings(context_); @@ -832,6 +843,9 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade if (need_only_count) input_format->needOnlyCount(); + if (prefetch_input_format) + input_format->prefetch(); + builder.init(Pipe(input_format)); configuration->addDeleteTransformers(object_info, builder, format_settings, parser_shared_resources, context_); @@ -977,7 +991,7 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade std::future StorageObjectStorageSource::createReaderAsync() { - return create_reader_scheduler([=, this] { return createReader(); }, Priority{}); + return create_reader_scheduler([=, this] { return createReader(/* prefetch_input_format */ true); }, Priority{}); } std::unique_ptr createReadBuffer( @@ -1099,6 +1113,7 @@ std::unique_ptr createReadBuffer( else { SipHash hash; + hash.update(getObjectStorageHash(*object_storage)); hash.update(object_info.getPath()); hash.update(object_info.metadata->etag); @@ -1147,7 +1162,9 @@ std::unique_ptr createReadBuffer( if (use_page_cache) { - PageCacheKey key = {.path = "s3:" + object_info.getPath(), .file_version = "etag:" + object_info.metadata->etag}; + PageCacheKey key = { + .path = fmt::format("s3:{}:{}", getObjectStorageHash(*object_storage), object_info.getPath()), + .file_version = "etag:" + object_info.metadata->etag}; impl = std::make_unique(key, effective_read_settings.page_cache, std::move(impl), modified_read_settings); } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.h b/src/Storages/ObjectStorage/StorageObjectStorageSource.h index 5cbe931a047e..375187276c51 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.h @@ -136,9 +136,10 @@ class StorageObjectStorageSource : public ISource size_t max_block_size, FormatParserSharedResourcesPtr parser_shared_resources, FormatFilterInfoPtr format_filter_info, - bool need_only_count); + bool need_only_count, + bool prefetch_input_format = false); - ReaderHolder createReader(); + ReaderHolder createReader(bool prefetch_input_format = false); std::future createReaderAsync(); diff --git a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h index e9d9bd0f7414..a338ae7dead0 100644 --- a/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h +++ b/src/Storages/ObjectStorageQueue/AzureQueue_fwd.h @@ -1,7 +1,7 @@ #pragma once #include #include -#include +#include #include namespace AzureQueue @@ -20,10 +20,7 @@ static inline std::unordered_map SETTINGS_TO_HIDE = std::string masked_value; if (!value.tryGet(masked_value)) return {}; - static re2::RE2 account_key_pattern = "AccountKey=.*?(;|$)"; - RE2::Replace(&masked_value, account_key_pattern, "AccountKey=[HIDDEN]\\1"); - static re2::RE2 sas_signature_pattern = "SharedAccessSignature=.*?(;|$)"; - RE2::Replace(&masked_value, sas_signature_pattern, "SharedAccessSignature=[HIDDEN]\\1"); + DB::maskAzureConnectionStringSecrets(masked_value); return fmt::format("'{}'", masked_value); }}, }; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp new file mode 100644 index 000000000000..e845fa34a6c0 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -0,0 +1,119 @@ +#include + +#include "config.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include + + +namespace DB +{ + +namespace +{ + +enum class MoveDestinationKind : uint8_t +{ + S3, + Azure, +}; + +std::optional getMoveDestinationKind(std::string_view name) +{ + /// The prefix is accepted for every queue setting, see `normalizeSetting` in `StorageObjectStorageQueue.cpp`. + static constexpr std::string_view legacy_prefix = "s3queue_"; + if (name.starts_with(legacy_prefix)) + name.remove_prefix(legacy_prefix.size()); + + if (name == "after_processing_move_uri") + return MoveDestinationKind::S3; + if (name == "after_processing_move_connection_string" || name == "after_processing_move_container") + return MoveDestinationKind::Azure; + return std::nullopt; +} + +AccessTypeObjects::Source getAccessSource(MoveDestinationKind kind) +{ + switch (kind) + { + case MoveDestinationKind::S3: + return AccessTypeObjects::Source::S3; + case MoveDestinationKind::Azure: + return AccessTypeObjects::Source::AZURE; + } +} + +/// A value that is not a `String` is never empty here: it is checked like a destination that cannot be parsed. +bool isEmptyValue(const Field & value) +{ + return value.getType() == Field::Types::String && value.safeGet().empty(); +} + +/// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +{ + const bool sets_destination = std::ranges::any_of( + changes, + [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); + if (!sets_destination) + return {}; + + /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only + /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against + /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). + const auto source = getAccessSource(table_kind); + AccessRightsElements res; + res.emplace_back(AccessType::WRITE, AccessTypeObjects::toStringSource(source)); + return res; +} + +} + +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::S3); +} + +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +{ + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); +} + +void checkObjectStorageQueueS3MoveDestinationHost( + [[maybe_unused]] const String & move_uri, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AWS_S3 + if (!move_uri.empty()) + S3::URI(move_uri).checkRemoteHostFilter(filter); +#endif +} + +void checkObjectStorageQueueAzureMoveDestinationHost( + [[maybe_unused]] const String & move_connection_string, + [[maybe_unused]] const String & move_container, + [[maybe_unused]] const RemoteHostFilter & filter) +{ +#if USE_AZURE_BLOB_STORAGE + if (!move_connection_string.empty()) + { + AzureBlobStorage::ConnectionParams connection_params; + AzureBlobStorage::processURL(move_connection_string, move_container, connection_params.endpoint, connection_params.auth_method); + /// Without the query: a connection string can carry a SAS, which the message of `checkURL` must not show. + String url = connection_params.getConnectionURL(); + url = url.substr(0, url.find_first_of("?#")); + filter.checkURL(Poco::URI(url)); + } +#endif +} + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h new file mode 100644 index 000000000000..40601b4b1145 --- /dev/null +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +namespace DB +{ + +class RemoteHostFilter; + +/// The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +/// `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads every processed file +/// with its own source credentials and writes it to the destination. So setting the destination needs +/// `WRITE` on the `S3` (or `AZURE`) source without a URL filter: the move writes keys built from +/// `after_processing_move_prefix` and the source keys, not from the URI, so a filtered grant cannot authorize them. +/// For `ALTER` it also needs `SELECT` on the table, because the creator of the table, not the user of the `ALTER`, +/// supplied the source and its credentials. + +/// The `StorageFactory::GetExportAccessFn` of `S3Queue` and `AzureQueue`: unfiltered `WRITE` if a setting moves files outside +/// the source bucket or container. Only these settings choose such a destination: `after_processing_move_uri` for S3, +/// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy +/// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. +/// An empty value disables the move destination, so it is not a destination and needs no grant. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); + +/// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. +/// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. +/// Does nothing when `move_uri` is empty. +void checkObjectStorageQueueS3MoveDestinationHost(const String & move_uri, const RemoteHostFilter & filter); + +/// The same for a move to another Azure container (see `StorageAzureConfiguration::check`). +/// Does nothing when `move_connection_string` is empty. +void checkObjectStorageQueueAzureMoveDestinationHost( + const String & move_connection_string, const String & move_container, const RemoteHostFilter & filter); + +} diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp index cd48a45926ea..a89c5ec4923a 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,11 @@ namespace S3AuthSetting extern const S3AuthSettingsString secret_access_key; } +namespace S3RequestSetting +{ + extern const S3RequestSettingsBool allow_native_copy; +} + #endif namespace ErrorCodes @@ -285,6 +291,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move S3 objects"); } + /// The settings are checked at `CREATE` and `ALTER` too. This is defense in depth for a table that was created before + /// those checks existed, or before the list of allowed hosts was tightened. If it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueS3MoveDestinationHost(move_uri, getContext()->getRemoteHostFilter()); + if (auto * s3_storage = dynamic_cast(object_storage.get()); s3_storage != nullptr) { auto src_client = s3_storage->getS3StorageClient(); @@ -304,6 +314,10 @@ void ObjectStorageQueuePostProcessor::moveS3Objects(const StoredObjects & object /* for_disk_s3 */ false ); auto dst_uri = S3::URI(move_uri); + /// Native copy sends `CopyObject` through the source client, so it writes to the source endpoint. That is the checked + /// destination only if both clients use the same endpoint, otherwise use the buffered copy, which uploads with `dst_client`. + if (src_client->getInitialEndpoint() != dst_client->getInitialEndpoint()) + s3_settings->request_settings[S3RequestSetting::allow_native_copy] = false; auto read_settings = getReadSettings(); const auto read_settings_to_use = s3_storage->patchSettings(read_settings); auto scheduler = threadPoolCallbackRunnerUnsafe( @@ -391,6 +405,9 @@ void ObjectStorageQueuePostProcessor::moveAzureBlobs(const StoredObjects & objec throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not enough settings to move Azure blobs"); } + /// See the comment in `moveS3Objects`: if it throws, nothing is copied and nothing is removed. + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, getContext()->getRemoteHostFilter()); + if (auto * azure_storage = dynamic_cast(object_storage.get()); azure_storage != nullptr) { auto contextPtr = getContext(); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp index 643418d037d7..45987c8046d3 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.cpp @@ -5,7 +5,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -58,14 +60,14 @@ namespace ErrorCodes DECLARE(String, partition_component, "", "Name of the capture group from partition_regex to use as partition key. Required when using partitioning_mode='regex'. Example: 'hostname'", 0) \ DECLARE(ObjectStorageQueueBucketingMode, bucketing_mode, ObjectStorageQueueBucketingMode::PATH, "Bucketing strategy for Ordered mode parallel processing: PATH (hash full file path, default), PARTITION (hash partition key, requires partitioning_mode != NONE)", 0) \ DECLARE(UInt32, after_processing_retries, 10, "Number of retries for the after_processing action before giving up", 0) \ - DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to", 0) \ + DECLARE(String, after_processing_move_uri, "", "S3 bucket URL to move processed files to. Setting it requires the `WRITE` grant on the `S3` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The URL must be allowed by `remote_url_allow_hosts`", 0) \ DECLARE(String, after_processing_move_prefix, "", "Path prefix to move processed files to", 0) \ DECLARE(String, after_processing_tag_key, "", "Tag key to tag processed files in the storage", 0) \ DECLARE(String, after_processing_tag_value, "", "Tag value to tag processed files in the storage", 0) \ DECLARE(String, after_processing_move_access_key_id, "", "S3 Access Key ID accompanying after_processing_move_uri", 0) \ DECLARE(String, after_processing_move_secret_access_key, "", "S3 Secret Access Key accompanying after_processing_move_uri", 0) \ - DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to", 0) \ - DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string", 0) \ + DECLARE(String, after_processing_move_connection_string, "", "Azure connection string to move processed files to. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table. The endpoint must be allowed by `remote_url_allow_hosts`", 0) \ + DECLARE(String, after_processing_move_container, "", "Azure container accompanying after_processing_move_connection_string. Setting it requires the `WRITE` grant on the `AZURE` source (not limited to a URL filter), and `ALTER` also requires `SELECT` on the table", 0) \ DECLARE(Bool, use_hive_partitioning, false, "DEPRECATED: Use partitioning_mode='hive' instead. Whether path contains hive partitioning and this engine should process such files with a separate processed files tracking per partition.", 0) \ #define LIST_OF_OBJECT_STORAGE_QUEUE_SETTINGS(M, ALIAS) \ @@ -107,7 +109,8 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const + const StorageObjectStorageQueue & storage, + bool display_secrets) const { MutableColumns & res_columns = params.res_columns; auto settings_changes_ast = storage.getInMemoryMetadataPtr()->settings_changes; @@ -127,6 +130,23 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( { return StorageObjectStorageQueue::isSettingChangeable(setting_name, (*this)[ObjectStorageQueueSetting::mode]); }; + /// Hides what `SHOW CREATE TABLE` hides. A secret is hidden whole, as its masker renders SQL. + auto render_value = [&](const std::string & setting_name, const Field & value) -> String + { + static constexpr std::string_view hidden_secret = "[HIDDEN]"; + if (!display_secrets) + { + for (const auto * settings_to_hide : {&S3Queue::SETTINGS_TO_HIDE, &AzureQueue::SETTINGS_TO_HIDE}) + { + auto it = settings_to_hide->find(setting_name); + if (it == settings_to_hide->end()) + continue; + if (auto masked = it->second(value); masked && masked->contains(hidden_secret)) + return String(hidden_secret); + } + } + return convertFieldToString(value); + }; for (const auto & change : impl->all()) { @@ -135,7 +155,7 @@ void ObjectStorageQueueSettings::dumpToSystemEngineSettingsColumns( res_columns[i++]->insert(database_name); res_columns[i++]->insert(table_name); res_columns[i++]->insert(name); - res_columns[i++]->insert(convertFieldToString(change.getValue())); + res_columns[i++]->insert(render_value(name, change.getValue())); res_columns[i++]->insert(change.getTypeName()); res_columns[i++]->insert(is_changed(name)); res_columns[i++]->insert(change.getDescription()); diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h index dad7144540bc..37c784da6d07 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSettings.h @@ -61,7 +61,8 @@ struct ObjectStorageQueueSettings MutableColumnsAndConstraints & params, const std::string & table_name, const std::string & database_name, - const StorageObjectStorageQueue & storage) const; + const StorageObjectStorageQueue & storage, + bool display_secrets) const; void loadFromQuery(ASTStorage & storage_def, bool is_attach, const StorageID & storage_id); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 10e4f39ec00e..718da1abc8cf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include @@ -22,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -140,9 +144,26 @@ namespace ErrorCodes namespace { + /// The move uses only the destination of the storage type of the table, so only that one is checked. + void checkMoveDestinationHost( + ObjectStorageType type, + const String & move_uri, + const String & move_connection_string, + const String & move_container, + const RemoteHostFilter & filter) + { + if (type == ObjectStorageType::S3) + checkObjectStorageQueueS3MoveDestinationHost(move_uri, filter); + else if (type == ObjectStorageType::Azure) + checkObjectStorageQueueAzureMoveDestinationHost(move_connection_string, move_container, filter); + } + void validateSettings( ObjectStorageQueueSettings & queue_settings, - bool is_attach) + ObjectStorageType type, + const RemoteHostFilter & remote_host_filter, + bool is_attach, + bool is_loading_from_existing_metadata) { if (!is_attach && !queue_settings[ObjectStorageQueueSetting::mode].changed) { @@ -201,6 +222,21 @@ namespace "Move of processed objects requires specifying target bucket/container or prefix"); } } + + /// The host filter of `configuration` covers the source only, so the move destination is checked here. + /// It is checked whenever it is set, not only for `after_processing = 'move'`: otherwise a table created with + /// `after_processing = 'keep'` and a destination that is not allowed could be switched to `move` by an `ALTER` + /// that does not change the destination. A table loaded from existing metadata must never fail to load. + if (!is_loading_from_existing_metadata) + { + checkMoveDestinationHost( + type, + queue_settings[ObjectStorageQueueSetting::after_processing_move_uri].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_connection_string].value, + queue_settings[ObjectStorageQueueSetting::after_processing_move_container].value, + remote_host_filter); + } + if (queue_settings[ObjectStorageQueueSetting::after_processing] == ObjectStorageQueueAction::TAG) { if (queue_settings[ObjectStorageQueueSetting::after_processing_tag_key].toString().empty()) @@ -307,7 +343,7 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( } const bool is_attach = mode > LoadingStrictnessLevel::CREATE; - validateSettings(*queue_settings_, is_attach); + validateSettings(*queue_settings_, type, context_->getRemoteHostFilter(), is_attach, isLoadingFromExistingMetadata(mode)); object_storage = configuration->createObjectStorage(context_, /* is_readonly */true, std::nullopt); FormatFactory::instance().checkFormatName(configuration->format); @@ -413,12 +449,18 @@ void StorageObjectStorageQueue::startup() /// Create metadata in keeper if it does not exits yet. /// Create a persistent node for the table under /registry node. bool created_new_metadata = false; - files_metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( + /// Keep a local handle: the factory call and the startup below do keeper I/O, which must not + /// run under `mutex`. + auto metadata = ObjectStorageQueueMetadataFactory::instance().getOrCreate( zookeeper_name, zk_path, std::move(temp_metadata), getStorageID(), created_new_metadata); + { + std::lock_guard lock(mutex); + files_metadata = metadata; + } /// Register the metadata in startup(), unregister in shutdown. /// (If startup is never called, shutdown also won't be called.) @@ -435,6 +477,7 @@ void StorageObjectStorageQueue::startup() /* is_drop */created_new_metadata, /* keep_data_in_keeper */false); + std::lock_guard lock(mutex); files_metadata.reset(); } }); @@ -453,7 +496,7 @@ void StorageObjectStorageQueue::startup() }); /// Start background tasks. - files_metadata->startup(); + metadata->startup(); for (auto & task : streaming_tasks) task->activateAndSchedule(); @@ -496,11 +539,19 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) tryLogCurrentException(log); } - if (files_metadata) + /// Drop the handle before the keeper cleanup below, so a concurrent reader sees the + /// shut-down state. The local copy keeps the metadata alive for that cleanup. + std::shared_ptr metadata; + { + std::lock_guard lock(mutex); + metadata = std::move(files_metadata); + } + + if (metadata) { try { - files_metadata->unregisterActive(getStorageID()); + metadata->unregisterActive(getStorageID()); } catch (...) { @@ -508,8 +559,6 @@ void StorageObjectStorageQueue::shutdown(bool is_drop) } ObjectStorageQueueMetadataFactory::instance().remove(zookeeper_name, zk_path, getStorageID(), is_drop, keep_data_in_keeper); - - files_metadata.reset(); } LOG_TRACE(log, "Shut down storage"); } @@ -1316,6 +1365,35 @@ void StorageObjectStorageQueue::checkAlterIsPossible(const AlterCommands & comma } } } + + /// The host filter of `configuration` covers the source only, so a new move destination is checked here. + /// `checkAlterIsPossible` runs on every host and the check depends only on the server config, so it is correct everywhere. + static constexpr std::array move_destination_settings{ + "after_processing_move_uri", "after_processing_move_connection_string", "after_processing_move_container"}; + + auto get_move_destination_value = [](const SettingsChanges * settings, std::string_view name) -> String + { + const Field * value = settings ? settings->tryGet(name) : nullptr; + return value ? convertFieldToString(*value) : String{}; + }; + + const bool move_destination_changed = std::ranges::any_of( + move_destination_settings, + [&](std::string_view name) + { return get_move_destination_value(old_settings, name) != get_move_destination_value(&new_settings, name); }); + + if (move_destination_changed) + { + const String move_connection_string = get_move_destination_value(&new_settings, "after_processing_move_connection_string"); + const String move_container = get_move_destination_value(&new_settings, "after_processing_move_container"); + + checkMoveDestinationHost( + type, + get_move_destination_value(&new_settings, "after_processing_move_uri"), + move_connection_string, + move_container, + local_context->getRemoteHostFilter()); + } } void StorageObjectStorageQueue::alter( @@ -1532,6 +1610,12 @@ const ObjectStorageQueueTableMetadata & StorageObjectStorageQueue::getTableMetad return files_metadata->getTableMetadata(); } +std::shared_ptr StorageObjectStorageQueue::tryGetFilesMetadata() const +{ + std::lock_guard lock(mutex); + return files_metadata; +} + std::shared_ptr StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate) { @@ -1571,11 +1655,16 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), /// so let's reconstruct. ObjectStorageQueueSettings settings; - /// If startup() for a table was not called, just use the default queue settings + /// If startup() for a table was not called, just use the default queue settings. + /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. if (!startup_finished) return settings; - const auto & table_metadata = getTableMetadata(); + auto metadata = tryGetFilesMetadata(); + if (!metadata) + return settings; + + const auto & table_metadata = metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) @@ -1591,12 +1680,12 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const settings[ObjectStorageQueueSetting::tracked_files_limit] = table_metadata.tracked_files_limit; settings[ObjectStorageQueueSetting::buckets] = table_metadata.buckets; - auto cleanup_interval_ms = files_metadata->getCleanupIntervalMS(); + auto cleanup_interval_ms = metadata->getCleanupIntervalMS(); settings[ObjectStorageQueueSetting::cleanup_interval_min_ms] = static_cast(cleanup_interval_ms.first); settings[ObjectStorageQueueSetting::cleanup_interval_max_ms] = static_cast(cleanup_interval_ms.second); - settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(files_metadata->getPersistentProcessingNodeTTLSeconds()); - settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = files_metadata->usePersistentProcessingNode(); - const auto & file_statuses_cache = files_metadata->getFileStatusesCache(); + settings[ObjectStorageQueueSetting::persistent_processing_node_ttl_seconds] = static_cast(metadata->getPersistentProcessingNodeTTLSeconds()); + settings[ObjectStorageQueueSetting::use_persistent_processing_nodes] = metadata->usePersistentProcessingNode(); + const auto & file_statuses_cache = metadata->getFileStatusesCache(); settings[ObjectStorageQueueSetting::metadata_cache_size_bytes] = file_statuses_cache.maxSizeInBytes(); settings[ObjectStorageQueueSetting::metadata_cache_size_elements] = file_statuses_cache.maxCount(); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index 5a251e7b7e16..902ec55b54bf 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -147,6 +147,8 @@ class StorageObjectStorageQueue : public IStorage, WithContext bool supportsColumnsWithDynamicStructure() const override { return true; } const ObjectStorageQueueTableMetadata & getTableMetadata() const; + /// Returns nullptr if the table is not started up or is already shut down. + std::shared_ptr tryGetFilesMetadata() const; std::shared_ptr createFileIterator(ContextPtr local_context, const ActionsDAG::Node * predicate); std::shared_ptr createSource( diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 27f3c6004559..d7ddf6e5d128 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -143,6 +144,7 @@ void registerStorageS3Queue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::S3, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getS3QueueMoveDestinationAccess, }); } #endif @@ -161,6 +163,7 @@ void registerStorageAzureQueue(StorageFactory & factory) .supports_schema_inference = true, .source_access_type = AccessTypeObjects::Source::AZURE, .has_builtin_setting_fn = ObjectStorageQueueSettings::hasBuiltin, + .get_export_access_fn = getAzureQueueMoveDestinationAccess, }); } #endif diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp index f5e81a4a4843..ec0c6ea0433a 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.cpp @@ -275,6 +275,14 @@ void StorageMaterializedPostgreSQL::dropInnerTableIfAny(bool sync, ContextPtr lo } +bool StorageMaterializedPostgreSQL::hasBucketedMapSerialization() const +{ + if (auto nested = tryGetNested()) + return nested->hasBucketedMapSerialization(); + return false; +} + + bool StorageMaterializedPostgreSQL::needRewriteQueryWithFinal(const Names & column_names) const { return needRewriteQueryWithFinalForStorage(column_names, getNested()); diff --git a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h index 0933a2772d9d..c133fee077bf 100644 --- a/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h +++ b/src/Storages/PostgreSQL/StorageMaterializedPostgreSQL.h @@ -91,6 +91,8 @@ class StorageMaterializedPostgreSQL final : public IStorage, WithContext bool needRewriteQueryWithFinal(const Names & column_names) const override; + bool hasBucketedMapSerialization() const override; + void read( QueryPlan & query_plan, const Names & column_names, diff --git a/src/Storages/StorageAlias.cpp b/src/Storages/StorageAlias.cpp index eb8bc370f85a..5160352e3432 100644 --- a/src/Storages/StorageAlias.cpp +++ b/src/Storages/StorageAlias.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -15,6 +16,9 @@ #include #include #include +#include +#include +#include namespace DB @@ -31,6 +35,7 @@ namespace ErrorCodes extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int BAD_ARGUMENTS; extern const int SUPPORT_IS_DISABLED; + extern const int NOT_IMPLEMENTED; } StorageAlias::StorageAlias( @@ -171,6 +176,26 @@ SinkToStoragePtr StorageAlias::write( return std::make_shared(*this, local_context, target_metadata); } +void StorageAlias::checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const +{ + /// `InterpreterAlterQuery` checks the export grants (`SELECT` on the table and its row policy) on the name in the query, + /// which is the alias, not the target. The refusal does not need the user, so it also holds on the hosts of `ON CLUSTER`. + for (const auto & command : commands) + { + if (command.type == AlterCommand::MODIFY_SETTING && !StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes).empty()) + { + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Changing the settings that send the data of a table elsewhere through an alias is not supported. " + "Execute the ALTER directly on the target table: {}.{}", + backQuoteIfNeed(target_database), + backQuoteIfNeed(target_table)); + } + } + + getTargetTable()->checkAlterIsPossible(commands, local_context); +} + void StorageAlias::alter( const AlterCommands & params, ContextPtr local_context, diff --git a/src/Storages/StorageAlias.h b/src/Storages/StorageAlias.h index 0753decac7e5..99a9167dd58d 100644 --- a/src/Storages/StorageAlias.h +++ b/src/Storages/StorageAlias.h @@ -55,7 +55,7 @@ class StorageAlias final : public IStorage, WithContext /// Distributed write to target table std::optional distributedWrite(const ASTInsertQuery & query, ContextPtr local_context) override; - void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override { getTargetTable()->checkAlterIsPossible(commands, local_context); } + void checkAlterIsPossible(const AlterCommands & commands, ContextPtr local_context) const override; /// Alter target table void alter( @@ -143,6 +143,7 @@ class StorageAlias final : public IStorage, WithContext std::optional supportedPrewhereColumns() const override { return getTargetTable()->supportedPrewhereColumns(); } bool canMoveConditionsToPrewhere() const override { return getTargetTable()->canMoveConditionsToPrewhere(); } bool supportsOptimizationToSubcolumns() const override { return getTargetTable()->supportsOptimizationToSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsDeduplication() const override { return getTargetTable()->supportsDeduplication(); } bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageBuffer.cpp b/src/Storages/StorageBuffer.cpp index 090058a95a95..2993357d6658 100644 --- a/src/Storages/StorageBuffer.cpp +++ b/src/Storages/StorageBuffer.cpp @@ -887,6 +887,13 @@ bool StorageBuffer::supportsPrewhere() const return false; } +bool StorageBuffer::hasBucketedMapSerialization() const +{ + if (auto destination = getDestinationTable()) + return destination->hasBucketedMapSerialization(); + return false; +} + bool StorageBuffer::checkThresholds(const Buffer & buffer, bool direct, time_t current_time, size_t additional_rows, size_t additional_bytes) const { time_t time_passed = 0; diff --git a/src/Storages/StorageBuffer.h b/src/Storages/StorageBuffer.h index 481647a89625..8da3169b9b2f 100644 --- a/src/Storages/StorageBuffer.h +++ b/src/Storages/StorageBuffer.h @@ -91,6 +91,7 @@ friend class BufferSink; bool supportsParallelInsert() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } diff --git a/src/Storages/StorageDistributed.cpp b/src/Storages/StorageDistributed.cpp index 478abb8530f7..2bdf34ab918b 100644 --- a/src/Storages/StorageDistributed.cpp +++ b/src/Storages/StorageDistributed.cpp @@ -1,5 +1,10 @@ #include +#include +#include +#include +#include + #include #include @@ -179,6 +184,7 @@ namespace Setting extern const SettingsBool prefer_global_in_and_join; extern const SettingsBool skip_unavailable_shards; extern const SettingsBool enable_global_with_statement; + extern const SettingsMap additional_table_filters; } namespace DistributedSetting @@ -1364,6 +1370,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser auto & select = query.select->as(); StoragePtr src_storage; + bool src_is_table_function = false; /// Distributed write only works in the most trivial case INSERT ... SELECT /// without any unions or joins on the right side @@ -1380,6 +1387,7 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (joined_tables.tablesCount() == 1) { src_storage = joined_tables.getLeftTableStorage(); + src_is_table_function = joined_tables.isLeftTableFunction(); } } } @@ -1387,6 +1395,19 @@ std::optional StorageDistributed::distributedWrite(const ASTInser if (!src_storage) return {}; + /// This is the only place source SELECT access is enforced in this case + /// (table functions have been already checked in ITableFunction::execute) + const auto src_id = src_storage->getStorageID(); + if (!src_is_table_function + && !local_context->getAccess()->isGranted(AccessType::SELECT, src_id.database_name, src_id.table_name)) + return {}; + if (auto row_policy_filter = local_context->getRowPolicyFilter(src_id.database_name, src_id.table_name, RowPolicyFilterType::SELECT_FILTER); + row_policy_filter && !row_policy_filter->isAlwaysTrue()) + return {}; + /// It is not easy to match this table only, analyzer also do not do it + if (!settings[Setting::additional_table_filters].value.empty()) + return {}; + if (auto src_distributed = std::dynamic_pointer_cast(src_storage)) { return distributedWriteBetweenDistributedTables(*src_distributed, query, local_context); diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 0cc905ab1d3c..4ced2fa21aa6 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -1,9 +1,12 @@ #include +#include #include #include #include #include +#include #include +#include #include #include #include @@ -267,4 +270,37 @@ const StorageFactory::StorageFeatures & StorageFactory::getStorageFeatures(const return it->second.features; } +AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & create) const +{ + AccessRightsElements res; + auto add = [&](const ASTStorage & storage) + { + if (!storage.engine || !storage.settings) + return; + auto it = storages.find(storage.engine->name); + if (it != storages.end() && it->second.features.get_export_access_fn) + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + }; + + if (create.storage) + add(*create.storage); + if (create.targets) + { + for (const ASTStorage * inner_engine : create.targets->getInnerEngines()) + add(*inner_engine); + } + return res; +} + +AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const +{ + AccessRightsElements res; + for (const auto & [_, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes)); + } + return res; +} + } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index d3e4ccc969d4..6babf823c358 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -16,6 +16,8 @@ namespace DB class Context; class ASTCreateQuery; class ASTStorage; +class AccessRightsElements; +class SettingsChanges; struct StorageID; struct ConstraintsDescription; @@ -33,6 +35,10 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// Used to validate if table settings belong to the engine or the query before the start of the query interpretation using HasBuiltinSettingFn = bool(std::string_view); + /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. + /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + struct Arguments { const String & engine_name; @@ -76,6 +82,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> std::optional source_access_type = std::nullopt; HasBuiltinSettingFn * has_builtin_setting_fn = nullptr; + GetExportAccessFn * get_export_access_fn = nullptr; }; using CreatorFn = std::function; @@ -111,6 +118,7 @@ class StorageFactory : private boost::noncopyable, public IHints<> .supports_schema_inference = false, .source_access_type = std::nullopt, .has_builtin_setting_fn = nullptr, + .get_export_access_fn = nullptr, }); const Storages & getAllStorages() const @@ -140,6 +148,13 @@ class StorageFactory : private boost::noncopyable, public IHints<> const StorageFeatures & getStorageFeatures(const String & storage_name) const; + /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` + /// table. An unknown engine needs nothing here: creating it fails later. + AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, + /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. + AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; + private: Storages storages; }; diff --git a/src/Storages/StorageInMemoryMetadata.cpp b/src/Storages/StorageInMemoryMetadata.cpp index 7982f7de575a..f99761a93ff7 100644 --- a/src/Storages/StorageInMemoryMetadata.cpp +++ b/src/Storages/StorageInMemoryMetadata.cpp @@ -20,6 +20,8 @@ #include #include +#include + namespace DB { @@ -198,6 +200,47 @@ ContextMutablePtr StorageInMemoryMetadata::getSQLSecurityOverriddenContext(Conte new_context->setUser(getDefinerID(context)); + /// `Context::setUser` only sets the access-control identity (`user_id`); it does not touch the + /// user names in `ClientInfo`. That is harmless when there is an invoker whose names were copied + /// above, but a scheduled refresh of a refreshable materialized view builds its context from the + /// global context, where `current_user`, `initial_user` and `authenticated_user` are empty. + /// `RemoteQueryExecutor` sends the names as-is, and a shard that accepts the interserver + /// `` treats an empty `initial_user` as "interserver mode": it skips authentication + /// (see `TCPHandler::receiveQuery`) and executes the query with full access + /// (see `Context::getAccess`, `full_access = !user_id`). Stamp the definer into the empty fields + /// so the remote leg of the query is bounded by the same identity as the local one. Non-empty + /// fields are left alone so `currentUser` inside an ordinary `DEFINER` view still returns the + /// invoker. `AsynchronousInsertQueue` and `InterpreterExecuteAsQuery` do the same. + { + const auto & new_client_info = new_context->getClientInfo(); + const bool current_user_empty = new_client_info.current_user.empty(); + const bool initial_user_empty = new_client_info.initial_user.empty(); + const bool authenticated_user_empty = new_client_info.authenticated_user.empty(); + + if (current_user_empty || initial_user_empty || authenticated_user_empty) + { + const auto definer_name = new_context->getUserName(); + if (current_user_empty) + new_context->setCurrentUserName(definer_name); + if (initial_user_empty) + { + new_context->setInitialUserName(definer_name); + /// The shard authenticates the definer by `initial_user` and checks `initial_address` + /// against the allowed hosts of that user. Without an invoker, the address is the + /// unspecified `0.0.0.0`, which only matches users with `HOST ANY`. The query is + /// produced by this server itself, so present it as coming from the local host. + if (!new_client_info.initial_address || new_client_info.initial_address->host().isWildcard()) + new_context->setInitialAddress(Poco::Net::SocketAddress(Poco::Net::IPAddress("127.0.0.1"), 0)); + } + if (authenticated_user_empty) + { + ClientInfo client_info_with_definer = new_context->getClientInfo(); + client_info_with_definer.authenticated_user = definer_name; + new_context->setClientInfo(client_info_with_definer); + } + } + } + new_context->clampToSettingsConstraints(changed_settings, SettingSource::QUERY); new_context->applySettingsChanges(changed_settings); new_context->setSetting("allow_ddl", 1); diff --git a/src/Storages/StorageMaterializedView.cpp b/src/Storages/StorageMaterializedView.cpp index cd9b89b12c7b..05223ca73bf7 100644 --- a/src/Storages/StorageMaterializedView.cpp +++ b/src/Storages/StorageMaterializedView.cpp @@ -559,10 +559,19 @@ ContextMutablePtr StorageMaterializedView::createRefreshContext(const String & l { ContextPtr table_context = getContext(); ClientInfo client_info = table_context->getClientInfo(); - client_info.interface = ClientInfo::Interface::BACKGROUND; - client_info.client_name = "refreshable materialized view"; - auto refresh_context = getInMemoryMetadataPtr()->getSQLSecurityOverriddenContext(table_context, &client_info); - refresh_context->setClientInfo(client_info); + auto view_metadata = getInMemoryMetadataPtr(); + auto refresh_context = view_metadata->getSQLSecurityOverriddenContext(table_context, &client_info); + /// For `SQL SECURITY DEFINER`, `getSQLSecurityOverriddenContext` fills the empty user names in + /// the context's `ClientInfo` with the definer. Do not assign the local `client_info` copy to + /// the context: `setClientInfo` replaces the whole struct and would wipe that identity out. + /// Re-read it instead, so that a view without SQL security (which gets a plain copy) also gets + /// these fields. + { + ClientInfo refresh_client_info = refresh_context->getClientInfo(); + refresh_client_info.interface = ClientInfo::Interface::BACKGROUND; + refresh_client_info.client_name = "refreshable materialized view"; + refresh_context->setClientInfo(refresh_client_info); + } refresh_context->setSetting("database_replicated_allow_replicated_engine_arguments", 3); refresh_context->setSetting("log_comment", log_comment); refresh_context->setQueryKind(ClientInfo::QueryKind::INITIAL_QUERY); diff --git a/src/Storages/StorageMaterializedView.h b/src/Storages/StorageMaterializedView.h index 62331b24f329..a4d72e909292 100644 --- a/src/Storages/StorageMaterializedView.h +++ b/src/Storages/StorageMaterializedView.h @@ -36,6 +36,7 @@ class StorageMaterializedView final : public IStorage, WithMutableContext bool supportsFinal() const override { return getTargetTable()->supportsFinal(); } bool supportsParallelInsert() const override { return getTargetTable()->supportsParallelInsert(); } bool supportsSubcolumns() const override { return getTargetTable()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getTargetTable()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override; bool supportsTransactions() const override { return getTargetTable()->supportsTransactions(); } diff --git a/src/Storages/StorageMerge.cpp b/src/Storages/StorageMerge.cpp index 202aae98818e..a70dd5e4659b 100644 --- a/src/Storages/StorageMerge.cpp +++ b/src/Storages/StorageMerge.cpp @@ -318,6 +318,12 @@ bool StorageMerge::supportsPrewhere() const return traverseTablesUntil([](const auto & table) { return !table->supportsPrewhere(); }) == nullptr; } +bool StorageMerge::hasBucketedMapSerialization() const +{ + /// The rewritten query is sent to every underlying table, so all of them must benefit from it. + return traverseTablesUntil([](const auto & table) { return !table->hasBucketedMapSerialization(); }) == nullptr; +} + bool StorageMerge::canMoveConditionsToPrewhere() const { /// NOTE: This check and the above check are used during query analysis as condition for applying diff --git a/src/Storages/StorageMerge.h b/src/Storages/StorageMerge.h index 2c1eafc7f808..948a5f50694f 100644 --- a/src/Storages/StorageMerge.h +++ b/src/Storages/StorageMerge.h @@ -51,6 +51,7 @@ class StorageMerge final : public IStorage, WithContext bool supportsSampling() const override { return true; } bool supportsFinal() const override { return true; } bool supportsSubcolumns() const override { return true; } + bool hasBucketedMapSerialization() const override; bool supportsColumnsWithDynamicStructure() const override { return true; } bool supportsPrewhere() const override; std::optional supportedPrewhereColumns() const override; diff --git a/src/Storages/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index 8419b2aea6c2..cecedf79cca5 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -1114,6 +1114,11 @@ QueryPipeline StorageMergeTree::updateLightweight(const MutationCommands & comma /// Updates currently don't work with parallel replicas. context_copy->setSetting("max_parallel_replicas", Field(1)); + /// A snapshot cached by `enable_shared_storage_snapshot_in_query` before the wait for committing + /// inserts above (e.g. by the validation of `IN` operands in `InterpreterUpdateQuery`) would hide + /// the parts committed during the wait from the update. See `StorageReplicatedMergeTree::updateLightweight`. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); auto sink = std::make_shared(*this, std::move(patch_metadata), std::move(update_holder), context_copy); @@ -2800,25 +2805,24 @@ void StorageMergeTree::replacePartitionFrom(const StoragePtr & source_table, con String partition_id; + /// The merges_blocker must live until the end of the function to prevent background mutations + /// from starting on parts in the target partition between when we stop waiting and when we + /// actually remove old parts via removePartsInRangeFromWorkingSet. Without this, a mutation + /// could "resurrect" old data by completing on an already-removed part and adding a new version + /// of it back to the working set. + ActionLock merges_blocker; if (is_all) { if (replace) throw DB::Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Only support DROP/DETACH/ATTACH PARTITION ALL currently"); + merges_blocker = stopMergesAndWait(); } else { partition_id = getPartitionIDFromQuery(partition, local_context); + merges_blocker = stopMergesAndWaitForPartition(partition_id); } - /// We use the global `stopMergesAndWait` (not the per-partition variant) because the - /// per-partition blocker check in `scheduleDataProcessingJob` happens outside - /// `currently_processing_in_background_mutex`, creating a race window where a mutation - /// can be selected inside the mutex, pass the per-partition check outside the mutex, - /// and get scheduled after the blocker was set but before we call - /// `removePartsInRangeFromWorkingSet`, "resurrecting" old data. - /// The global blocker is checked inside the mutex, eliminating this race. - ActionLock merges_blocker = stopMergesAndWait(); - auto source_metadata_snapshot = source_table->getInMemoryMetadataPtr(); auto my_metadata_snapshot = getInMemoryMetadataPtr(); diff --git a/src/Storages/StorageMongoDB.cpp b/src/Storages/StorageMongoDB.cpp index 6a6fbeca720e..e4dff78729a2 100644 --- a/src/Storages/StorageMongoDB.cpp +++ b/src/Storages/StorageMongoDB.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -36,6 +37,7 @@ #include #include +#include #include using bsoncxx::builder::basic::document; @@ -49,6 +51,7 @@ namespace DB namespace ErrorCodes { + extern const int ACCESS_DENIED; extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int NOT_IMPLEMENTED; @@ -78,6 +81,53 @@ void MongoDBConfiguration::checkCollection() const throw Exception(ErrorCodes::BAD_ARGUMENTS, "MongoDB collection name must be non-empty and must not contain NUL characters"); } +namespace +{ + +void throwIfServerCredentials(const mongocxx::uri & uri, std::string_view remedy) +{ + /// Only these take the credentials from the connection string; `MONGODB-OIDC`, `MONGODB-AWS`, `GSSAPI` and + /// `MONGODB-X509` use the server's. Without a mechanism the driver uses SCRAM or no authentication. Names are case-insensitive. + static constexpr std::string_view allowed_mechanisms[] = {"SCRAM-SHA-1", "SCRAM-SHA-256", "PLAIN"}; + + const String mechanism = uri.auth_mechanism(); + const bool is_allowed_mechanism = mechanism.empty() + || std::ranges::any_of(allowed_mechanisms, [&](std::string_view allowed) { return equalsCaseInsensitive(mechanism, allowed); }); + + if (!is_allowed_mechanism) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB authentication mechanism '{}' is not allowed, because it authenticates with " + "credentials of the server process. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a password " + "in the connection string{}.", + mechanism, remedy); + + /// The driver stores the deprecated `sslClientCertificateKeyFile` under the canonical name, so this covers both. + if (uri.tls_certificate_key_file()) + throw Exception( + ErrorCodes::ACCESS_DENIED, + "MongoDB connection option `tlsCertificateKeyFile` is not allowed, because it makes the server present a " + "client certificate from its own filesystem. Use SCRAM-SHA-1, SCRAM-SHA-256 or PLAIN with a username and a " + "password in the connection string{}.", + remedy); +} + +} + +void MongoDBConfiguration::checkServerCredentialsForTable(const ContextPtr & context) const +{ + /// In `clickhouse-local` the user is the operator, so the credentials of the process are theirs to use. + if (context->getApplicationType() != Context::ApplicationType::SERVER) + return; + + throwIfServerCredentials(*uri, ""); +} + +void MongoDBConfiguration::checkServerCredentialsForDictionary() const +{ + throwIfServerCredentials(*uri, ", or define the dictionary in the server configuration files"); +} + StorageMongoDB::StorageMongoDB( const StorageID & table_id_, MongoDBConfiguration configuration_, @@ -104,6 +154,9 @@ Pipe StorageMongoDB::read( size_t max_block_size, size_t /*num_streams*/) { + /// Checked per read, with the query's settings: a table created with `mongodb(...)` is built with the global context. + configuration.checkServerCredentialsForTable(context); + storage_snapshot->check(column_names); Block sample_block; diff --git a/src/Storages/StorageMongoDB.h b/src/Storages/StorageMongoDB.h index 5d436a874803..ee514c16762a 100644 --- a/src/Storages/StorageMongoDB.h +++ b/src/Storages/StorageMongoDB.h @@ -53,6 +53,9 @@ struct MongoDBConfiguration void checkHosts(const ContextPtr & context) const; void checkCollection() const; + void checkServerCredentialsForTable(const ContextPtr & context) const; + void checkServerCredentialsForDictionary() const; + bool isOidColumn(const std::string & name) const { return oid_fields.contains(name); diff --git a/src/Storages/StorageProxy.h b/src/Storages/StorageProxy.h index 57c14568e56d..aa24e39addb6 100644 --- a/src/Storages/StorageProxy.h +++ b/src/Storages/StorageProxy.h @@ -38,6 +38,7 @@ class StorageProxy : public IStorage bool noPushingToViewsOnInserts() const override { return getNested()->noPushingToViewsOnInserts(); } bool hasEvenlyDistributedRead() const override { return getNested()->hasEvenlyDistributedRead(); } bool supportsSubcolumns() const override { return getNested()->supportsSubcolumns(); } + bool hasBucketedMapSerialization() const override { return getNested()->hasBucketedMapSerialization(); } bool supportsColumnsWithDynamicStructure() const override { return getNested()->supportsColumnsWithDynamicStructure(); } ColumnSizeByName getColumnSizes() const override { return getNested()->getColumnSizes(); } diff --git a/src/Storages/StorageReplicatedMergeTree.cpp b/src/Storages/StorageReplicatedMergeTree.cpp index 853396096da3..9707592466a1 100644 --- a/src/Storages/StorageReplicatedMergeTree.cpp +++ b/src/Storages/StorageReplicatedMergeTree.cpp @@ -249,6 +249,7 @@ namespace FailPoints extern const char rmt_merge_selecting_task_no_free_threads[]; extern const char rmt_merge_selecting_task_max_part_size[]; extern const char rmt_delay_execute_drop_range[]; + extern const char rmt_restore_replica_pause_before_metadata_version_raise[]; } namespace ErrorCodes @@ -7069,6 +7070,7 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( createReplica(metadata_snapshot, zookeeper_retries_info); createNewZooKeeperNodes(zookeeper_retries_info); + FailPointInjection::pauseFailPoint(FailPoints::rmt_restore_replica_pause_before_metadata_version_raise); /// Bump the /metadata ZNode version to match the max parts metadata version. /// The table's in-memory metadata_version is derived from the /metadata ZNode stat.version @@ -7076,12 +7078,41 @@ void StorageReplicatedMergeTree::restoreMetadataInZooKeeper( if (max_parts_metadata_version > 0) { auto zookeeper = getZooKeeper(); - String metadata_str = zookeeper->get(zookeeper_path + "/metadata"); - for (int32_t i = 0; i < max_parts_metadata_version; ++i) - zookeeper->set(zookeeper_path + "/metadata", metadata_str); - zookeeper->set(replica_path + "/metadata_version", std::to_string(max_parts_metadata_version)); + /// Each batch logs an ALTER_METADATA entry of the version it reaches, so a replica that cloned an earlier one catches up. + Coordination::Stat metadata_stat; + Coordination::Stat columns_stat; + String metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + String columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + while (metadata_stat.version < max_parts_metadata_version) + { + const auto target = static_cast(std::min( + max_parts_metadata_version, Int64{metadata_stat.version} + static_cast(zkutil::MULTI_BATCH_SIZE))); + + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(zookeeper_path + "/columns", columns_stat.version)); + for (int32_t version = metadata_stat.version; version < target; ++version) + ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/metadata", version + 1 == target ? metadata_str : "", version)); + + ReplicatedMergeTreeLogEntryData entry; + entry.type = LogEntry::ALTER_METADATA; + entry.source_replica = replica_name; + entry.metadata_str = metadata_str; + entry.columns_str = columns_str; + entry.alter_version = target; + entry.create_time = time(nullptr); + entry.have_mutation = false; + ops.emplace_back(zkutil::makeCreateRequest(zookeeper_path + "/log/log-", entry.toString(), zkutil::CreateMode::PersistentSequential)); - LOG_INFO(log, "Bumped metadata version to {} to match parts", max_parts_metadata_version); + Coordination::Responses responses; + const Coordination::Error code = zookeeper->tryMulti(ops, responses); + if (code != Coordination::Error::ZOK && code != Coordination::Error::ZBADVERSION) + zkutil::KeeperMultiException::check(code, ops, responses); + + metadata_str = zookeeper->get(zookeeper_path + "/metadata", &metadata_stat); + columns_str = zookeeper->get(zookeeper_path + "/columns", &columns_stat); + } + + LOG_INFO(log, "Raised metadata version to {} to match parts", metadata_stat.version); } LOG_INFO(log, "Created ZK nodes for table"); @@ -8433,6 +8464,13 @@ QueryPipeline StorageReplicatedMergeTree::updateLightweight(const MutationComman waitForCommittingOpsToFinish(zookeeper, context_copy->getPartitionIdToMaxBlock(getStorageID().uuid), ops, backoff_ms, sync_timeout); } + /// With `enable_shared_storage_snapshot_in_query` the update reads with the snapshot of this table + /// cached for the whole query. Anything analyzed before this point may have cached one, e.g. the + /// validation of `IN` operands in `InterpreterUpdateQuery`. Such a snapshot predates the wait for committing inserts above, so the + /// parts that arrived during the wait would be invisible to the update and their rows would stay + /// unchanged. Discard it, so that the update and its subqueries share a snapshot taken now. + discardSharedStorageSnapshot(context_copy); + auto pipeline = updateLightweightImpl(commands, context_copy); auto patch_metadata = DB::getPatchPartMetadata(pipeline.getHeader(), context_copy); diff --git a/src/Storages/System/StorageSystemMutations.cpp b/src/Storages/System/StorageSystemMutations.cpp index 7514ed309af7..b3b65c6003ed 100644 --- a/src/Storages/System/StorageSystemMutations.cpp +++ b/src/Storages/System/StorageSystemMutations.cpp @@ -10,14 +10,67 @@ #include #include #include +#include #include #include #include +#include +#include +#include namespace DB { +namespace Setting +{ + extern const SettingsUInt64 max_parser_depth; + extern const SettingsUInt64 max_parser_backtracks; +} + +namespace ErrorCodes +{ + extern const int SYNTAX_ERROR; + extern const int TOO_DEEP_RECURSION; + extern const int TOO_SLOW_PARSING; +} + +/// The mutation entry keeps the real text of the command, because the mutation is executed from it +/// (on every replica, for replicated tables). Hide the secrets on the way out instead, the way +/// `system.distributed_ddl_queue` does. The command is formatted the same way as the stored text, +/// so only the secrets differ from it. +static String hideSecretsInCommand(const ContextPtr & context, const String & command) +{ + /// Nothing to parse, see `MutationCommand::ast`. + if (command.empty()) + return command; + + const auto & settings = context->getSettingsRef(); + ParserAlterCommandList parser; + ASTPtr ast; + try + { + ast = parseQuery(parser, command, 0, settings[Setting::max_parser_depth], settings[Setting::max_parser_backtracks]); + } + catch (const Exception & e) + { + /// The text may be unparseable on another server version, so hide the whole command instead of failing the table. + if (e.code() != ErrorCodes::SYNTAX_ERROR + && e.code() != ErrorCodes::TOO_DEEP_RECURSION + && e.code() != ErrorCodes::TOO_SLOW_PARSING) + throw; + return "[HIDDEN]"; + } + + return ast->formatWithPossiblyHidingSensitiveData( + /*max_length=*/0, + /*one_line=*/true, + /*show_secrets=*/false, + /*print_pretty_type_names=*/false, + /*identifier_quoting_rule=*/IdentifierQuotingRule::WhenNecessary, + /*identifier_quoting_style=*/IdentifierQuotingStyle::Backticks); +} + ColumnsDescription StorageSystemMutations::getColumnsDescription() { @@ -65,10 +118,11 @@ Block StorageSystemMutations::getFilterSampleBlock() const }; } -void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const +void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const { const auto access = context->getAccess(); const bool check_access_for_databases = !access->isGranted(AccessType::SHOW_TABLES); + const bool show_secrets = canDisplaySecrets(context); /// Collect a set of *MergeTree tables. std::map> merge_tree_tables; @@ -169,25 +223,43 @@ void StorageSystemMutations::fillData(MutableColumns & res_columns, ContextPtr c parts_postpone_reasons_map.emplace_back(std::move(key_value)); } - size_t col_num = 0; - res_columns[col_num++]->insert(database); - res_columns[col_num++]->insert(table); - - res_columns[col_num++]->insert(status.id); - res_columns[col_num++]->insert(status.command); - res_columns[col_num++]->insert(UInt64(status.create_time)); - res_columns[col_num++]->insert(block_partition_ids); - res_columns[col_num++]->insert(block_numbers); - res_columns[col_num++]->insert(parts_in_progress_names); - res_columns[col_num++]->insert(parts_to_do_names); - res_columns[col_num++]->insert(parts_to_do_names.size()); - res_columns[col_num++]->insert(parts_postpone_reasons_map); - res_columns[col_num++]->insert(status.is_done); - res_columns[col_num++]->insert(status.is_killed); - res_columns[col_num++]->insert(status.latest_failed_part); - res_columns[col_num++]->insert(UInt64(status.latest_fail_time)); - res_columns[col_num++]->insert(status.latest_fail_reason); - res_columns[col_num++]->insert(status.latest_fail_error_code_name); + size_t src_index = 0; + size_t res_index = 0; + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(database); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(table); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.id); + /// Parsing the command costs much more than everything else here, so it is done only when the column is queried. + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(show_secrets ? status.command : hideSecretsInCommand(context, status.command)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.create_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_partition_ids); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(block_numbers); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_in_progress_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_to_do_names.size()); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(parts_postpone_reasons_map); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_done); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.is_killed); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_failed_part); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(UInt64(status.latest_fail_time)); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_reason); + if (columns_mask[src_index++]) + res_columns[res_index++]->insert(status.latest_fail_error_code_name); } } } diff --git a/src/Storages/System/StorageSystemMutations.h b/src/Storages/System/StorageSystemMutations.h index 5341838a65e3..c3f897491fc7 100644 --- a/src/Storages/System/StorageSystemMutations.h +++ b/src/Storages/System/StorageSystemMutations.h @@ -21,8 +21,9 @@ class StorageSystemMutations final : public IStorageSystemOneBlock protected: using IStorageSystemOneBlock::IStorageSystemOneBlock; - void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector) const override; + void fillData(MutableColumns & res_columns, ContextPtr context, const ActionsDAG::Node * predicate, std::vector columns_mask) const override; Block getFilterSampleBlock() const override; + bool supportsColumnsMask() const override { return true; } }; } diff --git a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp index b573828ddee1..444e3d74a08b 100644 --- a/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp +++ b/src/Storages/System/StorageSystemObjectStorageQueueSettings.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( const ActionsDAG::Node *, std::vector) const { + const bool display_secrets = canDisplaySecrets(context); auto add_table = [&]( const DatabaseTablesIteratorPtr & it, StorageObjectStorageQueue & storage) { @@ -52,7 +54,7 @@ void StorageSystemObjectStorageQueueSettings::fillData( auto constraints_and_current_profiles = context->getSettingsConstraintsAndCurrentProfiles(); const auto & constraints = constraints_and_current_profiles->constraints; MutableColumnsAndConstraints params(res_columns, constraints); - storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage); + storage.getSettings().dumpToSystemEngineSettingsColumns(params, it->name(), it->databaseName(), storage, display_secrets); }; const auto access = context->getAccess(); diff --git a/src/TableFunctions/ITableFunction.cpp b/src/TableFunctions/ITableFunction.cpp index fcd19f5b5408..9624c7464e48 100644 --- a/src/TableFunctions/ITableFunction.cpp +++ b/src/TableFunctions/ITableFunction.cpp @@ -55,11 +55,22 @@ void ITableFunction::checkEngineAccess(ContextPtr context) const context->checkAccess(AccessType::TABLE_ENGINE, engine); } +void ITableFunction::checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const +{ + auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); + if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) + context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); +} + ColumnsDescription ITableFunction::getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const { /// Resolving table structure is always a read operation. checkSourceAccess(context, /*is_insert_query*/ false); checkEngineAccess(context); + /// Resolving the structure may access the source (e.g. schema inference fetches a URL), so it must be + /// gated in the same way as `execute`: otherwise `DESCRIBE TABLE url(...)` would let a user who cannot + /// run the table function (e.g. under `readonly = 1`) make the server request an endpoint. + checkCreateTemporaryTableAccess(context, /*is_insert_query*/ false); return getActualTableStructure(context, is_insert_query); } @@ -73,9 +84,7 @@ StoragePtr ITableFunction::execute(const ASTPtr & ast_function, ContextPtr conte /// Deliberately not under `check_source_access`: no caller takes over the engine check. checkEngineAccess(context); - auto table_function_properties = TableFunctionFactory::instance().tryGetProperties(getName()); - if (is_insert_query || !(table_function_properties && table_function_properties->allow_readonly)) - context->checkAccess(AccessType::CREATE_TEMPORARY_TABLE); + checkCreateTemporaryTableAccess(context, is_insert_query); auto context_to_use = use_global_context ? context->getGlobalContext() : context; diff --git a/src/TableFunctions/ITableFunction.h b/src/TableFunctions/ITableFunction.h index 0aeb1d497e1a..6579ff2ce25a 100644 --- a/src/TableFunctions/ITableFunction.h +++ b/src/TableFunctions/ITableFunction.h @@ -88,8 +88,9 @@ class ITableFunction : public std::enable_shared_from_this StoragePtr execute(const ASTPtr & ast_function, ContextPtr context, const std::string & table_name, ColumnsDescription cached_columns_ = {}, bool use_global_context = false, bool is_insert_query = false) const; - /// Returns actual table structure after enforcing source access checks. - /// Use this instead of getActualTableStructure() from outside execute(). + /// Returns actual table structure after enforcing the same access checks as `execute`: source, engine, + /// and `CREATE TEMPORARY TABLE` (for table functions not allowed in readonly mode). + /// Use this instead of `getActualTableStructure` from outside `execute`. ColumnsDescription getActualTableStructureWithAccess(ContextPtr context, bool is_insert_query) const; /// Check that the user has the required source access (e.g. READ ON MYSQL, WRITE ON S3). @@ -98,6 +99,10 @@ class ITableFunction : public std::enable_shared_from_this /// Check the `TABLE ENGINE` grant, for engines that opt in via `requiresTableEngineGrant`. void checkEngineAccess(ContextPtr context) const; + /// Check the `CREATE TEMPORARY TABLE` grant, required to use a table function unless it is allowed + /// in readonly mode and the query is not an insert. + void checkCreateTemporaryTableAccess(ContextPtr context, bool is_insert_query) const; + virtual ~ITableFunction() = default; protected: diff --git a/src/configure_config.cmake b/src/configure_config.cmake index 39b16eeebbe7..0d3a4da3abaa 100644 --- a/src/configure_config.cmake +++ b/src/configure_config.cmake @@ -150,6 +150,9 @@ endif() if (TARGET ch_contrib::parquet) set(USE_PARQUET 1) set(USE_ARROW 1) +endif() +# The ORC reader and writer are implemented in ClickHouse and need only the compression libraries. +if (TARGET ch_contrib::snappy) set(USE_ORC 1) endif() if (TARGET ch_contrib::liburing) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 26adc0ca8970..08f04e9081b2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -59,8 +59,38 @@ def tune_local_port_range(): ) +def is_xdist_replacement_worker(): + """True when this worker was spawned to replace one that died mid-run. + + `pytest-xdist` numbers a replacement past the size of the original pool, so `gw8` in a pool of + eight (`gw0`..`gw7`) is a replacement. A replacement starts a fresh pytest *session*, which + re-runs every session-scoped fixture - and `cleanup_environment` kills every container on the + host, including the ones the workers that are still running own. One worker dying, from an OOM + kill for instance, would otherwise take the containers of the whole job with it. + """ + worker = os.environ.get("PYTEST_XDIST_WORKER", "") + count = os.environ.get("PYTEST_XDIST_WORKER_COUNT", "") + if not worker.startswith("gw") or not count.isdigit(): + return False + + index = worker.removeprefix("gw") + if not index.isdigit(): + return False + + return int(index) >= int(count) + + @pytest.fixture(autouse=True, scope="session") def cleanup_environment(): + if is_xdist_replacement_worker(): + logging.info( + "Worker %s replaces a worker that died, so the containers of the workers which are " + "still running are not ours to clean up. Skipping the environment cleanup.", + os.environ["PYTEST_XDIST_WORKER"], + ) + yield + return + try: result = run_and_check(["docker ps | wc -l"], shell=True) if int(result) > 1: diff --git a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml index d4ac4986c22d..ad199feefc1e 100644 --- a/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml +++ b/tests/integration/test_allowed_url_from_config/configs/config_with_hosts.xml @@ -2,6 +2,7 @@ host:80 ^[a-z]*\.ru$ + .*\.allowed\.example diff --git a/tests/integration/test_allowed_url_from_config/test.py b/tests/integration/test_allowed_url_from_config/test.py index 78ff4b22d321..b43422300bba 100644 --- a/tests/integration/test_allowed_url_from_config/test.py +++ b/tests/integration/test_allowed_url_from_config/test.py @@ -72,6 +72,43 @@ def test_azure_host_filter_before_client_creation(start_cluster, query): assert node5.query(container_requests) == before +def test_object_storage_queue_move_destination_host_filter(start_cluster): + # The source is on an allowed host (`host:80`), so only the move destination can be rejected. `node1` has no + # Keeper, so a rejection with "not allowed" must come from the settings validation, which runs before any + # Keeper access. + s3_queue = ( + "CREATE TABLE s3queue_move_host (x UInt8) " + "ENGINE = S3Queue('http://host:80/bucket/data/', 'key', 'secret', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_uri = '{}', " + "after_processing_move_access_key_id = 'key', after_processing_move_secret_access_key = 'secret'" + ) + azure_queue = ( + "CREATE TABLE azurequeue_move_host (x UInt8) " + "ENGINE = AzureQueue('http://host:80', 'container', '*', 'account', 'YQ==', 'CSV') " + "SETTINGS mode = 'unordered', after_processing = 'move', " + "after_processing_move_connection_string = " + "'DefaultEndpointsProtocol=http;AccountName=account;AccountKey=YQ==;BlobEndpoint=http://host:123/account;', " + "after_processing_move_container = 'dst'" + ) + + try: + error = node1.query_and_get_error(s3_queue.format("http://host:123/bucket/")) + assert "not allowed" in error, error + + error = node1.query_and_get_error( + azure_queue, settings={"azure_sdk_max_retries": 0} + ) + assert "not allowed" in error, error + + # Control: an allowed destination passes the host check and only fails later, on the missing Keeper. + error = node1.query_and_get_error(s3_queue.format("http://host:80/bucket/")) + assert "not allowed" not in error, error + finally: + node1.query("DROP TABLE IF EXISTS s3queue_move_host SYNC") + node1.query("DROP TABLE IF EXISTS azurequeue_move_host SYNC") + + def test_config_with_only_primary_hosts(start_cluster): assert ( node2.query( @@ -217,6 +254,34 @@ def test_mysql_dictionary_host_filter(start_cluster): node5.query("DROP DICTIONARY IF EXISTS default.test_mysql_host_filter") +def test_mysql_database_host_filter(start_cluster): + # node5 denies all hosts; the check runs before any connection attempt. + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('10.0.0.1:3306', 'db', 'u', 'p')" + ) + node5.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nc AS " + "host = '10.0.0.1', port = 3306, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node5.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nc)" + ) + node5.query("DROP NAMED COLLECTION test_mysql_db_filter_nc") + + # node1's suffix rule would match the whole string, but the connector stops at the NUL; reject it. + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL('127.0.0.1\\0.allowed.example:1', 'db', 'u', 'p')" + ) + node1.query( + "CREATE NAMED COLLECTION IF NOT EXISTS test_mysql_db_filter_nul_nc AS " + "host = '127.0.0.1\\0.allowed.example', port = 1, database = 'db', user = 'u', password = 'p'" + ) + assert "not allowed" in node1.query_and_get_error( + "CREATE DATABASE test_mysql_db_filter ENGINE = MySQL(test_mysql_db_filter_nul_nc)" + ) + node1.query("DROP NAMED COLLECTION test_mysql_db_filter_nul_nc") + + def test_mysql_dictionary_replica_host_filter(start_cluster): """MySQL dictionary source with REPLICA(...) syntax should respect RemoteHostFilter.""" # Covers the replica branch: if (config.has(settings_config_prefix + ".replica")) @@ -335,3 +400,58 @@ def test_table_function_remote(start_cluster): "SELECT * FROM remote('localhost:800', system, metrics)" ) ) + + +# The catalog is built lazily on first use, so a query on a table connects to the metastore. +def hive_catalog_error(node, database, url): + node.query( + f"CREATE DATABASE {database} ENGINE = DataLakeCatalog('{url}') " + "SETTINGS catalog_type = 'hive', warehouse = 'test_warehouse'", + settings={"allow_experimental_database_hms_catalog": 1}, + ) + return node.query_and_get_error(f"SELECT * FROM {database}.`ns.tbl`") + + +def test_hive_catalog_host_filter(start_cluster): + url = "thrift://localhost:1" + try: + # Control first: `node4` declares no `remote_url_allow_hosts` at all, so its filter stays + # uninitialized and allows everything - the same statement gets past the check and fails at + # the network instead. Without this arm, a filter that rejected everything would also pass. + error = hive_catalog_error(node4, "test_hive_host_filter", url) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + + # `node5` declares an empty `remote_url_allow_hosts`, which allows nothing. + error = hive_catalog_error(node5, "test_hive_host_filter", url) + assert "UNACCEPTABLE_URL" in error, error + # The check must run before the connect, so the refusal carries no connection error. + assert "Connection refused" not in error, error + finally: + node4.query("DROP DATABASE IF EXISTS test_hive_host_filter") + node5.query("DROP DATABASE IF EXISTS test_hive_host_filter") + + +def test_hive_catalog_host_filter_rejects_nul(start_cluster): + try: + # Control: the suffix rule in `config_with_hosts.xml` admits this host, so it gets past the + # filter and fails at name resolution instead. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://hms.allowed.example:1" + ) + if "USE_HIVE" in error: + pytest.skip("ClickHouse was built without Hive support") + assert "UNACCEPTABLE_URL" not in error, error + node1.query("DROP DATABASE test_hive_host_filter_nul") + + # The same rule matches the whole string including the NUL, but `getaddrinfo` would stop at the + # NUL and connect to 127.0.0.1. The host must be refused before any connection attempt. + error = hive_catalog_error( + node1, "test_hive_host_filter_nul", "thrift://127.0.0.1\\0.allowed.example:1" + ) + assert "BAD_ARGUMENTS" in error, error + assert "Unexpected character" in error, error + assert "Connection refused" not in error, error + finally: + node1.query("DROP DATABASE IF EXISTS test_hive_host_filter_nul") diff --git a/tests/integration/test_arrowflight_interface/test.py b/tests/integration/test_arrowflight_interface/test.py index 634ade912d13..4a1c124f986e 100644 --- a/tests/integration/test_arrowflight_interface/test.py +++ b/tests/integration/test_arrowflight_interface/test.py @@ -519,6 +519,43 @@ def test_doget_multiple_chunks(): assert actual[1].column("name").equals(pa.chunked_array([pa.array(["cde"], type=pa.string())])) +# A result is split across several Arrow arrays only when it exceeds the 32-bit offsets of the +# String/Binary/List buffers, so a small one must arrive as a single chunk per column for every type. +def test_doget_single_chunk_per_column(): + node.query( + """ + CREATE TABLE mytable ( + id Int64, + s String, + ns Nullable(String), + lc LowCardinality(String), + arr Array(String), + m Map(String, String), + t Tuple(String, String), + fs FixedString(3) + ) ORDER BY id + """ + ) + node.query( + """ + INSERT INTO mytable SELECT + number, toString(number), if(number % 2, NULL, toString(number)), toString(number % 2), + [toString(number)], map('k', toString(number)), (toString(number), 'x'), toFixedString('abc', 3) + FROM numbers(4) + """ + ) + + client, options = get_client() + + descriptor = flight.FlightDescriptor.for_command("SELECT * FROM mytable ORDER BY id") + flight_info = client.get_flight_info(descriptor, options) + table = client.do_get(flight_info.endpoints[0].ticket, options).read_all() + + assert table.num_rows == 4 + for name, column in zip(table.schema.names, table.columns): + assert column.num_chunks == 1, f"column {name} was split into {column.num_chunks} chunks" + + # We don't support any formats different from "Arrow". def test_doget_cmd_select_invalid_format(): node.query("CREATE TABLE mytable (id Int64, name String) ORDER BY id") diff --git a/tests/integration/test_backup_restore_new/test.py b/tests/integration/test_backup_restore_new/test.py index d317a99a0b49..0df792a10ecc 100644 --- a/tests/integration/test_backup_restore_new/test.py +++ b/tests/integration/test_backup_restore_new/test.py @@ -1474,6 +1474,131 @@ def test_system_users_required_privileges(): instance.query("DROP USER u2") +# Access backups include every entity of a type, so these checks need this module's isolated server. +def test_restore_row_policy_replace_requires_scoped_drop(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROW POLICY ON test.table TO u2") + instance.query( + "CREATE ROW POLICY rowpol1 ON test.table AS RESTRICTIVE USING 1 TO ALL" + ) + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.row_policies TO {backup_name}") + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + + restore = f"RESTORE TABLE system.row_policies FROM {backup_name}" + select_filter = "SELECT select_filter FROM system.row_policies WHERE short_name = 'rowpol1' AND database = 'test' AND table = 'table'" + instance.query(f"{restore} SETTINGS create_access='if-not-exists'", user="u2") + assert instance.query(select_filter) == "owner = 1\n" + + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("GRANT DROP ROW POLICY ON test.another_table TO u2") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "owner = 1\n" + + instance.query("DROP ROW POLICY rowpol1 ON test.table") + error = instance.query_and_get_error( + f"{restore} SETTINGS create_access='replace'", user="u2" + ) + assert "ACCESS_DENIED" in error + assert "DROP ROW POLICY" in error + assert instance.query(select_filter) == "" + + instance.query(f"{restore} SETTINGS create_access='create'", user="u2") + assert instance.query(select_filter) == "1\n" + instance.query("ALTER ROW POLICY rowpol1 ON test.table USING owner = 1") + instance.query("GRANT DROP ROW POLICY ON test.table TO u2") + instance.query(f"{restore} SETTINGS create_access='replace'", user="u2") + assert instance.query(select_filter) == "1\n" + + +@pytest.mark.parametrize( + "kind,system_table,target", [("USER", "users", "u1"), ("ROLE", "roles", "r1")] +) +def test_restore_access_partial_revoke_cannot_cancel_drop(kind, system_table, target): + instance.query(f"CREATE {kind} {target} SETTINGS max_threads = 1") + instance.query(f"GRANT DROP {kind} ON * TO {target}") + instance.query(f"REVOKE DROP {kind} ON {target} FROM {target}") + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.{system_table} TO {backup_name}") + instance.query(f"ALTER {kind} {target} SETTINGS max_threads = 2") + + # Create the actor after the backup so its grants cannot mask the target's partial revoke. + instance.query("CREATE USER u2") + instance.query(f"GRANT CREATE {kind} ON {target} TO u2") + instance.query(f"GRANT DROP {kind} ON * TO u2 WITH GRANT OPTION") + instance.query(f"REVOKE DROP {kind} ON {target} FROM u2") + restore = f"RESTORE TABLE system.{system_table} FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert f"DROP {kind}" in error + assert "max_threads = 2" in instance.query(f"SHOW CREATE {kind} {target}") + + # Ordinary `DROP` is sufficient; the target's grants exclude `DROP` on itself. + instance.query(f"GRANT DROP {kind} ON {target} TO u2") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query(f"SHOW CREATE {kind} {target}") + + +def test_restore_access_partial_revokes_preserve_grant_and_table_requirements(): + instance.query("CREATE DATABASE test") + instance.query( + "CREATE TABLE test.table (owner UInt64) ENGINE = MergeTree ORDER BY owner" + ) + instance.query("INSERT INTO test.table VALUES (1)") + instance.query("CREATE ROLE r1 SETTINGS max_threads = 1") + instance.query("GRANT SELECT, INSERT ON test.* TO r1 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM r1") + instance.query("REVOKE INSERT ON test.table FROM r1") + backup_name = new_backup_name() + backup_tables = "TABLE system.roles, TABLE test.table" + instance.query(f"BACKUP {backup_tables} TO {backup_name}") + instance.query("ALTER ROLE r1 SETTINGS max_threads = 2") + + instance.query("CREATE USER u2") + instance.query("GRANT CREATE ROLE, DROP ROLE ON r1 TO u2") + instance.query("GRANT CREATE TABLE ON test.table TO u2") + instance.query("GRANT SELECT, INSERT ON test.* TO u2 WITH GRANT OPTION") + instance.query("REVOKE GRANT OPTION FOR SELECT ON test.table FROM u2") + restore = f"RESTORE TABLE system.roles FROM {backup_name} SETTINGS create_access='replace'" + error = instance.query_and_get_error(restore, user="u2") + assert "ACCESS_DENIED" in error + assert "SELECT" in error + assert "WITH GRANT OPTION" in error + assert "max_threads = 2" in instance.query("SHOW CREATE ROLE r1") + + instance.query("GRANT SELECT ON test.table TO u2 WITH GRANT OPTION") + instance.query(restore, user="u2") + assert "max_threads = 1" in instance.query("SHOW CREATE ROLE r1") + + instance.query("TRUNCATE TABLE test.table") + instance.query("REVOKE INSERT ON test.table FROM u2") + restore_with_table = ( + f"RESTORE {backup_tables} FROM {backup_name} SETTINGS create_access='replace'" + ) + error = instance.query_and_get_error(restore_with_table, user="u2") + assert "ACCESS_DENIED" in error + assert "INSERT" in error + assert instance.query("SELECT count() FROM test.table") == "0\n" + + instance.query("GRANT INSERT ON test.table TO u2") + instance.query(restore_with_table, user="u2") + assert instance.query("SELECT * FROM test.table") == "1\n" + + def test_system_users_async(): instance.query("CREATE USER u1 IDENTIFIED BY 'qwe123' SETTINGS custom_c = 3") diff --git a/tests/integration/test_crash_log/test.py b/tests/integration/test_crash_log/test.py index 3c11c28add8e..9990917c913c 100644 --- a/tests/integration/test_crash_log/test.py +++ b/tests/integration/test_crash_log/test.py @@ -55,9 +55,14 @@ def test_crash_log_synchronous(started_node): wait_for_clickhouse_stop(started_node) started_node.restart_clickhouse() crashes_count += 1 + # Report the rows that are there. Without them a lost row leaves only `'1' == '2'` behind, + # which says nothing about which of the two crashes failed to record itself. assert ( started_node.query("SELECT COUNT(*) FROM system.crash_log") == f"{crashes_count}\n" + ), started_node.query( + "SELECT event_time_microseconds, signal, signal_description, query " + "FROM system.crash_log ORDER BY event_time_microseconds FORMAT Vertical" ) diff --git a/tests/integration/test_database_glue/test.py b/tests/integration/test_database_glue/test.py index 585fe2899b5c..eac84dd81389 100644 --- a/tests/integration/test_database_glue/test.py +++ b/tests/integration/test_database_glue/test.py @@ -588,6 +588,62 @@ def test_timestamps(started_cluster): assert node.query(f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}`") == "2024-01-01 12:00:00.000000\t2024-01-01 12:00:00.000000\n" +def test_timestamp_types_cache_does_not_keep_metadata(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_ts_cache_{uuid.uuid4().hex}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + database_name = f"db_{test_ref}" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + schema = Schema( + NestedField(field_id=1, name="timestamp", field_type=TimestampType(), required=False), + NestedField(field_id=2, name="timestamptz", field_type=TimestamptzType(), required=False), + ) + table = create_table(catalog, root_namespace, table_name, schema, dir=test_ref) + + create_clickhouse_glue_database(started_cluster, node, database_name) + + def cache_metrics(): + return [ + int(value) + for value in node.query( + "SELECT value FROM system.metrics " + "WHERE metric IN ('GlueCatalogSchemaCacheBytes', 'GlueCatalogSchemaCacheEntries') ORDER BY metric" + ).split() + ] + + bytes_before, entries_before = cache_metrics() + + row = pa.Table.from_pylist( + [{"timestamp": datetime(2024, 1, 1, 12), "timestamptz": datetime(2024, 1, 1, 12, tzinfo=pytz.UTC)}] + ) + versions = 30 + for _ in range(versions): + table.append(row) + description = node.query(f"DESCRIBE TABLE {database_name}.`{root_namespace}.{table_name}`") + assert [line.split("\t")[1] for line in description.splitlines()] == [ + "Nullable(DateTime64(6))", + "Nullable(DateTime64(6, \\'UTC\\'))", + ] + + bytes_after, entries_after = cache_metrics() + assert entries_after - entries_before == versions + + metadata_size = int( + node.query( + f"SELECT max(_size) FROM s3('http://minio1:9001/warehouse-glue/{test_ref}/metadata/*.metadata.json', " + f"'{minio_access_key}', '{minio_secret_key}', 'One')" + ) + ) + assert bytes_after - bytes_before < metadata_size + + node.query(f"DROP DATABASE {database_name}") + + def test_insert(started_cluster): node = started_cluster.instances["node1"] diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index e979a99c18b8..fcdcf17d2989 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -806,3 +806,500 @@ def test_invalid_auth_header_format(started_cluster): """ ) assert "Invalid auth header format" in str(err.value) + + +def test_writes_mutate_update(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_update_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String, y Int32)") + + node.query(f"INSERT INTO {table_ref} VALUES ('123', 1);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456', 2);", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('999', 3);", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\t1\n456\t2\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = '777' WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n777\t1\n999\t3\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'goshan dr' WHERE x = '777';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\t2\n999\t3\ngoshan dr\t1\n" + + node.query(f"ALTER TABLE {table_ref} UPDATE x = 'pudge1000-7' WHERE y = 2;", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "999\t3\ngoshan dr\t1\npudge1000-7\t2\n" + + +def test_writes_mutate_delete(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_writes_mutate_delete_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + write_settings = {"allow_insert_into_iceberg": 1, "write_full_path_in_iceberg_metadata": 1} + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table(started_cluster, node, root_namespace, table_name, "(x String)") + + # DELETE on empty table is a no-op. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "" + + node.query(f"INSERT INTO {table_ref} VALUES ('123');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('456');", settings=write_settings) + node.query(f"INSERT INTO {table_ref} VALUES ('789'), ('890'), ('999');", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + # No-match DELETE keeps the table intact. + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = 'pudge1000-7';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n789\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '789';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "123\n456\n890\n999\n" + + # Lightweight DELETE syntax should work identically against catalog tables. + node.query(f"DELETE FROM {table_ref} WHERE x = '123';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n999\n" + + node.query(f"ALTER TABLE {table_ref} DELETE WHERE x = '999';", settings=write_settings) + assert node.query(f"SELECT * FROM {table_ref} ORDER BY ALL") == "456\n890\n" + + +def test_iceberg_file_progress_callback(started_cluster): + """ + Regression test for the `IcebergIterator::next` file-progress callback wiring (PR #105413). + + `IcebergIterator` stored a `FileProgressCallback` but never invoked it, so the + per-query `Progress.total_bytes_to_read` stayed at zero for Iceberg scans and + the progress bar showed no estimate. The fix invokes the callback with the data + file size for every object info returned. The assertion below uses the + `FileProgressCallbackInvocations` ProfileEvent, which is incremented inside the + callback lambda installed by `TCPHandler::setFileProgressCallback`, so removing + the `callback(...)` call in `IcebergIterator::next` makes this event stay at + zero for the test query. + """ + node = started_cluster.instances["node1"] + + test_ref = f"test_progress_callback_{uuid.uuid4().hex[:8]}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(root_namespace) + + table = create_table( + catalog, + root_namespace, + table_name, + DEFAULT_SCHEMA, + PartitionSpec(), + DEFAULT_SORT_ORDER, + ) + + # Append a small but non-empty batch so the iterator returns a data-file entry. + num_rows = 50 + data = [generate_record() for _ in range(num_rows)] + df = pa.Table.from_pylist(data) + table.append(df) + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + # `node.query` uses native TCP, the only protocol path where + # `setFileProgressCallback` is currently wired. `SELECT *` with `FORMAT Null` + # forces a full scan: the metadata-only `SELECT count()` path resolves the row + # count from manifest statistics and bypasses the data-file iterator. + query_id = f"iceberg_progress_callback_{uuid.uuid4().hex}" + node.query( + f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}` FORMAT Null", + query_id=query_id, + ) + + node.query("SYSTEM FLUSH LOGS") + + # `FileProgressCallbackInvocations` is incremented inside the lambda installed + # by `TCPHandler::setFileProgressCallback`. For an Iceberg-table scan it can + # only fire from `IcebergIterator::next` (the generic + # `StorageObjectStorageSource::KeysIterator` path is replaced by + # `IcebergIterator` for Iceberg storage), so a non-zero value proves the + # iterator's `callback(FileProgress(...))` invocation was executed. + profile_event_value = node.query( + f""" + SELECT ProfileEvents['FileProgressCallbackInvocations'] + FROM system.query_log + WHERE query_id = '{query_id}' AND type = 'QueryFinish' + ORDER BY event_time_microseconds DESC + LIMIT 1 + """ + ).strip() + assert profile_event_value, ( + f"`system.query_log` has no `QueryFinish` row for query_id={query_id}." + ) + file_progress_callback_invocations = int(profile_event_value) + assert file_progress_callback_invocations > 0, ( + f"Expected `FileProgressCallbackInvocations` > 0 from the Iceberg scan, " + f"got {file_progress_callback_invocations}. " + f"`IcebergIterator::next` did not invoke the file-progress callback " + f"(regression of PR #105413 wiring)." + ) + + +def test_alter_database_settings_not_supported(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"iceberg_alter_settings_{uuid.uuid4().hex}" + create_clickhouse_iceberg_database(started_cluster, node, db_name) + + fake_token = f"fake_secret_token_{uuid.uuid4().hex}" + + qid_alter = uuid.uuid4().hex + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = '{fake_token}'", + query_id=qid_alter, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING no_such_setting = 1" + ) + assert "BAD_ARGUMENTS" in error or "UNKNOWN_SETTING" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "other_warehouse" not in show_result + assert "onelake_bearer_token" not in show_result + node.query( + f"SELECT name FROM system.tables WHERE database = '{db_name}' SETTINGS show_data_lake_catalogs_in_system_tables = true" + ) + + node.query("SYSTEM FLUSH LOGS system.query_log") + logged_query = node.query( + f"SELECT arrayStringConcat(groupArray(query), '\\n') FROM system.query_log WHERE query_id = '{qid_alter}'" + ) + assert fake_token not in logged_query + assert "[HIDDEN]" in logged_query + + node.query(f"DROP DATABASE {db_name}") + + glue_db_name = f"glue_alter_settings_{uuid.uuid4().hex}" + node.query( + f""" + ATTACH DATABASE {glue_db_name} ENGINE = DataLakeCatalog('http://fake-glue:1') + SETTINGS catalog_type = 'glue', region = 'us-east-1', storage_endpoint = 'http://fake-glue:1/x' + """ + ) + error = node.query_and_get_error( + f"ALTER DATABASE {glue_db_name} MODIFY SETTING region = 'eu-west-1'" + ) + assert "NOT_IMPLEMENTED" in error + node.query(f"DROP DATABASE {glue_db_name}") + + +def test_alter_database_settings_rest_auth_header(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"rest_alter_auth_header_{uuid.uuid4().hex}" + old_header = f"Authorization: Bearer old_{uuid.uuid4().hex}" + new_header = f"Authorization: Bearer new_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-rest:1/api') + SETTINGS catalog_type = 'rest', warehouse = 'wh', auth_header = '{old_header}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING auth_header = '{new_header}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING catalog_credential = 'id:secret'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_header not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_header in engine_full_with_secrets + assert old_header not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_persistence(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_alter_persist_{uuid.uuid4().hex}" + old_token = f"secret_token_{uuid.uuid4().hex}" + new_token = f"secret_token_{uuid.uuid4().hex}" + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-0', onelake_tenant_id = 'tenant-1', onelake_bearer_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_tenant_id = 'tenant-2', onelake_bearer_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_client_id = 'client-1'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING warehouse = 'other_warehouse'" + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = ''" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert new_token not in show_result + assert old_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert "tenant-2" in engine_full_with_secrets + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.restart_clickhouse() + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert "tenant-2" in show_result + assert "tenant-0" not in show_result + assert "tenant-1" not in show_result + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert "tenant-2" in engine_full + assert "tenant-0" not in engine_full + assert "tenant-1" not in engine_full + assert new_token not in engine_full + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + node.query(f"DROP DATABASE {db_name}") + + +def test_alter_database_settings_onelake_refresh_token(started_cluster): + node = started_cluster.instances["node1"] + + db_name = f"onelake_refresh_token_{uuid.uuid4().hex}" + old_token = f"refresh_token_{uuid.uuid4().hex}" + new_token = f"refresh_token_{uuid.uuid4().hex}" + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_refresh_token = '{old_token}' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', oauth_server_use_request_body = 0 + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "oauth_server_use_request_body" in error + + # In refresh-token mode the catalog access token is reused for Azure storage, + # so a non-storage auth_scope is rejected at CREATE time. + error = node.query_and_get_error( + f""" + CREATE DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}', auth_scope = 'api://my-catalog/.default' + """, + settings={"allow_database_iceberg": 1}, + ) + assert "BAD_ARGUMENTS" in error + assert "auth_scope" in error + + node.query( + f""" + ATTACH DATABASE {db_name} ENGINE = DataLakeCatalog('http://fake-onelake:1/api') + SETTINGS catalog_type = 'onelake', warehouse = 'wh', onelake_tenant_id = 'tenant-1', onelake_client_id = 'client-1', onelake_refresh_token = '{old_token}' + """ + ) + + node.query( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_refresh_token = '{new_token}'" + ) + + error = node.query_and_get_error( + f"ALTER DATABASE {db_name} MODIFY SETTING onelake_bearer_token = 'token'" + ) + assert "BAD_ARGUMENTS" in error + + show_result = node.query(f"SHOW CREATE DATABASE {db_name}") + assert new_token not in show_result + assert "[HIDDEN]" in show_result + + node.restart_clickhouse() + + engine_full_with_secrets = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'", + settings={"format_display_secrets_in_show_and_select": 1}, + ) + assert new_token in engine_full_with_secrets + assert old_token not in engine_full_with_secrets + + engine_full = node.query( + f"SELECT engine_full FROM system.databases WHERE name = '{db_name}'" + ) + assert new_token not in engine_full + + node.query(f"DROP DATABASE {db_name}") + + +def test_catalog_listing_error_surfaces_in_system_tables(started_cluster): + """ + Regression test: an error from the catalog while listing tables (e.g. expired + catalog credentials) must not be silently turned into an empty listing when the + user explicitly opted into showing datalake catalogs in system tables with + show_data_lake_catalogs_in_system_tables=1. Without the opt-in the old tolerant + behaviour is kept (system tables must not fail because of one broken catalog). + """ + node = started_cluster.instances["node1"] + + root_namespace = f"clickhouse_{uuid.uuid4()}" + namespace = f"{root_namespace}_test_listing_error" + + catalog = load_catalog_impl(started_cluster) + catalog.create_namespace(namespace) + create_table(catalog, namespace, "table_x") + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + + node.query("SYSTEM ENABLE FAILPOINT datalake_get_tables_throw") + try: + assert ( + node.query( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}'" + ).strip() + == "0" + ) + + error = node.query_and_get_error( + f"SELECT count() FROM system.iceberg_files WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + + error = node.query_and_get_error( + f"SELECT name, engine FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "Injected catalog listing failure" in error + finally: + node.query("SYSTEM DISABLE FAILPOINT datalake_get_tables_throw") + + result = node.query( + f"SELECT name FROM system.tables WHERE database = '{CATALOG_NAME}' " + "SETTINGS show_data_lake_catalogs_in_system_tables = 1" + ) + assert "table_x" in result + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") + + +def test_catalog_commit_conflict_reaches_caller_at_once(started_cluster): + node = started_cluster.instances["node1"] + + test_ref = f"test_catalog_commit_conflict_{uuid.uuid4()}" + table_name = f"{test_ref}_table" + root_namespace = f"{test_ref}_namespace" + table_ref = f"{CATALOG_NAME}.`{root_namespace}.{table_name}`" + + create_clickhouse_iceberg_database(started_cluster, node, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node, root_namespace, table_name, "(x UInt64)" + ) + + # Every sink reads the branch tip in its constructor, and all `max_insert_threads` sinks are + # constructed before the pipeline starts, so all but one of them commit against a stale parent + # and are refused with `409`. That makes the conflict a property of the plan rather than a race. + num_writers = 4 + query_id = uuid.uuid4().hex + node.query( + f"INSERT INTO {table_ref} SELECT number FROM numbers_mt(4000000)", + query_id=query_id, + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + "max_insert_threads": num_writers, + "max_threads": num_writers, + }, + ) + + node.query("SYSTEM FLUSH LOGS system.text_log") + + conflicts, http_requests = map( + int, + node.query( + f""" + SELECT + countIf(logger_name LIKE 'RestCatalog%' AND message LIKE '%updateMetadata conflict%'), + countIf(logger_name = 'ReadWriteBufferFromHTTP') + FROM system.text_log + WHERE query_id = '{query_id}' AND message LIKE '%409%' + """ + ).split(), + ) + + assert conflicts, ( + "no writer was refused, so nothing about conflict handling was exercised" + ) + assert http_requests == conflicts, ( + f"{conflicts} refused commit(s) cost {http_requests} catalog requests, so a conflict is " + f"resent with backoff instead of being handed back to the sink at once" + ) + + assert int(node.query(f"SELECT count() FROM {table_ref}")) == 4000000 + + node.query(f"DROP DATABASE IF EXISTS {CATALOG_NAME}") diff --git a/tests/integration/test_dotnet_client/test.py b/tests/integration/test_dotnet_client/test.py index 76778a84edbd..80fea52d791a 100644 --- a/tests/integration/test_dotnet_client/test.py +++ b/tests/integration/test_dotnet_client/test.py @@ -54,11 +54,14 @@ def test_dotnet_client(started_cluster, dotnet_container): reference = fp.read() code, (stdout, stderr) = dotnet_container.exec_run( - "dotnet run --host {host} --port {port} --user default --password 123 --database default".format( + "dotnet /client/out/clickhouse.test.dll --host {host} --port {port} --user default --password 123 --database default".format( host=started_cluster.get_instance_ip("node"), port=8123 ), demux=True, ) - assert code == 0 - assert stdout == reference + # These two streams exist nowhere else: the client runs in its own container and nothing in the + # job collects its output. Reporting them here is what makes a client that died on a signal + # diagnosable at all, instead of leaving a bare exit code behind. + assert code == 0, f"stdout:\n{stdout!r}\nstderr:\n{stderr!r}" + assert stdout == reference, f"stderr:\n{stderr!r}" diff --git a/tests/integration/test_git_import/test.py b/tests/integration/test_git_import/test.py index 13c76498e0a5..e1c6fc623d29 100644 --- a/tests/integration/test_git_import/test.py +++ b/tests/integration/test_git_import/test.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import logging +import re import time import pytest @@ -40,8 +41,24 @@ def clone_git_repository(repo, dir, commit=None): time.sleep(1) +# `ClickHouseCluster` gives the whole container the running server's profraw merge pool +# (`LLVM_PROFILE_FILE=/debug/it-%c%4m.profraw`), which every `docker exec`-ed process inherits. +# A second writer cannot merge into a continuous-mode profile - it records its own writer's counter +# bias - so in a coverage build the profiling runtime writes +# `LLVM Profile Warning: Unable to merge profile data: source profile file is not compatible.` and +# two `File exists` errors to stderr. Give this one-shot process a file of its own: its coverage is +# still collected and it no longer touches the server's pool. +GIT_IMPORT_PROFILE_FILE = "/debug/git-import-%p.profraw" + +# One progress line per processed commit, which `git-import` writes to stderr. +COMMIT_PROGRESS_RE = re.compile(r"^\d+% \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [0-9a-f]{40} ") + + def run_git_import(dir): - command = f"cd {dir} && /usr/bin/clickhouse git-import 2>&1" + command = ( + f"cd {dir} && LLVM_PROFILE_FILE={GIT_IMPORT_PROFILE_FILE} " + "/usr/bin/clickhouse git-import 2>&1" + ) return node.exec_in_container(["bash", "-c", command]) @@ -176,7 +193,15 @@ def test_git_import(): create_tables() insert_into_tables(dir) - assert output.count("\n") == 26 + # `git-import` prints the `git log` command it runs and the commit count to stdout, and one + # progress line per commit to stderr, which the `2>&1` above merges into the same stream. Match + # those shapes instead of counting every newline, so that a line written by anything other than + # `git-import` - a profiling or sanitizer runtime, a loader warning - fails the thing it + # actually broke rather than this count. + lines = output.splitlines() + assert "git log --reverse --no-merges --pretty=%H" in lines, output + assert "Total 24 commits to process." in lines, output + assert sum(1 for line in lines if COMMIT_PROGRESS_RE.match(line)) == 24, output assert node.query("SELECT count() FROM commits") == "24\n" assert node.query("SELECT count() FROM file_changes") == "35\n" assert node.query("SELECT count(), round(avg(indent), 1) FROM line_changes") == TSV( diff --git a/tests/integration/test_keeper_remove_rejoin_leader/test.py b/tests/integration/test_keeper_remove_rejoin_leader/test.py index 8cb03c599d26..e51bbbdc7041 100644 --- a/tests/integration/test_keeper_remove_rejoin_leader/test.py +++ b/tests/integration/test_keeper_remove_rejoin_leader/test.py @@ -28,6 +28,7 @@ import json import os +import re import time import uuid from typing import NamedTuple @@ -132,6 +133,46 @@ def started_cluster(): pass +def _relax_timeouts_for_sanitizer(config_path): + """Rewrite a keeper config with relaxed Raft timeouts for sanitizer builds. + + Under sanitizers (ASan, MSan, TSan) CPU overhead can delay Raft + heartbeats enough to trigger spurious leader elections. This bumps + the heartbeat interval and election timeout so the cluster stays + stable even with 3-5x slowdown. + """ + with open(config_path) as f: + content = f.read() + + content = re.sub( + r"\d+", + "2000", + content, + ) + content = re.sub( + r"\d+", + "5000", + content, + ) + content = re.sub( + r"\d+", + "10000", + content, + ) + # Configs for nodes 1/2/3 omit election timeouts — add them. + if "" not in content: + content = re.sub( + r"([ \t]*)", + r"\g<1> 5000\n" + r"\g<1> 10000\n" + r"\g<1>", + content, + ) + + with open(config_path, "w") as f: + f.write(content) + + def send_rcfg(cluster, node, command, timeout_sec=60): result_str = keeper_utils.send_4lw_cmd( cluster, @@ -183,6 +224,30 @@ def test_leader_election_after_rolling_membership_change(started_cluster): for n in [node1, node2, node3]: keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Under sanitizers, Raft heartbeats can be delayed enough to trigger + # spurious leader elections. Detect and relax timeouts if needed. + if node1.is_built_with_sanitizer(): + # Patch all 6 config files on disk. Nodes 4/5/6 will pick them + # up later when start_keeper copies them into the container. + for i in range(1, 7): + _relax_timeouts_for_sanitizer( + os.path.join(CONFIG_DIR, _get_generated_cfg(node_names, i)) + ) + + # Rolling-restart nodes 1/2/3 so they pick up the relaxed + # timeouts. Only one node is down at a time, so quorum is kept. + for node_obj in [node1, node2, node3]: + cfg_name = _get_generated_cfg(node_names, node_id(node_obj)) + node_obj.stop_clickhouse() + node_obj.copy_file_to_container( + os.path.join(CONFIG_DIR, cfg_name), + "/etc/clickhouse-server/config.d/" + cfg_name, + ) + node_obj.start_clickhouse() + + for n in [node1, node2, node3]: + keeper_utils.wait_until_connected(cluster, n, timeout=60.0) + # Identify the current leader and the two followers dynamically so the # test does not depend on which node wins the initial election. leader = keeper_utils.get_leader(cluster, [node1, node2, node3]) diff --git a/tests/integration/test_mask_sensitive_info/test.py b/tests/integration/test_mask_sensitive_info/test.py index 83dd82d92c8b..7f17c145e335 100644 --- a/tests/integration/test_mask_sensitive_info/test.py +++ b/tests/integration/test_mask_sensitive_info/test.py @@ -725,13 +725,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"icebergAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] # DeltaLake table functions are not available under Memory Sanitizer (Rust code is not instrumented) @@ -742,9 +742,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '{s3_secret_access_key}')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '{s3_secret_access_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '{azure_account_key}')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '{azure_account_key}')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: @@ -764,13 +764,13 @@ def test_table_functions_object_storage_cluster(): f"icebergS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"icebergS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"azureBlobStorageCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"azureBlobStorageCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", f"icebergAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"icebergAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"icebergAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_delta_lake: @@ -780,9 +780,9 @@ def test_table_functions_object_storage_cluster(): f"deltaLakeS3Cluster('{ch_cluster}', '{s3_url}', '{s3_access_key_id}', '[HIDDEN]')", f"deltaLakeS3Cluster('{ch_cluster}', {named_collection}, url = '{s3_url}', access_key_id = '{s3_access_key_id}', secret_access_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{azure_storage_account_url}', 'test', 'test', '{azure_account_name}', '[HIDDEN]')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container_name = 'test', blobpath = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, storage_account_url = '{azure_storage_account_url}', container = 'test', blob_path = 'test', account_name = '{azure_account_name}', account_key = '[HIDDEN]')", f"deltaLakeAzureCluster('{ch_cluster}', '{masked_azure_connection_string}', 'test', 'test')", - f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container_name = 'test', blobpath = 'test')", + f"deltaLakeAzureCluster('{ch_cluster}', {named_collection}, connection_string = '{masked_azure_connection_string}', container = 'test', blob_path = 'test')", ] if has_paimon: diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..362c39c90ed8 --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,11 @@ + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py new file mode 100644 index 000000000000..3996927d149f --- /dev/null +++ b/tests/integration/test_refreshable_mv_definer_interserver_secret/test.py @@ -0,0 +1,102 @@ +import pytest + +from helpers.cluster import ClickHouseCluster, QueryRuntimeException + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + with_zookeeper=True, +) + +TENANT = {"user": "tenant", "password": "tpass"} + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def test_scheduled_refresh_of_definer_view_carries_definer_to_remote_shard( + started_cluster, +): + # Protected data lives only on node2. The tenant exists on both nodes but has no grant on it. + node2.query( + """ + CREATE DATABASE lab; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + CREATE TABLE lab.secrets (id UInt64, payload String) ENGINE = MergeTree ORDER BY id; + INSERT INTO lab.secrets VALUES (1, 'a'), (2, 'b'), (3, 'c'); + """ + ) + # With `table_engines_require_grant = false`, `TABLE ENGINE ON Distributed` is revoked unless the + # user also has `READ` and `WRITE` on the `REMOTE` source. + node1.query( + """ + CREATE DATABASE tenant_db; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT CREATE TABLE, SELECT, INSERT ON tenant_db.* TO tenant; + GRANT TABLE ENGINE ON Distributed TO tenant; + GRANT READ, WRITE ON REMOTE TO tenant; + """ + ) + + node1.query( + """ + CREATE TABLE tenant_db.dist (id UInt64, payload String) + ENGINE = Distributed('secure', 'lab', 'secrets', rand()); + CREATE TABLE tenant_db.target + (id UInt64, payload String, current_user String, authenticated_user String) + ENGINE = MergeTree ORDER BY id; + """, + **TENANT, + ) + + # A direct read through the Distributed table is denied on the remote shard. + assert "ACCESS_DENIED" in node1.query_and_get_error( + "SELECT * FROM tenant_db.dist", **TENANT + ) + + # The shard also checks the allowed hosts of the definer against `initial_address`. A scheduled + # refresh has no client, so it must present itself as coming from the local host of the + # initiator rather than from the unspecified address, which only `HOST ANY` users accept. + node2.query("ALTER USER tenant HOST LOCAL") + + # The refresh runs under the definer's identity and must be denied on the remote shard too. + # Before the fix, the refresh query was sent with an empty `initial_user`, which the remote + # shard treated as interserver mode and executed without any access checks. + node1.query( + """ + CREATE MATERIALIZED VIEW tenant_db.rmv REFRESH EVERY 1 YEAR APPEND TO tenant_db.target + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT id, payload, currentUser() AS current_user, authenticatedUser() AS authenticated_user + FROM tenant_db.dist; + """, + **TENANT, + ) + + with pytest.raises(QueryRuntimeException, match="ACCESS_DENIED"): + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT count() FROM tenant_db.target") == "0\n" + assert "ACCESS_DENIED" in node1.query( + "SELECT exception FROM system.view_refreshes WHERE database = 'tenant_db' AND view = 'rmv'" + ) + + # Once the definer is granted access on the remote shard, the refresh succeeds and the remote + # shard sees the definer as the current and authenticated user. + node2.query("GRANT SELECT ON lab.secrets TO tenant") + node1.query("SYSTEM REFRESH VIEW tenant_db.rmv") + node1.query("SYSTEM WAIT VIEW tenant_db.rmv") + assert node1.query("SELECT * FROM tenant_db.target ORDER BY id", **TENANT) == ( + "1\ta\ttenant\ttenant\n2\tb\ttenant\ttenant\n3\tc\ttenant\ttenant\n" + ) diff --git a/tests/integration/test_restore_replica_metadata_version/test.py b/tests/integration/test_restore_replica_metadata_version/test.py index b35af4075c11..4fc23ce116ae 100644 --- a/tests/integration/test_restore_replica_metadata_version/test.py +++ b/tests/integration/test_restore_replica_metadata_version/test.py @@ -36,6 +36,79 @@ def start_cluster(): cluster.shutdown() +def test_alter_after_concurrent_restore(start_cluster): + zk = cluster.get_kazoo_client("zoo1") + table = "test_concurrent_restore" + zk_path = f"/clickhouse/tables/{table}" + failpoint = "rmt_restore_replica_pause_before_metadata_version_raise" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + for node in [node_1, node_2]: + node.query( + f"CREATE TABLE {table} (n UInt32) " + f"ENGINE = ReplicatedMergeTree('{zk_path}/', '{node.name}') ORDER BY n" + ) + + # Two ALTERs bring the metadata version of the table, and of the part inserted after them, to 2 + for column in ["a", "b"]: + node_1.query( + f"ALTER TABLE {table} ADD COLUMN {column} UInt32", + settings={"alter_sync": 2}, + ) + node_1.query(f"INSERT INTO {table} VALUES (1, 1, 1)") + node_2.query(f"SYSTEM SYNC REPLICA {table}") + for node in [node_1, node_2]: + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + zk_rmr_with_retries(zk, zk_path) + for node in [node_1, node_2]: + node.query(f"SYSTEM RESTART REPLICA {table}") + + # Restore both replicas at the same time, as ON CLUSTER does: node_1 stops after it has + # restored the table in Keeper, before it raises the metadata version to the one of its part, + # and node_2 restores in the meantime by copying node_1 + node_1.query(f"SYSTEM ENABLE FAILPOINT {failpoint}") + restore = node_1.get_query_request(f"SYSTEM RESTORE REPLICA {table}") + node_1.query(f"SYSTEM WAIT FAILPOINT {failpoint} PAUSE") + node_2.query(f"SYSTEM RESTORE REPLICA {table}") + assert ( + node_2.query(f"SELECT is_readonly FROM system.replicas WHERE table = '{table}'") + == "0\n" + ) + node_1.query(f"SYSTEM DISABLE FAILPOINT {failpoint}") + restore.get_answer() + + for node in [node_1, node_2]: + node.query(f"SYSTEM SYNC REPLICA {table}") + + _, stat = zk.get(f"{zk_path}/metadata") + assert stat.version == 2 + for node in [node_1, node_2]: + version, _ = zk.get(f"{zk_path}/replicas/{node.name}/metadata_version") + assert version == b"2" + assert ( + node.query( + f"SELECT metadata_version FROM system.tables WHERE name = '{table}'" + ) + == "2\n" + ) + + # A replica left below the metadata version of the table rejects every ALTER with CANNOT_ASSIGN_ALTER + node_2.query(f"ALTER TABLE {table} ADD COLUMN c UInt32", settings={"alter_sync": 2}) + node_1.query(f"ALTER TABLE {table} ADD COLUMN d UInt32", settings={"alter_sync": 2}) + for node in [node_1, node_2]: + assert node.query(f"SELECT n, a, b, c, d FROM {table}") == "1\t1\t1\t0\t0\n" + + for node in [node_1, node_2]: + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + + def test_fix_metadata_version_on_attach_part_after_restore(start_cluster): zk = cluster.get_kazoo_client("zoo1") diff --git a/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py new file mode 100644 index 000000000000..d90720f797bd --- /dev/null +++ b/tests/integration/test_storage_iceberg_no_spark/test_manifest_length_cache_weight.py @@ -0,0 +1,99 @@ +""" +An Iceberg manifest-list entry may declare any `manifest_length`. Reading such a table must not +depend on that number: it used to become the metadata cache cell weight and terminate the server. +""" +import os +import shutil +import tempfile + +from helpers.iceberg_utils import get_uuid_str +from test_storage_iceberg_no_spark.test_local_path_traversal import ( + _download_table_from_container, + _get_manifest_paths_from_chain, + _modify_avro_file, +) + +NOCACHE = { + "use_iceberg_metadata_files_cache": False, + "use_parquet_metadata_cache": False, +} +CACHE = {"use_iceberg_metadata_files_cache": True} +HUGE_MANIFEST_LENGTH = 2**62 + + +def _make_table_with_manifest_length(instance, table_name, table_path, new_length): + """Build a well-formed IcebergLocal table with the cache off, then rewrite every + manifest-list entry's `manifest_length`. new_length=None rewrites the file without + changing the value. Returns the manifest files' real total size on disk.""" + instance.query( + f"CREATE TABLE {table_name} (c0 Int) ENGINE = IcebergLocal('{table_path}/', 'Parquet');", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + instance.query( + f"INSERT INTO {table_name} VALUES (1), (2), (3)", + settings={"allow_insert_into_iceberg": 1, **NOCACHE}, + ) + assert instance.query(f"SELECT count() FROM {table_name}", settings=NOCACHE).strip() == "3" + instance.query(f"DROP TABLE {table_name}") + + temp_dir = tempfile.mkdtemp() + try: + host_path = os.path.join(temp_dir, table_name) + os.makedirs(host_path, exist_ok=True) + _download_table_from_container(instance, table_path, host_path) + manifest_list_rel, manifest_rels = _get_manifest_paths_from_chain(host_path, table_path) + local_manifest_list = os.path.join(host_path, manifest_list_rel) + _modify_avro_file( + local_manifest_list, + ["manifest_length"], + (lambda v: v) if new_length is None else (lambda _: new_length), + ) + instance.copy_file_to_container(local_manifest_list, f"{table_path}/{manifest_list_rel}") + return sum(os.path.getsize(os.path.join(host_path, rel)) for rel in manifest_rels) + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + + +def _read_back(instance, table_path): + """Read with the metadata cache ON, from a cold cache: the cache-miss path is the only + one that builds the cell whose weight the declared length used to set. Returns the + query results plus the cache weight those reads produced.""" + instance.query("SYSTEM DROP ICEBERG METADATA CACHE") + count = instance.query(f"SELECT count() FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + total = instance.query(f"SELECT sum(c0) FROM icebergLocal('{table_path}/')", settings=CACHE).strip() + weight = instance.query( + "SELECT value FROM system.metrics WHERE metric = 'IcebergMetadataFilesCacheBytes'" + ).strip() + return count, total, int(weight) + + +def _assert_weighed_by_real_size(weight, manifest_bytes): + """A manifest is charged three times its size on storage, so the total must clear that + bound. Reading the size from the file rather than hardcoding it keeps this stable while + still failing if the weight ever comes from something other than the real size.""" + assert weight >= 3 * manifest_bytes, f"weight {weight} < 3 * {manifest_bytes}" + + +def test_iceberg_rewritten_manifest_list_is_readable(started_cluster_iceberg_no_spark): + """Control for the test below: the same Avro round-trip with the declared length + untouched. It runs first so that a regression of the fix, which aborts the server and + makes every later query in the package fail to connect, cannot mask this result.""" + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_manifest_list_roundtrip" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length(instance, table_name, table_path, None) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) + + +def test_iceberg_huge_manifest_length_is_readable(started_cluster_iceberg_no_spark): + instance = started_cluster_iceberg_no_spark.instances["node1"] + table_name = "test_iceberg_huge_manifest_length" + get_uuid_str() + table_path = f"/var/lib/clickhouse/user_files/iceberg_data/default/{table_name}" + manifest_bytes = _make_table_with_manifest_length( + instance, table_name, table_path, HUGE_MANIFEST_LENGTH + ) + count, total, weight = _read_back(instance, table_path) + assert (count, total) == ("3", "6") + _assert_weighed_by_real_size(weight, manifest_bytes) diff --git a/tests/integration/test_storage_s3/test.py b/tests/integration/test_storage_s3/test.py index eb975f052251..be913f27a387 100644 --- a/tests/integration/test_storage_s3/test.py +++ b/tests/integration/test_storage_s3/test.py @@ -2683,6 +2683,41 @@ def test_page_cache(started_cluster): assert 0 < int(gets) +def test_cache_key_includes_storage(started_cluster): + # The same key with the same content, so the same ETag, in another bucket or behind another endpoint: + # the filesystem cache and the page cache must not serve it the entry filled by the first object. + instance = started_cluster.instances["dummy"] + table_name = f"test_cache_key_includes_storage-{uuid.uuid4()}" + host = f"{started_cluster.minio_host}:{started_cluster.minio_port}" + ip = f"{started_cluster.minio_ip}:{started_cluster.minio_port}" + + for bucket in [started_cluster.minio_bucket, started_cluster.minio_bucket_2]: + instance.query( + f"insert into function s3('http://{host}/{bucket}/{table_name}.tsv', auto, 'x UInt64') select number from numbers(100) SETTINGS s3_truncate_on_insert=1" + ) + + urls = [ + f"http://{host}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{ip}/{started_cluster.minio_bucket}/{table_name}.tsv", + f"http://{host}/{started_cluster.minio_bucket_2}/{table_name}.tsv", + ] + for settings in ["filesystem_cache_name = 'cache1', enable_filesystem_cache=1", "use_page_cache_for_object_storage=1"]: + for url in urls: + query_id = f"{table_name}-{uuid.uuid4()}" + assert "100\n" == instance.query( + f"select sum(ignore(*) + 1) from s3('{url}', 'TSV', 'x UInt64') SETTINGS {settings}", + query_id=query_id, + ) + + instance.query("SYSTEM FLUSH LOGS") + + assert 0 < int( + instance.query( + f"SELECT ProfileEvents['S3GetObject'] FROM system.query_log WHERE query_id = '{query_id}' AND type = 'QueryFinish'" + ) + ) + + def test_archive(started_cluster): id = uuid.uuid4() bucket = started_cluster.minio_bucket diff --git a/tests/integration/test_storage_url/test.py b/tests/integration/test_storage_url/test.py index 8c7bc908f932..fa68686b1f67 100644 --- a/tests/integration/test_storage_url/test.py +++ b/tests/integration/test_storage_url/test.py @@ -115,7 +115,8 @@ def test_table_function_url_access_rights(): f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1" ) - node1.query("GRANT READ ON URL TO u1") + # Like `SELECT`, `DESCRIBE` of a table function also needs `CREATE TEMPORARY TABLE`. + node1.query("GRANT READ ON URL, CREATE TEMPORARY TABLE ON *.* TO u1") assert node1.query( f"DESCRIBE TABLE url('http://nginx:80/test_1', 'TSV')", user="u1", diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py b/tests/integration/test_streaming_engines_definer_interserver_secret/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml new file mode 100644 index 000000000000..0b5411455b46 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/rabbitmq.xml @@ -0,0 +1,6 @@ + + + root + clickhouse + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml new file mode 100644 index 000000000000..af0b7ad21cab --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/remote_servers.xml @@ -0,0 +1,14 @@ + + + + + foo + + node2 + 9000 + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml new file mode 100644 index 000000000000..ae00b3b543f9 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/configs/users.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + ::/0 + + default + default + 1 + + + + + + + + diff --git a/tests/integration/test_streaming_engines_definer_interserver_secret/test.py b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py new file mode 100644 index 000000000000..f14f501904b5 --- /dev/null +++ b/tests/integration/test_streaming_engines_definer_interserver_secret/test.py @@ -0,0 +1,299 @@ +# pylint: disable=unused-argument +# pylint: disable=redefined-outer-name +# pylint: disable=line-too-long + +""" +Pushes from streaming engines into a `Distributed` table must reach the shard under the definer. + +`Kafka`, `RabbitMQ` and the other streaming engines never write anywhere themselves: a consumed +batch is pushed only into the dependent materialized views, from a copy of the global context that +has no user. A view with `SQL SECURITY DEFINER` switches that push to the definer. When the view's +target is a `Distributed` table over a cluster with an interserver ``, the definer's name +must travel with the query: before the fix `Context::setUser` left the `ClientInfo` user names +empty, the shard received an empty `initial_user`, treated the query as interserver mode and +executed it with full access. A tenant that could create tables only in its own database could +chain `Kafka -> MATERIALIZED VIEW -> Distributed('secure', default, secret_data)` and write into +a table on the shard it had no `INSERT` grant on. + +The `secure` cluster consists of `node2` only, so a table on `node1` can reach `default.secret_data` +solely over the interserver connection. Every pipeline is built twice with the same statements: by +`tenant`, who has no grants on `node2` and whose rows must be rejected there, and by `writer`, who +has `INSERT` on the target and whose rows must arrive. In both cases the shard must see the +definer's name in `system.query_log`. + +The push is also checked with `distributed_foreground_insert = 0`, where the rows go through the +background directory queue of the `Distributed` table: the persisted insert must keep the definer's +name, although the streaming context has `query_kind = NO_QUERY`. +""" + +import json +import time + +import pika +import pytest + +import helpers.kafka.common as k +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +node1 = cluster.add_instance( + "node1", + main_configs=["configs/remote_servers.xml", "configs/rabbitmq.xml"], + user_configs=["configs/users.xml"], + with_kafka=True, + with_rabbitmq=True, +) +node2 = cluster.add_instance( + "node2", + main_configs=["configs/remote_servers.xml"], + user_configs=["configs/users.xml"], +) + +WRITER = "writer" +TENANT = "tenant" +CREDENTIALS = { + WRITER: {"user": WRITER, "password": "wpass"}, + TENANT: {"user": TENANT, "password": "tpass"}, +} +ROWS_PER_PIPELINE = 2 + +# How long a streaming engine gets to consume the messages and push them to the shard. Consumer +# group setup in Kafka alone can take several seconds. +DELIVERY_WAIT_SECONDS = 60 + +users = pytest.mark.parametrize("user", [WRITER, TENANT]) + + +def database(user): + return f"{user}_db" + + +def query_as(user, sql): + return node1.query(sql, **CREDENTIALS[user]) + + +def remote_rows(): + return int(node2.query("SELECT count() FROM default.secret_data")) + + +def shard_inserts(user, condition): + """Number of `INSERT` queries into the protected table that the shard executed under `user`.""" + node2.query("SYSTEM FLUSH LOGS") + return int( + node2.query( + f""" + SELECT count() FROM system.query_log + WHERE user = '{user}' AND query LIKE 'INSERT INTO default.secret_data%' AND {condition} + """ + ) + ) + + +def shard_finished_inserts(user): + return shard_inserts(user, "type = 'QueryFinish'") + + +def shard_denied_inserts(user): + # The access check happens before the pipeline starts, so the shard logs the denial as + # `ExceptionBeforeStart`. + return shard_inserts( + user, + "type IN ('ExceptionBeforeStart', 'ExceptionWhileProcessing') AND exception_code = 497", + ) + + +def wait_until(condition, timeout=DELIVERY_WAIT_SECONDS): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(1) + return False + + +@pytest.fixture(scope="module", autouse=True) +def started_cluster(): + try: + cluster.start() + + # The protected table lives on the shard only. Both users exist on both nodes, but on + # the shard only `writer` may insert into it. + node2.query( + """ + CREATE TABLE default.secret_data (key Int) ENGINE = MergeTree ORDER BY key; + CREATE USER writer IDENTIFIED WITH plaintext_password BY 'wpass'; + CREATE USER tenant IDENTIFIED WITH plaintext_password BY 'tpass'; + GRANT INSERT ON default.secret_data TO writer; + """ + ) + for user in (WRITER, TENANT): + db = database(user) + # Send to the shard synchronously by default, so that a push either delivers the rows + # or fails right away, without a background directory queue in between. + # With `table_engines_require_grant = false`, `TABLE ENGINE` on a source engine is + # revoked unless the user also has `READ` and `WRITE` on its source. + node1.query( + f""" + CREATE USER {user} IDENTIFIED WITH plaintext_password BY '{CREDENTIALS[user]["password"]}' + SETTINGS distributed_foreground_insert = 1; + CREATE DATABASE {db}; + GRANT ALL ON {db}.* TO {user}; + GRANT TABLE ENGINE ON Distributed, TABLE ENGINE ON Kafka, TABLE ENGINE ON RabbitMQ TO {user}; + GRANT READ, WRITE ON REMOTE, READ, WRITE ON KAFKA, READ, WRITE ON RABBITMQ TO {user}; + """ + ) + query_as( + user, + f"CREATE TABLE {db}.dist (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + + yield cluster + finally: + cluster.shutdown() + + +@pytest.fixture(autouse=True) +def clean_remote_table(): + node2.query("TRUNCATE TABLE default.secret_data") + yield + + +def drop_pipeline(user, source): + """Stop the streaming table, so that a rejected push is not retried into the next test.""" + db = database(user) + query_as(user, f"DROP TABLE {db}.{source}_to_dist") + query_as(user, f"DROP TABLE {db}.{source} SYNC") + + +def create_definer_view(user, source, target="dist"): + """A view owned by `user` that pushes the source rows into the user's `Distributed` table.""" + db = database(user) + query_as( + user, + f""" + CREATE MATERIALIZED VIEW {db}.{source}_to_dist TO {db}.{target} + DEFINER = CURRENT_USER SQL SECURITY DEFINER + AS SELECT key FROM {db}.{source} + """, + ) + + +def check_delivery(user, finished_before, denied_before): + """The shard must have executed the push under the user's name, with the outcome the user's + grants dictate: the rows arrive for `writer` and are rejected for `tenant`.""" + if user == WRITER: + assert wait_until(lambda: remote_rows() == ROWS_PER_PIPELINE) + assert shard_finished_inserts(WRITER) > finished_before + else: + assert wait_until( + lambda: shard_denied_inserts(TENANT) > denied_before or remote_rows() > 0 + ) + assert remote_rows() == 0 + assert shard_denied_inserts(TENANT) > denied_before + + +def check_direct_insert(user): + """The control case: a direct `INSERT` carries the user's name to the shard, where it is checked. + + It passes without the fix as well, so it is not a separate test: bugfix validation requires every + new test to fail on the unfixed binary. It runs before a streaming pipeline instead.""" + db = database(user) + if user == WRITER: + query_as(WRITER, f"INSERT INTO {db}.dist VALUES (1)") + assert remote_rows() == 1 + else: + error = node1.query_and_get_error( + f"INSERT INTO {db}.dist VALUES (1)", **CREDENTIALS[TENANT] + ) + assert "ACCESS_DENIED" in error + assert remote_rows() == 0 + node2.query("TRUNCATE TABLE default.secret_data") + + +@users +@pytest.mark.parametrize("foreground", [1, 0]) +def test_kafka(user, foreground): + db = database(user) + topic = f"definer_interserver_{user}_{foreground}" + k.kafka_create_topic(k.get_admin_client(cluster), topic) + + query_as( + user, + f""" + CREATE TABLE {db}.kafka (key Int) ENGINE = Kafka + SETTINGS kafka_broker_list = 'kafka1:19092', + kafka_topic_list = '{topic}', + kafka_group_name = '{topic}', + kafka_format = 'JSONEachRow', + kafka_flush_interval_ms = 1000 + """, + ) + # A separate `Distributed` table per mode, so that a rejected file left in the background queue + # is dropped together with the table and is not retried into the next test. + target = f"dist_{foreground}" + query_as( + user, + f"CREATE TABLE {db}.{target} (key Int) ENGINE = Distributed(secure, default, secret_data)", + ) + # The definer's settings apply to the push. It is not set in the server's profile, because the + # settings of the context the push starts from would override the definer's ones. + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = {foreground}") + create_definer_view(user, "kafka", target) + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + k.kafka_produce( + cluster, topic, [json.dumps({"key": i}) for i in range(ROWS_PER_PIPELINE)] + ) + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "kafka") + query_as(user, f"DROP TABLE {db}.{target} SYNC") + node1.query(f"ALTER USER {user} SETTINGS distributed_foreground_insert = 1") + + +@users +def test_rabbitmq(user): + check_direct_insert(user) + db = database(user) + exchange = f"definer_interserver_{user}" + + query_as( + user, + f""" + CREATE TABLE {db}.rabbitmq (key Int) ENGINE = RabbitMQ + SETTINGS rabbitmq_host_port = 'rabbitmq1:5672', + rabbitmq_exchange_name = '{exchange}', + rabbitmq_format = 'JSONEachRow', + rabbitmq_flush_interval_ms = 1000, + rabbitmq_max_block_size = 100 + """, + ) + create_definer_view(user, "rabbitmq") + + # The exchange and the queue are declared by the table in the background; messages + # published before that are dropped by RabbitMQ. + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: RabbitMQ setup completed") + node1.wait_for_log_line(f"StorageRabbitMQ .{db}.rabbitmq.: Queue .* is declared") + + try: + finished_before = shard_finished_inserts(user) + denied_before = shard_denied_inserts(user) + + credentials = pika.PlainCredentials("root", "clickhouse") + parameters = pika.ConnectionParameters( + cluster.rabbitmq_ip, cluster.rabbitmq_port, "/", credentials + ) + connection = pika.BlockingConnection(parameters) + channel = connection.channel() + for i in range(ROWS_PER_PIPELINE): + channel.basic_publish( + exchange=exchange, routing_key="", body=json.dumps({"key": i}) + ) + connection.close() + + check_delivery(user, finished_before, denied_before) + finally: + drop_pipeline(user, "rabbitmq") diff --git a/tests/integration/test_totp_auth/test_totp.py b/tests/integration/test_totp_auth/test_totp.py index d682ecf94848..7aa30c96a53c 100644 --- a/tests/integration/test_totp_auth/test_totp.py +++ b/tests/integration/test_totp_auth/test_totp.py @@ -98,9 +98,37 @@ def test_one_time_password(started_cluster): query_text, user="totuser", password=f"aa+bb+{old_password}" ) - assert "REQUIRED_SECOND_FACTOR" in node.query_and_get_error( - query_text, user="totuser", password=f"aa+bb" + # Without a code the response does not depend on the password, so the error REQUIRED_SECOND_FACTOR + # does not confirm a guessed password: a wrong or an empty password gets exactly the same error + error_without_code = node.query_and_get_error( + query_text, user="totuser", password="aa+bb" ) + assert "REQUIRED_SECOND_FACTOR" in error_without_code + for password in ["wrongpwd", ""]: + assert error_without_code == node.query_and_get_error( + query_text, user="totuser", password=password + ) + + http_responses = [ + node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": password}, + ) + for password in ["aa+bb", "wrongpwd"] + ] + for response in http_responses: + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "767" + assert http_responses[0].text == http_responses[1].text + + response = node.http_request( + "", + params={"query": query_text}, + headers={"X-ClickHouse-User": "totuser", "X-ClickHouse-Key": "aa+bb+000000000"}, + ) + assert response.status_code == 403 + assert response.headers["X-ClickHouse-Exception-Code"] == "516" assert "totuser42\n" == node.query( query_text, user="totuser", password=f"aa+bb+{get_otp('totuser')}" @@ -196,13 +224,17 @@ def test_interactive_totp_authentication(started_cluster): # Then enter wrong TOTP when prompted c.expect("TOTP.*:") - c.send(f"000000", eol="\r") + c.send("000000000", eol="\r") c.expect(expected_error) - with client(command=f"{client_command(user0)} --password aa+bb+000000") as c: + # A wrong code of the configured length (9 digits); a suffix of another length counts as no code + with client(command=f"{client_command(user0)} --password aa+bb+000000000") as c: c.expect(expected_error) + # A wrong password without a code is asked for the code like a right one, and fails only after that with client(command=f"{client_command(user0)} --password wrongpwd") as c: + c.expect("TOTP.*:") + c.send(get_otp(user0), eol="\r") c.expect(expected_error) with client( @@ -370,7 +402,10 @@ def test_one_time_only_no_password(started_cluster): assert f"{user0}42\n" == node.query(query_text, user=user0, password=get_otp(user0)) + # The client cannot know that the account has no password: it asks for the password first with client(command=f"{client_command(user0)}") as c: + c.expect("Password.*:") + c.send("", eol="\r") c.expect("TOTP.*:") c.send(get_otp(user0, offset_steps=1), eol="\r") c.expect(prompt) diff --git a/tests/performance/map_bucketed_serialization.xml b/tests/performance/map_bucketed_serialization.xml index d86c681a4f3b..e5016ad60d46 100644 --- a/tests/performance/map_bucketed_serialization.xml +++ b/tests/performance/map_bucketed_serialization.xml @@ -1,6 +1,6 @@ @@ -107,7 +107,7 @@ CREATE TABLE map_subcol_pw_mixed (id UInt64, tags Map(String, String), value UInt32) @@ -126,7 +126,7 @@ OPTIMIZE TABLE map_subcol_pw_mixed FINAL SETTINGS mutations_sync=1 - diff --git a/tests/performance/prewhere_subcolumn_read_steps.xml b/tests/performance/prewhere_subcolumn_read_steps.xml new file mode 100644 index 000000000000..04cb68d9dd07 --- /dev/null +++ b/tests/performance/prewhere_subcolumn_read_steps.xml @@ -0,0 +1,19 @@ + + + 0 + + + CREATE TABLE t_prewhere_json (id UInt64, j JSON(max_dynamic_paths = 0)) ENGINE = MergeTree ORDER BY id + CREATE TABLE t_prewhere_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0 + + INSERT INTO t_prewhere_json SELECT number, concat('{{"kind":"a","n":', toString(number), ',"payload":"', repeat('x', 2000), '"}}') FROM numbers_mt(3000000) + INSERT INTO t_prewhere_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> repeat('v', 60), range(16))) FROM numbers_mt(10000000) + + + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j)) > 10 + SELECT count() FROM t_prewhere_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 + SELECT count() FROM t_prewhere_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 + + DROP TABLE IF EXISTS t_prewhere_json + DROP TABLE IF EXISTS t_prewhere_map + diff --git a/tests/queries/0_stateless/00900_long_parquet_load_2.sh b/tests/queries/0_stateless/00900_long_parquet_load_2.sh index dc8d68888463..b58b54143176 100755 --- a/tests/queries/0_stateless/00900_long_parquet_load_2.sh +++ b/tests/queries/0_stateless/00900_long_parquet_load_2.sh @@ -47,6 +47,10 @@ EXCLUDE=( # malformed on purpose, so loading it here would print an exception. 05035_delta_byte_array_zero_values.parquet 05035_delta_byte_array_decimal.parquet + # `INT96` timestamps outside the `DateTime64(9)` range (throws with the default `date_time_overflow_behavior`), tested by 05443. + 05443_int96_out_of_range.parquet + # `INT96` timestamp on the lower boundary day of the `DateTime64(9)` range, tested by 05444. + 05444_int96_lower_boundary.parquet ) for NAME in $(find "$DATA_DIR" -type f \( -iname '*.parquet' -o -iname '*.parquet.gz' \) -print0 | xargs -0 -n 1 basename | LC_ALL=C sort | grep -vFf <(printf '%s\n' "${EXCLUDE[@]}")); do diff --git a/tests/queries/0_stateless/01035_avg.reference b/tests/queries/0_stateless/01035_avg.reference index 1f47b3a8b7ea..192bceec0560 100644 --- a/tests/queries/0_stateless/01035_avg.reference +++ b/tests/queries/0_stateless/01035_avg.reference @@ -1,6 +1,6 @@ nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan --0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.493856 32355.57552 499999.5 499999.5 499999.5 499999.5 499999.5 499999.5 -0.000500002 0.49999949943727 -0.000005 -0.000004999999999999992 --2767.546272 -999999 --0.50000449943727 +-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 127.467744 31470.715104 124999.5 124999.5 124999.5 124999.5 124999.5 124999.5 -0.0005000056 0.12499949943764 -0.000005000000000000001 -0.0000050000000000000334 +-3182.944672 +249999 +-0.12500449943764 1 1 \N \N 1 1 diff --git a/tests/queries/0_stateless/01035_avg.sql b/tests/queries/0_stateless/01035_avg.sql index 0f7baddaec57..a8aae4480e66 100644 --- a/tests/queries/0_stateless/01035_avg.sql +++ b/tests/queries/0_stateless/01035_avg.sql @@ -27,7 +27,7 @@ SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(f32), avg(f64), avg(d32), avg(d64), avg(d128), avg(d256) FROM test_01035_avg; -INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 1000000; +INSERT INTO test_01035_avg (u64) SELECT number FROM system.numbers LIMIT 250000; SELECT avg(i8), avg(i16), avg(i32), avg(i64), avg(i128), avg(i256), avg(u8), avg(u16), avg(u32), avg(u64), avg(u128), avg(u256), diff --git a/tests/queries/0_stateless/01252_weird_time_zone.reference b/tests/queries/0_stateless/01252_weird_time_zone.reference index 90f5bf0e30dd..a93b19a6dd70 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.reference +++ b/tests/queries/0_stateless/01252_weird_time_zone.reference @@ -5,3 +5,41 @@ Pacific/Kwajalein 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Apia 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Enderbury 2020-01-02 03:04:05 2020-01-02 00:00:00 3 Pacific/Fakaofo 2020-01-02 03:04:05 2020-01-02 00:00:00 3 +--- offset of zones that crossed the international date line +Pacific/Kiritimati 50400 +Pacific/Apia 46800 +Pacific/Fakaofo 46800 +Pacific/Enderbury 46800 +Pacific/Kanton 46800 +Pacific/Kwajalein 43200 +Kwajalein 43200 +--- the same zones before their jump, and a +13:45 zone, must not move +Pacific/Apia -39600 +Pacific/Fakaofo -39600 +Pacific/Chatham 49500 +Pacific/Chatham 45900 +--- negative offsets before the epoch +Africa/Abidjan -968 +Africa/Accra -52 +Africa/Addis_Ababa 9320 +Europe/Moscow 9017 +--- parseDateTime agrees with toDateTime on an affected zone +1 +1 +1 +1 +1 +1 +--- other consumers of the offset ++1400 +2025-06-14 22:00:00 2025-06-16 02:00:00 +2025-06-14 22:00:00.500 2025-06-16 02:00:00.500 +--- consumers that reduce the offset modulo a day must be unaffected +12:00:00 12:00:00.500 +1970-01-02 12:00:00 2025-06-15 00:00:00 12 2025-06-15 +--- daylight saving transitions keep their sub-day offset +-18000 -14400 -18000 +--- inside and outside the lookup table window report the same offset +1 +--- every zone agrees with rendering the instant as local text and reading it back as UTC +0 diff --git a/tests/queries/0_stateless/01252_weird_time_zone.sql b/tests/queries/0_stateless/01252_weird_time_zone.sql index c4919ca4fe01..729eea83216d 100644 --- a/tests/queries/0_stateless/01252_weird_time_zone.sql +++ b/tests/queries/0_stateless/01252_weird_time_zone.sql @@ -13,3 +13,56 @@ SELECT 'Pacific/Kwajalein', rand() as r, toHour(toDateTime(r, 'Pacific/Kwajalein SELECT 'Pacific/Apia', rand() as r, toHour(toDateTime(r, 'Pacific/Apia') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Enderbury', rand() as r, toHour(toDateTime(r, 'Pacific/Enderbury') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; SELECT 'Pacific/Fakaofo', rand() as r, toHour(toDateTime(r, 'Pacific/Fakaofo') AS t) AS h, t, toTypeName(t) FROM numbers(1000000) WHERE h < 0 OR h > 23 ORDER BY h LIMIT 1 BY h; + +-- timezoneOffset must report the true UTC offset, including its whole-day component (issue #115281). +SELECT '--- offset of zones that crossed the international date line'; +SELECT 'Pacific/Kiritimati', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Enderbury', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Enderbury')); +SELECT 'Pacific/Kanton', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kanton')); +SELECT 'Pacific/Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kwajalein')); +SELECT 'Kwajalein', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Kwajalein')); + +SELECT '--- the same zones before their jump, and a +13:45 zone, must not move'; +SELECT 'Pacific/Apia', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Apia')); +SELECT 'Pacific/Fakaofo', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Fakaofo')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2010-01-01 12:00:00', 'Pacific/Chatham')); +SELECT 'Pacific/Chatham', timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Chatham')); + +SELECT '--- negative offsets before the epoch'; +SELECT 'Africa/Abidjan', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Abidjan')); +SELECT 'Africa/Accra', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Accra')); +SELECT 'Africa/Addis_Ababa', timeZoneOffset(toDateTime64(-1900000000, 0, 'Africa/Addis_Ababa')); +SELECT 'Europe/Moscow', timeZoneOffset(toDateTime64(-1900000000, 0, 'Europe/Moscow')); + +SELECT '--- parseDateTime agrees with toDateTime on an affected zone'; +SELECT toUnixTimestamp(parseDateTime('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeOrNull('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTime64('2025-06-15 12:00:00', '%Y-%m-%d %H:%i:%S', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00', 'yyyy-MM-dd HH:mm:ss', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeBestEffort('2025-06-15 12:00:00', 'Pacific/Kiritimati')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); +SELECT toUnixTimestamp(parseDateTimeInJodaSyntax('2025-06-15 12:00:00 Pacific/Kiritimati', 'yyyy-MM-dd HH:mm:ss z')) = toUnixTimestamp(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- other consumers of the offset'; +SELECT formatDateTime(toDateTime64(1750000000, 0, 'UTC'), '%z', 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00' AS DateTime), 'Pacific/Kiritimati'); +SELECT toUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'), fromUTCTimestamp(CAST('2025-06-15 12:00:00.500' AS DateTime64(3)), 'Pacific/Kiritimati'); + +SELECT '--- consumers that reduce the offset modulo a day must be unaffected'; +SELECT CAST(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati') AS Time), CAST(toDateTime64('2025-06-15 12:00:00.5', 3, 'Pacific/Kiritimati') AS Time64(3)); +SELECT toTime(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toStartOfDay(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toHour(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')), toDate(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')); + +SELECT '--- daylight saving transitions keep their sub-day offset'; +SELECT timeZoneOffset(toDateTime('2025-03-09 01:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-03-09 03:00:00', 'America/New_York')), timeZoneOffset(toDateTime('2025-11-02 03:00:00', 'America/New_York')); + +SELECT '--- inside and outside the lookup table window report the same offset'; +SELECT timeZoneOffset(toDateTime64(1750000000, 0, 'Pacific/Kiritimati')) = timeZoneOffset(toDateTime64(90000000000, 0, 'Pacific/Kiritimati')); + +SELECT '--- every zone agrees with rendering the instant as local text and reading it back as UTC'; +WITH + arrayJoin([toDateTime64(1262347200, 0, 'UTC'), toDateTime64(1750000000, 0, 'UTC'), toDateTime64(2000000000, 0, 'UTC')]) AS ts, + formatDateTime(ts, '%z', time_zone) AS z, + (toInt64(substring(z, 2, 2)) * 3600 + toInt64(substring(z, 4, 2)) * 60) * multiIf(substring(z, 1, 1) = '-', -1, 1) AS reported, + toInt64(toDateTime(formatDateTime(ts, '%Y-%m-%d %H:%i:%S', time_zone), 'UTC')) - toInt64(ts) AS expected +SELECT count() FROM system.time_zones WHERE reported != expected; diff --git a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference index d771371b2644..0eb78aef3648 100644 --- a/tests/queries/0_stateless/01308_orc_output_format_arrays.reference +++ b/tests/queries/0_stateless/01308_orc_output_format_arrays.reference @@ -1 +1 @@ -0bedc9eaf0b07ce14f59ffd25e1a6df6 - +75b5b0cbd2734c37f4f02bd726c4ea60 - diff --git a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh index a44ae6f1e95a..960f2f03174f 100755 --- a/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh +++ b/tests/queries/0_stateless/01514_distributed_cancel_query_on_error.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash -# Tags: distributed +# Tags: distributed, no-llvm-coverage +# no-llvm-coverage: the test needs the shard accumulating `repeat('a', 100000)` per row to hit +# `max_memory_usage=1G` and emit `Query memory limit exceeded` before the other shard cancels. +# LLVM source-based coverage instrumentation perturbs this memory-tracking cadence, so the +# expected exception sometimes does not surface on `127.3` before cancellation, leaving an empty +# `grep` match and a flaky FAIL. CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -9,7 +14,11 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # 1 on 127.2 # 2 on 127.3 # max_block_size to fail faster -# max_memory_usage/_shard_num/repeat() will allow failure on the first shard earlier. +# `groupArrayIf` on `_shard_num` makes `127.3` the only shard that can run out of memory: on +# `127.2` the condition is false for every row, so its aggregate states never grow and it just +# streams `system.numbers` until the initiator cancels it. Before this, `127.2` accumulated +# one-byte strings and reached the same `max_memory_usage` only about 20% later than `127.3`, so +# which shard failed first was a race. opts=( "--max_memory_usage=1G" "--max_block_size=50" @@ -17,9 +26,30 @@ opts=( "--max_distributed_connections=2" "--max_bytes_before_external_group_by=0" "--max_bytes_ratio_before_external_group_by=0" + # The query reads `system.numbers` until a shard runs out of memory, so `max_memory_usage` + # has to be the only limit that can stop it. The test profile of the CI configuration + # (tests/config/users.d/limits.yaml) sets `max_rows_to_read = 20000000`, which `127.2` and + # the initiator reach at about the same time as `127.3` reaches `max_memory_usage`; the query + # then fails with `TOO_MANY_ROWS` instead of `MEMORY_LIMIT_EXCEEDED` and the `grep` below + # finds nothing. + "--max_rows_to_read=0" + # `127.2` now never fails on its own, so if the cancellation this test is about ever breaks, + # the query would stream forever and the test would be killed by the runner's timeout with no + # output. Fail it with `TIMEOUT_EXCEEDED` instead, far above the ~1s the expected exception + # needs. + "--max_execution_time=100" ) -${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArray(repeat('a', if(_shard_num == 2, 100000, 1))), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" |& { - # the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. - grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" - # while if this will not correctly then it will got the exception from the 127.2:9000 and fail -} +LOG="$CLICKHOUSE_TMP/err-$CLICKHOUSE_DATABASE" +trap 'rm -f "$LOG"' EXIT + +${CLICKHOUSE_CLIENT} "${opts[@]}" -q "SELECT groupArrayIf(repeat('a', 100000), _shard_num == 2), number%100000 k from remote('127.{2,3}', system.numbers) GROUP BY k LIMIT 10e6" > "$LOG" 2>&1 +CODE=$? + +# the query should fail earlier on 127.3 and 127.2 should not even go to the memory limit exceeded error. +# while if this will not correctly then it will got the exception from the 127.2:9000 and fail +if ! grep -F -q "DB::Exception: Received from 127.3:${CLICKHOUSE_PORT_TCP}. DB::Exception: Query memory limit exceeded:" "$LOG"; then + # stderr only on the failing path: a test that writes there and exits 0 is a FAIL for the runner. + echo "Fail, Code: $CODE, client output:" >&2 + cat "$LOG" >&2 + exit 1 +fi diff --git a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 index 2b1dc6c1c781..89f267e614a3 100644 --- a/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 +++ b/tests/queries/0_stateless/01721_join_implicit_cast_long.sql.j2 @@ -1,4 +1,8 @@ --- Tags: long +-- Tags: long, no-msan +-- no-msan: 5 join algorithms x ~78 statements, several of them deliberately spilling, average +-- ~183s under MSan against ~4s in a release build; the p99 is 73% of the 600s per-test budget, so +-- a run that gets killed on the timeout is an ordinary tail event. Join implicit-cast semantics +-- get no MSan-specific coverage, and the test still runs under ASan, UBSan and TSan. SET enable_analyzer = 1; DROP TABLE IF EXISTS t1; diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference index 9942759a9480..2d3bd2d2ebfd 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.reference @@ -1,3 +1,5 @@ 1 10 42 53 1 10 42 53 1 10 42 53 +1 +1 0 0 0 diff --git a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql index c49bf392895b..31bf6c5e6524 100644 --- a/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql +++ b/tests/queries/0_stateless/02302_defaults_in_columnar_formats.sql @@ -6,3 +6,13 @@ insert into function file(currentDatabase() || '_data_02302.orc') select 1 as x, select * from file(currentDatabase() || '_data_02302.orc', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_orc_allow_missing_columns=1; insert into function file(currentDatabase() || '_data_02302.arrow') select 1 as x, null::Nullable(UInt8) as xx settings engine_file_truncate_on_insert=1; select * from file(currentDatabase() || '_data_02302.arrow', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_arrow_allow_missing_columns=1; + +-- The next two queries test the native Parquet reader, so they pin it (some release branches still randomize it off). +-- A count-only read reads just the single smallest declared column, so `d` must stay strictly +-- narrower than every other column for this to exercise a defaulted one. The count cache would +-- answer before a reader exists, and the two count-only optimizations are randomized off in some runs, so all three are pinned. +-- Missing columns are rejected so that a read which is not count-only fails here instead of +-- synthesizing `d` into a correctly sized mask and returning the same count with no guard in place. +select count() from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt64, d UInt8 default 10') settings use_cache_for_count_from_files = 0, optimize_count_from_files = 1, optimize_trivial_count_query = 1, input_format_parquet_allow_missing_columns = 0, input_format_parquet_use_native_reader_v3 = 1; +-- With the setting off no `default` expression is applied, so the columns keep their type defaults. +select * from file(currentDatabase() || '_data_02302.parquet', auto, 'x UInt8, xx UInt8 default 10, y default 42, z default x + xx + y') settings input_format_parquet_allow_missing_columns=1, input_format_defaults_for_omitted_fields=0, input_format_parquet_use_native_reader_v3=1; diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference new file mode 100644 index 000000000000..0f9d2713f87d --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.reference @@ -0,0 +1 @@ +idx text diff --git a/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql new file mode 100644 index 000000000000..a629b362ee8e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_add_with_invalid_alter_command.sql @@ -0,0 +1,24 @@ +-- An `ALTER` that adds an index is authorized against the schema the whole statement produces. +-- That must not skip the validation of its other commands and run into an exception. + +SET enable_full_text_index = 1; + +DROP TABLE IF EXISTS tab; +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab + RENAME COLUMN missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 1; -- { serverError NOT_FOUND_COLUMN_IN_BLOCK } + +ALTER TABLE tab + RENAME COLUMN val TO a, + RENAME COLUMN a TO b, + ADD INDEX idx(id) TYPE minmax GRANULARITY 1; -- { serverError NOT_IMPLEMENTED } + +ALTER TABLE tab + RENAME COLUMN IF EXISTS missing TO renamed, + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1; + +SELECT name, type FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab'; + +DROP TABLE tab; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.reference b/tests/queries/0_stateless/02346_text_index_transform_access.reference new file mode 100644 index 000000000000..1c382f1ae6da --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.reference @@ -0,0 +1,19 @@ +1. Direct call denied. +2. Denied in a preprocessor. +3. Denied when nested under a String result. +4. Denied via ALTER ADD INDEX. +5. Unprivileged expression unaffected. +1 +6. Accepted with the privilege, so not a blocklist. +1 +7. Existing index stays readable without the privilege. +1 +8. Unrelated ALTER does not re-authorize. +1 +9. Neither does DETACH/ATTACH. +1 +10. Redeclaring with a privileged function is denied. +11. The transform preflight does not reject what a plain ALTER accepts. +idx_pre +12. A statement without a transform is not analyzed at all. +idx_minmax diff --git a/tests/queries/0_stateless/02346_text_index_transform_access.sql b/tests/queries/0_stateless/02346_text_index_transform_access.sql new file mode 100644 index 000000000000..62903e79d44b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access.sql @@ -0,0 +1,124 @@ +-- Text index `preprocessor` expressions must only use functions the user declaring +-- the index is permitted to run. +-- +-- The test needs a function the current user may not run. Introspection functions fit: they are +-- refused both without the grant and, as here, with `allow_introspection_functions = 0`. Using the +-- setting keeps the test in plain SQL, with no second user to create. + +DROP TABLE IF EXISTS tab; + +-- The test configuration sets this to 1. +SET allow_introspection_functions = 0; + +SELECT '1. Direct call denied.'; + +SELECT demangle('_ZNK2DB7Context9getAccessEv'); -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. Denied in a preprocessor.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Denied when nested under a String result.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, demangle(val))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '4. Denied via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)); -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '5. Unprivileged expression unaffected.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'Hello World'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; + +SELECT '6. Accepted with the privilege, so not a blocklist.'; + +SET allow_introspection_functions = 1; + +-- `demangle` returns a non-mangled argument unchanged. +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; + +INSERT INTO tab VALUES (1, 'hello world'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '7. Existing index stays readable without the privilege.'; + +SET allow_introspection_functions = 0; + +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +SELECT '8. Unrelated ALTER does not re-authorize.'; + +ALTER TABLE tab ADD COLUMN extra UInt8 DEFAULT 0; +ALTER TABLE tab RENAME COLUMN val TO val2; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '9. Neither does DETACH/ATTACH.'; + +DETACH TABLE tab; +ATTACH TABLE tab; +SELECT count() FROM tab WHERE hasAllTokens(val2, ['hello']); + +SELECT '10. Redeclaring with a privileged function is denied.'; + +ALTER TABLE tab DROP INDEX idx, + ADD INDEX idx(val2) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val2)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +DROP TABLE tab; + +SELECT '11. The transform preflight does not reject what a plain ALTER accepts.'; + +CREATE TABLE tab_preflight (id UInt64, val String, num UInt64) +ENGINE = MergeTree ORDER BY id SETTINGS auto_statistics_types = 'minmax'; + +-- The preflight must drop implicit statistics too, or `ADD STATISTICS` looks like a duplicate. +ALTER TABLE tab_preflight ADD INDEX idx_pre(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val)) GRANULARITY 1, + ADD STATISTICS num TYPE minmax; + +SELECT name FROM system.data_skipping_indices +WHERE database = currentDatabase() AND table = 'tab_preflight' ORDER BY name; + +DROP TABLE tab_preflight; + +SELECT '12. A statement without a transform is not analyzed at all.'; + +SET allow_statistics = 1; +CREATE TABLE tab_plain (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS auto_statistics_types = 'minmax'; + +ALTER TABLE tab_plain ADD INDEX idx_minmax(x) TYPE minmax GRANULARITY 1, ADD STATISTICS x TYPE minmax; + +SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab_plain'; + +DROP TABLE tab_plain; diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference new file mode 100644 index 000000000000..8a97bd9c341e --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.reference @@ -0,0 +1,3 @@ +1. ALTER ADD INDEX is denied. +2. CREATE TABLE is denied. +3. Accepted with the privilege. diff --git a/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql new file mode 100644 index 000000000000..67ca0d15dcdc --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_access_replicated_database.sql @@ -0,0 +1,40 @@ +-- Tags: zookeeper, no-replicated-database +-- no-replicated-database: the test creates its own Replicated database + +-- A Replicated database hands the DDL to replicas that apply it without the submitting user, so the +-- permission check happens on the node it was submitted to. See 02346_text_index_transform_access +-- for the checks themselves, and 02346_text_index_transform_on_cluster for `ON CLUSTER`. + +SET allow_introspection_functions = 0; + +-- {CLICKHOUSE_DATABASE_1} may be left over from a previous run, hence the DROP. +DROP DATABASE IF EXISTS {CLICKHOUSE_DATABASE_1:Identifier}; +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} +ENGINE = Replicated('/clickhouse/02346_text_index_transform_access/{database}', 'shard1', 'replica1') FORMAT Null; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab (id UInt64, val String) +ENGINE = MergeTree ORDER BY id FORMAT Null; + +SELECT '1. ALTER ADD INDEX is denied.'; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '2. CREATE TABLE is denied.'; + +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab_denied +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) +) +ENGINE = MergeTree ORDER BY id; -- { serverError FUNCTION_NOT_ALLOWED } + +SELECT '3. Accepted with the privilege.'; + +SET allow_introspection_functions = 1; + +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tab + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val)) GRANULARITY 1 FORMAT Null; + +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} FORMAT Null; diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.reference b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference new file mode 100644 index 000000000000..3954d852fafa --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.reference @@ -0,0 +1,6 @@ +1. A set from a table. +2. A subquery. +3. A dictionary lookup. +4. The same via ALTER ADD INDEX. +5. A literal set is still accepted. +1 diff --git a/tests/queries/0_stateless/02346_text_index_transform_data_access.sql b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql new file mode 100644 index 000000000000..9d785850ee83 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_data_access.sql @@ -0,0 +1,68 @@ +-- Text index transforms are analysed under the global context, so anything that reads a table or a +-- dictionary while being analysed would do it with full access, and constant folding could reveal +-- what it read. A transform must be a pure function of the indexed value, so these are rejected +-- before any analysis. See 02346_text_index_transform_access for the function permission checks. + +DROP TABLE IF EXISTS tab; +DROP TABLE IF EXISTS set_source; +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dict_source; + +CREATE TABLE set_source (x String) ENGINE = Set; +INSERT INTO set_source VALUES ('secret'); + +CREATE TABLE dict_source (id UInt64, value String) ENGINE = MergeTree ORDER BY id; +INSERT INTO dict_source VALUES (1, 'secret'); +CREATE DICTIONARY dict (id UInt64, value String) PRIMARY KEY id +SOURCE(CLICKHOUSE(TABLE 'dict_source')) LAYOUT(FLAT()) LIFETIME(0); + +SELECT '1. A set from a table.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '2. A subquery.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = concat(val, (SELECT any(value) FROM dict_source))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '3. A dictionary lookup.'; + +CREATE TABLE tab +( + id UInt64, + val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))) +) +ENGINE = MergeTree ORDER BY id; -- { serverError INCORRECT_QUERY } + +SELECT '4. The same via ALTER ADD INDEX.'; + +CREATE TABLE tab (id UInt64, val String) ENGINE = MergeTree ORDER BY id; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN set_source, val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN (SELECT x FROM set_source), val, '')); -- { serverError INCORRECT_QUERY } +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', + preprocessor = concat(val, toString(toUInt64(dictGetString(currentDatabase() || '.dict', 'value', toUInt64(1)))))); -- { serverError INCORRECT_QUERY } + +SELECT '5. A literal set is still accepted.'; + +ALTER TABLE tab ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = if(val IN ('hello', 'world'), val, val)); +INSERT INTO tab VALUES (1, 'hello there'); +SELECT count() FROM tab WHERE hasAllTokens(val, ['hello']); + +DROP TABLE tab; +DROP DICTIONARY dict; +DROP TABLE dict_source; +DROP TABLE set_source; diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference new file mode 100644 index 000000000000..91fa6db49214 --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.reference @@ -0,0 +1,14 @@ +1. ALTER ADD INDEX with a transform is refused. +1 +2. CREATE with a transform is refused. +1 +3. Refused on the legacy entry-format path too, which normalizes on the host. +1 +4. Indices inherited by CREATE AS on the legacy path are refused. +1 +5. An index without a transform is unaffected. +idx_plain +6. CREATE AS with an explicit engine and no privilege on the source. +SHOW COLUMNS ON default.tab +7. The same for a source that does not exist. +SHOW COLUMNS ON default.missing diff --git a/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh new file mode 100755 index 000000000000..15b49c8bf03b --- /dev/null +++ b/tests/queries/0_stateless/02346_text_index_transform_on_cluster.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database +# no-replicated-database: ON CLUSTER is not allowed for a Replicated database + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The hosts of an `ON CLUSTER` query resolve a text index transform against their own schema and +# without the submitting user, so it is refused unless they run as that user. + +USER="user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER IF EXISTS $USER; + CREATE TABLE tab (id UInt64, val String, lowered String ALIAS lower(val)) ENGINE = MergeTree ORDER BY id; +" + +echo '1. ALTER ADD INDEX with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lowered) +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '2. CREATE with a transform is refused.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_transform ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '3. Refused on the legacy entry-format path too, which normalizes on the host.' +$CLICKHOUSE_CLIENT --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_legacy ON CLUSTER test_shard_localhost + (id UInt64, val String, INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(val))) + ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '4. Indices inherited by CREATE AS on the legacy path are refused.' +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.src_transform (id UInt64, val String, + INDEX idx(val) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = demangle(val))) ENGINE = MergeTree ORDER BY id" +$CLICKHOUSE_CLIENT --allow_introspection_functions 1 --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst_inherited ON CLUSTER test_shard_localhost + AS ${CLICKHOUSE_DATABASE}.src_transform ENGINE = MergeTree ORDER BY id +" 2>&1 | grep -c -m1 "distributed_ddl_use_initial_user_and_roles" + +echo '5. An index without a transform is unaffected.' +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + ALTER TABLE tab ON CLUSTER test_shard_localhost + ADD INDEX idx_plain(val) TYPE text(tokenizer = 'splitByNonAlpha') +" +$CLICKHOUSE_CLIENT -q "SELECT name FROM system.data_skipping_indices WHERE database = currentDatabase() AND table = 'tab' ORDER BY name" + +# With an explicit engine `setEngine` does not look at `AS src`, and the inherited indices are inspected +# on the initiator, so describing the source has to be authorized first. +$CLICKHOUSE_CLIENT -n -q " + CREATE USER $USER; + GRANT CREATE TABLE ON ${CLICKHOUSE_DATABASE}.dst TO $USER; + GRANT TABLE ENGINE ON MergeTree TO $USER; +" + +echo '6. CREATE AS with an explicit engine and no privilege on the source.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.tab ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.tab" + +echo '7. The same for a source that does not exist.' +$CLICKHOUSE_CLIENT --user "$USER" --distributed_ddl_entry_format_version 2 --distributed_ddl_output_mode none -q " + CREATE TABLE ${CLICKHOUSE_DATABASE}.dst ON CLUSTER test_shard_localhost AS ${CLICKHOUSE_DATABASE}.missing ENGINE = MergeTree ORDER BY tuple() +" 2>&1 | grep -o -m1 "SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.missing" + +$CLICKHOUSE_CLIENT -n -q " + DROP USER $USER; + DROP TABLE tab; + DROP TABLE src_transform; +" diff --git a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 index 45c6b5fe5f3f..d05007d356e4 100644 --- a/tests/queries/0_stateless/02372_analyzer_join.sql.j2 +++ b/tests/queries/0_stateless/02372_analyzer_join.sql.j2 @@ -1,4 +1,4 @@ --- Tags: long +-- Tags: long, no-msan SET enable_analyzer = 1; SET single_join_prefer_left_table = 0; diff --git a/tests/queries/0_stateless/02426_orc_bug.reference b/tests/queries/0_stateless/02426_orc_bug.reference index 4f76072e70d1..d5f93b43aa8d 100644 --- a/tests/queries/0_stateless/02426_orc_bug.reference +++ b/tests/queries/0_stateless/02426_orc_bug.reference @@ -1 +1 @@ -64a50db9526e0e3aa8c969939922658d - +f8d66b83061a9b0ce960c0b9ce32a64c - diff --git a/tests/queries/0_stateless/02884_authentication_quota.reference b/tests/queries/0_stateless/02884_authentication_quota.reference index d8ed6d97b505..c41269381185 100644 --- a/tests/queries/0_stateless/02884_authentication_quota.reference +++ b/tests/queries/0_stateless/02884_authentication_quota.reference @@ -6,7 +6,7 @@ > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -18,9 +18,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login @@ -32,7 +32,7 @@ QUOTA_EXCEEDED > Login to the user account using the wrong password. password is incorrect > Quota is exceeded 1 >= 1. Login with correct password should fail. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 2 1 > Alter the quota with MAX FAILED SEQUENTIAL AUTHENTICATIONS = 4 @@ -44,9 +44,9 @@ password is incorrect password is incorrect password is incorrect password is incorrect -QUOTA_EXCEEDED +password is incorrect > Also try to login with correct password. Quota should stay exceeded. -QUOTA_EXCEEDED +password is incorrect > Check the failed_sequential_authentications, max_failed_sequential_authentications fields. 6 4 > Reset the quota by increasing MAX FAILED SEQUENTIAL AUTHENTICATIONS and successful login diff --git a/tests/queries/0_stateless/02884_authentication_quota.sh b/tests/queries/0_stateless/02884_authentication_quota.sh index bca24bf6cc27..b092e0b35359 100755 --- a/tests/queries/0_stateless/02884_authentication_quota.sh +++ b/tests/queries/0_stateless/02884_authentication_quota.sh @@ -18,7 +18,7 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Quota is exceeded 1 >= 1. Login with correct password should fail." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" @@ -37,10 +37,10 @@ function login_test() ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' - ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "wrong_pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Also try to login with correct password. Quota should stay exceeded." - ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'QUOTA_EXCEEDED' + ${CLICKHOUSE_CLIENT} --user ${USER} --password "pass" --query "select 1 format Null" 2>&1 | grep -m1 -o 'password is incorrect' echo "> Check the failed_sequential_authentications, max_failed_sequential_authentications fields." ${CLICKHOUSE_CLIENT} -q "SELECT failed_sequential_authentications, max_failed_sequential_authentications FROM system.quotas_usage WHERE quota_name = '${QUOTA}'" diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference new file mode 100644 index 000000000000..8c21354a38e1 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.reference @@ -0,0 +1,6 @@ +1 +0 +0 +1 +0 +0 diff --git a/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh new file mode 100755 index 000000000000..bc088b046271 --- /dev/null +++ b/tests/queries/0_stateless/03100_lwu_58_pruning_empty_partition_zookeeper.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel, no-replicated-database, no-shared-merge-tree +# no-parallel: uses a global failpoint and two replicas with stopped replication queues. +# no-fasttest: a test that arms a global failpoint must run alone, and such tests are kept out of the fast test. +# no-replicated-database: the test controls replication queues of individual tables. +# no-shared-merge-tree: the failpoint is in the `ReplicatedMergeTree` block allocation path. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +set -e + +function cleanup_tables() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R2" 2>/dev/null || true + wait || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R2 SYNC" 2>/dev/null || true + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS $R1 SYNC" 2>/dev/null || true +} + +function cleanup() +{ + cleanup_tables +} +trap cleanup EXIT + +# Runs a lightweight update of partition 2 whose rows arrive from the other replica while the update +# waits for committing inserts, and checks that the update has patched all of them. +function run_case() +{ + local name=$1 + local assignment=$2 + R1=t_lwu_prune_empty_03100_58_${name}_r1 + R2=t_lwu_prune_empty_03100_58_${name}_r2 + + $CLICKHOUSE_CLIENT --query " + SET insert_keeper_fault_injection_probability = 0.0; + + DROP TABLE IF EXISTS $R2 SYNC; + DROP TABLE IF EXISTS $R1 SYNC; + + CREATE TABLE $R1 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r1') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + CREATE TABLE $R2 (p UInt8, x UInt64, v UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name', 'r2') + PARTITION BY p ORDER BY x + SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + remove_empty_parts = 0; + + INSERT INTO $R1 SELECT 1, number, 1 FROM numbers(50); + INSERT INTO $R1 SELECT 2, number, 1 FROM numbers(50); + SYSTEM SYNC REPLICA $R2; + + ALTER TABLE $R1 DELETE WHERE p = 2 SETTINGS mutations_sync = 2; + + SYSTEM STOP REPLICATION QUEUES $R1; + + SELECT count() FROM system.parts + WHERE database = currentDatabase() AND table = '$R1' AND partition_id = '2' AND active AND rows = 0; + " + + $CLICKHOUSE_CLIENT --query "INSERT INTO $R2 SELECT 2, 1000000 + number, 1 FROM numbers(30)" + + block_numbers_path="/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_lwu_prune_empty_03100_58_$name/block_numbers/2" + block_count_before=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + + $CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT rmt_lightweight_update_sleep_after_block_allocation" + + $CLICKHOUSE_CLIENT --query "UPDATE $R1 SET v = $assignment WHERE p = 2 SETTINGS enable_lightweight_update = 1, enable_shared_storage_snapshot_in_query = 1" & + + for _ in {0..300}; do + sleep 0.3 + block_count_after=$($CLICKHOUSE_CLIENT --query " + SYSTEM FLUSH LOGS zookeeper_log; + SELECT count() FROM system.zookeeper_log + WHERE type = 'Response' AND op_num = 'Create' AND path = '$block_numbers_path/block-' + AND startsWith(path_created, '$block_numbers_path/block-')") + if [[ "$block_count_after" -gt "$block_count_before" ]]; then + break + fi + done + + if [[ "$block_count_after" -le "$block_count_before" ]]; then + echo "Failed to observe a new block allocation for lightweight update at $block_numbers_path" >&2 + exit 2 + fi + + $CLICKHOUSE_CLIENT --query "SYSTEM START REPLICATION QUEUES $R1" + + wait + + + result=$($CLICKHOUSE_CLIENT --query " + SYSTEM SYNC REPLICA $R1; + SYSTEM SYNC REPLICA $R2; + + SELECT count() FROM $R1 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1; + SELECT count() FROM $R2 WHERE p = 2 AND v = 1 SETTINGS apply_patch_parts = 1") + + if [[ "$result" != $'0\n0' ]]; then + echo "Unexpected unpatched-row counts in case $name:" >&2 + echo "$result" >&2 + $CLICKHOUSE_CLIENT --query " + SELECT 'patch parts', name, rows FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND startsWith(name, 'patch') + ORDER BY table, name; + SELECT 'partition 2 parts', table, name, rows, min_block_number, max_block_number FROM system.parts + WHERE database = currentDatabase() AND table IN ('$R1', '$R2') AND partition_id = '2' + ORDER BY table, name; + SELECT 'frozen mutation version', table, mutation_id, block_numbers.partition_id, block_numbers.number + FROM system.mutations + WHERE database = currentDatabase() AND table = '$R1' + ORDER BY create_time DESC;" >&2 + exit 1 + fi + + echo "$result" + + cleanup_tables +} + +run_case plain 999 +# The `IN` operand names the updated table, so validating it in `InterpreterUpdateQuery` takes a storage +# snapshot of the table before the update waits for committing inserts. +run_case in_assignment "if((p, x, v) IN t_lwu_prune_empty_03100_58_in_assignment_r1, 999, 998)" diff --git a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh index 6819deea1fc1..35498f567da2 100755 --- a/tests/queries/0_stateless/03595_read_orc_file_segfault.sh +++ b/tests/queries/0_stateless/03595_read_orc_file_segfault.sh @@ -15,7 +15,7 @@ ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} SYNC" ${CLICKHOUSE_CLIENT} --query "CREATE TABLE ${TABLE_NAME} (c0 Int) ENGINE = File(ORC, '${USER_FILES_PATH}/${TEST_FILE}')" ${CLICKHOUSE_CLIENT} --query "INSERT INTO TABLE ${TABLE_NAME} (c0) VALUES (1),(2),(3),(5.4)" -${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx SETTINGS input_format_orc_use_fast_decoder = 0" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM file('${USER_FILES_PATH}/${TEST_FILE}', 'ORC') AS tx" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS ${TABLE_NAME} sync" diff --git a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference index 2217316a750e..8f35989d78b9 100644 --- a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference +++ b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.reference @@ -10,6 +10,8 @@ Expression Name: v Description: set GRANULARITY 1 Condition: true - Parts: 0/1 - Granules: 0/1 - Ranges: 0 + Parts: 1/1 + Granules: 1/1 + Ranges: 1 +1 +1 diff --git a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql index c799670ca5db..d3a92f2e129a 100644 --- a/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql +++ b/tests/queries/0_stateless/03707_set_index_bad_get_null_bug.sql @@ -13,3 +13,8 @@ ORDER BY (ts); INSERT INTO test (v) FORMAT Values ('VALUE1'); EXPLAIN indexes = 1, description=0 SELECT CAST(NULL, 'Nullable(String)') AS source, v AS v FROM test WHERE (source = 'VALUE1') OR (v ILIKE 'VALUE1'); + +-- The row matches via the second disjunct, so the granule must not be pruned: the set +-- index must return the same rows as a scan with skip indexes disabled. +SELECT count() FROM test WHERE (CAST(NULL, 'Nullable(String)') = 'VALUE1') OR (v ILIKE 'VALUE1'); +SELECT count() FROM test WHERE (CAST(NULL, 'Nullable(String)') = 'VALUE1') OR (v ILIKE 'VALUE1') SETTINGS use_skip_indexes = 0; diff --git a/tests/queries/0_stateless/03784_bad_base_backup.sh b/tests/queries/0_stateless/03784_bad_base_backup.sh index ef0cdd18a110..6ac1401f2fea 100755 --- a/tests/queries/0_stateless/03784_bad_base_backup.sh +++ b/tests/queries/0_stateless/03784_bad_base_backup.sh @@ -48,3 +48,15 @@ thread & thread & wait + +# The databases are created outside of the test database, so they must be dropped here: +# leftover `Replicated` databases break tests that enumerate all `Replicated` databases of the server, +# such as `05061_system_drop_database_replica_access`. Wait for the `ASYNC` backups to finish first. +for _ in $(seq 1 600) +do + [[ $($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.backups WHERE status = 'CREATING_BACKUP' AND name LIKE '%${CLICKHOUSE_DATABASE}%'") == 0 ]] && break + sleep 0.1 +done + +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d1_$CLICKHOUSE_DATABASE SYNC" +$CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS d2_$CLICKHOUSE_DATABASE SYNC" diff --git a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh index 6db574849a79..6548e86729d7 100755 --- a/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh +++ b/tests/queries/0_stateless/03822_file_function_read_on_file_grant.sh @@ -16,7 +16,7 @@ EOF (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "ACCESS_DENIED") >= 1 )) && echo "ACCESS_DENIED" || echo "UNEXPECTED"; -${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user"; +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE, CREATE TEMPORARY TABLE ON *.* TO $user"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "SELECT file('$missing_txt')" 2>&1 | grep -c "FILE_DOESNT_EXIST") >= 1 )) && echo "FILE_DOESNT_EXIST" || echo "UNEXPECTED"; (( $(${CLICKHOUSE_CLIENT} --user $user --query "DESCRIBE TABLE file('$missing_csv', 'CSV')" 2>&1 | grep -c "CANNOT_STAT") >= 1 )) && echo "CANNOT_STAT" || echo "UNEXPECTED"; diff --git a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh index 3e4c623ee8e6..8caf9b22b41b 100755 --- a/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh +++ b/tests/queries/0_stateless/03923_kafka2_keeper_offsets.sh @@ -30,7 +30,7 @@ $CLICKHOUSE_CLIENT --allow_experimental_kafka_offsets_storage_in_keeper 1 -q " kafka_format = 'JSONEachRow', kafka_max_block_size = 100, kafka_keeper_path = '$KEEPER_PATH', - kafka_replica_name = 'r1'; + kafka_replica_name = '{replica}'; " # Create destination table diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference index 491b7765b057..7d4cda3c2395 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.reference @@ -16,7 +16,7 @@ 1 1 1 --- Optimization also works with basic (non-bucketed) serialization +-- No optimization with basic (non-bucketed) serialization 1 -- Correctness: results with optimization 7 7 70 diff --git a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql index c9eaddb60218..e161a47a3cfa 100644 --- a/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql +++ b/tests/queries/0_stateless/03989_map_subcolumn_function_to_subcolumns.sql @@ -150,20 +150,19 @@ SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHE -- ========================================== -- Section 8: basic serialization (not with_buckets) --- The optimization still applies because DataTypeMap exposes dynamic subcolumns --- regardless of serialization version. With basic serialization, the whole map is --- read and the key is extracted; with_buckets reads only the relevant bucket. +-- The rewrite is not applied: with basic serialization the key subcolumn reads the whole map anyway. -- ========================================== DROP TABLE t_map_subcolumns; CREATE TABLE t_map_subcolumns (id UInt64, m Map(String, UInt64)) -ENGINE = MergeTree ORDER BY id; +ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; INSERT INTO t_map_subcolumns SELECT number, map('key1', number) FROM numbers(10); -SELECT '-- Optimization also works with basic (non-bucketed) serialization'; -SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; +SELECT '-- No optimization with basic (non-bucketed) serialization'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_subcolumns WHERE m['key1'] > 5) WHERE explain LIKE '%m.key_key1%'; -- ========================================== -- Section 9: Correctness - verify actual query results after optimization diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference index 89024e17dd7f..a108bf0eea76 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.reference @@ -54,7 +54,7 @@ 98 98 2 99 99 1 -- Section 4: PREWHERE with basic serialization --- Optimization still rewrites to subcolumn +-- No rewrite to subcolumn 1 -- Correctness: PREWHERE with basic serialization 96 96 960 diff --git a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql index a3594aff2a1b..db0474ce8c2a 100644 --- a/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql +++ b/tests/queries/0_stateless/04000_map_subcolumns_prewhere.sql @@ -133,7 +133,7 @@ DROP TABLE t_map_prewhere; -- ========================================== -- Section 4: PREWHERE with basic serialization (non-bucketed) --- Optimization still applies, but reads the whole map internally. +-- No rewrite to the key subcolumn, it would read the whole map anyway. -- ========================================== DROP TABLE IF EXISTS t_map_prewhere; @@ -141,14 +141,15 @@ CREATE TABLE t_map_prewhere (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id SETTINGS map_serialization_version = 'basic', + map_serialization_version_for_zero_level_parts = 'basic', min_bytes_for_wide_part = 1, min_rows_for_wide_part = 1; INSERT INTO t_map_prewhere SELECT number, map('key1', number, 'key2', number * 10) FROM numbers(100); SELECT '-- Section 4: PREWHERE with basic serialization'; -SELECT '-- Optimization still rewrites to subcolumn'; -SELECT count() > 0 FROM ( +SELECT '-- No rewrite to subcolumn'; +SELECT count() = 0 FROM ( EXPLAIN actions = 1 SELECT id, m FROM t_map_prewhere PREWHERE m['key1'] > 95 ) WHERE explain LIKE '%m.key_key1%'; diff --git a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql index 05fe94c220e0..d0a35aacb003 100644 --- a/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql +++ b/tests/queries/0_stateless/04039_text_index_map_values_subcolumn.sql @@ -1,7 +1,7 @@ -- Tags: no-random-settings -- Tests that text indexes built on mapValues(m) work correctly when the analyzer --- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form. +-- rewrites arrayElement(m, 'key') into the map.key_* subcolumn form, which it does only for bucketed Maps. SET enable_analyzer = 1; @@ -16,7 +16,8 @@ CREATE TABLE tab ) ENGINE = MergeTree ORDER BY id -SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0; +SETTINGS index_granularity = 1, index_granularity_bytes = '10M', min_bytes_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; INSERT INTO tab VALUES (0, {'service':'web-api'}), (1, {'service':'backend'}), (2, {'service':'frontend'}); diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference new file mode 100644 index 000000000000..e99e8dbc05e4 --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.reference @@ -0,0 +1,8 @@ +1 +0 +1 +0 +1 +0 +1 +0 diff --git a/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql new file mode 100644 index 000000000000..0965065b3bbe --- /dev/null +++ b/tests/queries/0_stateless/04113_has_subsequence_empty_haystack.sql @@ -0,0 +1,9 @@ +SELECT hasSubsequenceUTF8('', ''); +SELECT hasSubsequenceUTF8('', 'a'); +SELECT hasSubsequenceCaseInsensitiveUTF8('', ''); +SELECT hasSubsequenceCaseInsensitiveUTF8('', 'A'); + +SELECT hasSubsequenceUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceUTF8(materialize(''), materialize('a')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('')); +SELECT hasSubsequenceCaseInsensitiveUTF8(materialize(''), materialize('A')); diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference new file mode 100644 index 000000000000..382c328e0874 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.reference @@ -0,0 +1,3 @@ +2 20 +2 20 +2099-01-01 00:00:00 20 diff --git a/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql new file mode 100644 index 000000000000..06a0cd88ef07 --- /dev/null +++ b/tests/queries/0_stateless/04266_ttl_with_subcolumn_expression.sql @@ -0,0 +1,34 @@ +SET mutations_sync = 1; + +-- Test that TTL expressions referencing subcolumns work correctly. +-- Previously, executeExpressionAndGetColumn used getByName which failed +-- for subcolumns not present as top-level columns in the block. +-- We test both INSERT (updateTTL in MergeTreeDataWriter) and merge +-- (TTL algorithms in the merge pipeline) paths. + +-- Case 1: Tuple subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol; +CREATE TABLE t_ttl_subcol (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL t.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol VALUES ((1, '2000-01-01'), 10); +INSERT INTO t_ttl_subcol VALUES ((2, '2099-01-01'), 20); +OPTIMIZE TABLE t_ttl_subcol FINAL; +SELECT t.a, val FROM t_ttl_subcol ORDER BY val; +DROP TABLE t_ttl_subcol; + +-- Case 2: Tuple subcolumn with function in TTL expression +DROP TABLE IF EXISTS t_ttl_subcol_func; +CREATE TABLE t_ttl_subcol_func (t Tuple(a UInt32, d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL toDate(t.d) + INTERVAL 1 MONTH; +INSERT INTO t_ttl_subcol_func VALUES ((1, '2000-01-01 12:00:00'), 10); +INSERT INTO t_ttl_subcol_func VALUES ((2, '2099-01-01 12:00:00'), 20); +OPTIMIZE TABLE t_ttl_subcol_func FINAL; +SELECT t.a, val FROM t_ttl_subcol_func ORDER BY val; +DROP TABLE t_ttl_subcol_func; + +-- Case 3: JSON subcolumn in TTL expression +DROP TABLE IF EXISTS t_ttl_json_subcol; +CREATE TABLE t_ttl_json_subcol (json JSON(d DateTime), val Int32) ENGINE = MergeTree ORDER BY val TTL json.d + INTERVAL 1 MONTH; +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2000-01-01"}', 10); +INSERT INTO t_ttl_json_subcol VALUES ('{"d" : "2099-01-01"}', 20); +OPTIMIZE TABLE t_ttl_json_subcol FINAL; +SELECT json.d, val FROM t_ttl_json_subcol ORDER BY val; +DROP TABLE t_ttl_json_subcol; diff --git a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh index 6dfb8038211b..1639da5845ab 100755 --- a/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh +++ b/tests/queries/0_stateless/04337_orc_schema_inference_deep_recursion.sh @@ -7,10 +7,9 @@ # grind (and could overflow the native stack), uncancellable. It must now be rejected as # TOO_DEEP_RECURSION once the nesting exceeds max_parser_depth. # -# 2. The Apache ORC C++ library (convertType) builds its own orc::Type tree by recursing over the -# file footer before any ClickHouse code runs. A pathologically deep file used to overflow the -# native stack there (crashing the process / triggering the OOM killer). The library now bounds -# the nesting depth and rejects such a file instead of crashing. +# 2. The ORC reader builds its type tree by recursing over the file footer before the schema +# inference runs. A pathologically deep file must not overflow the native stack there: the +# reader bounds the nesting depth and rejects such a file. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -55,18 +54,24 @@ orc.write_table(pa.table({'x': pa.array([], type=t)}), '$2') " } -# (1) A moderate file (200 levels) that the ORC library builds fine, with max_parser_depth lowered +# (1) A moderate file (200 levels) that the ORC reader builds fine, with max_parser_depth lowered # below the nesting so parseORCType rejects it deterministically and build-independently. gen_orc 200 "${TMP_DIR}/moderate.orc" $CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/moderate.orc', ORC) SETTINGS max_parser_depth = 100" 2>&1 \ | expect_contains parser_depth_limit TOO_DEEP_RECURSION -# (2) A file nested past the ORC library's own limit. Even with max_parser_depth raised so high that -# parseORCType would accept it, the library must reject it (without crashing). The library throws +# (2) A file nested past the ORC reader's own limit. Even with max_parser_depth raised so high that +# parseORCType would accept it, the reader must reject it (without crashing). The reader throws # before recursing past its limit, so this is safe to run. gen_orc 3000 "${TMP_DIR}/deep.orc" -$CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1 \ - | expect_contains orc_library_depth_limit "nesting depth exceeds the limit" +# Under TSan the stack size check allows only 5% of the stack, so it can reject the file before the depth limit. +out=$($CLICKHOUSE_LOCAL --query "DESC TABLE file('${TMP_DIR}/deep.orc', ORC) SETTINGS max_parser_depth = 100000" 2>&1) +if printf '%s\n' "$out" | grep -qF -e "nesting depth exceeds the limit" -e "TOO_DEEP_RECURSION"; then + echo "orc_library_depth_limit: nesting depth exceeds the limit" +else + echo "orc_library_depth_limit: expected 'nesting depth exceeds the limit', got:" + printf '%s\n' "$out" | head -3 +fi # (3) max_parser_depth=0 means unlimited (matching the SQL parser), so a moderately nested file must # still be inferred normally rather than rejected by the explicit limit. diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.reference b/tests/queries/0_stateless/04338_async_insert_current_user.reference new file mode 100644 index 000000000000..161fe963e5bf --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.reference @@ -0,0 +1,6 @@ +1 1 1 +2 1 1 +1 1 1 +2 1 1 +10 1 1 +20 1 1 diff --git a/tests/queries/0_stateless/04338_async_insert_current_user.sql b/tests/queries/0_stateless/04338_async_insert_current_user.sql new file mode 100644 index 000000000000..5a04881f9670 --- /dev/null +++ b/tests/queries/0_stateless/04338_async_insert_current_user.sql @@ -0,0 +1,43 @@ +-- Regression test for issue #107530: context-dependent functions such as currentUser() +-- must evaluate to the inserting user (not an empty string) on the async_insert flush path, +-- both in DEFAULT/MATERIALIZED column expressions and in materialized views. + +DROP TABLE IF EXISTS t_async_user; +DROP TABLE IF EXISTS t_async_user_src; +DROP TABLE IF EXISTS t_async_user_dst; +DROP VIEW IF EXISTS t_async_user_mv; + +-- DEFAULT / MATERIALIZED column expressions calling currentUser(). +CREATE TABLE t_async_user +( + x Int32, + u_default String DEFAULT currentUser(), + u_materialized String MATERIALIZED currentUser() +) +ENGINE = MergeTree ORDER BY x; + +INSERT INTO t_async_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1); +INSERT INTO t_async_user (x) SETTINGS async_insert = 0 VALUES (2); + +-- The async row (x=1) and the sync row (x=2) must both record the inserting user. +-- Before the fix the async row recorded an empty string. +SELECT x, u_default = currentUser() AS default_matches, length(u_default) > 0 AS default_non_empty +FROM t_async_user ORDER BY x; +SELECT x, u_materialized = currentUser() AS materialized_matches, length(u_materialized) > 0 AS materialized_non_empty +FROM t_async_user ORDER BY x; + +-- Materialized view selecting currentUser(). +CREATE TABLE t_async_user_src (x Int32) ENGINE = MergeTree ORDER BY x; +CREATE TABLE t_async_user_dst (x Int32, u String) ENGINE = MergeTree ORDER BY x; +CREATE MATERIALIZED VIEW t_async_user_mv TO t_async_user_dst AS SELECT x, currentUser() AS u FROM t_async_user_src; + +INSERT INTO t_async_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10); +INSERT INTO t_async_user_src SETTINGS async_insert = 0 VALUES (20); + +SELECT x, u = currentUser() AS mv_matches, length(u) > 0 AS mv_non_empty +FROM t_async_user_dst ORDER BY x; + +DROP VIEW t_async_user_mv; +DROP TABLE t_async_user_dst; +DROP TABLE t_async_user_src; +DROP TABLE t_async_user; diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference new file mode 100644 index 000000000000..697f9b3fa30a --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.reference @@ -0,0 +1,3 @@ +1 1 1 1 +2 1 1 1 +10 1 1 1 diff --git a/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh new file mode 100755 index 000000000000..b457807b3384 --- /dev/null +++ b/tests/queries/0_stateless/04339_async_insert_authenticated_user.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Regression test for issue #107530: authenticatedUser() must evaluate to the +# originally authenticated user (not an empty string, and not currentUser()) on the +# async_insert flush path. Uses EXECUTE AS so currentUser() and authenticatedUser() +# diverge: the test then fails if setAuthenticatedUserName is removed (au becomes empty) +# or wired to the wrong value (au becomes the impersonated user). + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +AUTH_USER="auth_user_${CLICKHOUSE_DATABASE}" +APP_USER="app_user_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER IF EXISTS ${APP_USER}" +$CLICKHOUSE_CLIENT --query "CREATE USER ${AUTH_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "CREATE USER ${APP_USER} IDENTIFIED WITH no_password" +$CLICKHOUSE_CLIENT --query "GRANT IMPERSONATE ON ${APP_USER} TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "GRANT ALL ON ${CLICKHOUSE_DATABASE}.* TO ${APP_USER}" + +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP VIEW IF EXISTS t_auth_user_mv" + +# DEFAULT columns: currentUser() = impersonated user, authenticatedUser() = original user. +$CLICKHOUSE_CLIENT --query " +CREATE TABLE t_auth_user +( + x Int32, + cu String DEFAULT currentUser(), + au String DEFAULT authenticatedUser() +) +ENGINE = MergeTree ORDER BY x" + +# Async insert (x=1) and sync insert (x=2), both under EXECUTE AS the impersonated user. +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (1)" +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user (x) SETTINGS async_insert = 0 VALUES (2)" + +# The async row (x=1) and the sync row (x=2) must both record currentUser()=impersonated +# and authenticatedUser()=originally authenticated. Before the fix the async row recorded +# an empty authenticatedUser(). cu_ne_au proves the two ClientInfo fields are restored +# independently (it would be false if authenticatedUser were mis-wired to currentUser). +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user ORDER BY x" + +# Materialized view selecting authenticatedUser() under EXECUTE AS on the async path. +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_src (x Int32) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE TABLE t_auth_user_dst (x Int32, cu String, au String) ENGINE = MergeTree ORDER BY x" +$CLICKHOUSE_CLIENT --query "CREATE MATERIALIZED VIEW t_auth_user_mv TO t_auth_user_dst AS SELECT x, currentUser() AS cu, authenticatedUser() AS au FROM t_auth_user_src" + +$CLICKHOUSE_CLIENT --user "${AUTH_USER}" --query \ + "EXECUTE AS ${APP_USER}; INSERT INTO ${CLICKHOUSE_DATABASE}.t_auth_user_src SETTINGS async_insert = 1, wait_for_async_insert = 1 VALUES (10)" + +$CLICKHOUSE_CLIENT --query " +SELECT + x, + cu = '${APP_USER}' AS cu_is_impersonated, + au = '${AUTH_USER}' AS au_is_authenticated, + cu != au AS cu_ne_au +FROM t_auth_user_dst ORDER BY x" + +$CLICKHOUSE_CLIENT --query "DROP VIEW t_auth_user_mv" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_dst" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user_src" +$CLICKHOUSE_CLIENT --query "DROP TABLE t_auth_user" +$CLICKHOUSE_CLIENT --query "DROP USER ${AUTH_USER}" +$CLICKHOUSE_CLIENT --query "DROP USER ${APP_USER}" diff --git a/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference new file mode 100644 index 000000000000..add40c4db3ca --- /dev/null +++ b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.reference @@ -0,0 +1,14 @@ +50 +50 +50 +50 +50 +50 +50 +50 +50 +33 +50 +50 +1 +1 diff --git a/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql new file mode 100644 index 000000000000..c653a112c5f6 --- /dev/null +++ b/tests/queries/0_stateless/04627_set_index_null_const_no_prune.sql @@ -0,0 +1,50 @@ +-- Regression test for https://github.com/ClickHouse/ClickHouse/issues/103103 +-- A NULL-valued atom (e.g. toInt64OrNull('x')) reaching the set skip index was bit-wrapped by +-- __bitWrapperFunc and propagated NULL instead of the UNKNOWN mask, so the granule check wrongly +-- pruned matching granules and the query returned fewer rows than with skip indexes disabled. + +DROP TABLE IF EXISTS t_null_const_set_index; + +CREATE TABLE t_null_const_set_index (v Int64, lc LowCardinality(String), INDEX i lc TYPE set(64) GRANULARITY 1) +ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 32; + +INSERT INTO t_null_const_set_index SELECT number, toString(number % 3) FROM numbers(100); + +-- Disable the query condition cache so every query below is analyzed by the index, not served +-- from a cached verdict, and both granule-filtering paths are exercised deterministically: +-- secondary_indices_enable_bulk_filtering = 1 -> getPossibleGranules, 0 -> mayBeTrueOnGranule. +SET use_query_condition_cache = 0; + +-- All of the following match 50 rows via the second disjunct and must not be pruned. +-- Before the fix they returned 0 with the index. Run each under both granule paths. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 1; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toInt64OrNull('x')) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 0; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND nullIf(1, 1)) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 1; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND nullIf(1, 1)) OR v < 50 SETTINGS secondary_indices_enable_bulk_filtering = 0; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND CAST(NULL AS Nullable(Int64))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND toUInt8OrNull('x')) OR v < 50; +-- The NULL value may be hidden behind a function that suppresses constant folding, so the atom +-- is not a folded ColumnConst; identity() and materialize() must be handled the same way. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND identity(toInt64OrNull('x'))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND materialize(toInt64OrNull('x'))) OR v < 50; +-- NULL value next to a predicate on the indexed column itself, and under NOT. +SELECT count() FROM t_null_const_set_index WHERE (lc = '1' AND toInt64OrNull('x')) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE NOT ((lc = '1' AND toInt64OrNull('x')) OR v >= 50); +-- Non-integer typed NULL and bare NULL route to UNKNOWN already; must stay 50. +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND CAST(NULL AS Nullable(Float64))) OR v < 50; +SELECT count() FROM t_null_const_set_index WHERE (v = 1 AND NULL) OR v < 50; + +-- The NULL atom must not disable pruning: the index still prunes a granule it can legitimately +-- exclude. `lc = '999'` matches nothing, so every granule is skipped (`Granules: 0/`, +-- asserted format-agnostically since the total depends on the randomized part type). +SELECT count() > 0 AS prunes_nonmatching_granules +FROM (EXPLAIN indexes = 1 SELECT count() FROM t_null_const_set_index WHERE lc = '999') +WHERE explain ILIKE '%Granules: 0/%'; + +-- With the NULL atom present, a matching disjunct must still keep its granules: the index is +-- analyzed (the UNKNOWN atom does not disable it) and does not prune to zero. +SELECT count() = 0 AS null_atom_keeps_matching_granules +FROM (EXPLAIN indexes = 1 SELECT count() FROM t_null_const_set_index WHERE (lc = '1' AND toInt64OrNull('x')) OR lc = '2') +WHERE explain ILIKE '%Granules: 0/%'; + +DROP TABLE t_null_const_set_index; diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference new file mode 100644 index 000000000000..f693c2c0ae49 --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.reference @@ -0,0 +1,9 @@ +345 +11400 +168 5800 +[0,1,2,3,4,5,6,7,8,9,10,11,12] +3 3 +10 10 +17 4 +24 11 +1152 71944 diff --git a/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql new file mode 100644 index 000000000000..4ce81b48033e --- /dev/null +++ b/tests/queries/0_stateless/04628_multistep_prewhere_default_column.sql @@ -0,0 +1,23 @@ +-- Multi-step PREWHERE must keep columns needed to evaluate `DEFAULT`s of columns missing in the part. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default; + +CREATE TABLE t_multistep_prewhere_default (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple(); +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default ADD COLUMN v Int64 DEFAULT k % 13; +ALTER TABLE t_multistep_prewhere_default ADD COLUMN w Int64 DEFAULT k + length(s); + +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +SELECT sum(v) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'; +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3' AND k % 2 = 1; +SELECT arraySort(groupUniqArray(v)) FROM (SELECT DISTINCT v FROM t_multistep_prewhere_default WHERE k <= 395 AND s = '3'); +SELECT k, v FROM t_multistep_prewhere_default WHERE k <= 30 AND s = '3' ORDER BY k; + +-- Parts written after the ALTER store v and w physically. +INSERT INTO t_multistep_prewhere_default SELECT number, toString(number % 7), 42, 43 FROM numbers(1000, 100); +SELECT sum(v), sum(w) FROM t_multistep_prewhere_default WHERE k <= 1050 AND s = '3'; + +DROP TABLE t_multistep_prewhere_default; diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference new file mode 100644 index 000000000000..22b6a5ac9c04 --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.reference @@ -0,0 +1,6 @@ +350 +350 +4 4 +11 11 +18 5 +25 12 diff --git a/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql new file mode 100644 index 000000000000..46e95b8cd3dd --- /dev/null +++ b/tests/queries/0_stateless/04629_multistep_prewhere_default_column_patch_parts.sql @@ -0,0 +1,25 @@ +-- Multi-step PREWHERE must see patched values of the columns it carries over to evaluate `DEFAULT`s. +-- https://github.com/ClickHouse/ClickHouse/issues/111757 + +DROP TABLE IF EXISTS t_multistep_prewhere_default_patch; + +SET enable_lightweight_update = 1, apply_patch_parts = 1; +SET optimize_move_to_prewhere = 1, move_all_conditions_to_prewhere = 1, enable_multiple_prewhere_read_steps = 1; + +CREATE TABLE t_multistep_prewhere_default_patch (k UInt32, s String) ENGINE = MergeTree ORDER BY tuple() +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1; + +SYSTEM STOP MERGES t_multistep_prewhere_default_patch; + +INSERT INTO t_multistep_prewhere_default_patch SELECT number, toString(number % 7) FROM numbers(1000); +ALTER TABLE t_multistep_prewhere_default_patch ADD COLUMN v Int64 DEFAULT k % 13; + +UPDATE t_multistep_prewhere_default_patch SET k = k + 1 WHERE 1; + +-- Both queries must agree: `v` is missing in the part, so it is evaluated from the patched `k`. +SELECT sum((k % 13)::Int64) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; +SELECT sum(v) FROM t_multistep_prewhere_default_patch WHERE k <= 396 AND s = '3'; + +SELECT k, v FROM t_multistep_prewhere_default_patch WHERE k <= 30 AND s = '3' ORDER BY k; + +DROP TABLE t_multistep_prewhere_default_patch; diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference new file mode 100644 index 000000000000..7bed391e68f3 --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.reference @@ -0,0 +1,4 @@ +INCORRECT_DATA +0 0 +1 1 +2 2 diff --git a/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh new file mode 100755 index 000000000000..57a8727696be --- /dev/null +++ b/tests/queries/0_stateless/04856_orc_corrupt_stripe_footer.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The stripe footer of this blob is truncated, so reading it must fail with a regular +# INCORRECT_DATA exception. +BLOB='4f52431100000a061204080150005500000a280a06000000000000121e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc1550000f0000780039604d293e0b00006e0007dda36300f00a0608061000180b0a0608061001182d0a0608011001180a0a060805100118081204080010001204080210001a03474d545100000a260a04080150000a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc155000b500000803107e1a0a08031038181220342801220f080c1201011a0263302000280030002208080920002800300030013a04080150003a1e08014a1818b8fef997d7d63820b8fef997d7d63828c1fc1530c1fc15500040904e48016200085d1005188080102202000c282b300682f403034f524317' + +# The fixture must stay pure even-length lowercase hex: unhex's result for a non-hex character is +# implementation-defined, so one invalid character makes the corrupt footer decoder-dependent and +# this test silently stops asserting anything. +if [[ ! $BLOB =~ ^[0-9a-f]+$ ]] || (( ${#BLOB} % 2 )); then + echo "BLOB must be an even-length string of [0-9a-f]" >&2 + exit 1 +fi + +$CLICKHOUSE_LOCAL -q "SELECT c0 FROM format(ORC, 'c0 DateTime64(3)', unhex('$BLOB'));" 2>&1 \ + | grep -oE "INCORRECT_DATA" \ + | sort -u + +# Well-formed ORC must still read back unchanged. +DATA_FILE="$CLICKHOUSE_TMP/04856_orc_control_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_LOCAL -q "SELECT number AS a, toString(number) AS b FROM numbers(3) FORMAT ORC" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT a, b FROM file('$DATA_FILE', ORC) ORDER BY a" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference new file mode 100644 index 000000000000..1f714f4b2082 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.reference @@ -0,0 +1,14 @@ +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +BROTLI compression in ORC files is not supported +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +CANNOT_EXTRACT_TABLE_STRUCTURE +INCORRECT_DATA +0 +1 +2 diff --git a/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh new file mode 100755 index 000000000000..dd54288e64f9 --- /dev/null +++ b/tests/queries/0_stateless/05036_orc_unimplemented_codec_no_abort.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Truncating this fixture to 289 bytes leaves byte 6 in the postscript's compression field. Codec 6 +# is BROTLI, which the ORC format declares but this reader does not implement. The reader rejects it +# with a NOT_IMPLEMENTED exception; it must never be a logical error, which aborts in debug and +# sanitizer builds. +DATA_FILE="$CLICKHOUSE_TMP/05036_orc_codec6_${CLICKHOUSE_DATABASE}.orc" +head -c 289 "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$DATA_FILE" + +# Both the schema-inference path and the explicit-structure path reach the reader, so both are +# asserted here. Match on the error text, never on the exit status: ClickHouse exits with the error +# code truncated to a byte, so 636 and 124 are the same outcome. +for query in \ + "SELECT * FROM file('$DATA_FILE', ORC) FORMAT Null" \ + "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" \ + "SELECT count() FROM file('$DATA_FILE', ORC, 'x Int32')" \ + "DESCRIBE file('$DATA_FILE', ORC)" \ + "SELECT * FROM format(ORC, 'x Int32', (SELECT * FROM file('$DATA_FILE', RawBLOB))) FORMAT Null" +do + # An abort prints nothing at all, so classify explicitly rather than letting the arm go silent: + # a missing line is much harder to read in a diff than a named verdict. + OUT=$($CLICKHOUSE_LOCAL --query "$query" 2>&1) + if [ -z "$OUT" ]; then + echo "no output at all" + else + echo "$OUT" | grep -o -m1 'BROTLI compression in ORC files is not supported\|Logical error' || echo "unexpected: $OUT" + fi +done + +# The message must name the codec, and must not call the file corrupt: a well-formed +# Brotli-compressed ORC file takes this same path. +$CLICKHOUSE_LOCAL --query "SELECT * FROM file('$DATA_FILE', ORC, 'x Int32') FORMAT Null" 2>&1 \ + | grep -o -m1 'BROTLI compression in ORC files is not supported\|CORRUPTED\|INCORRECT_DATA' + +# Neighbouring truncations are genuinely corrupt and must keep reporting corruption rather than the +# codec gap. Schema inference wraps every non-retryable cause in one outer code, so that arm alone +# cannot tell the two apart; the explicit-structure arm bypasses the wrapper and surfaces the inner +# classification, and counting the codec error there pins them apart. +for length in 200 400 +do + NEIGHBOUR="$CLICKHOUSE_TMP/05036_orc_${length}_${CLICKHOUSE_DATABASE}.orc" + head -c $length "$CUR_DIR"/data_orc/orc_nested_union_type.orc > "$NEIGHBOUR" + $CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC) FORMAT Null" 2>&1 \ + | grep -o -m1 'CANNOT_EXTRACT_TABLE_STRUCTURE\|Logical error' + EXPLICIT=$($CLICKHOUSE_LOCAL --query "SELECT * FROM file('$NEIGHBOUR', ORC, 'x Int32') FORMAT Null" 2>&1) + echo "$EXPLICIT" | grep -o -m1 'INCORRECT_DATA\|Logical error' || echo "unexpected: $EXPLICIT" + echo "$EXPLICIT" | grep -c 'BROTLI compression' + rm "$NEIGHBOUR" +done + +# Well-formed ORC must still read back unchanged. +$CLICKHOUSE_LOCAL --query "SELECT i FROM file('$CUR_DIR/data_orc/orc_union_type.orc', ORC) ORDER BY i" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference new file mode 100644 index 000000000000..98fb6a686563 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.reference @@ -0,0 +1,4 @@ +1 +1 +1 +1 diff --git a/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh new file mode 100755 index 000000000000..0e451abc8151 --- /dev/null +++ b/tests/queries/0_stateless/05053_replicated_max_logs_to_keep_zero.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: zookeeper, replica, no-shared-merge-tree, no-replicated-database +# no-shared-merge-tree: the setting bounds the ReplicatedMergeTree log, which SharedMergeTree does not have +# no-replicated-database: the ZooKeeper path and the replica name are literal, so they collide between the hosts of the database + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# The oldest kept log record names the threshold that log pointers of inactive replicas are compared +# with, so a window that keeps no records at all has no meaning. +ERR="A setting's value has to be greater than 0" + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs_zero (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# An ATTACH that carries a full definition is user input too, and reaches the same check. +uuid=$($CLICKHOUSE_CLIENT --query "SELECT generateUUIDv4()") +$CLICKHOUSE_CLIENT --query " + ATTACH TABLE max_logs_zero UUID '$uuid' (x UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r', '1') ORDER BY x + SETTINGS max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +$CLICKHOUSE_CLIENT --query " + CREATE TABLE max_logs (x UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/r2', '1') ORDER BY x; +" +$CLICKHOUSE_CLIENT --query " + ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 0; +" 2>&1 | grep -F -q "$ERR" && echo 1 || echo 0 + +# A positive value is still accepted and stored. +$CLICKHOUSE_CLIENT --query "ALTER TABLE max_logs MODIFY SETTING max_replicated_logs_to_keep = 1;" +$CLICKHOUSE_CLIENT --query " + SELECT count() FROM system.tables + WHERE database = currentDatabase() AND name = 'max_logs' + AND engine_full LIKE '%max_replicated_logs_to_keep = 1%'; +" + +$CLICKHOUSE_CLIENT --query "DROP TABLE max_logs SYNC" diff --git a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference index ec35dc29b3b4..6be1fa0c53ad 100644 --- a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference +++ b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.reference @@ -1,5 +1,9 @@ SASL mechanism longer than the message: error response password without a terminator: error response +password message at the Int32 maximum: error response +password message above the limit: error response +SASL initial response at the Int32 maximum: error response +SASL final response at the Int32 maximum: error response well-formed exchange: query result received query with a smuggled tail: error response query shorter than declared: error response diff --git a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh index e5fd34c2db3f..b5d3e9b7acef 100755 --- a/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh +++ b/tests/queries/0_stateless/05054_postgresql_protocol_message_size.sh @@ -32,6 +32,32 @@ def connect(): return sock +def connect_short(): + """A connection whose client timeout is well below the server's `handshake_timeout_milliseconds` (30 + seconds by default), so a message the server waits for shows up as a client timeout. With a timeout + at or above the handshake timeout the server would answer the same error response on its own, and a + regression that only makes the server wait would not be noticed.""" + sock = socket.create_connection(("127.0.0.1", port), timeout=5) + sock.settimeout(5) + return sock + + +def read_message(sock): + """Reads one backend message: a type byte, a length that counts itself, and the body.""" + def recv_exactly(size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise AssertionError("the connection closed before a complete message") + data += chunk + return data + + message_type = recv_exactly(1) + (length,) = struct.unpack(">i", recv_exactly(4)) + return message_type, recv_exactly(length - 4) + + def startup(sock, user): payload = ("user\x00" + user + "\x00\x00").encode() sock.sendall(struct.pack(">ii", 8 + len(payload), 196608) + payload) @@ -93,6 +119,46 @@ except (BrokenPipeError, ConnectionResetError, socket.timeout): print("password without a terminator:", outcome(sock)) sock.close() +# The declared length of a message that is parsed before authentication is bounded by the server, because +# the client that declares it is not trusted yet. Otherwise the client declares the Int32 maximum and the +# server buffers up to 2 GiB of payload that never completes. +sock = connect_short() +startup(sock, user_plain) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("password message at the Int32 maximum:", outcome(sock)) +sock.close() + +# The same for a length just above the limit, which pins the boundary itself. +sock = connect_short() +startup(sock, user_plain) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 10001)) +print("password message above the limit:", outcome(sock)) +sock.close() + +# The same for a `SASLInitialResponse`. +sock = connect_short() +startup(sock, user_scram) +read_message(sock) +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("SASL initial response at the Int32 maximum:", outcome(sock)) +sock.close() + +# The same for a `SASLResponse`, the second SCRAM message. A well-formed client-first message is needed +# to get there, and its own declared lengths stay small. +sock = connect_short() +startup(sock, user_scram) +read_message(sock) +client_first = b"n,,n=,r=abcdefghijklmnopqrstuvwx" +body = b"SCRAM-SHA-256\x00" + struct.pack(">i", len(client_first)) + client_first +sock.sendall(b"p" + struct.pack(">i", 4 + len(body)) + body) +message_type, body = read_message(sock) +assert message_type == b"R" and struct.unpack(">i", body[:4])[0] == 11, body +sock.sendall(b"p" + struct.pack(">i", 0x7FFFFFFF)) +print("SASL final response at the Int32 maximum:", outcome(sock)) +sock.close() + # A well-formed exchange still works: authenticate and run a query. def read_until_ready(sock): data = b"" diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference new file mode 100644 index 000000000000..743f61f80a90 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.reference @@ -0,0 +1,9 @@ +String: batches>1=1 64 2016 1 +Nullable(String): batches>1=1 64 2016 1 +LowCardinality: batches>1=1 64 2016 4 +Array(String): batches>1=1 64 2016 1 +Map: batches>1=1 64 2016 1 +Tuple: batches>1=1 64 2016 1 +FixedString: batches>1=1 64 2016 1 +FixedString fixed-width: batches>1=0 64 2016 1 +UInt64: batches>1=0 64 2016 64 diff --git a/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh new file mode 100755 index 000000000000..695c740a9cd8 --- /dev/null +++ b/tests/queries/0_stateless/05055_arrow_split_large_record_batch.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Arrow offsets its String/Binary/List buffers with 32-bit integers, so a block holding more than that has +# to be written as several record batches. `output_format_arrow_max_record_batch_size_bytes` lowers the +# bound, which exercises the same splitting with kilobytes instead of the 2 GiB a real overflow needs. +# +# Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_split.arrows" +trap 'rm -f "$FILE"' EXIT + +batches() { + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY +} + +run() { + local label="$1" expr="$2" limit="$3" extra="${4:-}" + $CLICKHOUSE_LOCAL --allow_suspicious_fixed_string_types 1 --query " + SELECT number AS n, ${expr} AS v + FROM numbers(64) + SETTINGS max_block_size = 64, + output_format_arrow_compression_method = 'none', + output_format_arrow_max_record_batch_size_bytes = ${limit}${extra} + FORMAT ArrowStream + " > "$FILE" + echo -n "${label}: batches>1=$([ "$(batches)" -gt 1 ] && echo 1 || echo 0) " + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(n), uniqExact(v) FROM file('$FILE', ArrowStream)" +} + +# One block of 64 rows against a small bound, so each shape must split. +run "String" "repeat('x', 64)" 512 +run "Nullable(String)" "if(number % 3 = 0, NULL, repeat('y', 64))::Nullable(String)" 512 +run "LowCardinality" "toLowCardinality(repeat(toString(number % 4), 64))" 512 +run "Array(String)" "[repeat('z', 64)]" 512 +run "Map" "map('k', repeat('m', 64))" 512 +run "Tuple" "(repeat('p', 64), repeat('q', 64))" 512 +# Only the offsets mode gives `FixedString` a buffer the bound applies to; the default maps it to a +# fixed-width Arrow type instead. +run "FixedString" "toFixedString(repeat('f', 64), 64)" 512 ", output_format_arrow_fixed_string_as_fixed_byte_array = 0" + +# A fixed-width column has no offsets buffer to overflow, so the bound leaves it in one batch. +run "FixedString fixed-width" "toFixedString(repeat('f', 64), 64)" 512 +run "UInt64" "number" 64 diff --git a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh index ff237fd5db5b..20fc7c819b31 100755 --- a/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh +++ b/tests/queries/0_stateless/05055_format_schema_source_query_background_access.sh @@ -14,7 +14,7 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) BG_MESSAGE="M_bg_${CLICKHOUSE_DATABASE}" FG_MESSAGE="M_fg_${CLICKHOUSE_DATABASE}" -START=$(${CLICKHOUSE_CLIENT} --query "SELECT toString(now64(6))") +START=$(${CLICKHOUSE_CLIENT} --query "SELECT toUnixTimestamp64Micro(now64(6))") ${CLICKHOUSE_CLIENT} --query " CREATE TABLE dest_bg (s String) ENGINE = File(ProtobufSingle) @@ -33,10 +33,11 @@ do ${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS text_log" # The logger is checked too because this query is itself written to the text log, so otherwise # an iteration would match the previous one instead of the background exception. + # `event_date` is in the server time zone, and the session one is randomized. refused=$(${CLICKHOUSE_CLIENT} --query " SELECT count() > 0 FROM system.text_log - WHERE event_date >= toDate('${START}') - AND event_time_microseconds >= toDateTime64('${START}', 6) + WHERE event_date >= yesterday() + AND event_time_microseconds >= fromUnixTimestamp64Micro(${START}) AND logger_name LIKE '%StorageBuffer%' AND message LIKE '%can only be executed on behalf of a user%'") [ "$refused" = "1" ] && break diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference new file mode 100644 index 000000000000..5567708ffa73 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.reference @@ -0,0 +1,2 @@ +HTTP status code: 409 +requests: 1 diff --git a/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh new file mode 100755 index 000000000000..1a260ca3f719 --- /dev/null +++ b/tests/queries/0_stateless/05055_http_conflict_is_not_retried.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +# `409 Conflict` reports a state mismatch on the server, so resending the same bytes cannot succeed. +# Retrying it only postpones the error the caller has to act on: an Iceberg REST catalog commit +# refused with `409` was resent `http_max_tries` times with backoff, adding ~32 seconds per conflict. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HTTP_PORT=$(python3 -c " +import socket +s = socket.socket() +s.bind(('127.0.0.1', 0)) +print(s.getsockname()[1]) +s.close() +") + +python3 -c " +import threading +from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + +requests = 0 +lock = threading.Lock() + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + global requests + if self.path == '/requests': + with lock: + body = str(requests).encode() + self.send_response(200) + else: + with lock: + requests += 1 + body = b'{\"error\": \"conflict\"}' + self.send_response(409) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + +ThreadingHTTPServer(('127.0.0.1', $HTTP_PORT), Handler).serve_forever() +" & +HTTP_PID=$! + +trap 'kill $HTTP_PID 2>/dev/null' EXIT + +for _ in {1..100}; do + if [ "$(${CLICKHOUSE_CURL} -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${HTTP_PORT}/requests")" = "200" ]; then + break + fi + sleep 0.1 +done + +${CLICKHOUSE_CLIENT} --query "SELECT * FROM url('http://127.0.0.1:${HTTP_PORT}/data', JSONEachRow, 'x Int32')" 2>&1 | grep -o "HTTP status code: 409" | head -n 1 + +echo "requests: $(${CLICKHOUSE_CURL} -s "http://127.0.0.1:${HTTP_PORT}/requests")" diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference new file mode 100644 index 000000000000..fe1489a7d47e --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.reference @@ -0,0 +1,4 @@ +low_cardinality_as_dictionary=0 record batches for 3 blocks: 3 +6 15 +low_cardinality_as_dictionary=1 record batches for 3 blocks: 3 +6 15 diff --git a/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh new file mode 100755 index 000000000000..bff3fc53e4fa --- /dev/null +++ b/tests/queries/0_stateless/05056_arrow_record_batch_split_boundaries.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The writer splits a chunk across record batches only when it exceeds the 32-bit offsets of the Arrow +# buffers, so a small result must give exactly one batch per block for every type shape. A wrong row +# count from the split logic shows up only here: the data reads back correctly either way. +# +# `FORMAT ArrowStream` into a file rather than `INSERT INTO FUNCTION file`, whose path squashes the +# blocks into one. Compression is off because older pyarrow cannot read the "uncompressed" sentinel. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +GEN="SELECT + toString(number) AS s, + if(number % 3 = 0, NULL, toString(number))::Nullable(String) AS ns, + toLowCardinality(toString(number % 2)) AS lc, + arrayMap(x -> toString(x), range(number % 3)) AS arr, + arrayMap(y -> arrayMap(x -> toString(x), range(y)), range(number % 3)) AS arr2, + map(toString(number), toString(number % 2)) AS m, + (toString(number), toString(number % 2)) AS t, + toFixedString(toString(number), 3) AS fs, + number AS u +FROM numbers(6)" + +for lc_as_dict in 0 1; do + $CLICKHOUSE_LOCAL --query "${GEN} SETTINGS + max_block_size = 2, + output_format_arrow_compression_method = 'none', + output_format_arrow_fixed_string_as_fixed_byte_array = 0, + output_format_arrow_low_cardinality_as_dictionary = ${lc_as_dict} + FORMAT ArrowStream" > "$FILE" + + echo -n "low_cardinality_as_dictionary=${lc_as_dict} record batches for 3 blocks: " + python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + print(sum(1 for _ in ipc.open_stream(src))) +PY + + $CLICKHOUSE_LOCAL --query "SELECT count(), sum(u) FROM file('$FILE', ArrowStream)" +done diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference new file mode 100644 index 000000000000..15e7d3a0e939 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.reference @@ -0,0 +1,22 @@ +-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs +3 +-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs +3 +-- a nested unknown setting still throws +1 +-- a nested value the setting cannot take still throws +1 +-- a nested clause forwarded to the shards carries the clamped value +1 +-- the same query for an unconstrained user reads both shards +6 +-- a view with an invalid nested setting in its stored body fails on a direct read +1 +-- and on a remote shard through Distributed +1 +-- a parameterized view with an invalid nested setting fails on a direct read +1 +-- and on a remote shard +1 +-- the session settings are untouched +false diff --git a/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh new file mode 100755 index 000000000000..f05616c8d829 --- /dev/null +++ b/tests/queries/0_stateless/05141_settings_constraints_nested_settings_effective.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer +# (the clamp is analyzer-path behaviour; the legacy interpreter throws on such a nested clause) +# A nested `SETTINGS` clause is clamped to the session's settings constraints, and the clamped clause is +# what the query node keeps. So a shard receives the clamped clause, and an +# unknown name or an uncastable value in a nested clause throws, as it does in a top-level clause - also +# when the clause sits in a view's stored body and the view is read on a remote shard. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Users and settings profiles are server-global, so their names carry the test database to keep this +# test safe against a concurrent copy of itself - which is how the flaky check runs it. +SUFFIX="05141_${CLICKHOUSE_DATABASE}" +CONST_USER="user_const_${SUFFIX}" +CONST_PROFILE="profile_const_${SUFFIX}" +RO_USER="user_ro_${SUFFIX}" +RO_PROFILE="profile_ro_${SUFFIX}" +FREE_USER="user_free_${SUFFIX}" +DIST_USER="user_dist_${SUFFIX}" +DIST_PROFILE="profile_dist_${SUFFIX}" +TABLE="t_05141" +DIST_TABLE="dist_05141" +VIEW="v_05141" +DIST_VIEW="dist_v_05141" +PARAM_VIEW="pv_05141" + +${CLICKHOUSE_CLIENT} --query " +DROP USER IF EXISTS ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE IF EXISTS ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW IF EXISTS ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; + +CREATE TABLE ${CLICKHOUSE_DATABASE}.${TABLE} (id UInt32, s String) ENGINE = MergeTree ORDER BY id; +INSERT INTO ${CLICKHOUSE_DATABASE}.${TABLE} VALUES (1, 'a'), (2, 'b'), (3, 'c'); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE} AS ${CLICKHOUSE_DATABASE}.${TABLE} + ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${TABLE}); + +CREATE SETTINGS PROFILE ${CONST_PROFILE} SETTINGS use_query_cache = 0 CONST; +CREATE SETTINGS PROFILE ${RO_PROFILE} SETTINGS readonly = 1 CONST; +CREATE SETTINGS PROFILE ${DIST_PROFILE} SETTINGS max_rows_to_read MAX 2; +CREATE USER ${CONST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${CONST_PROFILE}; +CREATE USER ${RO_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${RO_PROFILE}; +CREATE USER ${FREE_USER} IDENTIFIED WITH no_password; +CREATE USER ${DIST_USER} IDENTIFIED WITH no_password SETTINGS PROFILE ${DIST_PROFILE}; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.* TO ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +" + +# `CREATE` does not analyze the body of a view with an explicit column list nor of a parameterized view, so +# such definitions can carry an invalid nested setting. +${CLICKHOUSE_CLIENT} --query " +CREATE VIEW ${CLICKHOUSE_DATABASE}.${VIEW} (x UInt8) AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1); +CREATE TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW} (x UInt8) ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), ${VIEW}); +CREATE VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW} AS SELECT * FROM (SELECT 1 AS x SETTINGS max_threds = 1) WHERE x = {p:UInt8}; +" + +# The bare binary, not ${CLICKHOUSE_CLIENT}: the harness's randomized settings would be rejected for the readonly user. +RESTRICTED_CLIENT="${CLICKHOUSE_CLIENT_BINARY} --host=${CLICKHOUSE_HOST} --port=${CLICKHOUSE_PORT_TCP} --database=${CLICKHOUSE_DATABASE}" +CONST="${RESTRICTED_CLIENT} --user=${CONST_USER}" +RO="${RESTRICTED_CLIENT} --user=${RO_USER}" +FREE="${RESTRICTED_CLIENT} --user=${FREE_USER}" +DIST="${RESTRICTED_CLIENT} --user=${DIST_USER}" + +echo "-- use_query_cache = 0 CONST: a nested use_query_cache = 1 is clamped and the query runs" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- readonly = 1: a nested use_query_cache = 1 is clamped and the query runs" +${RO} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS use_query_cache = 1)" + +echo "-- a nested unknown setting still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threds = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a nested value the setting cannot take still throws" +${CONST} --query "SELECT count() FROM (SELECT id FROM ${TABLE} SETTINGS max_threads = 'abc')" 2>&1 | grep -c -F "CANNOT_PARSE_INPUT_ASSERTION_FAILED" + +# The IN subquery runs on the shards, whose user has no constraints. It must arrive with the value the +# initiator clamped (2, so reading 3 rows fails there), not with the value as written. +echo "-- a nested clause forwarded to the shards carries the clamped value" +${DIST} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" 2>&1 | grep -c -F "TOO_MANY_ROWS" + +echo "-- the same query for an unconstrained user reads both shards" +${FREE} --query "SELECT count() FROM ${DIST_TABLE} WHERE id IN (SELECT id FROM ${TABLE} SETTINGS max_rows_to_read = 100)" + +# The bare binary again: `${CLICKHOUSE_CLIENT}` adds `--send_logs_level`, so the server's error log line would +# be printed too and `grep -c` would count two lines. +echo "-- a view with an invalid nested setting in its stored body fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${VIEW}" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# `prefer_localhost_replica = 0` is explicit: the local shard is analyzed under the initiator's query kind +# and already throws, so only the remote path exercises the fix, and the harness randomizes this setting. +echo "-- and on a remote shard through Distributed" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${DIST_VIEW} SETTINGS prefer_localhost_replica = 0" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- a parameterized view with an invalid nested setting fails on a direct read" +${RESTRICTED_CLIENT} --query "SELECT * FROM ${PARAM_VIEW}(p = 1)" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +# 127.0.0.2 is the non-local shard of `test_cluster_two_shards`; the port is explicit so the test runs on +# a non-default port; the database is qualified because the remote session does not inherit the test database. +echo "-- and on a remote shard" +${RESTRICTED_CLIENT} --query "SELECT * FROM remote('127.0.0.2:${CLICKHOUSE_PORT_TCP}', view(SELECT * FROM ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}(p = 1)))" 2>&1 | grep -c -F "UNKNOWN_SETTING" + +echo "-- the session settings are untouched" +${CONST} --query "SELECT getSetting('use_query_cache')" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${TABLE}; +DROP TABLE ${CLICKHOUSE_DATABASE}.${DIST_VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${VIEW}; +DROP VIEW ${CLICKHOUSE_DATABASE}.${PARAM_VIEW}; +DROP USER ${CONST_USER}, ${RO_USER}, ${FREE_USER}, ${DIST_USER}; +DROP SETTINGS PROFILE ${CONST_PROFILE}, ${RO_PROFILE}, ${DIST_PROFILE}; +" diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference new file mode 100644 index 000000000000..6ee89cf48413 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.reference @@ -0,0 +1,18 @@ +-- control: the setting is not changed in the session +0 1 +-- control: compatibility = '26.1' in a nested clause moves the setting to its old default +1 0 +-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level +1 1 +-- and stays on the query node +1 +-- same clause: an equal assignment before compatibility keeps the current value +1 1 +-- same clause: an equal assignment before a profile that carries compatibility keeps the current value +1 1 +-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one +1 +-- child scope: the same with a profile that carries compatibility in the inner one +1 +-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery +1 diff --git a/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh new file mode 100755 index 000000000000..03ce5a1eebc0 --- /dev/null +++ b/tests/queries/0_stateless/05175_nested_settings_equal_value_marks_changed.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-old-analyzer + +# A nested `SETTINGS` change equal to the current value is applied and marks the setting as changed +# in the subquery's context, as at the top level. That flag is what `compatibility` respects +# ("changed manually" settings are left alone), also when `compatibility` sits in a profile or in +# a nested query, so the flag must not be dropped as a "no-op". + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Settings profiles are server-global, so the name carries the test database. +PROFILE="p_compat_05175_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE IF EXISTS ${PROFILE}" +${CLICKHOUSE_CLIENT} --query "CREATE SETTINGS PROFILE ${PROFILE} SETTINGS compatibility = '26.1'" + +Q="SELECT changed, value FROM system.settings WHERE name = 'ignore_format_null_for_explain'" + +echo "-- control: the setting is not changed in the session" +${CLICKHOUSE_CLIENT} --query "${Q}" + +echo "-- control: compatibility = '26.1' in a nested clause moves the setting to its old default" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS compatibility = '26.1')" + +echo "-- an equal nested assignment is applied and marked changed in the subquery's context, as at the top level" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- and stays on the query node" +${CLICKHOUSE_CLIENT} --query "EXPLAIN QUERY TREE SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1)" | grep -c "SETTINGS ignore_format_null_for_explain=" + +echo "-- same clause: an equal assignment before compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, compatibility = '26.1')" + +echo "-- same clause: an equal assignment before a profile that carries compatibility keeps the current value" +${CLICKHOUSE_CLIENT} --query "SELECT * FROM (${Q} SETTINGS ignore_format_null_for_explain = 1, profile = '${PROFILE}')" + +echo "-- child scope: an equal assignment in the outer subquery protects the setting from compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- child scope: the same with a profile that carries compatibility in the inner one" +${CLICKHOUSE_CLIENT} --query "SELECT value FROM (SELECT * FROM (${Q} SETTINGS profile = '${PROFILE}') SETTINGS ignore_format_null_for_explain = 1)" + +echo "-- top level over HTTP: an equal assignment protects the setting from compatibility in a subquery" +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "SELECT value FROM (${Q} SETTINGS compatibility = '26.1') SETTINGS ignore_format_null_for_explain = 1" + +${CLICKHOUSE_CLIENT} --query "DROP SETTINGS PROFILE ${PROFILE}" diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference new file mode 100644 index 000000000000..06604339ef49 --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.reference @@ -0,0 +1,7 @@ +ACCESS_DENIED: necessary to have the grant READ, WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +ACCESS_DENIED: Missing permissions: WRITE ON FILE +tables named stolen: 0 +staged directory is still in place +424242 diff --git a/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh new file mode 100755 index 000000000000..1fa58284b9aa --- /dev/null +++ b/tests/queries/0_stateless/05218_attach_table_from_path_read_on_file_grant.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Tags: no-object-storage, no-replicated-database +# no-object-storage: the query attaches a directory on the local disk, and there the table data lives on +# object storage. +# no-replicated-database: a Replicated database enqueues the query before the path is resolved against +# `user_files`, and the DDL worker then rejects the path as outside of `user_files`. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ATTACH TABLE ... FROM ''` reads a directory in `user_files` as the data of the new table and moves it to +# the data path of the table, so it needs `READ ON FILE` like the `file` function and `WRITE ON FILE` like +# renaming files after processing. Without that check `CREATE TABLE` on a table of their own is enough for a +# user to read and consume data that somebody else staged in `user_files`. + +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +staged_root="${CLICKHOUSE_TEST_UNIQUE_NAME}_staged" +staged_table_dir="${staged_root}/data/staging/protected" + +# Stage a MergeTree table directory in `user_files` with clickhouse-local, as an admin or a migration +# workflow would do. An Ordinary database keeps the table directory at a known place. +${CLICKHOUSE_LOCAL} --path "${USER_FILES_PATH}/${staged_root}" --allow_deprecated_database_ordinary=1 --query " + CREATE DATABASE staging ENGINE = Ordinary; + CREATE TABLE staging.protected (id UInt64, secret UInt64) ENGINE = MergeTree ORDER BY id; + INSERT INTO staging.protected VALUES (1, 424242); +" + +${CLICKHOUSE_CLIENT} <&1 | grep -qF "$1"; then + echo "ACCESS_DENIED: $1" + else + echo "UNEXPECTED: the attach was not denied with: $1" + fi + ${CLICKHOUSE_CLIENT} --query "SELECT 'tables named stolen:', count() FROM system.tables WHERE database = currentDatabase() AND name = 'stolen'" + if [ -d "${USER_FILES_PATH}/${staged_table_dir}" ]; then + echo "staged directory is still in place" + else + echo "UNEXPECTED: the staged directory is gone" + fi +} +check_denied_and_untouched "necessary to have the grant READ, WRITE ON FILE" +${CLICKHOUSE_CLIENT} --query "GRANT READ ON FILE TO $user" +check_denied_and_untouched "Missing permissions: WRITE ON FILE" + +# With both grants the same query attaches the data. +${CLICKHOUSE_CLIENT} --query "GRANT WRITE ON FILE TO $user" +${CLICKHOUSE_CLIENT} --user "$user" --query "$attach_query" +${CLICKHOUSE_CLIENT} --user "$user" --query "SELECT secret FROM stolen" + +${CLICKHOUSE_CLIENT} <&1 \ + | tr '\t' ' ' | grep -oE "QUOTA_REQUIRES_CLIENT_KEY|^[[:alnum:]_]+ [[:digit:]]+$" +} + +echo "1. warm two cached quota contexts of the same user, without and with a quota key" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "2. a tightening that keeps the key type reaches the warm context" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} FOR INTERVAL 100 YEAR MAX queries = 900" +usage --user "${user}" + +echo "3. switching the key type to client_key must reach both warm contexts" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY client_key FOR INTERVAL 100 YEAR MAX queries = 800" +usage --user "${user}" +usage --user "${user}" --quota_key kb + +echo "4. a user whose context was never cached is rejected the same way" +usage --user "${control_user}" + +echo "5. reverting the key type lets the never-detached context resume" +${CLICKHOUSE_CLIENT} -q "ALTER QUOTA ${quota} KEYED BY user_name FOR INTERVAL 100 YEAR MAX queries = 700" +usage --user "${user}" + +${CLICKHOUSE_CLIENT} -q "DROP QUOTA ${quota}" +${CLICKHOUSE_CLIENT} -q "DROP USER ${user}, ${control_user}" diff --git a/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference new file mode 100644 index 000000000000..08c55835830b --- /dev/null +++ b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.reference @@ -0,0 +1,43 @@ +the reported oracle mismatch: count(p) + count(not p) + count(p is null) = count(*) +1 +predicate, row-level truth, answer over the partitioned table +assumeNotNull(c0) = 0 3 3 +assumeNotNull(c0) < 3 4 4 +NOT (assumeNotNull(c0) > 0) 3 3 +assumeNotNull(c0) >= 0 5 5 +assumeNotNull(c0) IN (0) 3 3 +isNull and isNotNull compared with a constant +(c0 IS NULL) >= true 2 2 +(c0 IS NOT NULL) < true 2 2 +not(1 < (c0 IS NULL)) 5 5 +the partition step is the sole pruner here, and it now keeps the NULL partition +MinMax +Condition: true +Parts: 4/4 +Partition +Condition: (isNull(c0) in [1, +Inf)) +Parts: 1/4 +ifNull and coalesce reach the same chain once the rewrite that usually hides them is off +ifNull(c0, 0) = 0 3 3 +coalesce(c0, 0) = 0 3 3 +NOT (ifNull(c0, 0) >= 7) 5 5 +NOT (coalesce(nullIf(c0, 5), 0) = 1) 4 4 +MinMax +Parts: 4/4 +Partition +Parts: 3/4 +reverse key 3 3 +LowCardinality(Nullable) key 3 3 +SummingMergeTree, the query the fuzzer reported +1 +control: with no NULL row the partition step is the only pruner and still prunes +isZeroOrNull(c0) >= true 1 +MinMax +Parts: 3/3 +Partition +Parts: 1/3 +control: the primary-key path already rejected the chain and is unchanged +assumeNotNull(c0) = 0 3 3 +control: a NULL-preserving wrapper maps the NULL row to NULL and still answers correctly +c0 + 1 = 1 1 1 +round(c0) = 0 1 1 diff --git a/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql new file mode 100644 index 000000000000..58bcbf7cc70d --- /dev/null +++ b/tests/queries/0_stateless/05233_assume_not_null_nullable_partition_key_pruning.sql @@ -0,0 +1,112 @@ +-- Tags: no-replicated-database, no-parallel-replicas +-- no-replicated-database: EXPLAIN output differs for replicated database. +-- no-parallel-replicas: EXPLAIN output differs for parallel replicas. +-- Test for https://github.com/ClickHouse/ClickHouse/issues/121133, https://github.com/ClickHouse/ClickHouse/issues/126369 and https://github.com/ClickHouse/ClickHouse/issues/127755 + +-- Randomized to 0 or 1, and the value changes the plan the EXPLAIN blocks below print. +SET parallel_replicas_local_plan = 1; +-- Statistics are a part-pruning source of their own; pinning it off keeps the Min-Max and +-- Partition steps the only pruners the EXPLAIN blocks below can attribute a Parts: count to. +SET use_statistics = 0; + +DROP TABLE IF EXISTS t_part; +DROP TABLE IF EXISTS t_flat; + +-- `t_flat` holds the same rows behind an unprunable key, so its answer is the row-level truth +-- that every other table below must reproduce. +CREATE TABLE t_part (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +CREATE TABLE t_flat (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY tuple() ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_part VALUES (NULL), (0), (1), (5), (NULL); +INSERT INTO t_flat VALUES (NULL), (0), (1), (5), (NULL); + +SELECT 'the reported oracle mismatch: count(p) + count(not p) + count(p is null) = count(*)'; +SELECT (SELECT count() FROM t_part WHERE assumeNotNull(c0) = 0) + + (SELECT count() FROM t_part WHERE NOT (assumeNotNull(c0) = 0)) + + (SELECT count() FROM t_part WHERE (assumeNotNull(c0) = 0) IS NULL) + = (SELECT count() FROM t_part) AS tlp_identity_holds; + +SELECT 'predicate, row-level truth, answer over the partitioned table'; +SELECT 'assumeNotNull(c0) = 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_part WHERE assumeNotNull(c0) = 0); +SELECT 'assumeNotNull(c0) < 3', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) < 3), (SELECT count() FROM t_part WHERE assumeNotNull(c0) < 3); +SELECT 'NOT (assumeNotNull(c0) > 0)', (SELECT count() FROM t_flat WHERE NOT (assumeNotNull(c0) > 0)), (SELECT count() FROM t_part WHERE NOT (assumeNotNull(c0) > 0)); +SELECT 'assumeNotNull(c0) >= 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) >= 0), (SELECT count() FROM t_part WHERE assumeNotNull(c0) >= 0); +-- A set atom carries its own copy of the chain and is applied by MergeTreeSetIndex, not by KeyCondition. +SELECT 'assumeNotNull(c0) IN (0)', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) IN (0)), (SELECT count() FROM t_part WHERE assumeNotNull(c0) IN (0)); + +SELECT 'isNull and isNotNull compared with a constant'; +SELECT '(c0 IS NULL) >= true', (SELECT count() FROM t_flat WHERE (c0 IS NULL) >= true), (SELECT count() FROM t_part WHERE (c0 IS NULL) >= true); +SELECT '(c0 IS NOT NULL) < true', (SELECT count() FROM t_flat WHERE (c0 IS NOT NULL) < true), (SELECT count() FROM t_part WHERE (c0 IS NOT NULL) < true); +SELECT 'not(1 < (c0 IS NULL))', (SELECT count() FROM t_flat WHERE not(1 < (c0 IS NULL))), (SELECT count() FROM t_part WHERE not(1 < (c0 IS NULL))); + +-- `isNull` reports no monotonicity, so only the single-point Partition step can use it: it is the sole +-- pruner and its Parts: denominator is the table's part count. +SELECT 'the partition step is the sole pruner here, and it now keeps the NULL partition'; +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_part WHERE (c0 IS NULL) >= true + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0 +) WHERE explain LIKE '%Condition%' OR explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +SELECT 'ifNull and coalesce reach the same chain once the rewrite that usually hides them is off'; +SELECT 'ifNull(c0, 0) = 0', (SELECT count() FROM t_flat WHERE ifNull(c0, 0) = 0), (SELECT count() FROM t_part WHERE ifNull(c0, 0) = 0); +SELECT 'coalesce(c0, 0) = 0', (SELECT count() FROM t_flat WHERE coalesce(c0, 0) = 0), (SELECT count() FROM t_part WHERE coalesce(c0, 0) = 0); +-- The rewrite applies only to a non-negated condition, so a negated one reaches the chain with the rewrite on. +SELECT 'NOT (ifNull(c0, 0) >= 7)', (SELECT count() FROM t_flat WHERE NOT (ifNull(c0, 0) >= 7)), (SELECT count() FROM t_part WHERE NOT (ifNull(c0, 0) >= 7)); + +-- An inner link can also produce a real NULL: `nullIf` maps the exact point 5 to one, and the chain +-- leaves it untransformed just like an infinity bound. Such a bound compares as both inside and +-- outside every range, so the negated atom is the form that can wrongly prune it; keep it negated. +SELECT 'NOT (coalesce(nullIf(c0, 5), 0) = 1)', (SELECT count() FROM t_flat WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1)), (SELECT count() FROM t_part WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1)); +-- Partition 1 is still pruned, so such a bound costs its own partition and no other. +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_part WHERE NOT (coalesce(nullIf(c0, 5), 0) = 1) + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0, use_skip_indexes = 0 +) WHERE explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +DROP TABLE IF EXISTS t_rev; +CREATE TABLE t_rev (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY (c0 DESC) +SETTINGS allow_nullable_key = 1, allow_experimental_reverse_key = 1; +INSERT INTO t_rev VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'reverse key', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_rev WHERE assumeNotNull(c0) = 0); + +DROP TABLE IF EXISTS t_lc; +SET allow_suspicious_low_cardinality_types = 1; +CREATE TABLE t_lc (c0 LowCardinality(Nullable(Int))) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_lc VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'LowCardinality(Nullable) key', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_lc WHERE assumeNotNull(c0) = 0); + +DROP TABLE IF EXISTS t_smt; +CREATE TABLE t_smt (c0 Nullable(Int)) ENGINE = SummingMergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_smt VALUES (NULL), (0), (1), (NULL); +SELECT 'SummingMergeTree, the query the fuzzer reported'; +SELECT (SELECT count() FROM t_smt WHERE assumeNotNull(t_smt.c0) = false) + + (SELECT count() FROM t_smt WHERE NOT (assumeNotNull(t_smt.c0) = false)) + + (SELECT count() FROM t_smt WHERE (assumeNotNull(t_smt.c0) = false) IS NULL) + = (SELECT count() FROM t_smt) AS tlp_identity_holds; + +SELECT 'control: with no NULL row the partition step is the only pruner and still prunes'; +DROP TABLE IF EXISTS t_nonull; +CREATE TABLE t_nonull (c0 Nullable(Int)) ENGINE = MergeTree PARTITION BY (c0) ORDER BY tuple() SETTINGS allow_nullable_key = 1; +INSERT INTO t_nonull VALUES (0), (1), (5); +SELECT 'isZeroOrNull(c0) >= true', count() FROM t_nonull WHERE isZeroOrNull(c0) >= true; +SELECT trimLeft(explain) FROM ( + EXPLAIN indexes = 1 SELECT c0 FROM t_nonull WHERE isZeroOrNull(c0) >= true + SETTINGS optimize_use_implicit_projections = 0, optimize_use_projections = 0 +) WHERE explain LIKE '%Parts%' OR explain LIKE '%MinMax%' OR explain LIKE '%Partition%'; + +SELECT 'control: the primary-key path already rejected the chain and is unchanged'; +DROP TABLE IF EXISTS t_pk; +CREATE TABLE t_pk (c0 Nullable(Int)) ENGINE = MergeTree ORDER BY c0 SETTINGS allow_nullable_key = 1, index_granularity = 1; +INSERT INTO t_pk VALUES (NULL), (0), (1), (5), (NULL); +SELECT 'assumeNotNull(c0) = 0', (SELECT count() FROM t_flat WHERE assumeNotNull(c0) = 0), (SELECT count() FROM t_pk WHERE assumeNotNull(c0) = 0); + +SELECT 'control: a NULL-preserving wrapper maps the NULL row to NULL and still answers correctly'; +SELECT 'c0 + 1 = 1', (SELECT count() FROM t_flat WHERE c0 + 1 = 1), (SELECT count() FROM t_part WHERE c0 + 1 = 1); +SELECT 'round(c0) = 0', (SELECT count() FROM t_flat WHERE round(c0) = 0), (SELECT count() FROM t_part WHERE round(c0) = 0); + +DROP TABLE t_part; +DROP TABLE t_flat; +DROP TABLE t_rev; +DROP TABLE t_lc; +DROP TABLE t_smt; +DROP TABLE t_nonull; +DROP TABLE t_pk; diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference new file mode 100644 index 000000000000..c9a233584ace --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.reference @@ -0,0 +1,5 @@ +t_05291 (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE v = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291 (UPDATE _row_exists = 0 WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +t_05291_replicated (DELETE WHERE id IN (SELECT CAST(c1, \'UInt64\') FROM s3(\'http://127.0.0.1:1/nope.csv\', \'AKIAFAKEKEYID\', \'[HIDDEN]\', \'CSV\', \'c1 String\'))) +0 diff --git a/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql new file mode 100644 index 000000000000..58aa5021b160 --- /dev/null +++ b/tests/queries/0_stateless/05291_system_mutations_hide_secrets.sql @@ -0,0 +1,47 @@ +-- Tags: no-fasttest +-- no-fasttest: the `s3` table function is not in the fast test build. + +-- A mutation entry keeps the real text of its commands, because the mutation is executed from it (on every +-- replica, for replicated tables). `system.mutations.command` must still hide the credentials of the table +-- functions in the mutation subqueries, the way the query log does. + +SET mutations_sync = 0; +SET lightweight_deletes_sync = 0; +SET allow_nondeterministic_mutations = 1; + +DROP TABLE IF EXISTS t_05291; +DROP TABLE IF EXISTS t_05291_replicated; + +CREATE TABLE t_05291 (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id; +CREATE TABLE t_05291_replicated (id UInt64, v UInt64) +ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/t_05291_replicated', 'r1') ORDER BY id; + +INSERT INTO t_05291 SELECT number, number FROM numbers(10); +INSERT INTO t_05291_replicated SELECT number, number FROM numbers(10); + +-- Keep the mutations pending, so that they stay in `system.mutations`. +SYSTEM STOP MERGES t_05291; +SYSTEM STOP MERGES t_05291_replicated; + +ALTER TABLE t_05291 DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291DELETE', 'CSV', 'c1 String')); +ALTER TABLE t_05291 UPDATE v = 0 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291UPDATE', 'CSV', 'c1 String')); +DELETE FROM t_05291 WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291LIGHTWEIGHT', 'CSV', 'c1 String')); +ALTER TABLE t_05291_replicated DELETE WHERE id IN + (SELECT c1::UInt64 FROM s3('http://127.0.0.1:1/nope.csv', 'AKIAFAKEKEYID', 'SECRET05291REPLICATED', 'CSV', 'c1 String')); + +-- The replica loads the mutations from ZooKeeper asynchronously; `PULL` fetches them synchronously. +SYSTEM SYNC REPLICA t_05291_replicated PULL; + +SELECT table, command FROM system.mutations WHERE database = currentDatabase() ORDER BY table, mutation_id; + +-- A secret cannot be probed with a filter on the column either. +SELECT count() FROM system.mutations WHERE database = currentDatabase() AND position(command, 'SECRET05291') > 0; + +-- `KILL MUTATION` parses the command that it reads from `system.mutations` to check the access rights. +KILL MUTATION WHERE database = currentDatabase() AND table = 't_05291' FORMAT Null; + +DROP TABLE t_05291; +DROP TABLE t_05291_replicated; diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference new file mode 100644 index 000000000000..a685fc6d0653 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.reference @@ -0,0 +1,6 @@ +-- baseline: the policy confines the user to its single tenant (1) +1 +-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards) +8 +-- and the shards consumed it through an explicit __getScalar reference (1) +1 diff --git a/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh new file mode 100755 index 000000000000..add1062cda49 --- /dev/null +++ b/tests/queries/0_stateless/05292_row_policy_scalar_subquery_cache_bypass.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# A row policy whose USING expression contains a scalar subquery (here `has((SELECT [2]), tenant_id)`) +# is resolved through the analyzer's scalar-subquery cache, which lives in the same `Context::scalars` +# map that a client can write to with a `Scalar` packet (the `clickhouse-client --external ... --scalar` +# feature). A restricted user could therefore name a client scalar with the policy subquery's query-tree +# hash and forge its result, replacing `(SELECT [2])` with an attacker-chosen array and reading every +# tenant's rows. On 26.3 `clickhouse-client` cannot send scalars (no `--external ... --scalar`), so the +# forged-scalar cases are left out and this test only pins the policy baseline and that scalars shipped +# to shards in distributed queries still resolve. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# User and policy names are server-global, so suffix them with the (unique) test database. +user="u_scalar_rlp_${CLICKHOUSE_DATABASE}" +policy="rp_scalar_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}" + +${CLICKHOUSE_CLIENT} --query " +DROP TABLE IF EXISTS docs; +CREATE TABLE docs (id UInt64, tenant_id UInt8, secret String) ENGINE = MergeTree ORDER BY id; +INSERT INTO docs SELECT number, number, 'secret-' || toString(number) FROM numbers(1, 8); + +CREATE USER ${user} NOT IDENTIFIED; +GRANT SELECT ON ${CLICKHOUSE_DATABASE}.docs TO ${user}; +-- The policy confines ${user} to tenant 2 only, via a scalar subquery. +CREATE ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING has((SELECT [2]), tenant_id) TO ${user}; +-- Once a table has any policy, \`throw_on_unmatched_row_policies\` (on in the test config) rejects +-- reads by users no policy matches, so the default user needs a permissive one of its own. +CREATE ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs FOR SELECT USING 1 TO ALL EXCEPT ${user}; +" + +echo "-- baseline: the policy confines the user to its single tenant (1)" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SELECT count() FROM ${CLICKHOUSE_DATABASE}.docs SETTINGS enable_scalar_subquery_optimization = 1" + +# Marking wire scalars as client-supplied must not disturb distributed queries: the initiator computes +# an array-returning scalar subquery once and ships the result to the shards in the same `Scalar` packet, +# where it arrives through `addClientScalar`. The shard consumes it through the explicit `__getScalar` +# reader, which still reads client-supplied entries, rather than through the narrowed subquery cache. +log_comment="scalar_rlp_dist_${CLICKHOUSE_DATABASE}" + +echo "-- a scalar subquery shipped to the shards still resolves there (8 = 4 tenants x 2 shards)" +${CLICKHOUSE_CLIENT} --log_comment "${log_comment}" --query " +SELECT count() FROM cluster('test_cluster_two_shards', '${CLICKHOUSE_DATABASE}', docs) +WHERE has((SELECT [2, 3, 4, 5]), tenant_id) +SETTINGS prefer_localhost_replica = 0, enable_scalar_subquery_optimization = 1" + +echo "-- and the shards consumed it through an explicit __getScalar reference (1)" +# The secondary queries log `current_database = 'default'` rather than the test database, so they are +# selected by the id of the initial query, which does carry it. +${CLICKHOUSE_CLIENT} --query " +SYSTEM FLUSH LOGS query_log; +SELECT count() > 0 FROM system.query_log +WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 0 + AND query LIKE '%__getScalar%' + AND initial_query_id IN ( + SELECT query_id FROM system.query_log + WHERE event_date >= yesterday() AND type = 'QueryFinish' AND is_initial_query = 1 + AND current_database = currentDatabase() AND log_comment = '${log_comment}')" + +${CLICKHOUSE_CLIENT} --query " +DROP ROW POLICY ${policy} ON ${CLICKHOUSE_DATABASE}.docs; +DROP ROW POLICY ${policy}_all ON ${CLICKHOUSE_DATABASE}.docs; +DROP TABLE docs; +" +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference new file mode 100644 index 000000000000..88b9566a6b12 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.reference @@ -0,0 +1,3 @@ +column 20 is out of range, the file has 5 columns +column 20 is out of range, the file has 5 columns +100 4950 diff --git a/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh new file mode 100755 index 000000000000..27b41467be72 --- /dev/null +++ b/tests/queries/0_stateless/05317_orc_corrupt_stripe_footer_stream_column.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: Depends on S3 + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A 569-byte ORC file (id Int64, name String, v Float64, part Int32) with one row, whose stripe footer declares a +# row index stream for column 20, but the file has 5 columns. Two readers indexed the selected-column mask with +# that id and aborted the server; both must report a malformed file instead: +# - remote reads prebuffer stripes (`ORC::Reader::preBuffer`), so the file is read through s3; +# - predicate pushdown loads the row indexes (`ORC::RowReader::loadStripeIndex`), also for local files. The +# predicate must keep the stripe (`id >= 0`; the row has id 1), or the stripe statistics skip it first. +ORC_B64=$(tr -d '\n' <<'B64' +T1JDEQAACgYSBAgBUAArAAAKEwoDAAAAEgwIARIGCAIQAhgCUAAzAAAKFwoFAAAAAAASDggBIggKAWESAWEYAlAAUwAACicKAgAA +EiEIARobCQAAAAAAAPg/EQAAAAAAAPg/GQAAAAAAAPg/UAArAAAKEwoDAAAAEgwIARIGCAAQABgAUAAHAABCAIADAABhBwAAQACA +EQAAAAAAAAAA+D8HAABAAACuAAAotS/9IGR1AgCEAwoGCAYQABgLCgYIBhABGBgCGBwDGCwUARABGAYCGAQKBggCEAIDARAEGAYS +AggAEgIIAgASAggCCAB7/hAam+nkirydJ0AbQIZdZQm6AAAotS/9IF+lAgBEBApdCgQIAVAACg4IARIGCAIQAhgCUABYBgoQCAEi +CAoBYRIBYQoKIwgBGhsJAPg/EQD4PxkA+D9QAFgLABAAGABQAFgGBQBKyAIaAUJwd1jtfAJ4AQAotS/9IOydBQBCyiYskLc5//// +///w6acgxiIELbemIDUZs4IjVzcRUBwT/pE0KZF9o02pZZNSphSQJ3okw0BbBghYiEDLlRuOvFiuU8aKKePElHHiyPYGVW7/bcVn +e6TQcm1Ni83htzOUa/ujDT2c/5Sg/4wO/hPqp6rnKrCqiyUKQ5//PDC42JMILQmsez1JVU0+1/o9wp3ZDoEFo2mF6HyRLSE6DwgA +SsgCGgFCcHdas32g06DT47p5Bgi/ARAFGICAECICAAwoYDAJgvQDA09SQxg= +B64 +) +FILE="05317_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$FILE', format='RawBLOB') SELECT base64Decode('$ORC_B64')" + +# Stripes are prebuffered only with `remote_filesystem_read_prefetch`, which CI randomizes. +$CLICKHOUSE_CLIENT --remote_filesystem_read_prefetch 1 \ + --query "SELECT * FROM s3(s3_conn, filename='$FILE', format='ORC') FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' + +# Predicate pushdown (on by default) on a local file, which is never prebuffered. +LOCAL_FILE="05317_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --engine_file_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION file('$LOCAL_FILE', 'RawBLOB') SELECT base64Decode('$ORC_B64')" +$CLICKHOUSE_CLIENT --input_format_orc_filter_push_down 1 \ + --query "SELECT * FROM file('$LOCAL_FILE', 'ORC') WHERE id >= 0 FORMAT Null" 2>&1 \ + | grep -o -m1 'column 20 is out of range, the file has 5 columns' +rm -f "${USER_FILES_PATH:?}/$LOCAL_FILE" + +# The server is still alive, and a valid ORC file is still read through the same path. +VALID="05317_valid_${CLICKHOUSE_DATABASE}.orc" +$CLICKHOUSE_CLIENT --s3_truncate_on_insert 1 \ + --query "INSERT INTO FUNCTION s3(s3_conn, filename='$VALID', format='ORC') SELECT number AS id, toString(number) AS s FROM numbers(100)" +$CLICKHOUSE_CLIENT --query "SELECT count(), sum(id) FROM s3(s3_conn, filename='$VALID', format='ORC')" diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference new file mode 100644 index 000000000000..21113e5c614b --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.reference @@ -0,0 +1,18 @@ +-- Q-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded LF +contains CR, LF or NUL +400 +-- B-encoded CRLF +contains CR, LF or NUL +400 +-- Q-encoded NUL +contains CR, LF or NUL +400 +-- Encoded word in the middle of the value +contains CR, LF or NUL +400 +-- Other encoded words are still decoded +café au lait +café diff --git a/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh new file mode 100755 index 000000000000..ef96f960e4b3 --- /dev/null +++ b/tests/queries/0_stateless/05339_http_header_rfc2047_line_break.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# An RFC 2047 encoded word must not decode into CR, LF or NUL inside a header value: +# such a value could split the header when it is forwarded (e.g. to an HTTP authentication server). + +function check_rejected() +{ + local header="$1" + ${CLICKHOUSE_CURL} -sS -H "$header" -w '%{http_code}\n' "${CLICKHOUSE_URL}&query=SELECT+1" | grep -o -F -e 'contains CR, LF or NUL' -e '400' +} + +echo "-- Q-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?Q?x=0D=0AInjected:_1?=' +echo "-- Q-encoded LF" +check_rejected 'X-Test: =?UTF-8?Q?x=0AInjected:_1?=' +echo "-- B-encoded CRLF" +check_rejected 'X-Test: =?UTF-8?B?eA0KSW5qZWN0ZWQ6IDE=?=' +echo "-- Q-encoded NUL" +check_rejected 'X-Test: =?UTF-8?Q?x=00y?=' +echo "-- Encoded word in the middle of the value" +check_rejected 'X-Test: prefix =?UTF-8?Q?=0D=0A?= suffix' + +echo "-- Other encoded words are still decoded" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?Q?caf=C3=A9_au_lait?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" +${CLICKHOUSE_CURL} -sS -H 'X-Test: =?UTF-8?B?Y2Fmw6k=?=' "${CLICKHOUSE_URL}&allow_get_client_http_header=1" -d "SELECT getClientHTTPHeader('X-Test')" diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference new file mode 100644 index 000000000000..7a770acba3a2 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.reference @@ -0,0 +1,7 @@ +json_whole 1 +json_whole_prewhere 1 +json_other_path 1 +tuple_whole 1 +map_size_and_key 1 +maps_other_map 1 +map_key_and_whole 1 diff --git a/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql new file mode 100644 index 000000000000..a87623566a81 --- /dev/null +++ b/tests/queries/0_stateless/05339_prewhere_subcolumn_read_steps.sql @@ -0,0 +1,79 @@ +-- Tags: no-parallel-replicas +-- no-parallel-replicas: read_bytes in the initiator's query_log does not include the replicas' reads. + +-- A condition on a cheap subcolumn gets its own PREWHERE read step, so the column it is combined with is read +-- only for the rows it keeps. No row passes the first condition, so a case reads about the bytes of that one alone. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; +SET optimize_move_to_prewhere = 1; +SET query_plan_optimize_prewhere = 1; +SET move_all_conditions_to_prewhere = 1; +SET enable_multiple_prewhere_read_steps = 1; +SET use_query_condition_cache = 0; + +DROP TABLE IF EXISTS t_json; +DROP TABLE IF EXISTS t_tuple; +DROP TABLE IF EXISTS t_map; +DROP TABLE IF EXISTS t_maps; + +CREATE TABLE t_json (id UInt64, j JSON) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +CREATE TABLE t_tuple (id UInt64, t Tuple(kind String, payload String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; +-- Bucketed, with as many buckets as keys, so that `m['k1']` reads one bucket and not the whole Map. +CREATE TABLE t_map (id UInt64, m Map(String, String)) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, + map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets', + map_buckets_strategy = 'constant', max_buckets_in_map = 16, map_buckets_min_avg_size = 0; +CREATE TABLE t_maps (id UInt64, c Tuple(left Map(String, String), right Map(String, String))) ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +-- Random values, so that the size of a column on disk, by which the conditions are ordered, reflects the cost of reading it. +INSERT INTO t_json SELECT number, concat('{"kind":"a","payload":"', hex(randomString(500)), '"}') FROM numbers(20000); +INSERT INTO t_tuple SELECT number, tuple('a', hex(randomString(500))) FROM numbers(20000); +INSERT INTO t_map SELECT number, mapFromArrays(arrayMap(i -> 'k' || toString(i), range(16)), arrayMap(i -> hex(randomString(30)), range(16))) FROM numbers(20000); +INSERT INTO t_maps SELECT number, tuple(map('k', 'a'), map('k', hex(randomString(500)))) FROM numbers(20000); + +SELECT count() FROM t_json WHERE j.kind = 'b' FORMAT Null SETTINGS log_comment = 'json_cheap'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' FORMAT Null SETTINGS log_comment = 'tuple_cheap'; +SELECT count() FROM t_map WHERE length(m) = 3 FORMAT Null SETTINGS log_comment = 'map_cheap'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' FORMAT Null SETTINGS log_comment = 'map_key_cheap'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' FORMAT Null SETTINGS log_comment = 'maps_cheap'; + +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole'; +SELECT count() FROM t_json PREWHERE j.kind = 'b' AND length(toString(j)) > 10 FORMAT Null SETTINGS log_comment = 'json_whole_prewhere'; +SELECT count() FROM t_json WHERE j.kind = 'b' AND length(toString(j.payload)) > 10 FORMAT Null SETTINGS log_comment = 'json_other_path'; +SELECT count() FROM t_tuple WHERE t.kind = 'b' AND length(toString(t)) > 10 FORMAT Null SETTINGS log_comment = 'tuple_whole'; +-- PREWHERE keeps the written order, which the WHERE optimizer may change based on the column sizes. +SELECT count() FROM t_map PREWHERE length(m) = 3 AND m['k1'] != '' FORMAT Null SETTINGS log_comment = 'map_size_and_key'; +SELECT count() FROM t_maps WHERE c.left['k'] = 'b' AND c.right['k'] != '' FORMAT Null SETTINGS log_comment = 'maps_other_map'; +SELECT count() FROM t_map WHERE m['k1'] = 'x' AND length(toString(m)) > 10 FORMAT Null SETTINGS log_comment = 'map_key_and_whole'; + +SYSTEM FLUSH LOGS query_log; + +SELECT c.case_name, q.bytes < 2 * base.bytes +FROM VALUES('idx UInt8, case_name String, base_name String', + (1, 'json_whole', 'json_cheap'), + (2, 'json_whole_prewhere', 'json_cheap'), + (3, 'json_other_path', 'json_cheap'), + (4, 'tuple_whole', 'tuple_cheap'), + (5, 'map_size_and_key', 'map_cheap'), + (6, 'maps_other_map', 'maps_cheap'), + (7, 'map_key_and_whole', 'map_key_cheap')) AS c +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS q ON q.log_comment = c.case_name +INNER JOIN +( + SELECT log_comment, max(read_bytes) AS bytes FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' GROUP BY log_comment +) AS base ON base.log_comment = c.base_name +ORDER BY c.idx; + +DROP TABLE t_json; +DROP TABLE t_tuple; +DROP TABLE t_map; +DROP TABLE t_maps; diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference new file mode 100644 index 000000000000..fcc2c16d9ebd --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.reference @@ -0,0 +1,30 @@ +bucketed MergeTree +1 +MergeTree with bucketed zero-level parts +1 +basic MergeTree +1 +Memory +1 +explicit key subcolumn of a basic Map +8 8 +9 9 +results +8 8 +9 9 +8 8 +9 9 +8 8 +9 9 +Merge over a bucketed table +1 +MaterializedView with a bucketed target +1 +Buffer with a bucketed destination +1 +Merge over a bucketed and a basic table +1 +8 8 +8 8 +9 9 +9 9 diff --git a/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql new file mode 100644 index 000000000000..cd62f633bf69 --- /dev/null +++ b/tests/queries/0_stateless/05340_map_element_to_subcolumn_bucketed_only.sql @@ -0,0 +1,75 @@ +-- `m['key']` is rewritten to the Map key subcolumn `m.key_` only when the table serializes Maps +-- with buckets, because only then can a single key be read without the whole Map. +-- Both serialization settings are named in every table, clickhouse-test randomizes them. + +SET enable_analyzer = 1; +SET optimize_functions_to_subcolumns = 1; + +DROP TABLE IF EXISTS t_map_buffer; +DROP TABLE IF EXISTS t_map_mv; +DROP TABLE IF EXISTS t_map_merge; +DROP TABLE IF EXISTS t_map_memory; +DROP TABLE IF EXISTS t_map_basic; +DROP TABLE IF EXISTS t_map_zero_level_bucketed; +DROP TABLE IF EXISTS t_map_bucketed; + +CREATE TABLE t_map_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_zero_level_bucketed (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'with_buckets'; +CREATE TABLE t_map_basic (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'basic', map_serialization_version_for_zero_level_parts = 'basic'; +CREATE TABLE t_map_memory (id UInt64, m Map(String, UInt64)) ENGINE = Memory; + +INSERT INTO t_map_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_zero_level_bucketed SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_basic SELECT number, map('k', number) FROM numbers(10); +INSERT INTO t_map_memory SELECT number, map('k', number) FROM numbers(10); + +SELECT 'bucketed MergeTree'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MergeTree with bucketed zero-level parts'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_zero_level_bucketed WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'basic MergeTree'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_basic WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Memory'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_memory WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +SELECT 'explicit key subcolumn of a basic Map'; +SELECT id, m.key_k FROM t_map_basic WHERE m.key_k > 7 ORDER BY id; + +SELECT 'results'; +SELECT id, m['k'] FROM t_map_bucketed WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_basic WHERE m['k'] > 7 ORDER BY id; +SELECT id, m['k'] FROM t_map_memory WHERE m['k'] > 7 ORDER BY id; + +-- Engines that pass the analyzed query to other tables answer for those tables. +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_bucketed$'); +CREATE MATERIALIZED VIEW t_map_mv (id UInt64, m Map(String, UInt64)) ENGINE = MergeTree ORDER BY id +SETTINGS map_serialization_version = 'with_buckets', map_serialization_version_for_zero_level_parts = 'with_buckets' +AS SELECT id, m FROM t_map_bucketed; +CREATE TABLE t_map_buffer (id UInt64, m Map(String, UInt64)) +ENGINE = Buffer(currentDatabase(), t_map_bucketed, 1, 10, 100, 10000, 1000000, 10000000, 100000000); + +SELECT 'Merge over a bucketed table'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'MaterializedView with a bucketed target'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_mv WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT 'Buffer with a bucketed destination'; +SELECT count() > 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_buffer WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; + +-- The query is sent to every table of a Merge, so all of them must be bucketed. +DROP TABLE t_map_merge; +CREATE TABLE t_map_merge (id UInt64, m Map(String, UInt64)) ENGINE = Merge(currentDatabase(), '^t_map_(bucketed|basic)$'); + +SELECT 'Merge over a bucketed and a basic table'; +SELECT count() = 0 FROM (EXPLAIN actions = 1 SELECT id FROM t_map_merge WHERE m['k'] > 7) WHERE explain LIKE '%m.key_k%'; +SELECT id, m['k'] FROM t_map_merge WHERE m['k'] > 7 ORDER BY id; + +DROP TABLE t_map_buffer; +DROP TABLE t_map_mv; +DROP TABLE t_map_merge; +DROP TABLE t_map_memory; +DROP TABLE t_map_basic; +DROP TABLE t_map_zero_level_bucketed; +DROP TABLE t_map_bucketed; diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference new file mode 100644 index 000000000000..dfd940ddad71 --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.reference @@ -0,0 +1,3 @@ +3000 30 +3000 4501500 +1000 499500 diff --git a/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh new file mode 100755 index 000000000000..f36ec224287c --- /dev/null +++ b/tests/queries/0_stateless/05406_iceberg_write_many_partitions_thread_pool.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires `IcebergLocal` (USE_AVRO build option) + +# Each finished Iceberg data file used to keep its Parquet encoder threads until the commit, so writing +# 30 partitions with `max_threads = 16` needed 480 threads of the 300-thread global pool. +# https://github.com/ClickHouse/ClickHouse/issues/126508 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 16); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 16); do printf ', number * %d' "$i"; done) +SETTINGS="SET allow_insert_into_iceberg = 1, max_insert_threads = 1, max_threads = 16, output_format_parquet_parallel_encoding = 1" + +# INSERT, then ALTER TABLE ... UPDATE, which writes one position delete file and one data file per partition. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32 ${COLS}) ENGINE = IcebergLocal('${TABLE_DIR}/update/') PARTITION BY p; + INSERT INTO t SELECT number % 30 ${EXPRS} FROM numbers(3000); + SELECT count(), uniqExact(_path) FROM t; + ALTER TABLE t UPDATE c1 = c1 + 1 WHERE 1; + SELECT count(), sum(c1) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 + +# ALTER TABLE ... DELETE writes two-column position delete files, so it needs more partitions to fill the pool. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}; + CREATE TABLE t (p Int32, x Int64) ENGINE = IcebergLocal('${TABLE_DIR}/delete/') PARTITION BY p; + INSERT INTO t SELECT number % 80, number FROM numbers(2000); + ALTER TABLE t DELETE WHERE x >= 1000; + SELECT count(), sum(x) FROM t; +" -- --max_thread_pool_size=300 --thread_pool_queue_size=300 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference new file mode 100644 index 000000000000..636bda45df5e --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.reference @@ -0,0 +1,4 @@ +[[[[NULL]]],[[[NULL]]]] +[NULL,NULL] +4 2 +server is alive diff --git a/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh new file mode 100755 index 000000000000..81d6382e1910 --- /dev/null +++ b/tests/queries/0_stateless/05407_dynamic_deep_value_column_operations.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# The fast-test build is unoptimized and re-runs a new test several times under a 60s cap, while +# materializing a deeply nested Dynamic value whose operation does not trip the recursion guard takes +# superlinear time. The optimized stateless configurations run it within budget. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Each repetition of 1E2B0801 is a value of type Array(Dynamic(max_types=8)) with one element, so the +# nesting depth of the Dynamic value comes from the data, not from the declared type. The second row is NULL. +nested_value() { echo "format(RowBinary, 'd Dynamic', unhex(concat(repeat('1E2B0801', $1), '0000')))"; } + +$CLICKHOUSE_CLIENT -q "SELECT arraySort([d, d]) FROM $(nested_value 3)" + +# Depending on the build and the stack size, a deep value is either processed or rejected with +# TOO_DEEP_RECURSION, but it must never crash the server or use memory quadratic in the depth. +# Parsing a value takes time quadratic in its depth (every level has a longer type name), so the deepest value, +# which exhausts the stack in the release build, is only used for the operations that recurse into the nested +# columns: `index`, `compareAt`, and `filter`. +check_query() { + out=$($CLICKHOUSE_CLIENT -q "$1 FORMAT Null" 2>&1) + [[ -z "$out" || "$out" == *TOO_DEEP_RECURSION* ]] || echo "$1: $out" +} +table=$(nested_value 1000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d, arrayJoin([1, 2]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done +table=$(nested_value 9000) +for query in "SELECT [d] FROM $table" "SELECT arraySort([d, d]) FROM $table" "SELECT d FROM $table WHERE d IS NOT NULL"; do + check_query "$query" +done + +# Writing a part and merging parts go through the dynamic structure helpers of the column. +# Writing a part takes time quadratic in the nesting depth (every level adds substreams with longer names), +# so a depth that exhausts the stack takes tens of seconds; use a small depth that checks the normal path +# and stays far from the stack limit in sanitizer builds, where depth 300 already hits it. +# The substream names of a deep value exceed the file name length limit of the filesystem in a wide part, +# so they must be replaced with hashes regardless of the randomized MergeTree settings. +$CLICKHOUSE_CLIENT -q "CREATE TABLE deep_dynamic (d Dynamic) ENGINE = MergeTree ORDER BY tuple() SETTINGS replace_long_file_name_to_hash = 1, max_file_name_length = 127" +table=$(nested_value 64) +for query in "INSERT INTO deep_dynamic SELECT d FROM $table" "INSERT INTO deep_dynamic SELECT d FROM $table" "OPTIMIZE TABLE deep_dynamic FINAL"; do + out=$($CLICKHOUSE_CLIENT -q "$query" 2>&1) + [[ -z "$out" ]] || echo "$query: $out" +done +$CLICKHOUSE_CLIENT -q "SELECT count(), countIf(d IS NULL) FROM deep_dynamic" +$CLICKHOUSE_CLIENT -q "DROP TABLE deep_dynamic" + +$CLICKHOUSE_CLIENT -q "SELECT 'server is alive'" diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference new file mode 100644 index 000000000000..fcc653eab3e4 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.reference @@ -0,0 +1,5 @@ +writer: time zone is rejected +reader: time zone is rejected +reader file: time zone is rejected +--- stateless server is still alive --- +1 diff --git a/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh new file mode 100755 index 000000000000..f8e04add8d56 --- /dev/null +++ b/tests/queries/0_stateless/05407_orc_timezone_traversal_abort.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e + +# A malformed ORC timezone name used to reach an empty TZif file outside TZDIR and abort +# inside libc++. The time zones are now resolved only from the embedded time zone database, +# so such a name must be rejected without touching the file system. Keep each attempt in a child clickhouse-local process and disable core dumps. +ulimit -c 0 + +WORK_DIR="${CLICKHOUSE_TMP}/orc_timezone_traversal_${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${WORK_DIR}" +mkdir -p "${WORK_DIR}" +trap 'rm -rf "${WORK_DIR}"' EXIT + +regression_status=0 +python3 - "${WORK_DIR}" <<'PY' || regression_status=$? +import os +import pathlib +import shlex +import shutil +import subprocess +import sys + +work_dir = pathlib.Path(sys.argv[1]) +tz_dir = work_dir / "zoneinfo" / "a" / "b" +tz_dir.mkdir(parents=True) + +# Use real, minimal zone files so the valid setup and the ORC fixture can be loaded while +# TZDIR points at this private directory. The traversal resolves to this test's empty file. +system_zoneinfo = pathlib.Path("/usr/share/zoneinfo") +for zone in ("UTC", "America/Vancouver"): + source = system_zoneinfo / zone + if not source.is_file(): + raise SystemExit(f"required time zone file not found: {source}") + target = tz_dir / zone + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + +(work_dir / "outside").write_bytes(b"") +if (tz_dir / "../../../outside").resolve() != (work_dir / "outside").resolve(): + raise SystemExit("private timezone traversal fixture is misconfigured") +(work_dir / "dev").mkdir() +(work_dir / "dev" / "null").write_bytes(b"") +if (tz_dir / "../../../dev/null").resolve() != (work_dir / "dev" / "null").resolve(): + raise SystemExit("private ORC metadata traversal fixture is misconfigured") + +env = os.environ.copy() +env["TZDIR"] = str(tz_dir) +env["TZ"] = "UTC" +local_command = shlex.split(env["CLICKHOUSE_LOCAL"]) + + +def run_local(path, *args, query=None, input_data=None): + path.mkdir(parents=True, exist_ok=True) + command = local_command + ["--path", str(path), *args] + if query is not None: + command += ["--query", query] + return subprocess.run( + command, + input=input_data, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + + +safe_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='America/Vancouver', " + "output_format_orc_compression_method='none'" +) +fixture = run_local(work_dir / "safe", query=safe_query) +if fixture.returncode != 0 or not fixture.stdout.startswith(b"ORC"): + diagnostic = (fixture.stderr + fixture.stdout).decode(errors="replace") + raise SystemExit(f"could not create valid ORC fixture: {diagnostic[:1000]}") + +# Preserve the ORC file's byte lengths while replacing its writer timezone metadata +# with the path from the customer reproducer. This exercises a file supplied by a +# reader, without requiring a malicious query setting. +safe_name = b"America/Vancouver" +unsafe_name = b"../../../dev/null" +if len(safe_name) != len(unsafe_name) or fixture.stdout.count(safe_name) != 1: + raise SystemExit("valid ORC fixture has unexpected timezone metadata") +malicious_file = fixture.stdout.replace(safe_name, unsafe_name, 1) + +malicious_writer_query = ( + "SELECT toDateTime(0, 'America/Vancouver') AS t FORMAT ORC " + "SETTINGS output_format_orc_writer_time_zone_name='../../../outside', " + "output_format_orc_compression_method='none'" +) +writer = run_local(work_dir / "writer", query=malicious_writer_query) +reader = run_local( + work_dir / "reader", + "--input-format=ORC", + "--input_format_orc_reader_time_zone_name=../../../outside", + query="SELECT * FROM table", + input_data=fixture.stdout, +) +reader_file = run_local( + work_dir / "reader_file", + "--input-format=ORC", + query="SELECT * FROM table", + input_data=malicious_file, +) + +failed = False +for label, result in (("writer", writer), ("reader", reader), ("reader file", reader_file)): + if result.returncode < 0: + print(f"{label}: terminated by signal {-result.returncode}") + failed = True + elif result.returncode == 0: + print(f"{label}: malformed timezone unexpectedly succeeded") + failed = True + elif any( + message in result.stdout + result.stderr + for message in (b"is not supported. Use a name from `system.time_zones`", b"Cannot load time zone ../../../") + ): + print(f"{label}: time zone is rejected") + else: + diagnostic = (result.stderr + result.stdout).decode(errors="replace") + first_line = next((line for line in diagnostic.splitlines() if line), "no diagnostic") + print(f"{label}: unexpected error: {first_line[:300]}") + failed = True + +if failed: + raise SystemExit(1) +PY + +echo '--- stateless server is still alive ---' +${CLICKHOUSE_CLIENT} --query "SELECT 1" +exit "${regression_status}" diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference b/tests/queries/0_stateless/05427_azure_sas_url_parsing.reference new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql new file mode 100644 index 000000000000..329dfc62bcda --- /dev/null +++ b/tests/queries/0_stateless/05427_azure_sas_url_parsing.sql @@ -0,0 +1,9 @@ +-- Tags: no-fasttest +-- no-fasttest: needs Azure Blob Storage support, which is not built in the fast test. + +-- The (url, sas_token) form of the Azure table functions parses a URL that ends right after the host like the same URL +-- with a trailing slash (both then fail at format detection), and rejects a malformed abfss URL with BAD_ARGUMENTS. +SELECT * FROM azureBlobStorage('https://acc.blob.core.windows.net', 'sv=2022'); -- { serverError CANNOT_DETECT_FORMAT } +SELECT * FROM azureBlobStorage('abfss://foo.net', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://foo.net/c/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } +SELECT * FROM azureBlobStorage('abfss://c.x@acc.dfs.core.windows.net/p/x.csv', 'sv=2022'); -- { serverError BAD_ARGUMENTS } diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference new file mode 100644 index 000000000000..e838531bffe0 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.reference @@ -0,0 +1,51 @@ +LIKE `t0` +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(KEY `k` (`x`)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +c1 Nullable(Int64) +c2 Nullable(String) +1 a +2 b +LIKE `t0` +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(KEY `k` (`x`)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c +(`x` int, `y` varchar(10)) ENGINE=InnoDB +1 a +2 b +1 a +2 b +3 c +1 a +2 b +3 c diff --git a/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh new file mode 100755 index 000000000000..ab7e6079e829 --- /dev/null +++ b/tests/queries/0_stateless/05428_mysqldump_create_without_columns.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `CREATE TABLE` in a MySQL dump without column definitions (`CREATE TABLE ... LIKE`, or only indexes or constraints) +# gives no structure, so the structure is inferred from the data of the `INSERT`. + +function dump() +{ + printf 'CREATE TABLE `t1` %s;\n/*!40101 SET character_set_client = @saved_cs_client */;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB'; do + echo "$create" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "DESCRIBE TABLE table" + dump "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" +done + +# The `INSERT` immediately following the `CREATE TABLE` must not be skipped. + +function dump_single_insert() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"'),(2,'"'"'b'"'"');\n' "$1" +} + +function dump_multiple_inserts() +{ + printf 'CREATE TABLE `t1` %s;\nINSERT INTO `t1` VALUES (1,'"'"'a'"'"');\nINSERT INTO `t1` VALUES (2,'"'"'b'"'"');\nINSERT INTO `t1` VALUES (3,'"'"'c'"'"');\n' "$1" +} + +for create in 'LIKE `t0`' '(KEY `k` (`x`)) ENGINE=InnoDB' '(CONSTRAINT `c` CHECK (`x` > 0)) ENGINE=InnoDB' '(`x` int, `y` varchar(10)) ENGINE=InnoDB'; do + echo "$create" + dump_single_insert "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --query "SELECT * FROM table" + dump_multiple_inserts "$create" | $CLICKHOUSE_LOCAL --input-format MySQLDump --structure 'x UInt32, y String' --query "SELECT * FROM table" +done diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference new file mode 100644 index 000000000000..5453565c8dd8 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.reference @@ -0,0 +1,3 @@ +BAD_ARGUMENTS +x UInt32 +supported_values Map(String, UInt32) diff --git a/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh new file mode 100755 index 000000000000..e551cdbc6837 --- /dev/null +++ b/tests/queries/0_stateless/05429_protobuf_map_with_unsupported_value.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `map` whose value type is unsupported is skipped in schema inference with +# `input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1`. + +SCHEMADIR="$CUR_DIR/format_schemas" +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 0" 2>&1 | grep -o -m1 -F 'BAD_ARGUMENTS' +$CLICKHOUSE_LOCAL -q "DESC file('nonexist', 'Protobuf') SETTINGS format_schema = '$SCHEMADIR/05429_protobuf_map_with_unsupported_value.proto:MessageWithMaps', input_format_protobuf_skip_fields_with_unsupported_types_in_schema_inference = 1" diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference new file mode 100644 index 000000000000..739d1f2b1342 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.reference @@ -0,0 +1,4 @@ +Map(Int64, Nullable(Int64)) {1:1} +Map(Int64, Nullable(Int64)) {0:1} +Map(Int64, Nullable(Int64)) {2:3} +Map(Int64, Int64) {0:1} diff --git a/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql new file mode 100644 index 000000000000..fb99be351299 --- /dev/null +++ b/tests/queries/0_stateless/05441_msgpack_schema_inference_untypeable_map_key.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest +-- no-fasttest: MsgPack format is not available in the fasttest environment + +-- A MsgPack map whose first key has no inferable type (nil, empty array, empty map, nested map with a nil key) +-- must be reported as "cannot determine type", not dereferenced. + +SET input_format_msgpack_number_of_columns = 1; + +-- {1: 1} +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\x01\x01'); + +-- {nil: 1}, {[]: 1}, {{}: 1}, {{nil: 1}: 1} +DESC format(MsgPack, '\x81\xc0\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x90\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x80\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(MsgPack, '\x81\x81\xc0\x01\x01'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- {nil: 1}, {2: 3}: the type is taken from the second row. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01\x81\x02\x03'); + +-- {nil: 1} with schema_inference_hints, which the error message suggests. +SELECT toTypeName(c1), c1 FROM format(MsgPack, '\x81\xc0\x01') SETTINGS schema_inference_hints = 'c1 Map(Int64, Int64)'; diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference new file mode 100644 index 000000000000..98c80be8e58b --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.reference @@ -0,0 +1,5 @@ +0300000000000000 +c9b15b7fd5143f1d8f677be3dc4daab9 - +c9b15b7fd5143f1d8f677be3dc4daab9 - +9038957ba26f89fe09ee1964aad98576 - +9038957ba26f89fe09ee1964aad98576 - diff --git a/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh new file mode 100755 index 000000000000..d6493c3c6808 --- /dev/null +++ b/tests/queries/0_stateless/05441_rawblob_aggregate_function.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# `RawBLOB` must write the serialized state of an aggregate function, the same as its conversion to `String`, +# not the pointer to the state in memory. + +$CLICKHOUSE_CLIENT -q "SELECT sumState(number) FROM numbers(3) FORMAT RawBLOB" | od -An -tx1 | tr -d ' \n' +echo + +$CLICKHOUSE_CLIENT -q "SELECT quantileState(number) FROM numbers(100000) FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(quantileState(number) AS String) FROM numbers(100000) FORMAT RawBLOB" | md5sum + +$CLICKHOUSE_CLIENT -q "SELECT uniqExactState(number) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum +$CLICKHOUSE_CLIENT -q "SELECT CAST(uniqExactState(number) AS String) FROM numbers(10) GROUP BY number % 2 ORDER BY number % 2 FORMAT RawBLOB" | md5sum diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference new file mode 100644 index 000000000000..e5046dab0a10 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -0,0 +1,35 @@ +table created +-- ALTER with only ALTER SETTINGS +settings that are not a destination: allowed +-- ALTER with SELECT on the table, but no WRITE on S3 +-- ALTER ON CLUSTER is rejected by the initiator +-- ALTER ON CLUSTER of a table that does not exist on the initiator +-- ALTER with WRITE on S3 limited by a URL filter +-- ALTER with WRITE on S3 +destination with WRITE on S3: allowed +empty destination without WRITE on S3: allowed +-- ALTER with WRITE on S3, restricted by a row policy +empty destination with a row policy: allowed +-- ALTER through an Alias +settings that are not a destination through an alias: allowed +-- CREATE without WRITE on S3 or AZURE +table without a destination: created +-- CREATE AS with a destination, without WRITE on S3 +-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3 +-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3 +-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3 +-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3 +-- ATTACH with a full definition and a destination, without WRITE on S3 +-- RESTORE of a queue with a destination, without WRITE on S3 +0 +0 +0 +-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 +CREATE AS with WRITE on S3: created +materialized view with WRITE on S3: created +RESTORE with WRITE on S3: restored +RESTORE ON CLUSTER with WRITE on S3: restored +CREATE ON CLUSTER with WRITE on S3: created +CREATE AS ON CLUSTER with WRITE on S3: created +ATTACH with WRITE on S3: attached +RESTORE TEMPORARY with WRITE on S3: restored 1 diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh new file mode 100755 index 000000000000..5699f7262195 --- /dev/null +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -0,0 +1,377 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, zookeeper, no-replicated-database +# Tag no-fasttest: the `S3Queue` and `AzureQueue` engines are not built into the fast test build. +# Tag zookeeper: `S3Queue` keeps its state in Keeper, and `ON CLUSTER` queries use the distributed DDL queue. +# Tag no-replicated-database: with `access_control_improvements.enable_read_write_grants` disabled (the default), +# a replicated access storage round-trips the user through serialized SQL, which rewrites `WRITE ON S3('')` +# into the old-style whole-source `S3` grant without the filter. + +# The move destination of an `S3Queue` or `AzureQueue` table is the same data flow as +# `INSERT INTO FUNCTION s3('') SELECT * FROM
`: the table reads the processed files with its +# own credentials and writes them to the destination. So setting `after_processing_move_uri`, +# `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) +# source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. +# `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +db="${CLICKHOUSE_DATABASE}" +user_alter="s3queue_move_alter_${db}" +user_create="s3queue_move_create_${db}" +keeper_path="/s3queue_move_destination_access_${db}" +src="http://localhost:11111/test/${db}_move_src/" +dst="http://localhost:11111/test/${db}_move_dst/" +backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" +backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" +attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") +azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}', after_processing = 'keep' +" +echo "table created" + +$CLICKHOUSE_CLIENT -q " + CREATE USER ${user_alter}; + GRANT ALTER SETTINGS ON ${db}.t TO ${user_alter}; + CREATE USER ${user_create}; + GRANT CREATE TABLE ON ${db}.* TO ${user_create}; + GRANT TABLE ENGINE ON S3Queue TO ${user_create}; + GRANT TABLE ENGINE ON AzureQueue TO ${user_create}; +" + +echo "-- ALTER with only ALTER SETTINGS" + +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container redirects the move to another container of the same account. +# The check reads only the query, so it fails before the storage is involved, although `t` is an `S3Queue`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# Settings that do not choose a destination need only ALTER SETTINGS. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING polling_max_timeout_ms = 20000, after_processing_move_prefix = 'prefix_${db}' +" && echo "settings that are not a destination: allowed" + +echo "-- ALTER with SELECT on the table, but no WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${db}.t TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +# Changing only the container is a destination change that needs `WRITE` on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER is rejected by the initiator" + +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" + +# The grants come from the settings in the query, not from the table, so the initiator checks them without the table. +# With the grant, the query reaches the host and fails there. +$CLICKHOUSE_CLIENT -q "GRANT ALTER SETTINGS, SELECT ON ${db}.t_missing TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}.t_missing ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError UNKNOWN_TABLE } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3 limited by a URL filter" + +# The move writes keys built from the prefix and the source keys, so a URL filter cannot authorize them. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3('${dst}.*') TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3('${dst}.*') FROM ${user_alter}" + +echo "-- ALTER with WRITE on S3" + +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} +" && echo "destination with WRITE on S3: allowed" + +# Resetting the destination disables the move, so it needs no grant for a destination. +$CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination without WRITE on S3: allowed" + +echo "-- ALTER with WRITE on S3, restricted by a row policy" + +# The move copies whole files, so a user whose row policy hides rows of the table cannot set a destination. +$CLICKHOUSE_CLIENT -q " + GRANT WRITE ON S3 TO ${user_alter}; + CREATE ROW POLICY p_${db} ON ${db}.t USING x = 1 TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +# Turning the move off needs no check. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '' +" && echo "empty destination with a row policy: allowed" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY p_${db} ON ${db}.t; + REVOKE WRITE ON S3 FROM ${user_alter}; +" + +echo "-- ALTER through an Alias" + +# The export checks see only the name in the query, which is the alias, so the change is refused for every user. +$CLICKHOUSE_CLIENT --allow_experimental_alias_table_engine 1 -q "CREATE TABLE ${db}.t_alias ENGINE = Alias('${db}', 't')" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} + -- { serverError NOT_IMPLEMENTED } +" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 +" && echo "settings that are not a destination through an alias: allowed" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_alias SYNC" + +echo "-- CREATE without WRITE on S3 or AZURE" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + s3queue_after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'move', + after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' + -- { serverError ACCESS_DENIED } +" + +# The same CREATE without a destination, or with an empty one, needs no grant for it. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = 'keep', + after_processing_move_uri = '' +" && echo "table without a destination: created" + +echo "-- CREATE AS with a destination, without WRITE on S3" + +# The engine and the settings of `AS` are inherited after the query is parsed, so the check has to see the final definition. +# `AS` inherits the definition only when the query has no storage clause (with `SETTINGS`, the engine is +# `default_table_engine`), so the destination comes from the source table. +# The source has no `keeper_path`, so each copy gets its own default path from its `UUID`. +# `SELECT` is required because the definition of the source has secret parts. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_as_src (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', after_processing = 'move', after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "GRANT SHOW COLUMNS, SELECT ON ${db}.t_as_src TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE MATERIALIZED VIEW with a queue inner engine, without WRITE on S3" + +# The engine is an inner engine of the view, and the inner table is created as an internal query, which checks nothing. +$CLICKHOUSE_CLIENT -q "GRANT CREATE VIEW ON ${db}.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the legacy entry format, without WRITE on S3" + +# This format ships the query as written and the workers resolve `AS` with no user. +$CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_entry_format_version 2 -q " + CREATE TABLE ${db}.t_as_cluster ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE AS ON CLUSTER with the default entry format, without WRITE on S3" + +# This format builds the definition on the initiator. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src + -- { serverError ACCESS_DENIED } +" + +echo "-- CREATE ON CLUSTER with a queue engine and a destination, without WRITE on S3" + +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- ATTACH with a full definition and a destination, without WRITE on S3" + +# A full definition in `ATTACH` is a new definition, like `CREATE`. An `Atomic` database needs a `UUID` for it. +# The server warns that a full definition in `ATTACH` is not recommended, so only errors are sent to the client. +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + -- { serverError ACCESS_DENIED } +" + +echo "-- RESTORE of a queue with a destination, without WRITE on S3" + +# The restored definition comes from the backup, and the table is created by an internal query, +# so the restore has to authorize the destination before it creates anything. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" +$CLICKHOUSE_CLIENT -q "BACKUP TABLE ${db}.t_backup TO ${backup} FORMAT Null" +$CLICKHOUSE_CLIENT -q "DROP TABLE ${db}.t_backup SYNC" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup'" + +# The hosts create the tables with no user, so the initiator must authorize the destination. +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null + -- { serverError ACCESS_DENIED } +" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM system.tables WHERE database = '${db}' AND name = 't_backup_cluster'" + +# A temporary table keeps its engine, even with `restore_replace_external_engines_to_null`, so the same check applies. +# Temporary tables live in a session, so the table is created and backed up in one client. +$CLICKHOUSE_CLIENT -m -q " + CREATE TEMPORARY TABLE t_tmp_backup (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_tmp_backup', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys}; + BACKUP TEMPORARY TABLE t_tmp_backup TO ${backup_tmp} FORMAT Null; +" +$CLICKHOUSE_CLIENT -q "GRANT CREATE TEMPORARY TABLE ON *.* TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} + SETTINGS structure_only = 1, restore_replace_external_engines_to_null = 1 FORMAT Null; -- { serverError ACCESS_DENIED } + SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" + +# The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. +$CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_create}" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_as AS ${db}.t_as_src +" && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} + AS SELECT 1::UInt8 AS x +" && echo "materialized view with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup FROM ${backup} SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + RESTORE TABLE ${db}.t_backup AS ${db}.t_backup_cluster ON CLUSTER test_shard_localhost FROM ${backup} + SETTINGS structure_only = 1 FORMAT Null +" && echo "RESTORE ON CLUSTER with WRITE on S3: restored" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_create_cluster ON CLUSTER test_shard_localhost (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create_cluster', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "CREATE ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --distributed_ddl_output_mode none -q " + CREATE TABLE ${db}.t_as_cluster_new ON CLUSTER test_shard_localhost AS ${db}.t_as_src +" && echo "CREATE AS ON CLUSTER with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" --send_logs_level=error -q " + ATTACH TABLE ${db}.t_attach UUID '${attach_uuid}' (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_attach', after_processing = 'move', + after_processing_move_uri = '${dst}', ${keys} +" && echo "ATTACH with WRITE on S3: attached" +$CLICKHOUSE_CLIENT --user "${user_create}" -m -q " + RESTORE TEMPORARY TABLE t_tmp_backup FROM ${backup_tmp} SETTINGS structure_only = 1 FORMAT Null; + SELECT 'RESTORE TEMPORARY with WRITE on S3: restored', count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; +" + +$CLICKHOUSE_CLIENT -q " + DROP TABLE IF EXISTS ${db}.t_alias SYNC; + DROP TABLE IF EXISTS ${db}.t SYNC; + DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_as SYNC; + DROP TABLE IF EXISTS ${db}.t_as_src SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; + DROP TABLE IF EXISTS ${db}.t_create_cluster SYNC; + DROP TABLE IF EXISTS ${db}.t_attach SYNC; + DROP TABLE IF EXISTS ${db}.t_backup SYNC; + DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; + DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; + DROP USER IF EXISTS ${user_alter}, ${user_create}; +" diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference new file mode 100644 index 000000000000..1ee31d8b5520 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.reference @@ -0,0 +1,3 @@ +src 0 1 +src 1 2 +tgt 0 1 diff --git a/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql new file mode 100644 index 000000000000..71c125e9ef63 --- /dev/null +++ b/tests/queries/0_stateless/05443_async_insert_mv_dedup_empty_partition_block.sql @@ -0,0 +1,39 @@ +-- Two async inserts with the same `insert_deduplication_token` but different data are coalesced +-- into one batch. In the materialized view target, the rows of the two tokens land in different +-- partitions. For the partition of the second (duplicate) token, self-deduplication removes all +-- rows, and the recalculated block for that partition is empty. The empty block used to reach +-- `MergeTreeDataWriter::mergeBlock` and trigger the "Required source after the first merge is +-- not 0" logical error with `optimize_on_insert` enabled and a `ReplacingMergeTree` target. + +DROP TABLE IF EXISTS mv_dedup_empty; +DROP TABLE IF EXISTS tgt_dedup_empty; +DROP TABLE IF EXISTS src_dedup_empty; + +CREATE TABLE src_dedup_empty (p UInt64, v UInt64) ENGINE = MergeTree ORDER BY v; +CREATE TABLE tgt_dedup_empty (p UInt64, v UInt64) ENGINE = ReplacingMergeTree PARTITION BY p ORDER BY v + SETTINGS non_replicated_deduplication_window = 100; +CREATE MATERIALIZED VIEW mv_dedup_empty TO tgt_dedup_empty AS SELECT p, v FROM src_dedup_empty; + +SET async_insert = 1; +SET wait_for_async_insert = 0; +SET async_insert_deduplicate = 1; +SET deduplicate_blocks_in_dependent_materialized_views = 1; +SET optimize_on_insert = 1; +-- Prevent an automatic flush between the two inserts; the flush below is explicit. +SET async_insert_busy_timeout_min_ms = 600000; +SET async_insert_busy_timeout_max_ms = 600000; +SET async_insert_use_adaptive_busy_timeout = 0; + +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (0, 1); +INSERT INTO src_dedup_empty SETTINGS insert_deduplication_token = 'tok' VALUES (1, 2); + +SYSTEM FLUSH ASYNC INSERT QUEUE src_dedup_empty; + +-- The source table has no deduplication window, so it keeps both rows. In the target table the +-- second insert is a duplicate of the first by token, so only the first row survives. +SELECT 'src', p, v FROM src_dedup_empty ORDER BY v; +SELECT 'tgt', p, v FROM tgt_dedup_empty ORDER BY v; + +DROP TABLE mv_dedup_empty; +DROP TABLE tgt_dedup_empty; +DROP TABLE src_dedup_empty; diff --git a/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference new file mode 100644 index 000000000000..be1f63edcc4c --- /dev/null +++ b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.reference @@ -0,0 +1,12 @@ +a1 x1 x1 x Nullable(String) +a3 x1 x1 x Nullable(String) +a1 x1 x1 x +a3 x1 x1 x +a1 x1 x1 x Nullable(String) +a3 x1 x1 x Nullable(String) +a1 x1 x1 x +a3 x1 x1 x +a1 x1 x1 x +a3 x1 x1 x +a1 x1 x1 x +a3 x1 x1 x diff --git a/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql new file mode 100644 index 000000000000..1ad38d850bb4 --- /dev/null +++ b/tests/queries/0_stateless/05443_join_reorder_converted_outer_join_type_change.sql @@ -0,0 +1,71 @@ +-- https://github.com/ClickHouse/ClickHouse/issues/127331: with join_use_nulls = 1, an outer join converted to INNER and +-- reordered so that its null-supplying side is joined first failed with "Cannot fold actions for projection". + +DROP TABLE IF EXISTS a; +DROP TABLE IF EXISTS b; +DROP TABLE IF EXISTS c; +DROP TABLE IF EXISTS d; + +CREATE TABLE a (k String, t String, v String) ENGINE = MergeTree ORDER BY k; +CREATE TABLE b (k String, t String, x String) ENGINE = MergeTree ORDER BY k; +CREATE TABLE c (x String, t String, v String) ENGINE = MergeTree ORDER BY x; +INSERT INTO a VALUES ('k1', 't1', 'a1'), ('k2', 't1', 'a2'), ('k3', 't2', 'a3'); +INSERT INTO b VALUES ('k1', 't1', 'x1'), ('k2', 't1', 'x2'), ('k3', 't2', 'x1'); +INSERT INTO c VALUES ('x1', 't1', 'x'), ('x2', 't1', 'y'), ('x1', 't2', 'x'); + +SELECT a.v, b.x, c.x, c.v, toTypeName(c.x) +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND b.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'greedy'; + +SELECT a.v, b.x, c.x, c.v +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND b.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'dpsize'; + +-- There are no transitive predicates in this version, so `a.t = c.t` is written explicitly to let `c` be joined with `a` before `b`. +SELECT a.v, b.x, c.x, c.v, toTypeName(c.x) +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND a.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'greedy'; + +SELECT a.v, b.x, c.x, c.v +FROM a JOIN b ON a.k = b.k AND a.t = b.t LEFT JOIN c ON b.x = c.x AND a.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'dpsize'; + +SELECT ab.v, ab.x, c.x, c.v +FROM c RIGHT JOIN (SELECT a.v AS v, a.t AS t, b.x AS x FROM a JOIN b ON a.k = b.k AND a.t = b.t) AS ab ON ab.x = c.x AND ab.t = c.t +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'greedy'; + +DROP TABLE a; +DROP TABLE c; +CREATE TABLE a (k String, t String, v String) ENGINE = MergeTree ORDER BY k; +CREATE TABLE c (x String, t String, v String) ENGINE = MergeTree ORDER BY x; +CREATE TABLE d (w String) ENGINE = MergeTree ORDER BY w; +INSERT INTO a VALUES ('x1', 't1', 'a1'), ('x2', 't1', 'a2'), ('x1', 't2', 'a3'); +INSERT INTO c VALUES ('x1', 't1', 'x'), ('x2', 't1', 'y'); +INSERT INTO d VALUES ('x1'), ('x2'); + +SELECT a.v, b.x, c.x, c.v +FROM a JOIN d ON a.k = d.w JOIN b ON d.w = b.x AND a.t = b.t LEFT JOIN c ON b.x = c.x +WHERE c.v = 'x' ORDER BY ALL +SETTINGS join_use_nulls = 1, query_plan_convert_outer_join_to_inner_join = 1, + query_plan_optimize_join_order_limit = 10, use_hash_table_stats_for_join_reordering = 0, + query_plan_optimize_join_order_algorithm = 'dpsize'; + +DROP TABLE a; +DROP TABLE b; +DROP TABLE c; +DROP TABLE d; diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference new file mode 100644 index 000000000000..f7068f2917b6 --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.reference @@ -0,0 +1,7 @@ +parallel_distributed_insert_select=0 ACCESS_DENIED +parallel_distributed_insert_select=1 ACCESS_DENIED +parallel_distributed_insert_select=2 ACCESS_DENIED +0 +1 +row policy on source FALLBACK +additional_table_filters 0 diff --git a/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh new file mode 100755 index 000000000000..1c39f64182cf --- /dev/null +++ b/tests/queries/0_stateless/05443_parallel_distributed_insert_select_source_access.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="user_$CLICKHOUSE_DATABASE" + +$CLICKHOUSE_CLIENT -q " + CREATE TABLE secret_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + CREATE TABLE copy_local (id UInt64, secret String) ENGINE = MergeTree ORDER BY id; + INSERT INTO secret_local VALUES (1, 'secret'); + + CREATE TABLE src_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), secret_local, id); + CREATE TABLE dst_dist (id UInt64, secret String) ENGINE = Distributed(test_shard_localhost, currentDatabase(), copy_local, id); + + DROP USER IF EXISTS $user; + CREATE USER $user IDENTIFIED WITH no_password; + GRANT SELECT, INSERT ON $CLICKHOUSE_DATABASE.dst_dist TO $user; +" + +# The cluster has no interserver secret, so the shard runs the forwarded query under the credentials +# from the cluster configuration rather than as the caller. +client=($CLICKHOUSE_CLIENT --user "$user" --prefer_localhost_replica 0) + +for setting in 0 1 2; do + echo -n "parallel_distributed_insert_select=$setting " + "${client[@]}" --parallel_distributed_insert_select "$setting" -q "INSERT INTO dst_dist SELECT * FROM src_dist" |& + grep -o -m1 'ACCESS_DENIED' || echo 'NOT DENIED' +done + +# Read the destination directly: resolving `dst_dist` also authorizes `copy_local` once the shard +# query is planned on the initiator, which depends on the distributed plan settings. +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# With the grant in place the optimized path must still work. +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON $CLICKHOUSE_DATABASE.src_dist TO $user" +"${client[@]}" --parallel_distributed_insert_select 2 -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM copy_local" + +# A row policy on the source table cannot be applied by the optimized rewrite (it ships the query +# to the shards, where the policy on the Distributed table never applies), so it must fall back to +# the regular path. The regular path reads `src_dist` with a `SELECT` sent to the shard, while the +# optimized rewrite sends only an `INSERT ... SELECT` there, so the fallback is detected by the +# kind of the secondary queries in `system.query_log`. (The regular path of this branch does not +# enforce a row policy on a Distributed table, so the result of the copy itself is not checked.) +# +# The two fallback cases below pin serialize_query_plan = 0: with plan serialization the initiator +# plans the read of the underlying table itself and requires the caller's own SELECT on it, which +# these cases do not grant. +$CLICKHOUSE_CLIENT -q "CREATE ROW POLICY policy_05443 ON src_dist USING id != 1 TO $user" +query_id="05443_row_policy_${CLICKHOUSE_DATABASE}_$RANDOM" +"${client[@]}" --parallel_distributed_insert_select 2 --enable_analyzer 1 --enable_parallel_replicas 0 \ + --serialize_query_plan 0 --query_id "$query_id" \ + -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q " + DROP ROW POLICY policy_05443 ON src_dist; + SYSTEM FLUSH DISTRIBUTED dst_dist; + TRUNCATE TABLE copy_local; + SYSTEM FLUSH LOGS query_log; + SELECT + 'row policy on source', + if(countIf(query_kind = 'Select') > 0 AND countIf(query_kind = 'Insert' AND query ILIKE '%SELECT%') = 0, + 'FALLBACK', 'OPTIMIZED') + FROM system.query_log + WHERE event_date >= yesterday() AND initial_query_id = '$query_id' AND NOT is_initial_query AND type = 'QueryFinish' +" + +# additional_table_filters is keyed by the source table name, which the optimized rewrite would +# drop, so it must fall back to the regular path, which applies the filter: the only row has +# id = 1, nothing is copied and the destination stays empty. +echo -n "additional_table_filters " +"${client[@]}" --parallel_distributed_insert_select 2 --enable_parallel_replicas 0 --serialize_query_plan 0 \ + --additional_table_filters "{'src_dist' : 'id != 1'}" -q "INSERT INTO dst_dist SELECT * FROM src_dist" +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH DISTRIBUTED dst_dist; SELECT count() FROM copy_local" + +$CLICKHOUSE_CLIENT -q "DROP USER $user" diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference new file mode 100644 index 000000000000..aca8188dbcd7 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.reference @@ -0,0 +1,13 @@ +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE +0 1900-01-01 00:00:00.145224192 Nullable(DateTime64(9, \'UTC\')) +1 1900-01-01 00:00:00.000000000 Nullable(DateTime64(9, \'UTC\')) +2 2020-05-17 10:20:30.123456000 Nullable(DateTime64(9, \'UTC\')) +3 2262-04-11 23:47:16.854775807 Nullable(DateTime64(9, \'UTC\')) +4 \N Nullable(DateTime64(9, \'UTC\')) +0 1900-01-01 00:00:00.145225 Nullable(DateTime64(6, \'UTC\')) +1 1900-01-01 00:00:00.000000 Nullable(DateTime64(6, \'UTC\')) +2 2020-05-17 10:20:30.123456 Nullable(DateTime64(6, \'UTC\')) +3 2262-04-11 23:47:16.854775 Nullable(DateTime64(6, \'UTC\')) +4 \N Nullable(DateTime64(6, \'UTC\')) +2 diff --git a/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh new file mode 100755 index 000000000000..184859b09430 --- /dev/null +++ b/tests/queries/0_stateless/05443_parquet_int96_date_time_overflow_behavior.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# INT96 timestamps 0001-01-01, 1800-01-01 12:30, 2020-05-17 10:20:30.123456, 9999-12-31 23:59:59 and NULL, written by +# pyarrow with `use_deprecated_int96_timestamps=True`. The first and the fourth do not fit into Int64 nanoseconds. +DATA_FILE="${CUR_DIR}/data_parquet/05443_int96_out_of_range.parquet" + +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' +${CLICKHOUSE_LOCAL} --query "SELECT * FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'throw'" 2>&1 | grep -o -m1 'VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE' + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet) ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toTypeName(ts) FROM file('${DATA_FILE}', Parquet, 'id Int32, ts Nullable(DateTime64(6, \'UTC\'))') ORDER BY id SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT count() FROM file('${DATA_FILE}', Parquet) WHERE ts > '2000-01-01' SETTINGS date_time_overflow_behavior = 'saturate';" diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference new file mode 100644 index 000000000000..0b775a99cb4f --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.reference @@ -0,0 +1,2 @@ +0 1900-01-01 00:00:00.000000000 -9223329600000000000 +0 1900-01-01 00:00:00.000000000 -9223329600000000000 diff --git a/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh new file mode 100755 index 000000000000..39e02424f38a --- /dev/null +++ b/tests/queries/0_stateless/05444_parquet_int96_lower_boundary.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Parquet support + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A single INT96 timestamp 1677-09-21 12:00:00 (julian day 2333836, time of day 43200000000000 ns), written by pyarrow +# with `use_deprecated_int96_timestamps=True`. Midnight of that day does not fit into Int64 nanoseconds, but the full value +# -9223329600000000000 does, so it must be read exactly instead of being saturated to the Int64 minimum or rejected. +DATA_FILE="${CUR_DIR}/data_parquet/05444_int96_lower_boundary.parquet" + +${CLICKHOUSE_LOCAL} --query " + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'saturate'; + SELECT id, ts, toUnixTimestamp64Nano(ts) FROM file('${DATA_FILE}', Parquet) SETTINGS date_time_overflow_behavior = 'throw';" diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference new file mode 100644 index 000000000000..aa20b4a60886 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.reference @@ -0,0 +1 @@ +ACCESS_DENIED diff --git a/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh new file mode 100755 index 000000000000..71282f1c8437 --- /dev/null +++ b/tests/queries/0_stateless/05445_distributed_async_insert_batch_per_user.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tags: distributed, no-fasttest +# Tag no-fasttest: the interserver `` requires SSL, which the fast test build does not have. + +# Queued `Distributed` inserts of different users must not be sent in one batch: the batch is sent with +# the `ClientInfo` of its first file, and over a cluster with an interserver `` the shard +# authenticates the whole batch as that file's `initial_user`. Before the fix, rows of a user without +# the remote `INSERT` grant were delivered under the identity of a user that had it. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Flushing the rejected file (also when the table is dropped) logs the error on the server. +CLICKHOUSE_CLIENT=$(echo "$CLICKHOUSE_CLIENT" | sed "s/--send_logs_level=${CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL:-none}/--send_logs_level=none/g") + +WRITER="writer_${CLICKHOUSE_DATABASE}" +TENANT="tenant_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${WRITER}, ${TENANT}; + CREATE TABLE target (key Int) ENGINE = MergeTree ORDER BY key; + CREATE TABLE dist (key Int) ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), target, 0) + SETTINGS background_insert_batch = 1; + SYSTEM STOP DISTRIBUTED SENDS dist; + CREATE USER ${WRITER} IDENTIFIED WITH no_password; + CREATE USER ${TENANT} IDENTIFIED WITH no_password; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.dist TO ${WRITER}, ${TENANT}; + GRANT INSERT ON ${CLICKHOUSE_DATABASE}.target TO ${WRITER}; +" + +${CLICKHOUSE_CLIENT} --user "${WRITER}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (1)" +${CLICKHOUSE_CLIENT} --user "${TENANT}" --distributed_foreground_insert 0 --prefer_localhost_replica 0 -q "INSERT INTO dist VALUES (2)" + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH DISTRIBUTED dist" 2>&1 | grep -o -m1 "ACCESS_DENIED" +${CLICKHOUSE_CLIENT} -q "SELECT key FROM target WHERE key = 2" + +${CLICKHOUSE_CLIENT} -m -q " + DROP TABLE dist; + DROP USER ${WRITER}, ${TENANT}; +" diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference new file mode 100644 index 000000000000..65bc13dc12ac --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.reference @@ -0,0 +1,13 @@ +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', '[HIDDEN]', 'container', 'blob') +SELECT * FROM icebergAzure('[HIDDEN]', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = '[HIDDEN]', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +HIDDEN +0 1 +0 1 diff --git a/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh new file mode 100755 index 000000000000..8ef143807a79 --- /dev/null +++ b/tests/queries/0_stateless/05447_azure_sas_url_hidden_in_table_function.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no `azureBlobStorage` table function + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A storage account url carrying a credential of its own (a SAS `?sig=...`, `user:key@`), or a value that is +# not a plain string literal, is hidden whole in the Azure table functions, positional or as a named-collection +# override, as the `AzureBlobStorage` engine and the backup destination already do. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('https://user:plain_password@account.blob.core.windows.net', 'container', 'blob') +SELECT * FROM azureBlobStorage(concat('https://account.blob.core.windows.net/?sig=', 'plain_sas_signature'), 'container', 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'path') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container', blob_path = 'blob') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = 'https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', container = 'container') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, storage_account_url = 'https://account.blob.core.windows.net', container = 'container') +EOF + +# `SELECT` on a view implies `SHOW COLUMNS`, so a user granted only that sees the view definition through +# `SHOW CREATE TABLE` and `system.tables`, but not the SAS in it. +user="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +$CLICKHOUSE_CLIENT -q "DROP USER IF EXISTS ${user}" +$CLICKHOUSE_CLIENT -q "CREATE VIEW ${CLICKHOUSE_DATABASE}.v_sas AS SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/?sp=r&sig=plain_sas_signature', 'container', 'file.csv', 'CSV', 'none', 'id UInt8')" +$CLICKHOUSE_CLIENT -q "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'hello'" +$CLICKHOUSE_CLIENT -q "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.v_sas TO ${user}" + +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SHOW CREATE TABLE ${CLICKHOUSE_DATABASE}.v_sas" | grep -o -e 'plain_sas_signature' -e 'HIDDEN' +$CLICKHOUSE_CLIENT --user "${user}" --password hello -q "SELECT countIf(create_table_query LIKE '%plain_sas_signature%'), countIf(create_table_query LIKE '%[HIDDEN]%') FROM system.tables WHERE database = '${CLICKHOUSE_DATABASE}' AND name = 'v_sas'" + +# `EXPLAIN AST optimize = 1` expands the view, which executes the table function and needs more than `SELECT` +# on the view, so it is run as the default user, who sees no secrets either without +# `format_display_secrets_in_show_and_select`. +$CLICKHOUSE_CLIENT --format_display_secrets_in_show_and_select 0 -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN AST optimize = 1 SELECT * FROM ${CLICKHOUSE_DATABASE}.v_sas)" + +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.reference b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference new file mode 100644 index 000000000000..a46fd0469968 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.reference @@ -0,0 +1,14 @@ +1900-06-01 00:01:41.000007000 -2195942298999993 +1900-06-01 00:01:41.000000000 -2195942299000000 +1960-06-01 00:01:41.000007000 -302486298999993 +2000-06-01 00:01:41.000007000 959817701000007 +none 25000 609103159500350648 +zstd 25000 609103159500350648 +lz4 25000 609103159500350648 +snappy 25000 609103159500350648 +zlib 25000 609103159500350648 +expected 25000 609103159500350648 +1001 4500 5500 +1923 +['a','b','a','b'] +['a','b','a','b'] Array(LowCardinality(String)) diff --git a/tests/queries/0_stateless/05447_orc_native_reader_writer.sh b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh new file mode 100755 index 000000000000..bee99fd05840 --- /dev/null +++ b/tests/queries/0_stateless/05447_orc_native_reader_writer.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The Arrow ORC adapter stores negative nanoseconds for the timestamps before the epoch, +# and the reader must decode them as the reference implementation does. +$CLICKHOUSE_LOCAL -q "SELECT t, toUnixTimestamp64Micro(t) FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_arrow.orc', ORC) SETTINGS session_timezone = 'UTC'" + +DATA_FILE="$CLICKHOUSE_TMP/05447_${CLICKHOUSE_DATABASE}.orc" + +# Dictionary encoding of strings (with the row index and several row groups), a non-GMT writer time +# zone, and the values that need all integer encodings: repeats, deltas, outliers. +QUERY="SELECT number AS n, + toString(number % 13) AS low_cardinality, + if(number % 5 = 0, NULL, concat('value_', toString(number))) AS high_cardinality, + toDateTime64(1700000000 + number * 37, 3, 'UTC') AS ts, + if(number % 1000 = 0, 1000000000000, number % 7) AS outliers, + intDiv(number, 100) AS runs, + toDecimal128(number, 10) * -3 AS dec +FROM numbers(25000)" + +for compression in none zstd lz4 snappy zlib +do + $CLICKHOUSE_LOCAL -q "$QUERY FORMAT ORC SETTINGS output_format_orc_compression_method = '$compression', + output_format_orc_dictionary_key_size_threshold = 0.5, output_format_orc_row_index_stride = 1000, + output_format_orc_writer_time_zone_name = 'America/Los_Angeles'" > "$DATA_FILE" + $CLICKHOUSE_LOCAL -q "SELECT '$compression', count(), sum(cityHash64(*)) FROM file('$DATA_FILE', ORC, + 'n UInt64, low_cardinality String, high_cardinality Nullable(String), ts DateTime64(3, \'UTC\'), outliers UInt64, runs UInt64, dec Decimal(38, 10)') + SETTINGS input_format_orc_reader_time_zone_name = 'America/Los_Angeles'" +done +$CLICKHOUSE_LOCAL -q "SELECT 'expected', count(), sum(cityHash64(*)) FROM ($QUERY)" + +# Filter pushdown skips the row groups by the statistics in the row index. +$CLICKHOUSE_LOCAL -q "SELECT count(), min(n), max(n) FROM file('$DATA_FILE', ORC) WHERE n BETWEEN 4500 AND 5500 SETTINGS input_format_orc_filter_push_down = 1" +$CLICKHOUSE_LOCAL -q "SELECT count() FROM file('$DATA_FILE', ORC) WHERE low_cardinality = '12' SETTINGS input_format_orc_filter_push_down = 1" + +# The dictionary of a string column nested in an array can have more entries than the stripe has rows. +$CLICKHOUSE_LOCAL -q "SELECT ['a', 'b', 'a', 'b'] AS arr FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 0.5" > "$DATA_FILE" +$CLICKHOUSE_LOCAL -q "SELECT arr FROM file('$DATA_FILE', ORC, 'arr Array(String)')" +$CLICKHOUSE_LOCAL -q "SELECT arr, toTypeName(arr) FROM file('$DATA_FILE', ORC, 'arr Array(LowCardinality(String))')" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.reference b/tests/queries/0_stateless/05448_orc_date_after_2059.reference new file mode 100644 index 000000000000..62cea6b447e4 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.reference @@ -0,0 +1,12 @@ +0 1970-01-01 Nullable(Date32) +1 2059-09-17 Nullable(Date32) +2 2059-09-18 Nullable(Date32) +3 2100-01-01 Nullable(Date32) +4 2149-06-06 Nullable(Date32) +0 1970-01-01 +1 2059-09-17 +2 2059-09-18 +3 2100-01-01 +4 2149-06-06 +3 +4 diff --git a/tests/queries/0_stateless/05448_orc_date_after_2059.sh b/tests/queries/0_stateless/05448_orc_date_after_2059.sh new file mode 100755 index 000000000000..8cc480ff4b24 --- /dev/null +++ b/tests/queries/0_stateless/05448_orc_date_after_2059.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `Date` is the unsigned number of days, and the dates after 2059-09-18 (more than 32767 days) used +# to be written to ORC as negative numbers, which read back as the dates before 1970. +DATA_FILE="$CLICKHOUSE_TMP/05448_${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q "SELECT number AS n, toDate(d) AS d FROM values('number UInt64, d String', (0, '1970-01-01'), (1, '2059-09-17'), (2, '2059-09-18'), (3, '2100-01-01'), (4, '2149-06-06')) FORMAT ORC" > "$DATA_FILE" + +$CLICKHOUSE_LOCAL -q "SELECT n, d, toTypeName(d) FROM file('$DATA_FILE', ORC) ORDER BY n" +$CLICKHOUSE_LOCAL -q "SELECT n, d FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') ORDER BY n" + +# The statistics are correct as well, so the filter pushdown keeps the rows. +$CLICKHOUSE_LOCAL -q "SELECT n FROM file('$DATA_FILE', ORC, 'n UInt64, d Date') WHERE d > '2060-01-01' ORDER BY n SETTINGS input_format_orc_filter_push_down = 1" + +rm "$DATA_FILE" diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference new file mode 100644 index 000000000000..d5d2e9dad4f1 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.reference @@ -0,0 +1,5 @@ +-- page cache, prefetching read +0 0 +1 10 +2 20 +1 diff --git a/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh new file mode 100755 index 000000000000..8b52986339b5 --- /dev/null +++ b/tests/queries/0_stateless/05448_text_formats_read_padding_object_storage.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: S3 (MinIO) is not available in the fast test. + +# Parsing a short CSV object through the userspace page cache with a prefetching read must not read past the end of the +# page cache cell that holds it. A sanitizer build aborts on such a read. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}/data.csv" + +CONFIG_FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_page_cache.yaml" +echo "page_cache_max_size: 134217728" > "${CONFIG_FILE}" + +# A 14-byte object: "0,0\n1,10\n2,20\n". +${CLICKHOUSE_CLIENT} --query " + INSERT INTO FUNCTION s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a UInt32, b UInt32') + SELECT number, number * 10 FROM numbers(3) SETTINGS s3_truncate_on_insert = 1" + +echo "-- page cache, prefetching read" +${CLICKHOUSE_LOCAL} --config-file "${CONFIG_FILE}" --query " + SELECT * FROM s3('${S3_URL}', 'test', 'testtest', 'CSV', 'a String, b UInt32') ORDER BY b + SETTINGS input_format_parallel_parsing = 0, use_page_cache_for_object_storage = 1, + remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1; + SELECT value > 0 FROM system.metrics WHERE metric = 'PageCacheBytes'" + +rm "${CONFIG_FILE}" diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference new file mode 100644 index 000000000000..a4a9c43f01b2 --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.reference @@ -0,0 +1,8 @@ +1.6.0 0 18000000000 Mike +1.6.0 0 1 +1.6.0 1 18000000000 Mike +1.6.0 1 1 +1.6.11 0 18000000000 Mike +1.6.11 0 1 +1.6.11 1 18000000000 Mike +1.6.11 1 1 diff --git a/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh new file mode 100755 index 000000000000..30badff1fa0d --- /dev/null +++ b/tests/queries/0_stateless/05453_orc_bad_bloom_filter.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + + +# The bloom filters written by the C++ writer of ORC 1.6.0 - 1.6.11 and 1.7.0 use incorrect hashing (ORC-1024) +# and must be ignored, otherwise the filter pushdown skips the matching rows. +for version in 1.6.0 1.6.11 +do + for push_down in 0 1 + do + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, id, name + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id = 18000000000 + SETTINGS input_format_orc_filter_push_down = $push_down" + $CLICKHOUSE_LOCAL -q " + SELECT '$version', $push_down, count() + FROM file('$CUR_DIR/data_orc/bad_bloom_filter_$version.orc') + WHERE id IN (18000000000, 18000000001) + SETTINGS input_format_orc_filter_push_down = $push_down" + done +done diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference new file mode 100644 index 000000000000..cf669808c66d --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.reference @@ -0,0 +1,39 @@ +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +SELECT * FROM azureBlobStorage('[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('[HIDDEN]', 'https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', '[HIDDEN]') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];SharedAccessSignature=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage('[HIDDEN]', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=[HIDDEN]', account_key = '[HIDDEN]') +SELECT * FROM azureBlobStorage(azure_conf, '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = '[HIDDEN]', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = '[HIDDEN]', storage_account_url = '[HIDDEN]') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = '[HIDDEN]', connection_string = '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]', partition_strategy = 'none') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('[HIDDEN]', '[HIDDEN]') +CREATE TABLE test_azure (`key` UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', '[HIDDEN]') +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = '[HIDDEN]' +CREATE TABLE test_azure_queue (`key` UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=[HIDDEN];AccountKey=[HIDDEN]' +0 1 +0 1 +0 1 +0 1 +0 1 diff --git a/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh new file mode 100755 index 000000000000..6246ea1d8cb3 --- /dev/null +++ b/tests/queries/0_stateless/05458_azure_credentials_hidden_in_logged_queries.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no Azure table functions and engines, whose arguments it then hides whole + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `clickhouse-format` hides the credentials in the arguments of the Azure table functions and engines and in the +# `SETTINGS` clause of `AzureQueue`, wherever the parser reads them from. +while read -r query; do + $CLICKHOUSE_FORMAT --oneline --query "$query" +done <<'EOF' +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id', tenant_id = 'tid'), 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorageCluster('cluster', 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM icebergAzure('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', SETTINGS input_format_csv_skip_first_lines = 0) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials(client_id = 'id'), extra_credentials(tenant_id = 'tid'), 'plain_account_key', 'CSV') +SELECT * FROM azureBlobStorageCluster(extra_credentials(client_id = 'id'), 'https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature') +SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')) +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;BlobEndpoint=https://account.blob.core.windows.net', 'container', 'blob', 'account', 'plain_account_key') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;SharedAccessSignature=sp=r&sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2', 'container', 'blob') +SELECT * FROM azureBlobStorage('AccountName=account;BlobEndpoint=https://account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('account.blob.core.windows.net/?sig=plain_sas_signature', 'container', 'blob') +SELECT * FROM azureBlobStorage('HTTPS://user:plain_password=x@account.blob.core.windows.net/', 'container', 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', account_key = 'plain_account_key') +SELECT * FROM azureBlobStorage(azure_conf, client_secret = 'plain_client_secret', blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, container = headers('Authorization' = 'plain_header_secret'), blob_path = 'blob') +SELECT * FROM azureBlobStorage(azure_conf, connection_string = 'AccountName=account;AccountKey=plain_account_key', storage_account_url = 'AccountName=account;AccountKey=plain_account_key_2') +SELECT * FROM azureBlobStorageCluster('cluster', azure_conf, connection_string = concat('AccountName=account;AccountKey=', 'plain_account_key'), connection_string = 'AccountName=account;AccountKey=plain_account_key_2') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature', partition_strategy = 'none') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', partition_strategy = 'none', 'plain_account_key') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', 'CSV', extra_credentials(client_id = 'id', client_secret = 'plain_client_secret', role_arn = 'plain_role_arn')) +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage(azure_conf, sas_token = 'plain_sas_signature') +CREATE TABLE test_azure (key UInt64) ENGINE = AzureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'account', 'plain_account_key' = 'x') +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'HTTPS://account.blob.core.windows.net/?sig=plain_sas_signature' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'https://user:plain_password=x@account.blob.core.windows.net/' +CREATE TABLE test_azure_queue (key UInt64) ENGINE = AzureQueue('https://account.blob.core.windows.net', 'container', '*', 'CSV') SETTINGS after_processing_move_connection_string = 'AccountName=account;AccountKey=plain_account_key;AccountKey=plain_account_key_2' +EOF + +# The query tree hides an argument masked whole, not only the right side of a comparison. +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_signature' = 'x'))" +$CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_sas_signature%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM azureBlobStorage(azure_conf, 'sp=r&sig=plain_sas_signature' = 'x'))" + +# Nothing inside an Azure `extra_credentials(...)` is dumped, keys included. +for explain in "AST" "QUERY TREE run_passes = 0"; do + $CLICKHOUSE_CLIENT -q "SELECT countIf(explain LIKE '%plain_client_%'), countIf(explain LIKE '%[HIDDEN]%') FROM (EXPLAIN $explain SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net', 'container', 'blob', extra_credentials('plain_client_secret' = 'x', client_id = 'plain_client_id')))" +done + +# The statement is logged with the credential hidden. +$CLICKHOUSE_CLIENT -q "EXPLAIN AST SELECT * FROM azureBlobStorage('https://account.blob.core.windows.net/container/blob.csv', 'sp=r&sig=plain_sas_logged')" > /dev/null +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS query_log" +$CLICKHOUSE_CLIENT -q "SELECT countIf(query LIKE '%plain_sas_logged%'), countIf(query LIKE '%[HIDDEN]%') FROM system.query_log WHERE current_database = currentDatabase() AND query LIKE 'EXPLAIN AST%azureBlobStorage%' AND type = 'QueryFinish' AND is_initial_query" diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.reference b/tests/queries/0_stateless/05473_orc_footer_content_length.reference new file mode 100644 index 000000000000..ae5399ce4997 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.reference @@ -0,0 +1,2 @@ +1 True True +1 True True diff --git a/tests/queries/0_stateless/05473_orc_footer_content_length.sh b/tests/queries/0_stateless/05473_orc_footer_content_length.sh new file mode 100755 index 000000000000..78921273f950 --- /dev/null +++ b/tests/queries/0_stateless/05473_orc_footer_content_length.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. +# The `content_length` in the ORC footer covers only the stripes, not the metadata section with the stripe statistics. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +check() +{ + $CLICKHOUSE_LOCAL --query "$1" | python3 -c ' +import sys + +data = sys.stdin.buffer.read() + +def varint(buf, pos): + result = shift = 0 + while True: + byte = buf[pos] + pos += 1 + result |= (byte & 0x7f) << shift + shift += 7 + if byte < 0x80: + return result, pos + +def fields(buf): + pos = 0 + while pos < len(buf): + key, pos = varint(buf, pos) + if key & 7 == 0: + value, pos = varint(buf, pos) + elif key & 7 == 2: + length, pos = varint(buf, pos) + value = buf[pos:pos + length] + pos += length + else: + raise Exception("unexpected wire type") + yield key >> 3, value + +postscript_length = data[-1] +postscript = dict(fields(data[-1 - postscript_length:-1])) +footer_length = postscript[1] +footer = list(fields(data[-1 - postscript_length - footer_length:-1 - postscript_length])) +content_length = next(v for f, v in footer if f == 2) +stripes = [dict(fields(v)) for f, v in footer if f == 3] +stripes_length = sum(s.get(2, 0) + s.get(3, 0) + s.get(4, 0) for s in stripes) +print(len(stripes), content_length == stripes_length, postscript[5] > 0) +' +} + +check "SELECT number FROM numbers(3) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" +check "SELECT number, toString(number) FROM numbers(100000) FORMAT ORC SETTINGS output_format_orc_compression_method = 'none'" diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.reference b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference new file mode 100644 index 000000000000..754cd5dae768 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.reference @@ -0,0 +1,20 @@ +a Nullable(Int64) +b Nullable(Decimal(12, 0)) +c Nullable(Decimal(20, 2)) +d Nullable(Decimal(12, 2)) +e Nullable(Decimal(2, 2)) +17292380420 24 36164.16 0.03 0.01 +17292380421 38 63351.7 0.08 0.01 +17292380421 28 42673.96 0.09 0.06 +17292380421 40 76677.6 0.05 0.04 +17292380421 2 2096.48 0.07 0.07 +17292380421 42 45284.82 0.07 0.05 +17292380421 10 18572.9 0.01 0.08 +17292380422 12 14836.8 0.09 0.06 +17292380422 41 82152.52 0.07 0.02 +17292380422 38 47240.84 0.1 0 +38 0.08 +40 0.05 +42 0.07 +41 0.07 +38 0.1 diff --git a/tests/queries/0_stateless/05474_orc_decimal64_v2.sh b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh new file mode 100755 index 000000000000..94e31bf56154 --- /dev/null +++ b/tests/queries/0_stateless/05474_orc_decimal64_v2.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `decimal64_v2.orc` from the examples of apache/orc has the format version 1.9999 (`UNSTABLE_PRE_2_0`), +# where the DECIMAL columns with the precision up to 18 are signed RLEv2 integers without the SECONDARY stream. +$CLICKHOUSE_LOCAL -q "DESCRIBE file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT * FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC)" +$CLICKHOUSE_LOCAL -q "SELECT b, d FROM file('$CUR_DIR/data_orc/decimal64_v2.orc', ORC) WHERE b > 30 SETTINGS input_format_orc_filter_push_down = 1" diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference new file mode 100644 index 000000000000..8588a3ce6bb6 --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.reference @@ -0,0 +1,4 @@ +400 79800 0 399 +58 11571 +INCORRECT_DATA +1 diff --git a/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh new file mode 100755 index 000000000000..b0ebdedb176d --- /dev/null +++ b/tests/queries/0_stateless/05481_object_storage_parquet_footer_prefetch.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: needs MinIO + +# A source of an object storage reads the Parquet footer of its next file in the background, while it reads the current one. +# One stream (`max_threads = 1`) reads all files, so every file but the first one is read through a prefetched footer. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +DIR="${CLICKHOUSE_TEST_UNIQUE_NAME}" +Q="${CLICKHOUSE_TEST_UNIQUE_NAME}_" + +for i in 0 1 2 3; do + ${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/good/${i}.parquet', format = Parquet) SELECT number + ${i} * 100 AS x FROM numbers(100)" +done +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/0.parquet', format = Parquet) SELECT number AS x FROM numbers(100)" +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION s3(s3_conn, filename = '${DIR}/bad/1.parquet', format = RawBLOB) SELECT 'not a parquet file'" + +# The footer is read in advance only by the native Parquet reader, which CI randomizes on this branch. +SETTINGS="--max_threads 1 --use_parquet_metadata_cache 1 --input_format_parquet_use_native_reader_v3 1" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}1" --query "SELECT count(x), sum(x), min(x), max(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet')" +${CLICKHOUSE_CLIENT} $SETTINGS --query_id "${Q}2" --query "SELECT count(x), sum(x) FROM s3(s3_conn, filename = '${DIR}/good/*.parquet') WHERE x % 7 = 0" + +# The file that is not Parquet fails the query as it did before the footer was read in advance. +${CLICKHOUSE_CLIENT} $SETTINGS --query "SELECT sum(x) FROM s3(s3_conn, filename = '${DIR}/bad/*.parquet')" 2>&1 | grep -o -m1 "INCORRECT_DATA" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" + +# The second query finds all footers in the Parquet metadata cache. +# With parallel replicas, `s3` is rewritten to `s3Cluster` and the files are read by secondary queries, +# which run with `current_database = 'default'`, so the hits are summed over `initial_query_id`. +${CLICKHOUSE_CLIENT} --query " + SELECT sum(ProfileEvents['ParquetMetadataCacheHits']) >= 4 + FROM system.query_log + WHERE initial_query_id = '${Q}2' AND type = 'QueryFinish' + AND (current_database = currentDatabase() OR NOT is_initial_query) +" diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference new file mode 100644 index 000000000000..f23520f0dbfc --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.reference @@ -0,0 +1,2 @@ +batches: 4096 row counts: [64] +262144 1000 16777216 diff --git a/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh new file mode 100755 index 000000000000..e71fb6e12721 --- /dev/null +++ b/tests/queries/0_stateless/05483_arrow_record_batch_split_many_batches.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# ^ pyarrow is not available in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One large block split by a small `output_format_arrow_max_record_batch_size_bytes` into thousands of +# record batches. The `LowCardinality` column never needs a split itself, but measuring it is linear in +# the rows given, so this is the shape where measuring the whole remainder of the block +# for every batch would be quadratic. Every batch is bounded by the `String` column: 64 rows of 64 bytes. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}_many_batches.arrows" +trap 'rm -f "$FILE"' EXIT + +$CLICKHOUSE_LOCAL --query " + SELECT + toLowCardinality(toString(number % 1000)) AS lc, + repeat('x', 64) AS s + FROM numbers(262144) + SETTINGS + max_block_size = 262144, + output_format_arrow_max_record_batch_size_bytes = 4096, + output_format_arrow_compression_method = 'none' + FORMAT ArrowStream" > "$FILE" + +python3 - "$FILE" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +with pa.OSFile(sys.argv[1], "rb") as src: + batches = list(ipc.open_stream(src)) +print("batches:", len(batches), "row counts:", sorted({batch.num_rows for batch in batches})) +PY + +$CLICKHOUSE_LOCAL --query " + SELECT count(), uniqExact(lc), sum(length(s)) + FROM file('$FILE', ArrowStream)" diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference new file mode 100644 index 000000000000..d00491fd7e5b --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.reference @@ -0,0 +1 @@ +1 diff --git a/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh new file mode 100755 index 000000000000..eec443dcca49 --- /dev/null +++ b/tests/queries/0_stateless/05483_replicated_database_ddl_during_restore_replica.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Tags: zookeeper + +# `SYSTEM RESTORE DATABASE REPLICA` stops and replaces the DDL worker of a `Replicated` database. +# A DDL query that was concurrently waiting in the worker used to keep a raw pointer to it +# and dereference the destroyed worker (segmentation fault). Now such a query either succeeds +# or fails with an exception, and the server stays alive. + +# The racing queries fail with various errors by design; they are not interesting. +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=none + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +TIMEOUT=10 + +function ddl_thread() +{ + local i=0 + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + i=$((i + 1)) + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_${1}_${i} (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 + $CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS ${DB}.t_${1}_${i} SYNC" >/dev/null 2>&1 + done +} + +function sync_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +function restore_thread() +{ + local end=$((SECONDS + TIMEOUT)) + while [ $SECONDS -lt $end ]; do + $CLICKHOUSE_CLIENT --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 + done +} + +ddl_thread 1 & +ddl_thread 2 & +ddl_thread 3 & +sync_thread & +restore_thread & +restore_thread & +wait + +# The server is alive and the database still accepts DDL. +for _ in $(seq 1 60); do + $CLICKHOUSE_CLIENT --query "CREATE TABLE ${DB}.t_final (x UInt64) ENGINE = MergeTree ORDER BY x" >/dev/null 2>&1 && break + sleep 1 +done +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t_final" + +$CLICKHOUSE_CLIENT --query "DROP DATABASE ${DB} SYNC" diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference new file mode 100644 index 000000000000..587aee15552b --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.reference @@ -0,0 +1,5 @@ +restore is waiting 1 +create succeeded +restore finished +1 +0 diff --git a/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh new file mode 100755 index 000000000000..6ef139d50d2d --- /dev/null +++ b/tests/queries/0_stateless/05484_replicated_database_restore_replica_waits_for_initial_query.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# An initial DDL query of a `Replicated` database executes and commits on the submitting thread. +# `SYSTEM RESTORE DATABASE REPLICA` must wait for such a query that was already admitted by the old +# DDL worker before the new worker recovers the replica. Otherwise the query could commit its metadata +# while the recovery compares the Keeper snapshot with the local tables, and the recovery would move +# the just created table to the `_broken_replicated_tables` database. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" + +# Hold the initial `CREATE TABLE` after the DDL worker has admitted it, before it executes and commits. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = MergeTree ORDER BY x" & +create_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore stops the old DDL worker and then has to wait for the paused `CREATE TABLE`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $create_pid && echo "create succeeded" +# The restore proceeds only after the query has committed. The replica is not lost then (its digest is not empty), +# so the restore may refuse with `REPLICA_ALREADY_EXISTS`; either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +# The table created by the successful query is still there after the recovery of the replica. +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "EXISTS TABLE ${DB}.t" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference new file mode 100644 index 000000000000..799f581f2dea --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.reference @@ -0,0 +1,6 @@ +d_complex LOADED +d_simple LOADED +1 1 +alive +4 +0 diff --git a/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh new file mode 100755 index 000000000000..aa8ddefa8372 --- /dev/null +++ b/tests/queries/0_stateless/05488_ssd_cache_dictionary_cache_file_cannot_grow.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-llvm-coverage +# no-fasttest: waits 7 s for the update backoff; no-llvm-coverage: the file size limit below would also cut the coverage profile. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `ssd_cache` dictionaries whose cache file cannot grow for the next partition stay usable after the failed update, +# and the next update fails the same way. The file size limit lets the first 64 KiB of each cache file be allocated, +# but not the next 64 KiB, while 100 values of 1.2 KB need more than that. + +dir="${CLICKHOUSE_USER_FILES_UNIQUE:?}" +rm -rf "${dir:?}" +mkdir -p "$dir" +trap 'rm -rf "${dir:?}"' EXIT + +query=" +CREATE TABLE src (k UInt64, v String) ENGINE = Memory; +INSERT INTO src SELECT number, toString(number) || ':' || repeat('x', 1200) FROM numbers(100); + +CREATE DICTIONARY d_simple (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_simple')); + +CREATE DICTIONARY d_complex (k UInt64, v String DEFAULT '') PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'src')) LIFETIME(MIN 1000 MAX 1000) +LAYOUT(COMPLEX_KEY_SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 MAX_PARTITIONS_COUNT 4 PATH '$dir/d_complex')); + +-- Both updates fail, because the cache files cannot grow. +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +-- Wait for the 5-6 s backoff after a failed update, so that the next lookups update the dictionaries again. +SELECT sleep(3) FORMAT Null; +SELECT sleep(3) FORMAT Null; +SELECT sleep(1) FORMAT Null; + +SELECT dictGet('d_simple', 'v', number) FROM numbers(100) FORMAT Null; +SELECT dictGet('d_complex', 'v', tuple(number)) FROM numbers(100) FORMAT Null; + +SELECT name, status FROM system.dictionaries ORDER BY name; +SELECT dictGet('d_simple', 'v', toUInt64(0)) = '0:' || repeat('x', 1200), dictGet('d_complex', 'v', tuple(toUInt64(0))) = '0:' || repeat('x', 1200); +SELECT 'alive'; +" + +( + cd "$dir" || exit 1 + ulimit -c 0 + trap '' XFSZ + ulimit -f 100 + $CLICKHOUSE_LOCAL --ignore-error --send_logs_level=error --query "$query" 2>"$dir/stderr" +) + +# Each of the four failed updates reports the failed allocation, and none of them was refused by the backoff. +grep -o -F 'Cannot preallocate space' "$dir/stderr" | wc -l +grep -o -F 'nearest update is scheduled' "$dir/stderr" | wc -l diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference new file mode 100644 index 000000000000..350939450c19 --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.reference @@ -0,0 +1,25 @@ +--- readonly_1 +READONLY +READONLY +READONLY +READONLY +READONLY +OK +--- readonly_2 +OK +OK +OK +OK +OK +--- readonly_0 +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +OK +--- requests to the endpoint +readonly_2_cluster 1 +readonly_2_describe 1 +readonly_2_remote 1 +readonly_2_select 1 diff --git a/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh new file mode 100755 index 000000000000..621fcc5b8a8b --- /dev/null +++ b/tests/queries/0_stateless/05493_describe_table_function_create_temporary_table_access.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Resolving the structure of a table function (`DESCRIBE TABLE url(...)`, or a table function nested in +# `cluster`) must require the same `CREATE TEMPORARY TABLE` grant as reading from it, and must be refused +# before the source is contacted. Otherwise a user who cannot run `url` (e.g. under `readonly = 1`) can make +# the server request an arbitrary endpoint and read the response from the schema inference error. + +USER_READONLY_1="readonly_1_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_2="readonly_2_${CLICKHOUSE_TEST_UNIQUE_NAME}" +USER_READONLY_0="readonly_0_${CLICKHOUSE_TEST_UNIQUE_NAME}" +TEMP_CREDENTIALS="unknown" + +# Create users with different readonly settings. +function create_users() { + ${CLICKHOUSE_CLIENT} -m -q " + DROP USER IF EXISTS ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + CREATE USER ${USER_READONLY_1} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 1; + CREATE USER ${USER_READONLY_2} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}' SETTINGS readonly = 2; + -- \`readonly = 0\`, but without the \`CREATE TEMPORARY TABLE\` grant. + CREATE USER ${USER_READONLY_0} IDENTIFIED WITH PLAINTEXT_PASSWORD BY '${TEMP_CREDENTIALS}'; + GRANT SELECT ON *.*, READ ON URL, READ ON REMOTE TO ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${USER_READONLY_1}, ${USER_READONLY_2}; + " +} + +function drop_users() { + ${CLICKHOUSE_CLIENT} -q "DROP USER ${USER_READONLY_1}, ${USER_READONLY_2}, ${USER_READONLY_0}" +} + +# Instead of a mock server, use this server's HTTP interface: every request to it is logged in `system.query_log` +# with the marker given as the argument, so `check_endpoint_requests` can tell whether the source was contacted. +# It always responds in `JSONEachRow`, like the JSON metadata service in the original report: the format passed +# to `url` is how the response is parsed, so `Values` fails to parse it and would echo the body in the error. +function endpoint() { + local marker="$1" + echo "${CLICKHOUSE_PORT_HTTP_PROTO}://${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?database=${CLICKHOUSE_DATABASE}&query=SELECT+1+AS+x,+%27marker_${marker}%27+AS+m+FORMAT+JSONEachRow" +} + +# Run a query as the given user and print `READONLY`, `ACCESS_DENIED`, `OK`, or the full unexpected error. +# `CLICKHOUSE_CLIENT` passes randomized settings, which a `readonly = 1` user is not allowed to change. +function run() { + local user="$1" + local query="$2" + local output + output=$(${CLICKHOUSE_CLIENT_BINARY} --host "${CLICKHOUSE_HOST}" --port "${CLICKHOUSE_PORT_TCP}" \ + --user "${user}" --password "${TEMP_CREDENTIALS}" -q "${query}" 2>&1) + if [[ "${output}" =~ \((READONLY|ACCESS_DENIED)\) ]]; then + echo "${BASH_REMATCH[1]}" + elif [[ "${output}" == *Exception* ]]; then + echo "${output}" + else + echo "OK" + fi +} + +# Run all the queries as one user. The user name without the unique suffix (e.g. `readonly_1`) +# labels the output and the endpoint markers. +function check_user() { + local user="$1" + local label="${user%_"${CLICKHOUSE_TEST_UNIQUE_NAME}"}" + echo "--- ${label}" + run "${user}" "SELECT * FROM url('$(endpoint "${label}_select")', 'JSONEachRow')" + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_describe")', 'JSONEachRow')" + # With a format that fails to parse the response, the schema inference error would contain the response body. + # It is skipped for `readonly_2`, which is allowed to read the URL: its error text depends on the server version. + if [[ "${label}" != "readonly_2" ]]; then + run "${user}" "DESCRIBE TABLE url('$(endpoint "${label}_values")', 'Values')" + fi + + # `remote` is not allowed in readonly mode, so it is refused before the nested `url` is resolved. + run "${user}" "DESCRIBE TABLE remote('127.0.0.1', url('$(endpoint "${label}_remote")', 'JSONEachRow'))" + # `cluster` is allowed in readonly mode, but it resolves the structure of the nested `url` on the local shard. + run "${user}" "DESCRIBE TABLE cluster('test_shard_localhost', url('$(endpoint "${label}_cluster")', 'JSONEachRow'))" + + # Table functions allowed in readonly mode stay available without the grant. + run "${user}" "DESCRIBE TABLE numbers(1)" +} + +# Print the markers of the requests that reached the endpoint, i.e. which queries contacted the source. +# Only the queries of the `readonly = 2` user may appear: a marker without requests has no row. +function check_endpoint_requests() { + echo "--- requests to the endpoint" + ${CLICKHOUSE_CLIENT} -m -q " + SYSTEM FLUSH LOGS query_log; + SELECT extract(query, 'marker_([a-z0-9_]+)') AS marker, count() > 0 + FROM system.query_log + WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE 'SELECT 1 AS x, %marker_%' + GROUP BY marker + ORDER BY marker; + " +} + +create_users +for user in "${USER_READONLY_1}" "${USER_READONLY_2}" "${USER_READONLY_0}"; do + check_user "${user}" +done +check_endpoint_requests +drop_users diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference new file mode 100644 index 000000000000..2e0aea006e63 --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.reference @@ -0,0 +1,6 @@ +1 +2 +3 +4 +1 [1,2,3] +1 [1,2,3] diff --git a/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh new file mode 100755 index 000000000000..19aeaf05141f --- /dev/null +++ b/tests/queries/0_stateless/05493_msgpack_async_insert_after_invalid_entry.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: MsgPack format is not available in the fasttest environment + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One async insert batch reuses one MsgPack input format for all its entries. Each case queues an +# invalid entry followed by a valid one: the valid entry must be parsed from a clean state. + +url="${CLICKHOUSE_URL}&async_insert=1&wait_for_async_insert=0&async_insert_use_adaptive_busy_timeout=0&async_insert_busy_timeout_min_ms=100000&async_insert_busy_timeout_max_ms=100000" + +function insert_pair() +{ + local table=$1 bad=$2 good=$3 + printf '%b' "$bad" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + printf '%b' "$good" | ${CLICKHOUSE_CURL} -sS "${url}&query=INSERT+INTO+${table}+FORMAT+MsgPack" --data-binary @- + ${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH ASYNC INSERT QUEUE ${table}" + ${CLICKHOUSE_CLIENT} -q "SELECT * FROM ${table} ORDER BY ALL" +} + +${CLICKHOUSE_CLIENT} -q " + CREATE TABLE t_scalar (x UInt64) ENGINE = MergeTree ORDER BY x; + CREATE TABLE t_exception (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; + CREATE TABLE t_array (id UInt64, arr Array(UInt8)) ENGINE = MergeTree ORDER BY id; +" + +# A uint32 with 1 of its 4 bytes; the valid entry is four rows 1, 2, 3, 4. +insert_pair t_scalar '\xce\x00' '\x01\x02\x03\x04' +# A string inside Array(UInt8) is rejected in the middle of the array. +insert_pair t_exception '\x07\x92\x01\xa1x' '\x01\x93\x01\x02\x03' +# An array of 3 elements with only 1 present. +insert_pair t_array '\x07\x93\x01' '\x01\x93\x01\x02\x03' + +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_scalar; DROP TABLE t_exception; DROP TABLE t_array" diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference new file mode 100644 index 000000000000..60ef3fadf28c --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.reference @@ -0,0 +1,13 @@ +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string +which the MySQL client library would read as a list of hosts +which the MySQL client library would read as a connection plugin URL +which the MySQL client library would read as the end of the host +connection failed +port 0: rejected +dictionary 127.0.0.1 port 0: rejected +dictionary localhost port 0: unix socket +dictionary localhost port 0: rejected +localhost: tcp +which the MySQL client library would read as a connection string +which the MySQL client library would read as a connection string diff --git a/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh new file mode 100755 index 000000000000..bc24f80c9622 --- /dev/null +++ b/tests/queries/0_stateless/05493_mysql_host_connector_syntax.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MySQL client library is not built in the fast test + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The MySQL client library reinterprets some host strings: a connection string (which can set a socket, a plugin +# directory, TLS files), a connection plugin URL, a list of hosts, or a host cut at a NUL. They must be rejected +# before any connection attempt. + +# Prints how the host was rejected, or "connection failed" for an ordinary connection failure. +function check() +{ + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "$1" 2>&1 | tr -d '\000') + if grep -q -F "which the MySQL client library would read as" <<< "$output"; then + grep -o -m1 "which the MySQL client library would read as [a-zA-Z ]*" <<< "$output" + elif grep -q -F "ALL_CONNECTION_TRIES_FAILED" <<< "$output"; then + echo "connection failed" + else + echo "unexpected output: $output" + fi +} + +check "SELECT * FROM mysql('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('host=localhost;socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1,localhost:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('[replication://127.0.0.1]:1', 'db', 't', 'u', 'p')" +check "SELECT * FROM mysql('127.0.0.1\\0.example.com:1', 'db', 't', 'u', 'p')" + +# A plain host is passed through and fails to connect as usual. +check "SELECT * FROM mysql('127.0.0.1:1', 'db', 't', 'u', 'p')" + +# Port 0 would be replaced by the client library's default port. +$CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('127.0.0.1:0', 'db', 't', 'u', 'p')" 2>&1 \ + | grep -q -F "MySQL port 0" && echo "port 0: rejected" || echo "port 0: connection failed" + +# A dictionary socket is used only for `localhost`; for another host it is ignored and port 0 is rejected. +function check_dictionary() +{ + $CLICKHOUSE_CLIENT --send_logs_level=fatal -q " + CREATE DICTIONARY ${CLICKHOUSE_DATABASE}.d_mysql (x UInt64, y String) PRIMARY KEY x + SOURCE(MYSQL(HOST '$1' PORT 0 SOCKET '$2' USER 'u' PASSWORD 'p' DB 'db' TABLE 't')) + LAYOUT(FLAT()) LIFETIME(0)" + local output + output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM ${CLICKHOUSE_DATABASE}.d_mysql" 2>&1) + if grep -q -E "MySQL port 0|MySQL socket" <<< "$output"; then + echo "dictionary $1 port 0: rejected" + elif grep -q -F "through socket" <<< "$output"; then + echo "dictionary $1 port 0: unix socket" + else + echo "unexpected output: $output" + fi + $CLICKHOUSE_CLIENT -q "DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" +} +check_dictionary "127.0.0.1" "/nonexistent/mysqld.sock" +check_dictionary "localhost" "/nonexistent/mysqld.sock" +# The client library would read a socket starting with NUL as no socket and connect over TCP. +check_dictionary "localhost" "\\0" + +# `localhost` uses TCP to the given port, not the client library's default Unix socket. +output=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "SELECT * FROM mysql('localhost:1', 'db', 't', 'u', 'p')" 2>&1) +if grep -q -F "Can't connect to server on 'localhost'" <<< "$output"; then + echo "localhost: tcp" +elif grep -q -F "through socket" <<< "$output"; then + echo "localhost: unix socket" +else + echo "unexpected output: $output" +fi + +# The `MySQL` database engine and table engine use the same connection pool. +check "CREATE DATABASE ${CLICKHOUSE_DATABASE}_mysql ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 'u', 'p')" +check "CREATE TABLE ${CLICKHOUSE_DATABASE}.t_mysql (x UInt32) ENGINE = MySQL('socket=/nonexistent/mysqld.sock', 'db', 't', 'u', 'p'); SELECT * FROM ${CLICKHOUSE_DATABASE}.t_mysql" + +$CLICKHOUSE_CLIENT -q "DROP DATABASE IF EXISTS ${CLICKHOUSE_DATABASE}_mysql; DROP TABLE IF EXISTS ${CLICKHOUSE_DATABASE}.t_mysql; DROP DICTIONARY IF EXISTS ${CLICKHOUSE_DATABASE}.d_mysql" diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference new file mode 100644 index 000000000000..6ccddfe23c73 --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.reference @@ -0,0 +1,4 @@ +after_processing_move_access_key_id key_id_05493 +after_processing_move_connection_string [HIDDEN] +after_processing_move_secret_access_key [HIDDEN] +mode unordered diff --git a/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql new file mode 100644 index 000000000000..63571197469e --- /dev/null +++ b/tests/queries/0_stateless/05493_s3queue_settings_system_table_hide_secrets.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` engine is not built in the fast test. + +-- `system.s3_queue_settings` hides the secrets that `SHOW CREATE TABLE` hides. + +DROP TABLE IF EXISTS t_secrets; + +CREATE TABLE t_secrets (a String) +ENGINE = S3Queue('http://whatever-we-dont-care:9001/root/t_secrets/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', + after_processing_move_access_key_id = 'key_id_05493', + after_processing_move_secret_access_key = 'SEKRIT_05493_1', + after_processing_move_connection_string = 'DefaultEndpointsProtocol=https;AccountName=a;AccountKey=SEKRIT_05493_2;'; + +SELECT name, value +FROM system.s3_queue_settings +WHERE database = currentDatabase() AND table = 't_secrets' + AND name IN ('after_processing_move_access_key_id', 'after_processing_move_secret_access_key', + 'after_processing_move_connection_string', 'mode') +ORDER BY name; + +DROP TABLE t_secrets; diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference new file mode 100644 index 000000000000..573541ac9702 --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.reference @@ -0,0 +1 @@ +0 diff --git a/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql new file mode 100644 index 000000000000..1247bc62fb1f --- /dev/null +++ b/tests/queries/0_stateless/05498_s3_disk_sse_c_key_validation.sql @@ -0,0 +1,31 @@ +-- Tags: no-fasttest +-- no-fasttest: needs S3 support in the build. + +-- An SSE-C key that is not the base64 of a 256-bit key is rejected when the S3 client is created, before any request. + +-- Non-ASCII bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'éAAA'); -- { serverError BAD_ARGUMENTS } + +-- Valid base64 of 3 bytes. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'AAAA'); -- { serverError BAD_ARGUMENTS } + +-- An invalid character in a key of the right length. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAx!jM0NTY3ODkwMTIzNDU2Nzg5MDE='); -- { serverError BAD_ARGUMENTS } + +-- A valid key followed by more characters. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = 'MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=!'); -- { serverError BAD_ARGUMENTS } + +-- A valid key with surrounding whitespace. +CREATE TABLE t_sse_c (x UInt8) ENGINE = MergeTree ORDER BY x +SETTINGS disk = disk(type = 's3', endpoint = 'http://localhost:11111/test/05498/', no_sign_request = 1, skip_access_check = 1, + server_side_encryption_customer_key_base64 = ' MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE= '); -- { serverError BAD_ARGUMENTS } + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name = 't_sse_c'; diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference new file mode 100644 index 000000000000..573a680fbe86 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.reference @@ -0,0 +1,16 @@ +nanoseconds local push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds local push_down=1 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=0 lazy=1: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=0: (INCORRECT_DATA) +nanoseconds remote push_down=1 lazy=1: (INCORRECT_DATA) +statistics local push_down=0 lazy=0: 3 +statistics local push_down=0 lazy=1: 3 +statistics local push_down=1 lazy=0: 3 +statistics local push_down=1 lazy=1: 3 +statistics remote push_down=0 lazy=0: 3 +statistics remote push_down=0 lazy=1: 3 +statistics remote push_down=1 lazy=0: 3 +statistics remote push_down=1 lazy=1: 3 diff --git a/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh new file mode 100755 index 000000000000..53eae4b38eb0 --- /dev/null +++ b/tests/queries/0_stateless/05507_orc_malformed_timestamps.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The nanoseconds of a timestamp with the 7 removed trailing zeros overflow `Int64`. +orc_check nanoseconds "$DATA/malformed_timestamp_nanoseconds.orc" 't Nullable(DateTime64(9))' "SELECT count(), max(t) FROM SOURCE" \ + 'Invalid timestamp in ORC column 1: seconds=[0-9]+, encoded nanoseconds=-?[0-9]+' + +# The minimum nanoseconds in the statistics is 0x80000000: such statistics must not be used by the filter pushdown. +orc_check statistics "$DATA/malformed_timestamp_statistics_nanoseconds.orc" 't DateTime64(9)' \ + "SELECT count() FROM SOURCE WHERE t > toDateTime64('2000-01-01 00:00:00', 9, 'UTC')" diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference new file mode 100644 index 000000000000..17ac0b58ed17 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.reference @@ -0,0 +1,7 @@ +1e308 ['0','1','2','0','1','2','0','1','2','0'] +-1e308 ['0','1','2','0','1','2','0','1','2','0'] +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) +9223372036854775807 +-9223372036854775808 diff --git a/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh new file mode 100755 index 000000000000..6da24b0909d7 --- /dev/null +++ b/tests/queries/0_stateless/05508_orc_writer_out_of_range_values.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A dictionary threshold that does not fit in `size_t` when multiplied by the number of values. +for threshold in 1e308 -1e308; do + $CLICKHOUSE_LOCAL -q "SELECT toString(number % 3) AS s FROM numbers(10) FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = $threshold" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT '$threshold', groupArray(s) FROM table" +done + +# The extreme `DateTime64` values that cannot be stored in ORC with their statistics in milliseconds. +for value in 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(-9223372036854775808), '"'"'DateTime64(0)'"'"')' \ + 'reinterpret(toInt64(9223372036854775807), '"'"'DateTime64(1)'"'"')'; do + $CLICKHOUSE_LOCAL -q "SELECT $value AS t FORMAT ORC" 2>&1 >/dev/null | grep -oE '\(VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE\)' | head -n1 | grep . || echo "$value: no error" +done + +# The extreme values with the nanoseconds can be stored. +for value in 9223372036854775807 -9223372036854775808; do + $CLICKHOUSE_LOCAL -q "SELECT reinterpret(toInt64($value), 'DateTime64(9, \'UTC\')') AS t FORMAT ORC" \ + | $CLICKHOUSE_LOCAL --input-format ORC -q "SELECT reinterpret(t, 'Int64') FROM table" +done diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference new file mode 100644 index 000000000000..2d165fb8a6c0 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.reference @@ -0,0 +1,16 @@ +empty local push_down=0 lazy=0: (INCORRECT_DATA) +empty local push_down=0 lazy=1: (INCORRECT_DATA) +empty local push_down=1 lazy=0: (INCORRECT_DATA) +empty local push_down=1 lazy=1: (INCORRECT_DATA) +empty remote push_down=0 lazy=0: (INCORRECT_DATA) +empty remote push_down=0 lazy=1: (INCORRECT_DATA) +empty remote push_down=1 lazy=0: (INCORRECT_DATA) +empty remote push_down=1 lazy=1: (INCORRECT_DATA) +nulls local push_down=0 lazy=0: 5 5 +nulls local push_down=0 lazy=1: 5 5 +nulls local push_down=1 lazy=0: 5 5 +nulls local push_down=1 lazy=1: 5 5 +nulls remote push_down=0 lazy=0: 5 5 +nulls remote push_down=0 lazy=1: 5 5 +nulls remote push_down=1 lazy=0: 5 5 +nulls remote push_down=1 lazy=1: 5 5 diff --git a/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh new file mode 100755 index 000000000000..437d071ce5a5 --- /dev/null +++ b/tests/queries/0_stateless/05509_orc_malformed_dictionaries.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# A dictionary without entries referenced by the non-null values. +orc_check empty "$DATA/malformed_dictionary_empty.orc" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" \ + 'ORC dictionary index 0 at row 0 is out of range \[0, 0\)' + +# A valid empty dictionary of a column with only nulls. +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_nulls.orc" +trap 'rm -f "$FILE"' EXIT +$CLICKHOUSE_LOCAL -q "SELECT CAST(NULL, 'Nullable(String)') AS s FROM numbers(5) INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_dictionary_key_size_threshold = 1" +orc_check nulls "$FILE" 's Nullable(String)' "SELECT count(), countIf(s IS NULL) FROM SOURCE" diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.reference b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference new file mode 100644 index 000000000000..1e94a8329c54 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.reference @@ -0,0 +1,32 @@ +compression_block local push_down=0 lazy=0: 1 10000 +compression_block local push_down=0 lazy=1: 1 10000 +compression_block local push_down=1 lazy=0: 1 10000 +compression_block local push_down=1 lazy=1: 1 10000 +compression_block remote push_down=0 lazy=0: 1 10000 +compression_block remote push_down=0 lazy=1: 1 10000 +compression_block remote push_down=1 lazy=0: 1 10000 +compression_block remote push_down=1 lazy=1: 1 10000 +dictionary_size local push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size local push_down=1 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=0 lazy=1: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=0: (INCORRECT_DATA) +dictionary_size remote push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +snappy_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size local push_down=1 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=0 lazy=1: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=0: (INCORRECT_DATA) +zstd_chunk_size remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05510_orc_allocation_amplification.sh b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh new file mode 100755 index 000000000000..bc5685ba3187 --- /dev/null +++ b/tests/queries/0_stateless/05510_orc_allocation_amplification.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The memory must be allocated by the size of the data, not by the sizes declared in the file. +LIMIT='max_memory_usage = 100000000' + +# The declared compression block size is 1 GiB, the chunks are small. The schema inference reads the compressed footer. +orc_check compression_block "$DATA/malformed_compression_block_1g.orc" '' "SELECT count(), sum(length(s)) FROM SOURCE" '' "$LIMIT" + +# The declared dictionary size is 2^32 - 1, the stream has a few entries. +orc_check dictionary_size "$DATA/malformed_dictionary_size_max.orc" 's Nullable(String)' "SELECT count(), sum(length(s)) FROM SOURCE" \ + 'Unexpected end of ORC stream column 1 kind 2' "$LIMIT" + +# The sizes stored in the snappy and zstd chunks are 1 GiB, the chunks have a few bytes. +orc_check snappy_chunk_size "$DATA/malformed_snappy_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'snappy-compressed chunk of ORC file decompresses to 1073741824 bytes' "$LIMIT" +orc_check zstd_chunk_size "$DATA/malformed_zstd_chunk_size.orc" 'x Int64' "SELECT count() FROM SOURCE" \ + 'Malformed zstd-compressed data in ORC file' "$LIMIT" diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference new file mode 100644 index 000000000000..3c50f86ded0e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.reference @@ -0,0 +1,16 @@ +stripe local push_down=0 lazy=0: (INCORRECT_DATA) +stripe local push_down=0 lazy=1: (INCORRECT_DATA) +stripe local push_down=1 lazy=0: (INCORRECT_DATA) +stripe local push_down=1 lazy=1: (INCORRECT_DATA) +stripe remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe remote push_down=1 lazy=1: (INCORRECT_DATA) +stream local push_down=0 lazy=0: (INCORRECT_DATA) +stream local push_down=0 lazy=1: (INCORRECT_DATA) +stream local push_down=1 lazy=0: (INCORRECT_DATA) +stream local push_down=1 lazy=1: (INCORRECT_DATA) +stream remote push_down=0 lazy=0: (INCORRECT_DATA) +stream remote push_down=0 lazy=1: (INCORRECT_DATA) +stream remote push_down=1 lazy=0: (INCORRECT_DATA) +stream remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh new file mode 100755 index 000000000000..2d3b50f7f31e --- /dev/null +++ b/tests/queries/0_stateless/05511_orc_malformed_stripes_and_streams.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The sum of the offset and the lengths of the stripe overflows `UInt64`. +orc_check stripe "$DATA/malformed_stripe_offset_overflow.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stripe information at stripe index 0' + +# The length of a stream of a column that is not read is 2^64 - 1, the offsets of the next streams wrap around. +orc_check stream "$DATA/malformed_stream_offset_overflow.orc" 'b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Malformed stream.*11.*18446744073709551615' diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference new file mode 100644 index 000000000000..1fafd3d526a4 --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.reference @@ -0,0 +1,32 @@ +row_groups local push_down=1 lazy=0: (INCORRECT_DATA) +row_groups local push_down=1 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=1 lazy=1: (INCORRECT_DATA) +row_groups local push_down=0 lazy=0: (INCORRECT_DATA) +row_groups local push_down=0 lazy=1: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=0: (INCORRECT_DATA) +row_groups remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=0 lazy=0: (INCORRECT_DATA) +patched_base local push_down=0 lazy=1: (INCORRECT_DATA) +patched_base local push_down=1 lazy=0: (INCORRECT_DATA) +patched_base local push_down=1 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=0 lazy=1: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=0: (INCORRECT_DATA) +patched_base remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek local push_down=0 lazy=0: 1 +row_index_seek local push_down=0 lazy=1: 1 +row_index_seek local push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek local push_down=1 lazy=1: (INCORRECT_DATA) +row_index_seek remote push_down=0 lazy=0: 1 +row_index_seek remote push_down=0 lazy=1: 1 +row_index_seek remote push_down=1 lazy=0: (INCORRECT_DATA) +row_index_seek remote push_down=1 lazy=1: (INCORRECT_DATA) +row_index_control local push_down=0 lazy=0: 1 +row_index_control local push_down=0 lazy=1: 1 +row_index_control local push_down=1 lazy=0: 1 +row_index_control local push_down=1 lazy=1: 1 +row_index_control remote push_down=0 lazy=0: 1 +row_index_control remote push_down=0 lazy=1: 1 +row_index_control remote push_down=1 lazy=0: 1 +row_index_control remote push_down=1 lazy=1: 1 diff --git a/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh new file mode 100755 index 000000000000..163a644dea9f --- /dev/null +++ b/tests/queries/0_stateless/05512_orc_malformed_row_groups.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The stripe has 2^64 - 1 rows: rounding up the number of row groups overflows. +ORC_PUSH_DOWN_VALUES=1 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'The row index of ORC column 1 has 2 entries, less than the [0-9]+ row groups of stripe 0' +ORC_PUSH_DOWN_VALUES=0 orc_check row_groups "$DATA/malformed_row_group_count_overflow.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Unexpected end of ORC stream column 1 kind 1' + +# A PATCHED_BASE run whose last patch is a continuation (gap 255, patch 0). +orc_check patched_base "$DATA/malformed_patched_base_terminal_continuation.orc" 'x Int64' "SELECT count(), sum(x) FROM SOURCE" \ + 'Corrupt PATCHED_BASE encoded data in ORC stream column 1 kind 1 in stripe 0 \(unterminated gap\)' + +# A row index position beyond the end of the stream, and the same file with the valid position. +orc_check row_index_seek "$DATA/malformed_row_index_seek_past_stream.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" \ + 'Seek position 127 is beyond the end of ORC stream column 1 kind 1 in stripe 0 of size 3' +orc_check row_index_control "$DATA/row_index_seek_control.orc" 'x Int64' "SELECT x FROM SOURCE WHERE x = 1" diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference new file mode 100644 index 000000000000..bac3e0b9f016 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.reference @@ -0,0 +1,16 @@ +footer_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +footer_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics local push_down=1 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=0 lazy=1: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=0: (INCORRECT_DATA) +stripe_statistics remote push_down=1 lazy=1: (INCORRECT_DATA) diff --git a/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh new file mode 100755 index 000000000000..9c0fb713fb91 --- /dev/null +++ b/tests/queries/0_stateless/05513_orc_metadata_repeated_field_limits.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest, the test uses S3. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +# shellcheck source=./orc_malformed.lib +. "$CUR_DIR"/orc_malformed.lib + +DATA="$CUR_DIR/data_orc" + +# The number of the repeated objects in the metadata is limited by the numbers of the columns and the stripes. +orc_check footer_statistics "$DATA/malformed_footer_too_many_statistics.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many column statistics in ORC footer: 13, the file has 3 columns' +orc_check stripe_statistics "$DATA/malformed_metadata_too_many_stripes.orc" 'a UInt64, b String' "SELECT count(), sum(length(b)) FROM SOURCE" \ + 'Too many stripe statistics in ORC metadata, at most 1 expected' diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference new file mode 100644 index 000000000000..7f41d79fbe44 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.reference @@ -0,0 +1,21 @@ +t < fromUnixTimestamp64Nano(-500000001, 'UTC') +500 +500 0 499 +500 0 499 +t <= fromUnixTimestamp64Nano(-500000001, 'UTC') +600 +501 0 500 +501 0 500 +t = fromUnixTimestamp64Nano(-950000001, 'UTC') +100 +1 50 50 +1 50 50 +t = fromUnixTimestamp64Nano(-999500000, 'UTC') +1 +1 1 1 +1 1 1 +-2000000000 1 +-1 1 +-999500000 1 +-1500000 1 +1000000000 1 diff --git a/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh new file mode 100755 index 000000000000..21a4b8bb4428 --- /dev/null +++ b/tests/queries/0_stateless/05514_orc_timestamp_statistics_before_epoch.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Prints the number of rows that are not pruned, and the result with and without the filter pushdown. +function check() +{ + local condition=$1 + echo "$condition" + $CLICKHOUSE_LOCAL -q " + SELECT count() FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE indexHint($condition); + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition; + SELECT count(), min(number), max(number) FROM file('$FILE', 'ORC', 'number UInt64, t DateTime64(9, \'UTC\')') WHERE $condition + SETTINGS input_format_orc_filter_push_down = 0" +} + +# The timestamps before the epoch with a negative sub-millisecond part, from -1.000000001 to -0.001000001 seconds, +# in row groups of 100 rows. Their statistics must allow the pruning. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano(toInt64(number) * 1000000 - 1000000001, 'UTC') AS t FROM numbers(1000) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 100" +check "t < fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t <= fromUnixTimestamp64Nano(-500000001, 'UTC')" +check "t = fromUnixTimestamp64Nano(-950000001, 'UTC')" + +# A timestamp in the millisecond after -1 second, in its own row group: the pruning must keep it. +$CLICKHOUSE_LOCAL -q " + SELECT number, fromUnixTimestamp64Nano([-2000000000, -999500000, -500000000][number + 1], 'UTC') AS t FROM numbers(3) + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_row_index_stride = 1" +check "t = fromUnixTimestamp64Nano(-999500000, 'UTC')" + +# A file from PyArrow (the C++ writer of ORC) with a bloom filter, which rounds the negative milliseconds toward zero, +# and one row in each row group: the bloom filter must keep the matching rows. +for value in -2000000000 -1 -999500000 -1500000 1000000000; do + $CLICKHOUSE_LOCAL -q " + SELECT $value, count() FROM file('$CUR_DIR/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc', 'ORC', 't Nullable(DateTime64(9))') + WHERE t = fromUnixTimestamp64Nano($value)" +done diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.reference b/tests/queries/0_stateless/05515_orc_nullable_floats.reference new file mode 100644 index 000000000000..4aae050a32fc --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.reference @@ -0,0 +1,2 @@ +1 +1086 1410 5000 10000 0 diff --git a/tests/queries/0_stateless/05515_orc_nullable_floats.sh b/tests/queries/0_stateless/05515_orc_nullable_floats.sh new file mode 100755 index 000000000000..c7eba0810a43 --- /dev/null +++ b/tests/queries/0_stateless/05515_orc_nullable_floats.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +trap 'rm -f "$FILE"' EXIT + +# Nullable floats with different patterns of nulls, and special values, at the top level and nested. +QUERY=" + SELECT + number, + multiIf(k = 0, NULL, k = 1, nan, k = 2, inf, k = 3, -inf, k = 4, -0., k = 5, toFloat32(1e-42), toFloat32(number) / 7)::Nullable(Float32) AS f32, + multiIf(k2 = 0, NULL, k2 = 1, nan, k2 = 2, -inf, k2 = 3, 5e-324, k2 = 4, -0., number / 3.)::Nullable(Float64) AS f64, + if(intDiv(number, 1000) % 2 = 0, NULL, number / 2.)::Nullable(Float64) AS runs, + NULL::Nullable(Float32) AS all_null, + (number * 1.5)::Nullable(Float64) AS no_null, + arrayMap(x -> if(x % 3 = 0, NULL, toFloat32(x) / 4), range(number % 5))::Array(Nullable(Float32)) AS arr + FROM (SELECT number, cityHash64(number) % 9 AS k, cityHash64(number, 1) % 7 AS k2 FROM numbers(10000))" +STRUCTURE='number UInt64, f32 Nullable(Float32), f64 Nullable(Float64), runs Nullable(Float64), all_null Nullable(Float32), no_null Nullable(Float64), arr Array(Nullable(Float32))' +DIGEST="sum(cityHash64(number, isNull(f32), reinterpretAsUInt32(ifNull(f32, 0)), isNull(f64), reinterpretAsUInt64(ifNull(f64, 0)), + isNull(runs), ifNull(runs, 0), isNull(all_null), no_null, arrayMap(x -> (isNull(x), reinterpretAsUInt32(ifNull(x, 0))), arr)))" + +$CLICKHOUSE_LOCAL -q "$QUERY INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q " + SELECT (SELECT $DIGEST FROM ($QUERY)) = (SELECT $DIGEST FROM file('$FILE', 'ORC', '$STRUCTURE')); + SELECT countIf(f32 IS NULL), countIf(f64 IS NULL), countIf(runs IS NULL), countIf(all_null IS NULL), countIf(no_null IS NULL) FROM file('$FILE', 'ORC', '$STRUCTURE')" diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference new file mode 100644 index 000000000000..36b34a909261 --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.reference @@ -0,0 +1,6 @@ +restore is waiting 1 +alter succeeded +restore finished +x +y +0 diff --git a/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh new file mode 100755 index 000000000000..4083ae7715ff --- /dev/null +++ b/tests/queries/0_stateless/05546_replicated_database_restore_replica_waits_for_initial_alter.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest, no-parallel +# no-parallel: the `database_replicated_pause_before_initial_query_execution` failpoint fires globally, +# it would pause (or be consumed by) a DDL query of another `Replicated` database. + +# `SYSTEM RESTORE DATABASE REPLICA` waits for the initial DDL queries that the DDL worker has already admitted. +# An `ALTER` of a `ReplicatedMergeTree` table with `alter_sync = 1` waits until the table executes its +# `ALTER_METADATA` entry, which requires an active DDL worker of the database (`canExecuteReplicatedMetadataAlter`). +# The restore must not stop the worker before such a query finishes, otherwise both queries wait for each other. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +DB="rdb_${CLICKHOUSE_TEST_UNIQUE_NAME}" +ZK_PATH="/test/${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +FAILPOINT="database_replicated_pause_before_initial_query_execution" +RESTORE_QUERY_ID="restore_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --query "SYSTEM DISABLE FAILPOINT $FAILPOINT" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB} SYNC" >/dev/null 2>&1 ||: + $CLICKHOUSE_CLIENT --query "DROP DATABASE IF EXISTS ${DB}_broken_replicated_tables SYNC" >/dev/null 2>&1 ||: +} +trap cleanup EXIT + +$CLICKHOUSE_CLIENT --query "CREATE DATABASE ${DB} ENGINE = Replicated('${ZK_PATH}', 'shard1', 'replica1')" +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode=none --query "CREATE TABLE ${DB}.t (x UInt64) ENGINE = ReplicatedMergeTree ORDER BY x" + +# Hold the initial `ALTER` after the DDL worker has admitted it, before it executes. +$CLICKHOUSE_CLIENT --query "SYSTEM ENABLE FAILPOINT $FAILPOINT" +$CLICKHOUSE_CLIENT --alter_sync 1 --distributed_ddl_output_mode=none --query "ALTER TABLE ${DB}.t ADD COLUMN y UInt64" & +alter_pid=$! +$CLICKHOUSE_CLIENT --query "SYSTEM WAIT FAILPOINT $FAILPOINT PAUSE" + +$CLICKHOUSE_CLIENT --query_id "$RESTORE_QUERY_ID" --query "SYSTEM RESTORE DATABASE REPLICA ${DB}" >/dev/null 2>&1 & +restore_pid=$! + +# The restore has to wait for the paused `ALTER`. +for _ in $(seq 1 600); do + [ "$($CLICKHOUSE_CLIENT --query "SELECT count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'")" = 1 ] && break + sleep 0.1 +done +sleep 2 +$CLICKHOUSE_CLIENT --query "SELECT 'restore is waiting', count() FROM system.processes WHERE query_id = '$RESTORE_QUERY_ID'" + +# The `ALTER` finishes, including the wait for its `ALTER_METADATA` entry, and then the restore proceeds. +$CLICKHOUSE_CLIENT --query "SYSTEM NOTIFY FAILPOINT $FAILPOINT" +wait $alter_pid && echo "alter succeeded" +# The replica is not lost (its digest is not empty), so the restore may refuse with `REPLICA_ALREADY_EXISTS`; +# either way the DDL worker is re-created. +wait $restore_pid ||: +echo "restore finished" + +$CLICKHOUSE_CLIENT --query "SYSTEM SYNC DATABASE REPLICA ${DB}" +$CLICKHOUSE_CLIENT --query "SELECT name FROM system.columns WHERE database = '${DB}' AND table = 't' ORDER BY name" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = '${DB}_broken_replicated_tables'" diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference new file mode 100644 index 000000000000..4e3dc3cd1a09 --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.reference @@ -0,0 +1 @@ +4800 552844800 24 diff --git a/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh new file mode 100755 index 000000000000..b33d61ad599f --- /dev/null +++ b/tests/queries/0_stateless/05565_parquet_encoder_shared_thread_pool.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# - no-fasttest: requires the Parquet format (USE_PARQUET build option) + +# Every Parquet writer had its own pool of `max_threads` encoder threads, so many open writers with `max_threads = 32` +# did not fit in a 500-thread global pool: the 24 partitions of one stream. +# https://github.com/ClickHouse/ClickHouse/issues/129864 +# `BackgroundSchedulePool` starts all of its threads at once in this release, so its default size of 512 does not fit the pool. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +TABLE_DIR="${CLICKHOUSE_USER_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -rf "${TABLE_DIR}" +mkdir -p "${TABLE_DIR}" +trap 'rm -rf "${TABLE_DIR}"' EXIT + +COLS=$(for i in $(seq 48); do printf ', c%d Int64' "$i"; done) +EXPRS=$(for i in $(seq 48); do printf ', number * %d' "$i"; done) +SETTINGS="SET max_threads = 32, + output_format_parquet_parallel_encoding = 1, output_format_parquet_row_group_size = 200, + max_block_size = 1000, min_insert_block_size_rows = 1000, min_insert_block_size_bytes = 0" + +# Small row groups make every writer encode while the INSERT runs, not only when its file is finalized. +${CLICKHOUSE_LOCAL} --query " + ${SETTINGS}, max_insert_threads = 1; + INSERT INTO FUNCTION file('${TABLE_DIR}/file/{_partition_id}.parquet', 'Parquet', 'p UInt8 ${COLS}') PARTITION BY p + SELECT number % 24 ${EXPRS} FROM numbers(4800); + SELECT count(), sum(c48), uniqExact(_path) FROM file('${TABLE_DIR}/file/*.parquet'); +" -- --max_thread_pool_size=500 --thread_pool_queue_size=500 --background_schedule_pool_size=16 diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference new file mode 100644 index 000000000000..ec1c393fef3a --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.reference @@ -0,0 +1,3 @@ +1 +1 +still alive diff --git a/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql new file mode 100644 index 000000000000..36af86696314 --- /dev/null +++ b/tests/queries/0_stateless/05567_group_array_sample_counter_overflow.sql @@ -0,0 +1,28 @@ +-- A deserialized `groupArraySample` state may carry an arbitrary `total_values` counter. +-- Merging must not wrap it around to zero, which led to a division by zero. + +-- Valid states merge fine. +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')])); +SELECT length(arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')])); + +-- total_values = UINT64_MAX, merged with a state with one value. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('010141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0141FFFFFFFFFFFFFFFF173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420100000000000000173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +-- Both states have more values than the sample size, and their counters sum to 2^64. +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('0101410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)'), + CAST(unhex('0101420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), String)')]); -- { serverError INCORRECT_DATA } +SELECT arrayReduce('groupArraySampleMerge(1, 1)', [ + CAST(unhex('01410000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)'), + CAST(unhex('01420000000000000080173633363431333632323338343637393330303520302033'), 'AggregateFunction(groupArraySample(1, 1), UInt8)')]); -- { serverError INCORRECT_DATA } + +SELECT 'still alive'; diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.reference b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference new file mode 100644 index 000000000000..d509bf4d85ea --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.reference @@ -0,0 +1,21 @@ +Mechanisms that take the credentials from the server, and a client certificate file +refused +refused +refused +refused +refused +refused +refused +refused +Credentials in the connection string +connects +connects +connects +A MongoDB table is checked when it is read +refused +refused +So is a table created with CREATE TABLE ... AS mongodb(...) +x UInt8 +refused +And the table function with a named collection +refused diff --git a/tests/queries/0_stateless/05567_mongodb_server_credentials.sh b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh new file mode 100755 index 000000000000..e563e94de006 --- /dev/null +++ b/tests/queries/0_stateless/05567_mongodb_server_credentials.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB table function and table engine need USE_MONGODB + +# A query that reads with the `mongodb` table function or from a `MongoDB` table is refused with `ACCESS_DENIED` if the +# connection string makes the server authenticate with credentials of the server process. Nothing listens on +# 127.0.0.1:1, so a query that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +NC="nc_05567_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +check() +{ + $CLICKHOUSE_CLIENT -q "$1" 2>&1 | classify +} + +read_uri() +{ + check "SELECT count() FROM mongodb('mongodb://${HOST}/db?${TIMEOUTS}&$1', 'c', 'x UInt8')" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP TABLE IF EXISTS t_engine; + DROP TABLE IF EXISTS t_as_function; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Mechanisms that take the credentials from the server, and a client certificate file' +read_uri 'authMechanism=MONGODB-OIDC' +read_uri 'authmechanism=mongodb-oidc&authMechanismProperties=ENVIRONMENT:test' +read_uri 'authMechanism=MONGODB-AWS' +read_uri 'authMechanism=MONGODB-X509' +check "SELECT count() FROM mongodb('mongodb://user@${HOST}/db?${TIMEOUTS}&authMechanism=GSSAPI', 'c', 'x UInt8')" +read_uri 'tls=true&tlsCertificateKeyFile=/nonexistent.pem' +read_uri 'ssl=true&sslClientCertificateKeyFile=/nonexistent.pem' +check "SELECT count() FROM mongodb('${HOST}', 'db', 'c', '', '', 'x UInt8', '${TIMEOUTS}&authMechanism=MONGODB-OIDC')" + +echo 'Credentials in the connection string' +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256', 'c', 'x UInt8')" +check "SELECT count() FROM mongodb('mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=plain', 'c', 'x UInt8')" + + +echo 'A MongoDB table is checked when it is read' +$CLICKHOUSE_CLIENT -q "CREATE TABLE t_engine (x UInt8) ENGINE = MongoDB('${OIDC_URI}', 'c')" +check "SELECT count() FROM t_engine" +$CLICKHOUSE_CLIENT -m -q "DETACH TABLE t_engine; ATTACH TABLE t_engine;" +check "SELECT count() FROM t_engine" + +echo 'So is a table created with CREATE TABLE ... AS mongodb(...)' +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE t_as_function AS mongodb('${OIDC_URI}', 'c', 'x UInt8'); + DETACH TABLE t_as_function; + ATTACH TABLE t_as_function; + DESCRIBE t_as_function SETTINGS describe_compact_output = 1; +" +check "SELECT count() FROM t_as_function" + +echo 'And the table function with a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS uri = '${OIDC_URI}', collection = 'c', structure = 'x UInt8'" +check "SELECT count() FROM mongodb(${NC})" diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference new file mode 100644 index 000000000000..f0b81f6f43ed --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.reference @@ -0,0 +1,12 @@ +Refused +refused +refused +Credentials in the connection string +connects +The options that a dictionary adds to a named collection +refused +A named collection that changes after the dictionary is created +connects +refused +clickhouse-local is not restricted +connects diff --git a/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh new file mode 100755 index 000000000000..354ecf0acbb7 --- /dev/null +++ b/tests/queries/0_stateless/05568_mongodb_dictionary_server_credentials.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the MongoDB dictionary source needs USE_MONGODB + +# A MongoDB dictionary created with a DDL query may never make the server authenticate with credentials of the server +# process: the source is built when the server loads the dictionary, also after the named collection it refers to +# has changed. The dictionaries are loaded by `dictGet`. +# Nothing listens on 127.0.0.1:1, so a dictionary that is not refused fails to connect. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +HOST="127.0.0.1:1" +TIMEOUTS="connectTimeoutMS=100&serverSelectionTimeoutMS=100" +OIDC_URI="mongodb://${HOST}/db?${TIMEOUTS}&authMechanism=MONGODB-OIDC" +SCRAM_URI="mongodb://user:pass@${HOST}/db?${TIMEOUTS}&authMechanism=SCRAM-SHA-256" +NC="nc_05568_${CLICKHOUSE_DATABASE}" + +# Prints `refused` for `ACCESS_DENIED`, `connects` if the query got as far as connecting, or else the output. +classify() +{ + local output + output=$(cat) + if grep -q ACCESS_DENIED <<< "$output"; then + echo refused + elif grep -q 'No suitable servers found' <<< "$output"; then + echo connects + else + echo "$output" + fi +} + +# Runs the queries $1. +check() +{ + $CLICKHOUSE_CLIENT -m -q "$1" 2>&1 | classify +} + +# Creates the dictionary $1 with the source $2 and prints whether reading it is refused. +check_source() +{ + $CLICKHOUSE_CLIENT -q "CREATE DICTIONARY $1 (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB($2 COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" + check "SELECT dictGet('$1', 'v', tuple('k'))" +} + +cleanup() +{ + $CLICKHOUSE_CLIENT -m -q " + SET ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0; + DROP DICTIONARY IF EXISTS d_uri; + DROP DICTIONARY IF EXISTS d_options; + DROP DICTIONARY IF EXISTS d_scram; + DROP DICTIONARY IF EXISTS d_named_options; + DROP DICTIONARY IF EXISTS d_named_altered; + DROP NAMED COLLECTION IF EXISTS ${NC}; + " +} +trap cleanup EXIT +cleanup + +echo 'Refused' +check_source d_uri "URI '${OIDC_URI}'" +check_source d_options "HOST '127.0.0.1' PORT 1 DB 'db' USER '' PASSWORD '' OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" + +echo 'Credentials in the connection string' +check_source d_scram "URI '${SCRAM_URI}'" + +echo 'The options that a dictionary adds to a named collection' +$CLICKHOUSE_CLIENT -q "CREATE NAMED COLLECTION ${NC} AS host = '127.0.0.1', port = '1', db = 'db', user = '', password = ''" +check_source d_named_options "NAME ${NC} OPTIONS '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +$CLICKHOUSE_CLIENT -q "DROP DICTIONARY d_named_options" + +echo 'A named collection that changes after the dictionary is created' +$CLICKHOUSE_CLIENT -q "CREATE DICTIONARY d_named_altered (_id String, v String) PRIMARY KEY _id SOURCE(MONGODB(NAME ${NC} COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT())" +check "SELECT dictGet('d_named_altered', 'v', tuple('k'))" +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${NC} SET options = '${TIMEOUTS}&authMechanism=MONGODB-OIDC'" +check "SYSTEM RELOAD DICTIONARY d_named_altered; SELECT dictGet('d_named_altered', 'v', tuple('k'))" + +echo 'clickhouse-local is not restricted' +$CLICKHOUSE_LOCAL -m -q " + CREATE DICTIONARY d (_id String, v String) PRIMARY KEY _id + SOURCE(MONGODB(URI '${OIDC_URI}' COLLECTION 'c')) LAYOUT(COMPLEX_KEY_DIRECT()); + SELECT dictGet('d', 'v', tuple('k')); +" 2>&1 | classify diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference new file mode 100644 index 000000000000..338bce460b79 --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.reference @@ -0,0 +1,18 @@ +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `m` from type Map(String, String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `l` from type Array(String) to type Tuple(value Nullable(String)) +Code: 53 while converting column `s` from type Tuple(value String) to type Map(String, String) +Code: 53 while converting column `s` from type Tuple(value String) to type Array(String) +Code: 53 while converting column `lm` from type Array(Map(String, String)) to type Array(Tuple(value String)) +Code: 53 while converting column `sl` from type Tuple(a Array(String)) to type Tuple(a Map(String, String)) +2 {\'key\':\'profile\'} +2 [('key','profile')] +2 {'k':'(\'v\')'} +['(\'v\')'] +2 {'key':'profile'} ['profile'] ('profile') {'k':('v')} [{'k':'v'}] (['x']) +('profile',0) +2 +Code: 53 while converting column `m` from type Map(LowCardinality(String), LowCardinality(Nullable(String))) to type Tuple(value Nullable(String)) +Code: 53 while converting column `lm` from type Array(Map(LowCardinality(String), LowCardinality(Nullable(String)))) to type Array(Tuple(value String)) +{\'key\':\'profile\'} +{'key':'profile'} [{'k':'v'}] diff --git a/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh new file mode 100755 index 000000000000..f503b6d888fa --- /dev/null +++ b/tests/queries/0_stateless/05574_orc_requested_type_of_another_kind.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: ORC is not built in fasttest. + +# An ORC list, map or struct requested as a type of another kind is cast to it, not read as default values. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Prints the error code and the conversion of a query that has to fail. +function error() +{ + $CLICKHOUSE_LOCAL -q "$1" 2>&1 | tr '\n' ' ' | grep -o -E 'Code: [0-9]+|while converting column [^:]* to type [^:]*' | head -n 2 | paste -sd ' ' +} + +FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}.orc" +$CLICKHOUSE_LOCAL -q "SELECT 2::Int64 AS id, map('key', 'profile') AS m, ['profile'] AS l, + CAST(tuple('profile'), 'Tuple(value String)') AS s, map('k', CAST(tuple('v'), 'Tuple(value String)')) AS ms, + [map('k', 'v')] AS lm, CAST(tuple(['x']), 'Tuple(a Array(String))') AS sl FORMAT ORC" > "$FILE" +F="file('$FILE', ORC" + +# Conversions the cast cannot do. +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, m Tuple(value Nullable(String))') SETTINGS input_format_orc_allow_missing_columns = 0" +error "SELECT * FROM $F, 'id Int64, l Tuple(value Nullable(String))')" +error "SELECT * FROM $F, 'id Int64, s Map(String, String)')" +error "SELECT * FROM $F, 'id Int64, s Array(String)')" +error "SELECT * FROM $F, 'id Int64, lm Array(Tuple(value String))')" +error "SELECT * FROM $F, 'id Int64, sl Tuple(a Map(String, String))')" + +# Conversions the cast does, also of a map value. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m String')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Array(Tuple(String, String))')" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, ms Map(String, String)')" +$CLICKHOUSE_LOCAL -q "SELECT ms.values FROM $F, 'id Int64, ms Map(String, String)')" + +# Matching kinds, a Tuple naming only some of the fields, and the other columns of a mismatched structure. +$CLICKHOUSE_LOCAL -q "SELECT * FROM $F, 'id Int64, m Map(String, String), l Array(String), s Tuple(value String), + ms Map(String, Tuple(value String)), lm Array(Map(String, String)), sl Tuple(a Array(String))')" +$CLICKHOUSE_LOCAL -q "SELECT s FROM $F, 's Tuple(value String, other Int32)')" +$CLICKHOUSE_LOCAL -q "SELECT id FROM $F, 'id Int64, m Tuple(value Nullable(String))')" + +DICT_FILE="$(realpath "$CLICKHOUSE_TMP")/${CLICKHOUSE_TEST_UNIQUE_NAME}_dict.orc" +$CLICKHOUSE_LOCAL --output_format_orc_dictionary_key_size_threshold=1 -q "SELECT map('key', 'profile') AS m, [map('k', 'v')] AS lm FORMAT ORC" > "$DICT_FILE" +D="file('$DICT_FILE', ORC" +S="SETTINGS input_format_orc_dictionary_as_low_cardinality = 1" + +# A dictionary-encoded map key. +error "SELECT * FROM $D, 'm Tuple(value Nullable(String))') $S" +error "SELECT * FROM $D, 'lm Array(Tuple(value String))') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm String') $S" +$CLICKHOUSE_LOCAL -q "SELECT * FROM $D, 'm Map(String, String), lm Array(Map(String, String))') $S" + +rm -f "$FILE" +rm -f "$DICT_FILE" diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference new file mode 100644 index 000000000000..d0fcfd538e17 --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.reference @@ -0,0 +1,6 @@ +MEMORY_LIMIT_EXCEEDED +PrettyCompactMonoBlock 241 +MEMORY_LIMIT_EXCEEDED +PrettyCompact 241 +MEMORY_LIMIT_EXCEEDED +JSONColumns 241 diff --git a/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh new file mode 100755 index 000000000000..551f08b3f82c --- /dev/null +++ b/tests/queries/0_stateless/05615_formats_accumulating_result_memory_limit_in_local.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Every stored block is larger than the memory limit, so the format that accumulates the result fails to copy it +# when the next block arrives: the query must fail with an error, not crash. +for format in PrettyCompactMonoBlock PrettyCompact JSONColumns; do + $CLICKHOUSE_LOCAL --query " + CREATE TABLE t (x UInt64) ENGINE = Memory; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + INSERT INTO t SELECT number FROM numbers(5000000) SETTINGS max_block_size = 5000000, max_insert_block_size = 5000000; + SELECT * FROM t FORMAT $format SETTINGS max_threads = 1, max_memory_usage = '20Mi', + output_format_pretty_squash_consecutive_ms = 1000000, output_format_pretty_squash_max_wait_ms = 1000000; + " 2>&1 >/dev/null | grep -o -m1 'MEMORY_LIMIT_EXCEEDED' | head -n1 + echo "$format ${PIPESTATUS[0]}" +done diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference new file mode 100644 index 000000000000..8e054e883dc4 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.reference @@ -0,0 +1,9 @@ +1900-05-31 16:00:00 +1900-07-06 03:13:13 +1949-12-31 16:00:00 +1900-06-01 08:00:00 +1900-06-01 00:36:45 +1960-01-15 00:00:00 +0 1900-06-01 08:00:00.000000000 +1 1900-06-01 08:00:00.000000000 +1900-06-01 08:00:00.000000000 diff --git a/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh new file mode 100755 index 000000000000..61cb9f7a7221 --- /dev/null +++ b/tests/queries/0_stateless/05616_orc_timestamp_before_first_transition.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no ORC format + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Before the first transition of a time zone, the wall clock is kept with the oldest standard offset +# (Asia/Shanghai +08:00 until 1901), not with the local mean time, as in other ORC readers. +# `DateTime64` starts at 1900 on this branch. + +FILE="${CLICKHOUSE_TMP}/${CLICKHOUSE_DATABASE}.orc" + +$CLICKHOUSE_LOCAL -q " + SELECT arrayJoin([toDateTime64('1900-06-01 00:00:00', 0, 'UTC'), toDateTime64('1900-07-06 11:13:13', 0, 'UTC'), toDateTime64('1950-01-01 00:00:00', 0, 'UTC')]) AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Asia/Shanghai'" + +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# Europe/Lisbon starts with a no-op transition record in 1884 that keeps the local mean time (-00:36:45). +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'Europe/Lisbon'" + +# Europe/London had +01:00 in 1970 and +00:00 in 1960, a lower offset before the epoch must not shift the day. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1960-01-15 00:00:00', 0, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Europe/London'" +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(0, \'UTC\')')" + +# The timestamp statistics must agree with the values that are read, or the filter pushdown drops the row. +$CLICKHOUSE_LOCAL -q " + SELECT toDateTime64('1900-06-01 00:00:00', 9, 'UTC') AS ts + INTO OUTFILE '$FILE' TRUNCATE FORMAT ORC SETTINGS output_format_orc_writer_time_zone_name = 'Asia/Shanghai'" +for push_down in 0 1; do + $CLICKHOUSE_LOCAL -q " + SELECT $push_down, ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') + WHERE ts = toDateTime64('1900-06-01 08:00:00', 9, 'UTC') SETTINGS input_format_orc_filter_push_down = $push_down" +done + +# A time zone that `DateLUT` loads without an embedded file. +$CLICKHOUSE_LOCAL -q "SELECT ts FROM file('$FILE', ORC, 'ts DateTime64(9, \'UTC\')') SETTINGS input_format_orc_reader_time_zone_name = 'libc:UTC'" + +rm -f "$FILE" diff --git a/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference new file mode 100644 index 000000000000..1f7e29a97d9d --- /dev/null +++ b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.reference @@ -0,0 +1,153 @@ +-- { echo } + +SET engine_file_truncate_on_insert = 1; +SET allow_experimental_nullable_tuple_type = 1; +INSERT INTO FUNCTION file(currentDatabase() || '_05617.orc', 'ORC') SELECT + number AS id, + if(number = 0, [(1, 'a'), (2, 'b')], [])::Array(Tuple(a Int32, b String)) AS l, + if(number = 0, map('k1', (1, 'a'), 'k2', (2, 'b')), map())::Map(String, Tuple(a Int32, b String)) AS m, + map(CAST(tuple(toInt32(number)), 'Tuple(a Int32)'), 'v') AS mk, + CAST((toInt32(number), [(toInt32(number), 'x')]), 'Tuple(a Int32, l Array(Tuple(x Int32, y String)))') AS t, + [[(toInt32(number), 'x'), (1, 'y')]]::Array(Array(Tuple(a Int32, b String))) AS ll, + map('k', [(toInt32(number), 'x')])::Map(String, Array(Tuple(a Int32, b String))) AS ml, + if(number = 0, [(1, 'a'), NULL, (2, 'b')], [])::Array(Nullable(Tuple(a Int32, b String))) AS ln, + [(toInt32(number), 'c')]::Array(Tuple(A Int32, b String)) AS lc, + CAST((toInt32(number), map('k', (1, 'v'))), 'Tuple(a Int32, m Map(String, Tuple(a Int32, b String)))') AS tm, + [(1, tuple(2)), (3, tuple(4))]::Array(Tuple(x Int32, z Tuple(w Int32))) AS n, + [(1, [(1, 'a'), (2, 'b')])]::Array(Tuple(y Int32, x Array(Tuple(a Int32, b String)))) AS lx, + if(number = 0, [tuple(tuple(1)), tuple(NULL)], [tuple(NULL)])::Array(Tuple(b Nullable(Tuple(a Int32)))) AS nb, + map('k', (if(number = 0, tuple(1), NULL), if(number = 0, NULL, tuple('x'))))::Map(String, Tuple(b Nullable(Tuple(a Int32)), c Nullable(Tuple(x String)))) AS mb, + CAST((toInt32(number), [tuple(if(number = 0, tuple(1), NULL))]), 'Tuple(a Int32, l Array(Tuple(b Nullable(Tuple(a Int32)))))') AS tb, + if(number = 0, tuple(1, 'a'), NULL)::Nullable(Tuple(a Int32, b String)) AS ts, + [CAST(tuple(toDateTime64('3000-01-01 00:00:00', 0, 'UTC')), 'Tuple(a DateTime64(0, \'UTC\'))')] AS ld, + CAST([tuple(11, tuple(5))], 'Array(Tuple(w Int32, x Tuple(v Int32)))') AS an +FROM numbers(2); +-- A list element, a map value and a map key, also nested in a struct, a list or a map, and with NULL elements. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [(NULL),(NULL)] +1 [] +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(q Nullable(String)))') ORDER BY id; +0 {'k1':(NULL),'k2':(NULL)} +1 {} +SELECT id, mk FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mk Map(Tuple(z Nullable(Int32)), String)') ORDER BY id; +0 {(NULL):'v'} +1 {(NULL):'v'} +SELECT id, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(a Int32, l Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 (0,[(NULL)]) +1 (1,[(NULL)]) +SELECT id, ll FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ll Array(Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 [[(NULL),(NULL)]] +1 [[(NULL),(NULL)]] +SELECT id, ml FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ml Map(String, Array(Tuple(q Nullable(Int32))))') ORDER BY id; +0 {'k':[(NULL)]} +1 {'k':[(NULL)]} +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Array(Nullable(Tuple(q Nullable(Int32))))') ORDER BY id; +0 [(NULL),NULL,(NULL)] +1 [] +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id SETTINGS input_format_orc_row_batch_size = 1; +0 [(NULL),(NULL)] +1 [] +-- The same through a subcolumn of a struct and a subcolumn of a Nested column. +SELECT id, `t.a`, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.a` Int32, `t.l` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 0 [(NULL)] +1 1 [(NULL)] +SELECT id, `tm.m` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tm.m` Map(String, Tuple(q Nullable(String)))') ORDER BY id; +0 {'k':(NULL)} +1 {'k':(NULL)} +SELECT id, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [(NULL),(NULL)] +1 [(NULL),(NULL)] +SELECT id, `n.x`, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.x` Array(Int32), `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +0 [1,3] [(NULL),(NULL)] +1 [1,3] [(NULL),(NULL)] +-- A struct that contains such a list is read with its fields. +SELECT id, lx FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lx Array(Tuple(x Array(Tuple(q Nullable(Int32)))))') ORDER BY id; +0 [([(NULL),(NULL)])] +1 [([(NULL),(NULL)])] +-- A struct read whole by another column keeps its data. optimize_functions_to_subcolumns = 0 keeps `t.l` itself in the read. +SELECT id, t, length(`t.l`) FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t String, `t.l` Array(Tuple(q String, r String))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 (0,[(0,\'x\')]) 1 +1 (1,[(1,\'x\')]) 1 +-- A Tuple naming some of the fields, and case-insensitive matching. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Nullable(Int32)))') ORDER BY id; +0 [(1,NULL),(2,NULL)] +1 [] +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(a Int32, q Nullable(String)))') ORDER BY id; +0 {'k1':(1,NULL),'k2':(2,NULL)} +1 {} +SELECT id, lc FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lc Array(Tuple(a Int32))') ORDER BY id SETTINGS input_format_orc_case_insensitive_column_matching = 1; +0 [(0)] +1 [(1)] +-- A non-nullable Date32 field gets the same default with and without a field that is in the file, an Enum gets its first value. +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Date32, e Enum8(\'x\' = 1, \'y\' = 2))), m Map(String, Tuple(q Date32))') ORDER BY id; +0 [('1970-01-01','x'),('1970-01-01','x')] {'k1':('1970-01-01'),'k2':('1970-01-01')} +1 [] {} +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Date32)), m Map(String, Tuple(a Int32, q Date32))') ORDER BY id; +0 [(1,'1970-01-01'),(2,'1970-01-01')] {'k1':(1,'1970-01-01'),'k2':(2,'1970-01-01')} +1 [] {} +-- A requested struct field of such a struct keeps its presence, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id; +0 [((0)),(NULL)] +1 [(NULL)] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(a Nullable(Int32), q Int32))))') ORDER BY id; +0 [((1,0)),(NULL)] +1 [(NULL)] +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(q Int32)), b Nullable(Tuple(r String))))') ORDER BY id; +0 {'k':(NULL,(''))} +1 {'k':((0),NULL)} +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(x Nullable(String), q Int32)), b Nullable(Tuple(a Nullable(Int32), r String))))') ORDER BY id; +0 {'k':(NULL,(1,''))} +1 {'k':(('x',0),NULL)} +-- A NULL struct requested as non-Nullable is rejected or read as default, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +0 [((0)),((0))] +1 [((0))] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +0 [((1,0)),((NULL,0))] +1 [((NULL,0))] +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +-- Two columns reading the same struct with different types get the defaults of their own type. +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(q Nullable(Int32)))), `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) [(NULL,NULL)] +1 ([(NULL)]) [(NULL,NULL)] +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(e Enum8(\'x\' = 1)))), `t.l` Array(Tuple(r Nullable(String)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([('x')]) [(NULL)] +1 ([('x')]) [(NULL)] +SELECT id, `t.l`, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32))), t Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 [(NULL,NULL)] ([(NULL)]) +1 [(NULL,NULL)] ([(NULL)]) +-- Of two columns reading the same struct, one that requests a nested struct of it keeps that struct's presence. +SELECT id, tb, `tb.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.l` Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) [((0))] +1 ([(NULL)]) [(NULL)] +SELECT id, `tb.l`, tb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tb.l` Array(Tuple(b Nullable(Tuple(q Int32)))), tb Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 [((0))] ([(NULL)]) +1 [(NULL)] ([(NULL)]) +SELECT id, tb, `tb.a` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.a` Int32') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +0 ([(NULL)]) 0 +1 ([(NULL)]) 1 +-- A top-level struct keeps its presence too, also when missing columns are not allowed. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id; +0 (0) +1 \N +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id SETTINGS input_format_orc_allow_missing_columns = 0; +0 (0) +1 \N +-- A field read only for the size of its struct is not converted. +SELECT id, ld FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ld Array(Tuple(q Int32))') ORDER BY id; +0 [(0)] +1 [(0)] +-- An unnamed Tuple is matched by position and must have as many elements as the struct. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +-- The same for a Nested column that is not flattened. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Nested(q Int32)') ORDER BY id SETTINGS flatten_nested = 0; +0 [(0),(0)] +1 [] +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +0 [(NULL),(NULL),(NULL)] +1 [] +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(a Nullable(Int32), q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +0 [(1,NULL),(NULL,NULL),(2,NULL)] +1 [] diff --git a/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql new file mode 100644 index 000000000000..c0092342d918 --- /dev/null +++ b/tests/queries/0_stateless/05617_orc_nested_struct_without_requested_fields.sql @@ -0,0 +1,99 @@ +-- Tags: no-fasttest +-- no-fasttest: ORC is not available in fasttest builds +-- An ORC list or map whose element, key or value struct has none of the fields of the requested Tuple keeps its +-- elements, and each of them is filled with default values. + +-- { echo } + +SET engine_file_truncate_on_insert = 1; +SET allow_experimental_nullable_tuple_type = 1; + +INSERT INTO FUNCTION file(currentDatabase() || '_05617.orc', 'ORC') SELECT + number AS id, + if(number = 0, [(1, 'a'), (2, 'b')], [])::Array(Tuple(a Int32, b String)) AS l, + if(number = 0, map('k1', (1, 'a'), 'k2', (2, 'b')), map())::Map(String, Tuple(a Int32, b String)) AS m, + map(CAST(tuple(toInt32(number)), 'Tuple(a Int32)'), 'v') AS mk, + CAST((toInt32(number), [(toInt32(number), 'x')]), 'Tuple(a Int32, l Array(Tuple(x Int32, y String)))') AS t, + [[(toInt32(number), 'x'), (1, 'y')]]::Array(Array(Tuple(a Int32, b String))) AS ll, + map('k', [(toInt32(number), 'x')])::Map(String, Array(Tuple(a Int32, b String))) AS ml, + if(number = 0, [(1, 'a'), NULL, (2, 'b')], [])::Array(Nullable(Tuple(a Int32, b String))) AS ln, + [(toInt32(number), 'c')]::Array(Tuple(A Int32, b String)) AS lc, + CAST((toInt32(number), map('k', (1, 'v'))), 'Tuple(a Int32, m Map(String, Tuple(a Int32, b String)))') AS tm, + [(1, tuple(2)), (3, tuple(4))]::Array(Tuple(x Int32, z Tuple(w Int32))) AS n, + [(1, [(1, 'a'), (2, 'b')])]::Array(Tuple(y Int32, x Array(Tuple(a Int32, b String)))) AS lx, + if(number = 0, [tuple(tuple(1)), tuple(NULL)], [tuple(NULL)])::Array(Tuple(b Nullable(Tuple(a Int32)))) AS nb, + map('k', (if(number = 0, tuple(1), NULL), if(number = 0, NULL, tuple('x'))))::Map(String, Tuple(b Nullable(Tuple(a Int32)), c Nullable(Tuple(x String)))) AS mb, + CAST((toInt32(number), [tuple(if(number = 0, tuple(1), NULL))]), 'Tuple(a Int32, l Array(Tuple(b Nullable(Tuple(a Int32)))))') AS tb, + if(number = 0, tuple(1, 'a'), NULL)::Nullable(Tuple(a Int32, b String)) AS ts, + [CAST(tuple(toDateTime64('3000-01-01 00:00:00', 0, 'UTC')), 'Tuple(a DateTime64(0, \'UTC\'))')] AS ld, + CAST([tuple(11, tuple(5))], 'Array(Tuple(w Int32, x Tuple(v Int32)))') AS an +FROM numbers(2); + +-- A list element, a map value and a map key, also nested in a struct, a list or a map, and with NULL elements. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(q Nullable(String)))') ORDER BY id; +SELECT id, mk FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mk Map(Tuple(z Nullable(Int32)), String)') ORDER BY id; +SELECT id, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(a Int32, l Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ll FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ll Array(Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ml FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ml Map(String, Array(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Array(Nullable(Tuple(q Nullable(Int32))))') ORDER BY id; +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Nullable(Int32)))') ORDER BY id SETTINGS input_format_orc_row_batch_size = 1; + +-- The same through a subcolumn of a struct and a subcolumn of a Nested column. +SELECT id, `t.a`, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.a` Int32, `t.l` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, `tm.m` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tm.m` Map(String, Tuple(q Nullable(String)))') ORDER BY id; +SELECT id, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; +SELECT id, `n.x`, `n.z` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `n.x` Array(Int32), `n.z` Array(Tuple(q Nullable(Int32)))') ORDER BY id; + +-- A struct that contains such a list is read with its fields. +SELECT id, lx FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lx Array(Tuple(x Array(Tuple(q Nullable(Int32)))))') ORDER BY id; + +-- A struct read whole by another column keeps its data. optimize_functions_to_subcolumns = 0 keeps `t.l` itself in the read. +SELECT id, t, length(`t.l`) FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t String, `t.l` Array(Tuple(q String, r String))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- A Tuple naming some of the fields, and case-insensitive matching. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Nullable(Int32)))') ORDER BY id; +SELECT id, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, m Map(String, Tuple(a Int32, q Nullable(String)))') ORDER BY id; +SELECT id, lc FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, lc Array(Tuple(a Int32))') ORDER BY id SETTINGS input_format_orc_case_insensitive_column_matching = 1; + +-- A non-nullable Date32 field gets the same default with and without a field that is in the file, an Enum gets its first value. +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(q Date32, e Enum8(\'x\' = 1, \'y\' = 2))), m Map(String, Tuple(q Date32))') ORDER BY id; +SELECT id, l, m FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(a Int32, q Date32)), m Map(String, Tuple(a Int32, q Date32))') ORDER BY id; + +-- A requested struct field of such a struct keeps its presence, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Nullable(Tuple(a Nullable(Int32), q Int32))))') ORDER BY id; +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(q Int32)), b Nullable(Tuple(r String))))') ORDER BY id; +SELECT id, mb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, mb Map(String, Tuple(c Nullable(Tuple(x Nullable(String), q Int32)), b Nullable(Tuple(a Nullable(Int32), r String))))') ORDER BY id; + +-- A NULL struct requested as non-Nullable is rejected or read as default, the same as when one of its fields is requested. +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 1; +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } +SELECT id, nb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, nb Array(Tuple(b Tuple(a Nullable(Int32), q Int32)))') ORDER BY id SETTINGS input_format_null_as_default = 0; -- { serverError CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN } + +-- Two columns reading the same struct with different types get the defaults of their own type. +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(q Nullable(Int32)))), `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, t, `t.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, t Tuple(l Array(Tuple(e Enum8(\'x\' = 1)))), `t.l` Array(Tuple(r Nullable(String)))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, `t.l`, t FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `t.l` Array(Tuple(r Nullable(String), s Nullable(Int32))), t Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- Of two columns reading the same struct, one that requests a nested struct of it keeps that struct's presence. +SELECT id, tb, `tb.l` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.l` Array(Tuple(b Nullable(Tuple(q Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, `tb.l`, tb FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, `tb.l` Array(Tuple(b Nullable(Tuple(q Int32)))), tb Tuple(l Array(Tuple(q Nullable(Int32))))') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; +SELECT id, tb, `tb.a` FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, tb Tuple(l Array(Tuple(q Nullable(Int32)))), `tb.a` Int32') ORDER BY id SETTINGS optimize_functions_to_subcolumns = 0; + +-- A top-level struct keeps its presence too, also when missing columns are not allowed. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id; +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(q Int32))') ORDER BY id SETTINGS input_format_orc_allow_missing_columns = 0; + +-- A field read only for the size of its struct is not converted. +SELECT id, ld FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ld Array(Tuple(q Int32))') ORDER BY id; + +-- An unnamed Tuple is matched by position and must have as many elements as the struct. +SELECT id, ts FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ts Nullable(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Array(Tuple(Int32, String, Int32))') ORDER BY id; -- { serverError TYPE_MISMATCH } + +-- The same for a Nested column that is not flattened. +SELECT id, l FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, l Nested(q Int32)') ORDER BY id SETTINGS flatten_nested = 0; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; +SELECT id, ln FROM file(currentDatabase() || '_05617.orc', 'ORC', 'id UInt64, ln Nested(a Nullable(Int32), q Nullable(Int32))') ORDER BY id SETTINGS flatten_nested = 0; diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.0.orc new file mode 100644 index 0000000000000000000000000000000000000000..6c52f4f0f98b40dec581f1b02ec3936d34d62796 GIT binary patch literal 709 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo mQfoMv*fgJAnSmomfKj5Mfklalfk(r{fUW5ZGqZn?vp4|E0T8hO literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc b/tests/queries/0_stateless/data_orc/bad_bloom_filter_1.6.11.orc new file mode 100644 index 0000000000000000000000000000000000000000..fc3ffef8f18c17dc95f532108f94846c6cb9b894 GIT binary patch literal 717 zcmeYda+YOa;Nsz8VE_Ul77o?`1}g@J$3ah$(i<2Q4f(`X9foPp;g3RC==BExo1XeDT)j`@d*0UouL)T2hk0z`R(Z zLXP?4@vapcj<8#u@|yho1lyA79E~@e53qDH@+2HEcDVcTjX@hD4~ygm1wIL$ga_Wt zzJC_DaqeWa0J?nA^G7KSjEahUVXAU^VaMm3c@m;{OoekM0~>=D(Badqxf%=vTtb6b zHg4E<%CX3zKUbOK)={TKV@@6Y*h6V$&s+aIGd{jSwsL{0WmAA^^S*OhsY*>Z94N8MFvLc#_M{U zPrgjEZ*TIGPvvkpz~A`dxL36L%3Q1DZO2aANS!XVi~Tn%;2*O-D+9y-A7Da(f#LVT zLkEs9u=FG}9eptIV>|;`oST8cjU`yn0T@?~Iho0+PWefRNxqrcsZ$sjOivl|H5l+X zUsQAGG`hGcLZ?7l&5W5; zG3liD8Q;)^3ke1Z0goOeG;Y43sKXqlEyj0^flV7Dfr$jfbTo%{ws&7OR5!K^?J)Fo vQfoMv*fgI#S!njcc{ArNRAk^N5nz;PXkbxdV&Ks*F<@)@!p!U+JFZE-iyIBTGB(h%cBfX4BGjAJ&?Gn8U6&@(d& zz$y=vGO&;Wsxk>+P+(wKo$%nn**QlR@+j>TaZurBkYr%+<23NG2w({jkqGi}XJ9z6 zYbW!qRlXhHI#@oOiG6Td^2pN_EKS$M7W4_Nc>Rj~#nl5W{0t0koK8+IN-kjSYyv`D ze0)qod?H{j6B7>yAC~|R3qu>wgGrAQgcBw_c*b{mZuY+kFmEzQ>GXvtHD{W zWs;4rS`L~_X0e}<#`Zdy^-@fN9e2o_(5Co~&Su7rnHMtH82$lGnRVvG(L)DC4;)ZE zeNa{9)WwY{H(#^4HOd*NetdLvKd-FANsdH4L0}-t>A5j0stGG=rYRQ(FVL``E)@{c z*M0ZIflEH;k2rN4K6K*36_4{*Ji0C)IdSR0m4Neim{y!?@a9?3$G>FuO^5RVT}K_x zpW#^}ug521v|$3%saXw27$-3@JWde%aZ=^z*@HR-4S|as4*E8Gdp0$@cTAnwIkPpi z%P_FZ(6h@hvdhr5%P_RFv)Q$?x7ok>cmtzPw}gS?Pk~t{8%{Qy?rLq;ZaC;Qt=ZdS z%Hrgco38WrFxe(}Jv!Q5FKyK@N$^mZl1z-7O-v7)laHEP&>6R9%Nzphv`rVRkP+WK zv2p3ld7Z5S?X43RuADe;;?|1sEk78U&P>8TXu+-id_MC9Fa-<` z?lW*QFhnuTafo1Gc%1Y&K{#Q;gJ(<^dxYv@a%6g#dW4FAv=5MebWNDr~+4;VnvT^!awPNw&jholK~7@| z!qQ)f-`+hkxUucGmEX^Ib+-3k9pAk34oO3dhvpw=li&Ht=fd(`*2q-Zz@MuUHur+;QX7&$q76$-W;u-w_ literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc b/tests/queries/0_stateless/data_orc/malformed_dictionary_size_max.orc new file mode 100644 index 0000000000000000000000000000000000000000..27d3a7a5694c836382a434b145463145bc7e4969 GIT binary patch literal 174 zcmeYdaz2pEz)<19(7?sU!6?8e!2+b2fixqKW&+a8LQEVCLL5M`|3JVm#q91I!X?hd z!jTfdz{SszqQuF?SRuq%A#s8+fB~q=Sc(fsGDvVJXltY>ad7YmF)~Uq7ArAvup6XU xfwftoYja@mU`*n2&dE&9_Q)?SPUUb18qm-npv1($qakU)*7Sv$*+0lx8~}Ex9uxoo literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc b/tests/queries/0_stateless/data_orc/malformed_footer_too_many_statistics.orc new file mode 100644 index 0000000000000000000000000000000000000000..00ab37f164451f7d41fdd9918d3a60e6eb3fb9e1 GIT binary patch literal 353 zcmb7!55@c<-_od@Ma)J`I4HxfN+mPlz%p40|nh@xK=W-?pJwH%K)jX%p}<3F&Fh@rNx z?t8Y(IS+(X;JUy~Nt{KsDqAPB`oye0GaG+COmQR4^X~C!`ttU={aZS&{tbFtXANNv_gqUE3}AonBeEZn8f9rlbM|DkzZPz$`J=lJ`D{5 WN=ytq8jF|>*qXjDGy4ZQO8@|~r#gH9 literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc b/tests/queries/0_stateless/data_orc/malformed_patched_base_terminal_continuation.orc new file mode 100644 index 0000000000000000000000000000000000000000..43552b05c31d975806e7b28bf0348ac911b93320 GIT binary patch literal 83 zcmeYda_(bbf5@QqpMi^wgHeD{fZBafx-+D4Gk42F|jIl^(saf&@Ul}_i@Q96kobdi?g;4J`i%|p7O zHQHy4J^a)g0`Qj6YX%1aWcQxocSeo^^{~g%Xx3tINijrGbQqKXl}3-r5QS%EZ#Tnm$hsO_t_nvG%Tof%Rfa2K6BY3f#1KM=U?J&`Kze_YKPs*0 zx=Eu0j}P9!do!~|CB`MJ=O9i9z@@C6VX*Am!Mha&!ECV3S+H<8^mY#W1gIGH9|rxw zXpDOxF>EY&jzr&%B;N@{i#~~@xF<_qJ7Nf;voiJcyp((SJL0nbs+X1h!K@W3q*{Nxeoi)D+c$m>ztpwO3DRD- MFyFsQ%@$SX1Y@lyc>n+a literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc b/tests/queries/0_stateless/data_orc/malformed_timestamp_nanoseconds.orc new file mode 100644 index 0000000000000000000000000000000000000000..ab57ba54f6cb5f35ce2f2225cedead3e3c24d9e6 GIT binary patch literal 238 zcmeYdaz4P>@V{v>Ba?moe+amFYzD)Ut4a(EH!q|}F!G&RDZuEwo9hH)g+~tq6u9SsRejxb{KXpyLT!00RfJK%^8GkYtdsQIOT(QsUs?5n^PNVk}W&;@~vk yvI3i7h1U!R1`oz0F6W%gPb;1ObElwvGVV&dR5V73CA xVnx6dhY5Zjj7eP1Iho1X9{HuksT|=zmo_vAC^0ecXlNL)HGN@b_78Fv2LL-3L?-|M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc b/tests/queries/0_stateless/data_orc/malformed_zstd_chunk_size.orc new file mode 100644 index 0000000000000000000000000000000000000000..4f30ed6c7f1acfc4f1587ecd851ca828b38d2f80 GIT binary patch literal 38 scmeYda+Y9V(AcW~cL4(fg99T20|&nVt3(43uxKzeePL$y4{{a;0H`qt$^ZZW literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc b/tests/queries/0_stateless/data_orc/orc_nested_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..ed3597a70455f3319174fea0ea64f41d446cd797 GIT binary patch literal 666 zcmaix&q~8U5XNU_lXYBHS=Webywo6)Qz;&EDiqX}}d=Fp4 ztKzsxN?H%yzWek=6A!rcN(PZ|1U)2|F+f zWWX+C!3O6Z=i#sQ%pmv^#{76&%5v;*uMLjcUdixCsKY(M%hOn5oHKSQO2pknd z7L|gHsv1oio`%E7btpyAVMwAg?1CC}C6^^LhR zwLh!Q)l7zn1(v%$tsAu28&>Xva+&X5G332>ELE}3))P`rPmei1_n?FU6wIoLEbn+y zx|=2Gzb@vjC2M*Is*1l}t*q0qxQr`v&RGZfszKyT&K0WWt$Db%~yI3Rzfh`{f M`sGWh$!rvU0o^4u?*IS* literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/orc_union_type.orc b/tests/queries/0_stateless/data_orc/orc_union_type.orc new file mode 100644 index 0000000000000000000000000000000000000000..08c73c83fd428e64b0f74df501b573b0d8eb7b8d GIT binary patch literal 398 zcmeYdau#G@;9?VE;b012kOnfjxtJLk7$AIYAYT~5=iy)!V&e!A2$2X0U@%}{cr5fh zDV2dy(T>kel~3;&m*O!l&Sea23@BQdfLfRYSR~j27}yyY{xL8DNk4`VAnCx+0JNq8 z$Z}&;X<=ZnJ$aD#fB^@y0~3eqm*!uaW)*I7+WlY4H&#<#{+Oh#SHY8X=RnpKi2>>P z+5D?QuKz1<{`|h<^6n{bLhf1XSHJtolmc|qrUyw66Sxu@CfUgJIOWJFGARlvIv655 zae|Z_pV|VQ$qd~r(G1KCFMyg7#4OHf96fqaXM&pI;s>h^E>SshQ2EG_6G}%Tw2sbL zd0@f8gaZqX96qRh@VGj1mnEEJ{oaJQ}73 NY)xO7nf-&D#Q~MRda3{b literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/row_index_seek_control.orc b/tests/queries/0_stateless/data_orc/row_index_seek_control.orc new file mode 100644 index 0000000000000000000000000000000000000000..ede347aa81181c970ec5d83161d8595eef07a424 GIT binary patch literal 213 zcmY+7F$=;#426?iIYPMMI7E+5r66?dD4oO#c9E9SA0Uc@C^(4VSp3cY0MA1Nhvb8o z_g>n*7VQ$o4t{h(0M0Nv&0xVpxP3JIYGlb%2P@1(vknFuiM|L#i(WZm2t%pbYzLW0 z!oe?wDK^G5E4xc2?1fj^yr7)fIK&hmIdM`_6*JXeW{C~%rM{dF=jM999eEv|kE6{A OOffC>^QBbV*RwZ`5EX0y literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_arrow.orc new file mode 100644 index 0000000000000000000000000000000000000000..d6e0144685e7e91cbc4e2f76aba78db27c503b4f GIT binary patch literal 294 zcmeYda^_+aV&Py3VBnJHVqpLRA#n~CFF}d-S0A;$tXG(DYv0WG<_0&-0vIZo8Q1fF zHU<%<3}+*pj2X=Co-wUs{tp7J@2o(YK>&?!#l^uMlK_Jhv%7By$R%JG;c^KFv%n-qDJ~$TDPf^tsKKJd$H61S$SB2FqQIcR zV8Ecn!NCb(8L(J^&9cH}mcs-;55^=`BRwGGhyc2?p@Bt-iGfE$(SWV#3p2BSkh3@d Dw(m#M literal 0 HcmV?d00001 diff --git a/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc b/tests/queries/0_stateless/data_orc/timestamps_before_epoch_pyarrow_bloom_filter.orc new file mode 100644 index 0000000000000000000000000000000000000000..2afd747824ec0515a92db943df384c0a15d9573e GIT binary patch literal 517 zcmah_F-XHu5WUM!;u%X*Gw3%hG-L`zN_4CaLP4z{m7=SIgM;WMjv~5taS^)MxuUCE zXQx6PTq+J-6>$+1LF@hef*^>uyn8P%clTelR(5R9BwT}kal$cy%S#ikkZk6IWVM&3+yxPgX3uK-?@cBI7ut#aQ69Ap@RG z2HVjWORMWDLb5o9G+8=Y{U{Qd6XB0B)D1Zo%tuz3rj&>1G`*BQ+>fo1s*rPY z<~tIo>C52xd@=P*T`HPO=fa~AC5KX$QO)2}nRh1jyG=~AvjcuNo8b}B*Y_dmqTM+s z%Sgh-{5jA?(yFE`wR{4hIO~K=Wjl7=B}Xf}W{@pajjY)=+iq##pbu_Q=h(2_ti3>u z9J)?2=+GRx-X5s=SumAbf+5?n4%qkartR%4)<&I(Tt*DJ7X=wHr|d<1%^YzzE3xM> z-%7E|JP?a`XAz0(J?42JA3%DAus`Z&$y9Xaij(78A=2Oj@9du!#a=!NEc0aI_oNwy zL6aGK>2?l~?dJ7(AxI8I0lE`VGY3E}E@o%dTVTviD!?e2g#g2kAR) empty_values = 2; + map recursive_values = 3; + map big_enum_values = 4; + map supported_values = 5; +} diff --git a/tests/queries/0_stateless/orc_malformed.lib b/tests/queries/0_stateless/orc_malformed.lib new file mode 100644 index 000000000000..64f884cc4498 --- /dev/null +++ b/tests/queries/0_stateless/orc_malformed.lib @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2154 + +# Helpers to read (possibly malformed) ORC files from the tests: locally with `file` in clickhouse-local, and remotely +# with `s3` in the server, with the filter pushdown and the lazy dictionaries both enabled and disabled. + +ORC_S3_URL="http://localhost:11111/test/${CLICKHOUSE_TEST_UNIQUE_NAME}" +# The values of `input_format_orc_filter_push_down` to check. +ORC_PUSH_DOWN_VALUES="0 1" + +# Prints the result in one line, or the name of the error code (with the message if it does not match `expected_error`). +function orc_result() +{ + local output=$1 status=$2 expected_error=$3 + if [ "$status" -eq 0 ]; then + echo "$output" | tr '\n' ' ' | sed 's/ $//' + return + fi + local code + code=$(echo "$output" | grep -oE '\([A-Z_]{3,}\)' | tail -n1) + if [ -z "$code" ]; then + echo "unexpected failure with status $status: $(echo "$output" | head -n3)" + elif [ -z "$expected_error" ] || echo "$output" | grep -qE "$expected_error"; then + echo "$code" + else + echo "$code with an unexpected message: $(echo "$output" | head -n1 | cut -c1-300)" + fi +} + +# orc_check
`. The creator of the table supplied its source and credentials, - /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator - /// of `ON CLUSTER` can check them without the table. + /// so the reading part is `SELECT` on the table. For `ON CLUSTER`, `engine` is empty, so the grants can be checked + /// without the table. if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) { - auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + const auto & changes = command.settings_changes->as().changes; + auto export_access = engine.empty() + ? StorageFactory::instance().getExportAccessOfAnyEngine(changes) + : StorageFactory::instance().getExportAccess(changes, engine); if (!export_access.empty()) { required_access.append_range(std::move(export_access)); diff --git a/src/Interpreters/InterpreterAlterQuery.h b/src/Interpreters/InterpreterAlterQuery.h index 17afa140c8e7..604ad24376c6 100644 --- a/src/Interpreters/InterpreterAlterQuery.h +++ b/src/Interpreters/InterpreterAlterQuery.h @@ -22,14 +22,17 @@ class InterpreterAlterQuery : public IInterpreter, WithMutableContext BlockIO execute() override; - static AccessRightsElements getRequiredAccessForCommand(const ASTAlterCommand & command, const String & database, const String & table); + /// `engine` is the engine of the table, empty for `ON CLUSTER`. + static AccessRightsElements getRequiredAccessForCommand( + const ASTAlterCommand & command, const String & database, const String & table, const String & engine = {}); void extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr & ast, ContextPtr context) const override; bool supportsTransactions() const override { return true; } private: - AccessRightsElements getRequiredAccess() const; + /// `engine` is the engine of the table, empty if the table is not known. + AccessRightsElements getRequiredAccess(const String & engine = {}) const; BlockIO executeToTable(const ASTAlterQuery & alter); diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 08aa8818f4a3..7438cf1a85f3 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -109,6 +109,11 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration String getDataSourceDescription() const override { return std::filesystem::path(connection_params.getConnectionURLWithoutQuery()) / connection_params.getContainer(); } StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; + String getConnectionURLWithoutQuery() const + { + return connection_params.endpoint.sas_auth.empty() ? connection_params.getConnectionURLWithoutQuery() : connection_params.endpoint.storage_account_url; + } + void check(ContextPtr context) override; ObjectStoragePtr createObjectStorage(ContextPtr context, bool is_readonly, CredentialsConfigurationCallback refresh_credentials_callback) override; diff --git a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp index 8f1fa65d198a..c5526e732243 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp @@ -107,7 +107,10 @@ void StorageObjectStorageConfiguration::initialize( if (!disk_name.empty()) configuration_to_initialize.fromDisk(disk_name, engine_args, local_context, with_table_structure); else if (auto named_collection = tryGetNamedCollectionWithOverrides(engine_args, local_context, true, nullptr, table_id)) + { configuration_to_initialize.fromNamedCollection(*named_collection, local_context); + configuration_to_initialize.initialized_from_named_collection = true; + } else configuration_to_initialize.fromAST(engine_args, local_context, with_table_structure); diff --git a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h index 94a402f65613..60c7a675e90b 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h @@ -290,6 +290,9 @@ class StorageObjectStorageConfiguration bool partition_columns_in_data_file = true; std::shared_ptr partition_strategy; + /// Set by `initialize` when the arguments come from a named collection. + bool initialized_from_named_collection = false; + protected: void checkFormat() const; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp index d3e842d386b4..b0a584b674b5 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp @@ -44,6 +44,7 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; + extern const int METADATA_MISMATCH; extern const int REPLICA_ALREADY_EXISTS; extern const int SUPPORT_IS_DISABLED; extern const int TIMEOUT_EXCEEDED; @@ -359,7 +360,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, Coordination::Stat stat; auto metadata_str = zookeeper->get(fs::path(zookeeper_path) / "metadata", &stat); auto metadata_from_zk = ObjectStorageQueueTableMetadata::parse(metadata_str); - auto new_table_metadata{table_metadata}; + auto new_table_metadata{metadata_from_zk}; for (const auto & change : changes) { @@ -385,7 +386,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (change.name == "processing_threads_num") { const auto value = change.value.safeGet(); - if (table_metadata.processing_threads_num == value) + if (new_table_metadata.processing_threads_num == value) { LOG_TRACE(log, "Setting `processing_threads_num` already equals {}. " "Will do nothing", value); @@ -396,7 +397,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "loading_retries") { const auto value = change.value.safeGet(); - if (table_metadata.loading_retries == value) + if (new_table_metadata.loading_retries == value) { LOG_TRACE(log, "Setting `loading_retries` already equals {}. " "Will do nothing", value); @@ -407,7 +408,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "after_processing") { const auto value = ObjectStorageQueueTableMetadata::actionFromString(change.value.safeGet()); - if (table_metadata.after_processing == value) + if (new_table_metadata.after_processing == value) { LOG_TRACE(log, "Setting `after_processing` already equals {}. " "Will do nothing", value); @@ -418,7 +419,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "tracked_files_limit") { const auto value = change.value.safeGet(); - if (table_metadata.tracked_files_limit == value) + if (new_table_metadata.tracked_files_limit == value) { LOG_TRACE(log, "Setting `tracked_files_limit` already equals {}. " "Will do nothing", value); @@ -429,7 +430,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "tracked_file_ttl_sec") { const auto value = change.value.safeGet(); - if (table_metadata.tracked_files_ttl_sec == value) + if (new_table_metadata.tracked_files_ttl_sec == value) { LOG_TRACE(log, "Setting `tracked_file_ttl_sec` already equals {}. " "Will do nothing", value); @@ -458,6 +459,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (table_metadata.buckets == value) { LOG_TRACE(log, "Setting `buckets` already equals {}. Will do nothing", value); + new_table_metadata.buckets = value; continue; } if (table_metadata.buckets > 1) @@ -486,7 +488,10 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (is_initial_query) zookeeper->set(table_metadata_path, new_metadata_str, stat.version); - table_metadata.syncChangeableSettings(new_table_metadata); + NameSet changed_names; + for (const auto & change : changes) + changed_names.insert(change.name); + table_metadata.syncChangeableSettings(new_table_metadata, changed_names); } void ObjectStorageQueueMetadata::migrateToBucketsInKeeper(size_t value) @@ -510,10 +515,11 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( const ColumnsDescription & columns, const std::string & format, const ContextPtr & context, - bool is_attach, + const ObjectStorageQueueTableMetadata::Source & source, + bool strict, LoggerPtr log) { - ObjectStorageQueueTableMetadata table_metadata(settings, columns, format); + ObjectStorageQueueTableMetadata table_metadata(settings, columns, format, source); std::vector metadata_paths; size_t buckets_num = 0; @@ -550,16 +556,38 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( { auto zk_client = getZooKeeper(log, zookeeper_name); std::optional metadata_from_zk; + Coordination::Stat stat; if (zk_client->exists(table_metadata_path)) { - const auto metadata_str = zk_client->get(table_metadata_path); + const auto metadata_str = zk_client->get(table_metadata_path, &stat); LOG_TRACE(log, "Metadata in keeper: {}", metadata_str); metadata_from_zk.emplace(ObjectStorageQueueTableMetadata::parse(metadata_str)); } if (metadata_from_zk.has_value()) { table_metadata.adjustFromKeeper(metadata_from_zk.value()); + /// A named collection can change without an `ALTER` of the table, so its source is always checked. + if (!strict && !source.from_named_collection && !metadata_from_zk->source_hash.empty() + && table_metadata.source_hash != metadata_from_zk->source_hash) + { + LOG_WARNING(log, "The source of this table differs from the source of the queue"); + table_metadata.source_hash = metadata_from_zk->source_hash; + } table_metadata.checkEquals(metadata_from_zk.value()); + if (metadata_from_zk->source_hash.empty()) + { + if (strict) + throw Exception( + ErrorCodes::METADATA_MISMATCH, + "Existing table metadata in ZooKeeper has no source, as an older version wrote it. " + "Attach the main table (following the same `keeper_path`) of this queue on an upgraded server, or use another `keeper_path`"); + + if (!table_metadata.source_hash.empty()) + { + metadata_from_zk->source_hash = table_metadata.source_hash; + code = zk_client->trySet(table_metadata_path, metadata_from_zk->toString(), stat.version); + } + } return; } @@ -572,7 +600,7 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( "either `buckets`>1 or `processing_threads_num`>1 (works as `buckets` if it's not specified) " "will not work properly. Please specify them in the CREATE query. See documentation for more details."; - if (is_attach) + if (!strict) { LOG_WARNING(log, "{}", message); warned = true; @@ -637,6 +665,9 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( *code, exception.getPathForFirstFailedOp(), zookeeper_path.string()); continue; } + /// Keeper was changed after the metadata was read, for example by another server, so start again. + if (*code == Coordination::Error::ZBADVERSION || *code == Coordination::Error::ZNONODE) + continue; if (*code != Coordination::Error::ZOK) zkutil::KeeperMultiException::check(*code, requests, responses); } diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h index 9bcc7d620ead..9273f42b2f82 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h @@ -99,6 +99,8 @@ class ObjectStorageQueueMetadata /// - adjust, if needed and allowed, passed queue settings according to /// what is in keeper (for example, processing_threads_num is adjustable, /// because its default depends on the CPU cores on the server); + /// - if not `strict` or from a named collection, a table is loaded even if its source differs from keeper; + /// - if keeper has no `source` (metadata written by an older version), save the table's `source` there; static ObjectStorageQueueTableMetadata syncWithKeeper( const String & zookeeper_name, const fs::path & zookeeper_path, @@ -106,7 +108,8 @@ class ObjectStorageQueueMetadata const ColumnsDescription & columns, const std::string & format, const ContextPtr & context, - bool is_attach, + const ObjectStorageQueueTableMetadata::Source & source, + bool strict, LoggerPtr log); /// Alter settings in keeper metadata /// (rewrites what we write in syncWithKeeper()). diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp index e845fa34a6c0..ef8eb6e38554 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -57,16 +57,24 @@ bool isEmptyValue(const Field & value) return value.getType() == Field::Types::String && value.safeGet().empty(); } +bool changesSourceObjects(const SettingChange & change) +{ + /// `after_processing` other than `keep` modifies the source files. + return (change.name == "after_processing" || change.name == "s3queue_after_processing") + && change.value.safeGet() != "keep"; +} + /// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. -AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind, bool own_engine) { const bool sets_destination = std::ranges::any_of( changes, [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); - if (!sets_destination) + if (!sets_destination && !(own_engine && std::ranges::any_of(changes, changesSourceObjects))) return {}; /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For `after_processing`, the URL of the table is not known here either. /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). @@ -78,14 +86,14 @@ AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, M } -AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine) { - return getMoveDestinationAccess(changes, MoveDestinationKind::S3); + return getMoveDestinationAccess(changes, MoveDestinationKind::S3, own_engine); } -AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine) { - return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure, own_engine); } void checkObjectStorageQueueS3MoveDestinationHost( diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h index 40601b4b1145..6cb036e19b27 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -21,8 +21,10 @@ class RemoteHostFilter; /// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy /// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. /// An empty value disables the move destination, so it is not a destination and needs no grant. -AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); -AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); +/// If `own_engine` (the table has this engine, or its engine is not known, as for `ON CLUSTER`), `after_processing` +/// other than `keep` needs the same unfiltered `WRITE`. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine); /// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. /// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp index fa60b7b66327..4293fa10f335 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace DB @@ -59,7 +60,8 @@ namespace ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata( const ObjectStorageQueueSettings & engine_settings, const ColumnsDescription & columns_, - const std::string & format_) + const std::string & format_, + const Source & source) : format_name(format_) , columns(columns_.toString(true)) , mode(engine_settings[ObjectStorageQueueSetting::mode].toString()) @@ -76,6 +78,7 @@ ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata( , tracked_files_limit(engine_settings[ObjectStorageQueueSetting::tracked_files_limit]) , tracked_files_ttl_sec(engine_settings[ObjectStorageQueueSetting::tracked_file_ttl_sec]) , buckets(engine_settings[ObjectStorageQueueSetting::buckets]) + , source_hash(source.getHash()) { processing_threads_num_changed = engine_settings[ObjectStorageQueueSetting::processing_threads_num].changed; if (!processing_threads_num_changed && engine_settings[ObjectStorageQueueSetting::processing_threads_num] <= 1) @@ -118,6 +121,7 @@ String ObjectStorageQueueTableMetadata::toString() const json.set("partitioning_mode", partitioning_mode); json.set("partition_regex", partition_regex); json.set("partition_component", partition_component); + json.set("source_hash", source_hash); std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM oss.exceptions(std::ios::failbit); @@ -209,6 +213,7 @@ ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata(const Poco::JSO , tracked_files_limit(getOrDefault(json, "tracked_files_limit", "s3queue_", 0ULL)) , tracked_files_ttl_sec(getOrDefault(json, "tracked_files_ttl_sec", "", getOrDefault(json, "tracked_file_ttl_sec", "s3queue_", 0ULL))) , buckets(getOrDefault(json, "buckets", "", 0ULL)) + , source_hash(getOrDefault(json, "source_hash", "", "")) { validateMode(mode); } @@ -220,6 +225,21 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueTableMetadata::parse(const Str return ObjectStorageQueueTableMetadata(json); } +String ObjectStorageQueueTableMetadata::Source::getHash() const +{ + if (empty()) + return {}; + + /// With the lengths, bucket `ab` with path `c/*` and bucket `a` with path `bc/*` have different hashes. + SipHash hash; + for (const auto & part : {type, endpoint, bucket, path_pattern}) + { + hash.update(part.size()); + hash.update(part); + } + return getHexUIntLowercase(hash.get128()); +} + void ObjectStorageQueueTableMetadata::adjustFromKeeper(const ObjectStorageQueueTableMetadata & from_zk) { if (processing_threads_num != from_zk.processing_threads_num) @@ -261,6 +281,11 @@ void ObjectStorageQueueTableMetadata::checkImmutableFieldsEquals(const ObjectSto from_zk.mode, mode); + if (!from_zk.source_hash.empty() && source_hash != from_zk.source_hash) + throw Exception( + ErrorCodes::METADATA_MISMATCH, + "Existing table metadata in ZooKeeper differs in source (storage type, endpoint, bucket or path)"); + if (bucketing_mode != from_zk.bucketing_mode) throw Exception( ErrorCodes::METADATA_MISMATCH, diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h index f06cfe473a9c..6af691e8b105 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -19,6 +20,20 @@ class ReadBuffer; */ struct ObjectStorageQueueTableMetadata { + /// Where the queue reads files from, without credentials. Tables with the same `keeper_path` must have the same + /// source, because processed files are tracked only by their path. + struct Source + { + String type; + String endpoint; + String bucket; + String path_pattern; + bool from_named_collection = false; + + [[nodiscard]] bool empty() const { return endpoint.empty(); } + [[nodiscard]] String getHash() const; + }; + /// Non-changeable settings. const String format_name; const String columns; @@ -38,11 +53,13 @@ struct ObjectStorageQueueTableMetadata std::atomic buckets; bool processing_threads_num_changed = false; + String source_hash; ObjectStorageQueueTableMetadata( const ObjectStorageQueueSettings & engine_settings, const ColumnsDescription & columns_, - const std::string & format_); + const std::string & format_, + const Source & source); ObjectStorageQueueTableMetadata(const ObjectStorageQueueTableMetadata & other) : format_name(other.format_name) @@ -60,16 +77,22 @@ struct ObjectStorageQueueTableMetadata , tracked_files_limit(other.tracked_files_limit.load()) , tracked_files_ttl_sec(other.tracked_files_ttl_sec.load()) , buckets(other.buckets.load()) + , source_hash(other.source_hash) { } - void syncChangeableSettings(const ObjectStorageQueueTableMetadata & other) + void syncChangeableSettings(const ObjectStorageQueueTableMetadata & other, const NameSet & names) { - after_processing = other.after_processing.load(); - loading_retries = other.loading_retries.load(); - processing_threads_num = other.processing_threads_num.load(); - tracked_files_limit = other.tracked_files_limit.load(); - tracked_files_ttl_sec = other.tracked_files_ttl_sec.load(); + if (names.contains("after_processing")) + after_processing = other.after_processing.load(); + if (names.contains("loading_retries")) + loading_retries = other.loading_retries.load(); + if (names.contains("processing_threads_num")) + processing_threads_num = other.processing_threads_num.load(); + if (names.contains("tracked_files_limit")) + tracked_files_limit = other.tracked_files_limit.load(); + if (names.contains("tracked_file_ttl_sec")) + tracked_files_ttl_sec = other.tracked_files_ttl_sec.load(); } explicit ObjectStorageQueueTableMetadata(const Poco::JSON::Object::Ptr & json); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 718da1abc8cf..8b60165d8f1b 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -287,6 +287,8 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( std::optional format_settings_, ASTStorage * engine_args, LoadingStrictnessLevel mode, + ObjectStorageQueueTableMetadata::Source source, + bool strict_metadata_check, bool keep_data_in_keeper_) : IStorage(table_id_) , WithContext(context_) @@ -403,6 +405,11 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( &zookeeper_name); LOG_INFO(log, "Using zookeeper path: {}", zk_path.string()); + if (strict_metadata_check && source.empty()) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Cannot identify the source of the queue: the Azure endpoint is not an `http://` or `https://` URL"); + auto table_metadata = ObjectStorageQueueMetadata::syncWithKeeper( zookeeper_name, zk_path, @@ -410,7 +417,8 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( storage_metadata.getColumns(), configuration_->format, context_, - is_attach, + source, + strict_metadata_check, log); ObjectStorageType storage_type = engine_name == "S3Queue" ? ObjectStorageType::S3 : ObjectStorageType::Azure; @@ -1460,10 +1468,40 @@ void StorageObjectStorageQueue::alter( SettingsChanges changed_settings; std::set new_settings_set; + std::set settings_in_query; + for (const auto & command : alter_commands) + { + for (const auto & change : command.settings_changes) + settings_in_query.insert(change.name); + settings_in_query.insert(command.settings_resets.begin(), command.settings_resets.end()); + } + const auto mode = getTableMetadata().getMode(); const size_t dependencies_count = getDependencies(); bool requires_detached_mv = false; + auto read_settings_in_keeper = [this]() + { + String metadata_in_keeper; + ObjectStorageQueueMetadata::getKeeperRetriesControl(log).retryLoop( + [&] { metadata_in_keeper = getZooKeeper()->get(zk_path / "metadata"); }); + const auto table_metadata_in_keeper = ObjectStorageQueueTableMetadata::parse(metadata_in_keeper); + return getSettings(&table_metadata_in_keeper); + }; + /// Shared by all tables with this `keeper_path` on this server, can differ from this table's `old_settings`. + auto local_shared_metadata_settings = getSettings(&getTableMetadata()); + std::optional settings_in_keeper; + auto differs_from_queue = [&](const SettingChange & setting) + { + if (!ObjectStorageQueueTableMetadata::isStoredInKeeper(setting.name) || !isSettingChangeable(setting.name, mode)) + return false; + if (local_shared_metadata_settings.get(setting.name) != setting.value) + return true; + if (!settings_in_keeper) + settings_in_keeper.emplace(read_settings_in_keeper()); + return settings_in_keeper->get(setting.name) != setting.value; + }; + for (auto & setting : new_settings) { LOG_TEST(log, "New setting {}: {}", setting.name, setting.value); @@ -1479,7 +1517,8 @@ void StorageObjectStorageQueue::alter( old_settings->begin(), old_settings->end(), [&](const SettingChange & change) { return change.name == setting.name; }); - setting_changed = it == old_settings->end() || it->value != setting.value; + setting_changed = it == old_settings->end() || it->value != setting.value + || (settings_in_query.contains(setting.name) && differs_from_queue(setting)); } if (!setting_changed) continue; @@ -1649,7 +1688,7 @@ StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const Ac shutdown_called); } -ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const +ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings(const ObjectStorageQueueTableMetadata * table_metadata_) const { /// We do not store queue settings /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), @@ -1657,14 +1696,14 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const ObjectStorageQueueSettings settings; /// If startup() for a table was not called, just use the default queue settings. /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. - if (!startup_finished) + if (!startup_finished && !table_metadata_) return settings; auto metadata = tryGetFilesMetadata(); if (!metadata) return settings; - const auto & table_metadata = metadata->getTableMetadata(); + const auto & table_metadata = table_metadata_ ? *table_metadata_ : metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index 902ec55b54bf..923579ae718b 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -33,6 +33,8 @@ class StorageObjectStorageQueue : public IStorage, WithContext std::optional format_settings_, ASTStorage * engine_args, LoadingStrictnessLevel mode, + ObjectStorageQueueTableMetadata::Source source, + bool strict_metadata_check, bool keep_data_in_keeper_); String getName() const override { return engine_name; } @@ -64,7 +66,7 @@ class StorageObjectStorageQueue : public IStorage, WithContext zkutil::ZooKeeperPtr getZooKeeper() const; - ObjectStorageQueueSettings getSettings() const; + ObjectStorageQueueSettings getSettings(const ObjectStorageQueueTableMetadata * table_metadata = nullptr) const; /// Can setting be changed via ALTER TABLE MODIFY SETTING query. static bool isSettingChangeable(const std::string & name, ObjectStorageQueueMode mode); diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index d7ddf6e5d128..5408a63d273b 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -4,6 +4,10 @@ #include #include #include +#include +#if CLICKHOUSE_CLOUD +#include +#endif #include #include #include @@ -11,6 +15,7 @@ #include #include #include +#include #if USE_AWS_S3 #include @@ -41,6 +46,40 @@ namespace ObjectStorageQueueSetting extern const ObjectStorageQueueSettingsBool use_hive_partitioning; } +namespace +{ + +#if USE_AWS_S3 +ObjectStorageQueueTableMetadata::Source getQueueSource(const StorageS3Configuration & configuration, const ContextPtr &) +{ + /// `S3::URI` keeps the user info in the endpoint or the bucket name, so such a URL is parsed again without it. + auto url = configuration.url; + if (!url.uri.getUserInfo().empty()) + { + Poco::URI uri = url.uri; + uri.setUserInfo(""); + url = S3::URI( + uri.toString(), + /*allow_archive_path_syntax*/ false, + /*keep_presigned_query_parameters*/ true); + } + return {configuration.getTypeName(), url.endpoint, url.bucket, configuration.getRawPath().path}; +} +#endif + +#if USE_AZURE_BLOB_STORAGE +ObjectStorageQueueTableMetadata::Source getQueueSource(const StorageAzureConfiguration & configuration, const ContextPtr &) +{ + String endpoint = configuration.getConnectionURLWithoutQuery(); + const Poco::URI uri(endpoint); + if (uri.getScheme() != "http" && uri.getScheme() != "https") + return {}; + return {configuration.getTypeName(), std::move(endpoint), configuration.getNamespace(), configuration.getRawPath().path}; +} +#endif + +} + template StoragePtr createQueueStorage(const StorageFactory::Arguments & args) { @@ -116,6 +155,20 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) } } + auto source = getQueueSource(*configuration, args.getLocalContext()); + source.from_named_collection = configuration->initialized_from_named_collection; + + /// Another replica of a `Replicated` database replays the definition that its initiator has checked. + const auto metadata_txn = args.getLocalContext()->getZooKeeperMetadataTransaction(); + bool is_secondary_ddl_replay = metadata_txn && !metadata_txn->isInitialQuery(); +#if CLICKHOUSE_CLOUD + is_secondary_ddl_replay |= args.getLocalContext()->getClientInfo().is_shared_catalog_internal + && !SharedDatabaseCatalog::isInitialQuery(args.getLocalContext()); +#endif + const bool is_replayed_definition = !isFreshTableDefinition(args.mode, args.query.attach_short_syntax) + || is_secondary_ddl_replay || args.getLocalContext()->isRecoveryFromStoredMetadata(); + const bool strict_metadata_check = (args.is_restore_from_backup && !is_secondary_ddl_replay) || !is_replayed_definition; + return std::make_shared( std::move(queue_settings), std::move(configuration), @@ -127,6 +180,8 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) format_settings, args.storage_def, args.mode, + std::move(source), + strict_metadata_check, /* keep_data_in_keeper */ false); } diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 4ced2fa21aa6..0f0e1ef7056e 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -279,7 +279,7 @@ AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & crea return; auto it = storages.find(storage.engine->name); if (it != storages.end() && it->second.features.get_export_access_fn) - res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes, /* own_engine */ true)); }; if (create.storage) @@ -292,13 +292,24 @@ AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & crea return res; } +AccessRightsElements StorageFactory::getExportAccess(const SettingsChanges & changes, const String & engine) const +{ + AccessRightsElements res; + for (const auto & [name, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes, name == engine)); + } + return res; +} + AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const { AccessRightsElements res; for (const auto & [_, creator] : storages) { if (creator.features.get_export_access_fn) - res.append_range(creator.features.get_export_access_fn(changes)); + res.append_range(creator.features.get_export_access_fn(changes, /* own_engine */ true)); } return res; } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index 6babf823c358..69e5da3abae7 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -37,7 +37,8 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. - using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + /// If `own_engine`, also the grants for settings that modify the source files, e.g. `after_processing` of a queue. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes, bool own_engine); struct Arguments { @@ -151,6 +152,8 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` /// table. An unknown engine needs nothing here: creating it fails later. AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// For `changes` of a table with `engine`: the destinations of every engine, as below, and the source files of `engine` only. + AccessRightsElements getExportAccess(const SettingsChanges & changes, const String & engine) const; /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; diff --git a/tests/integration/test_storage_s3_queue/test_0.py b/tests/integration/test_storage_s3_queue/test_0.py index 7216375fe5a8..7662c1a38204 100644 --- a/tests/integration/test_storage_s3_queue/test_0.py +++ b/tests/integration/test_storage_s3_queue/test_0.py @@ -91,6 +91,16 @@ def started_cluster(): stay_alive=True, ) + cluster.add_instance( + "instance_old", + with_zookeeper=True, + image="clickhouse/clickhouse-server", + # A release older than this one that is no longer supported, so it never gets the source hash in a backport. + tag="25.10", + with_installed_binary=True, + stay_alive=True, + ) + logging.info("Starting cluster...") cluster.start() logging.info("Cluster started") @@ -960,6 +970,43 @@ def test_multiple_tables_meta_mismatch(started_cluster): ) +def test_source_hash_after_upgrade(started_cluster): + """A queue that an older version created gets the hash of its source in Keeper after the upgrade.""" + node = started_cluster.instances["instance_old"] + keeper_path = f"/clickhouse/test_upgrade_{generate_random_string()}" + + def create_queue(name, bucket): + return f""" + CREATE TABLE {name} (x String) + ENGINE = S3Queue('http://localhost:11111/{bucket}/upgrade/*', NOSIGN, 'CSV') + SETTINGS mode = 'unordered', keeper_path = '{keeper_path}' + """ + + def get_source_hash(): + return node.query( + f"SELECT JSONExtractString(value, 'source_hash') FROM system.zookeeper " + f"WHERE path = '{keeper_path}' AND name = 'metadata'" + ).strip() + + try: + node.query(create_queue("queue", "test")) + assert get_source_hash() == "" + + node.restart_with_latest_version() + # Tables are loaded in the background, and a query to a table waits until it is loaded. + node.query("DESCRIBE TABLE queue") + assert get_source_hash() != "" + + # Now the source is checked: a queue of another bucket cannot use this `keeper_path`. + error = node.query_and_get_error(create_queue("other", "other")) + assert "differs in source" in error + node.query(create_queue("same", "test")) + finally: + node.query("DROP TABLE IF EXISTS queue SYNC") + node.query("DROP TABLE IF EXISTS same SYNC") + node.restart_with_original_version() + + def test_virtual_columns(started_cluster): start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") node = started_cluster.instances["instance"] diff --git a/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference new file mode 100644 index 000000000000..a2e64b66af38 --- /dev/null +++ b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference @@ -0,0 +1,27 @@ +2 +3 +1 +1 +1 0 +tq_a delete +tq_b delete +tq_a keep +tq_b keep +tq_a delete +tq_b delete +tq_a keep +tq_b keep +keep +tq_a 1 +tq_b 1 +1 +1 +tq_s1 keep +tq_s2 keep +keep +tag +keep keep +keep keep +5 +2 +1 diff --git a/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql new file mode 100644 index 000000000000..e4850d75a65d --- /dev/null +++ b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql @@ -0,0 +1,234 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` and `AzureQueue` engines are not built in the fast test. +-- zookeeper: the immutable part of the queue metadata lives under `keeper_path` in keeper. + +-- A queue table stores the settings listed in `ObjectStorageQueueTableMetadata::isStoredInKeeper` +-- under its `keeper_path` (docs/reference/engines/table-engines/integrations/s3queue.mdx, section +-- `keeper_path`). A second table pointed at the same path must agree with what is already stored +-- there, so each of the immutable fields below is rejected with `METADATA_MISMATCH` on its own. +-- The object storage is never contacted: the metadata check happens while the engine is built. + +DROP TABLE IF EXISTS tq_base; +DROP TABLE IF EXISTS tq_bucket_base; + +CREATE TABLE tq_base (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +-- `after_processing`: stored as 'keep', local 'delete'. +CREATE TABLE tq1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + after_processing = 'delete'; -- { serverError METADATA_MISMATCH } + +-- `bucketing_mode`: stored as 'path', local 'partition'. A 'partition' bucketing mode hashes the +-- partition key instead of the path, so `bucketing_mode = 'partition'` is rejected outright unless a +-- partitioning mode is set too. To vary `bucketing_mode` alone, a second keeper path already stores +-- `partitioning_mode = 'regex'`, which needs no experimental setting. +CREATE TABLE tq_bucket_base (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_bucket', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', partition_component = 'part', + processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +CREATE TABLE tq2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_bucket', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', partition_component = 'part', + bucketing_mode = 'partition'; -- { serverError METADATA_MISMATCH } + +-- `partitioning_mode`: stored as 'none', local 'regex'. The stored `partition_regex` and +-- `partition_component` differ too, but the partitioning mode is compared first. +CREATE TABLE tq3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', + partition_component = 'part'; -- { serverError METADATA_MISMATCH } + +-- `partition_regex`: stored empty, local set. +CREATE TABLE tq4 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partition_regex = '(?P.+)'; -- { serverError METADATA_MISMATCH } + +-- `partition_component`: stored empty, local set. +CREATE TABLE tq5 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partition_component = 'part'; -- { serverError METADATA_MISMATCH } + +-- `tracked_files_limit`: stored as the default 1000, local 7. +CREATE TABLE tq6 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + tracked_files_limit = 7; -- { serverError METADATA_MISMATCH } + +-- `tracked_files_ttl_sec`: stored as the default 0, local 60. +CREATE TABLE tq7 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + tracked_file_ttl_sec = 60; -- { serverError METADATA_MISMATCH } + +-- `last_processed_path`: stored empty, local set. +CREATE TABLE tq8 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + last_processed_path = 'a.csv'; -- { serverError METADATA_MISMATCH } + +-- `source`: stored path `05366_queue/*`, local path `05366_other/*`. +CREATE TABLE tq9 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_other/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366'; -- { serverError METADATA_MISMATCH } + +-- `source`: bucket `test0` with path `5366_queue/*` is another source than bucket `test` with path `05366_queue/*`. +CREATE TABLE tq10 (x String) ENGINE = S3Queue('http://localhost:11111/test0/5366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366'; -- { serverError METADATA_MISMATCH } + +-- Every mismatching table was rejected, so only the two base tables exist. +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name LIKE 'tq%'; + +-- The check is selective: a table that agrees on all of the immutable fields joins the same path. +CREATE TABLE tq_same (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name LIKE 'tq%'; + +DROP TABLE tq_same; +DROP TABLE tq_bucket_base; +DROP TABLE tq_base; + +-- An `AzureQueue` and an `S3Queue` with the same endpoint, bucket and path read different storages. +CREATE TABLE tq_type_azure (x String) ENGINE = AzureQueue('http://localhost:11111', 'test', '05366_type/*', 'devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_type'; +CREATE TABLE tq_type_s3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_type/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_type'; -- { serverError METADATA_MISMATCH } +DROP TABLE tq_type_azure; + +-- The user info of a URL is not a part of the source. +CREATE TABLE tq_u (x String) ENGINE = S3Queue('http://user:secret@localhost:11111/test/05366_u/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info'; +CREATE TABLE tq_u2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_u/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info'; +DROP TABLE tq_u2; DROP TABLE tq_u; +-- Paths that differ only in a part like `&sig=` are different sources. +CREATE TABLE tq_sig (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_root&sig=a/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sig'; +CREATE TABLE tq_sig_z (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_root&sig=z/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sig'; -- { serverError METADATA_MISMATCH } +DROP TABLE tq_sig; + +-- Azure forms that have a source: a scheme in upper case, and an `abfss` URL with a separate SAS. +CREATE TABLE tq_az_upper (x String) ENGINE = AzureQueue('HTTP://localhost:11111', 'test', '05366_upper/*', 'devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_upper'; +CREATE TABLE tq_az_sas (x String) ENGINE = AzureQueue('abfss://cont@acc.dfs.core.windows.net/05366_sas/*.csv', 'sv=1&sig=2') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sas'; +SELECT JSONExtractString(value, 'source_hash') != '' FROM system.zookeeper WHERE path IN ('/clickhouse/' || currentDatabase() || '/05366_upper', '/clickhouse/' || currentDatabase() || '/05366_sas') AND name = 'metadata' ORDER BY path; +DROP TABLE tq_az_upper; +DROP TABLE tq_az_sas; + +-- `send_logs_level` keeps the warnings of the attached tables, and the errors of the refused queries, out of the test output. +SET send_logs_level = 'fatal'; + +CREATE TABLE tq_a (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_shared/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1; +CREATE TABLE tq_b (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_shared/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1, after_processing = 'keep'; +-- Keeper has only a hash of the source. +SELECT JSONExtractString(value, 'source_hash') != '', value LIKE '%05366_shared%' FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; + +-- Tables with the same `keeper_path` share `after_processing`: after the `ALTER` of `tq_a` both tables have `delete`, +-- while `tq_b` still has `keep` in its definition. +ALTER TABLE tq_a MODIFY SETTING after_processing = 'delete'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +-- Set `keep` in keeper, as the initiator of a `Replicated` database does before this server runs the query: only the copy of +-- this server still has `delete`, and the `ALTER` to `keep` below must still change it. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"delete"', '"after_processing":"keep"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +-- `tq_b` already has `keep` in its definition, but an `ALTER` or a `RESET` to `keep` must still change the queue. +-- The same holds for `tq_a`, whose definition already has `delete`. +ALTER TABLE tq_b MODIFY SETTING after_processing = 'keep'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +ALTER TABLE tq_a MODIFY SETTING after_processing = 'delete'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +ALTER TABLE tq_b RESET SETTING after_processing; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +-- Leave `keep` in the definition of `tq_a` too, so that both tables can be attached again below. +ALTER TABLE tq_a MODIFY SETTING after_processing = 'keep'; +-- The same holds for any setting stored in keeper that an `ALTER` can change, e.g. `processing_threads_num`. +ALTER TABLE tq_a MODIFY SETTING processing_threads_num = 2; +ALTER TABLE tq_b MODIFY SETTING processing_threads_num = 1; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'processing_threads_num' ORDER BY table; + +-- A setting that the mode does not allow to change can still be repeated with the value of the definition, +-- also when the queue uses the value of another table (`tq_o1` uses 4 threads of `tq_o`). +CREATE TABLE tq_o (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_o/*', NOSIGN, 'CSV') SETTINGS mode = 'ordered', keeper_path = '/clickhouse/{database}/05366_o', processing_threads_num = 4; +CREATE TABLE tq_o1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_o/*', NOSIGN, 'CSV') SETTINGS mode = 'ordered', keeper_path = '/clickhouse/{database}/05366_o', processing_threads_num = 1; +ALTER TABLE tq_o MODIFY SETTING processing_threads_num = 4; +ALTER TABLE tq_o1 MODIFY SETTING processing_threads_num = 1, polling_max_timeout_ms = 2000; +SELECT create_table_query LIKE '%processing_threads_num = 1%polling_max_timeout_ms = 2000%' FROM system.tables WHERE database = currentDatabase() AND name = 'tq_o1'; +ALTER TABLE tq_o MODIFY SETTING processing_threads_num = 5; -- { serverError SUPPORT_IS_DISABLED } +DROP TABLE tq_o; +DROP TABLE tq_o1; + +-- `parallel_inserts` is not stored in keeper, so repeating its value next to another setting changes only the other one. +CREATE TABLE tq_p (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_p/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_p', parallel_inserts = 1; +ALTER TABLE tq_p MODIFY SETTING parallel_inserts = 1, polling_max_timeout_ms = 2000; +SELECT create_table_query LIKE '%parallel_inserts = 1%polling_max_timeout_ms = 2000%' FROM system.tables WHERE database = currentDatabase() AND name = 'tq_p'; +DROP TABLE tq_p; + +-- `after_processing` is still checked when a table is attached, as on master. A table that fails to attach cannot be +-- detached again in a `Replicated` database, so this uses an `Atomic` one. +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} ENGINE = Atomic; +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale', after_processing = 'keep'; +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale', after_processing = 'keep'; +-- After the `ALTER` of `tq_s1`, `tq_s2` still has `keep` in its definition and keeper has `delete`. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'delete'; +DETACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; -- { serverError METADATA_MISMATCH } +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'keep'; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() || '_1' AND table IN ('tq_s1', 'tq_s2') AND name = 'after_processing' ORDER BY table; + +-- Set `after_processing` to `keep` directly in keeper, as another server would, while the copy of this server has `delete`. +-- Then a reattached table and a new table fail instead of taking the outdated `delete`. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'delete'; +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2 MODIFY SETTING after_processing = 'delete'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"delete"', '"after_processing":"keep"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +DETACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; -- { serverError METADATA_MISMATCH } +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale'; -- { serverError METADATA_MISMATCH } +-- An `ALTER` of another setting needs no `WRITE` grant, so it must not write the outdated `delete` of this server back to keeper. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING polling_max_timeout_ms = 2000; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +-- An `ALTER` of `after_processing` itself is written to keeper. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'tag', after_processing_tag_key = 'k', after_processing_tag_value = 'v'; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} SYNC; + +-- Set `delete` directly in keeper, as another server would, while the definition and the copy of this server have +-- `keep`. An explicit `keep` must still reach keeper, by a `MODIFY` and by a `RESET`. +CREATE TABLE tq_k (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_k/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_k', after_processing = 'keep'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"keep"', '"after_processing":"delete"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k MODIFY SETTING after_processing = 'keep'; +SELECT JSONExtractString(value, 'after_processing'), (SELECT value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table = 'tq_k' AND name = 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"keep"', '"after_processing":"delete"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k RESET SETTING after_processing; +SELECT JSONExtractString(value, 'after_processing'), (SELECT value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table = 'tq_k' AND name = 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +-- An `ALTER` changes only the settings it names: `loading_retries` set by another server stays in keeper. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"loading_retries":10', '"loading_retries":5') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k MODIFY SETTING polling_max_timeout_ms = 2000; +SELECT JSONExtractUInt(value, 'loading_retries') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +DROP TABLE tq_k; + +-- Change the source in keeper: the tables must still attach, with a warning. +DETACH TABLE tq_a; DETACH TABLE tq_b; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpOne(value, '"source_hash":"[^"]*"', '"source_hash":"00"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +ATTACH TABLE tq_b; ATTACH TABLE tq_a; +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name IN ('tq_a', 'tq_b'); + +-- A named collection can change without an `ALTER` of the table, so a table that uses one must still match the source +-- in keeper when it attaches. Changing the source in keeper has the same effect as changing the collection. +CREATE TABLE tq_nc (x String) ENGINE = S3Queue(s3_conn, filename = '05366_nc/*', format = 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_nc'; +DETACH TABLE tq_nc; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpOne(value, '"source_hash":"[^"]*"', '"source_hash":"00"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_nc' AND name = 'metadata'; +ATTACH TABLE tq_nc; -- { serverError METADATA_MISMATCH } +-- Without a source in keeper, as in metadata of an older version, the table attaches and writes its source there. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpAll(value, ',"source_hash":"[^"]*"', '') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_nc' AND name = 'metadata'; +ATTACH TABLE tq_nc; +DROP TABLE tq_nc; + +-- Remove `source` from keeper, as in metadata of an older version: the first attached table writes it back. +-- A new table must not join such metadata, because it could belong to another source. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpAll(value, ',"source_hash":"[^"]*"', '') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +DETACH TABLE tq_a; DETACH TABLE tq_b; +CREATE TABLE tq_c (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_c/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1; -- { serverError METADATA_MISMATCH } +ATTACH TABLE tq_b; ATTACH TABLE tq_a; +SELECT JSONExtractString(value, 'source_hash') NOT IN ('', '00') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; + +DROP TABLE tq_b; +DROP TABLE tq_a; diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference index e5046dab0a10..e1c3ed4e18d6 100644 --- a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -7,6 +7,8 @@ settings that are not a destination: allowed -- ALTER with WRITE on S3 limited by a URL filter -- ALTER with WRITE on S3 destination with WRITE on S3: allowed +after_processing = 'delete' with WRITE on S3: allowed +after_processing = 'delete' in a Replicated database with WRITE on S3: allowed empty destination without WRITE on S3: allowed -- ALTER with WRITE on S3, restricted by a row policy empty destination with a row policy: allowed @@ -26,6 +28,7 @@ table without a destination: created 0 -- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 CREATE AS with WRITE on S3: created +after_processing = 'delete' with WRITE on S3: created materialized view with WRITE on S3: created RESTORE with WRITE on S3: restored RESTORE ON CLUSTER with WRITE on S3: restored diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh index 5699f7262195..1f5f12aad788 100755 --- a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -12,6 +12,7 @@ # `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) # source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. # `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. +# `after_processing` = `delete`, `move` or `tag` modifies the source files, so it also needs `WRITE` on the source. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -25,6 +26,7 @@ src="http://localhost:11111/test/${db}_move_src/" dst="http://localhost:11111/test/${db}_move_dst/" backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +backup_src="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_src')" keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" @@ -33,6 +35,9 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_alias SYNC; DROP TABLE IF EXISTS ${db}.t SYNC; DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_delete SYNC; + DROP TABLE IF EXISTS ${db}.t_src SYNC; + DROP TABLE IF EXISTS ${db}.t_src_other SYNC; DROP TABLE IF EXISTS ${db}.t_as SYNC; DROP TABLE IF EXISTS ${db}.t_as_src SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; @@ -42,6 +47,7 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_backup SYNC; DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP DATABASE IF EXISTS ${db}_replicated SYNC; DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; DROP USER IF EXISTS ${user_alter}, ${user_create}; " @@ -102,6 +108,18 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " -- { serverError ACCESS_DENIED } " +# `delete`, `move` and `tag` modify the source files, so they need `WRITE` on `S3` too. +for action in delete move tag; do + $CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing = '${action}' + -- { serverError ACCESS_DENIED } + " +done +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" + echo "-- ALTER ON CLUSTER is rejected by the initiator" $CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" @@ -109,6 +127,10 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} -- { serverError ACCESS_DENIED } " +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" @@ -143,6 +165,28 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} " && echo "destination with WRITE on S3: allowed" +# `AzureQueue` also has `after_processing`, but an `S3Queue` table needs no grant on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing = 'delete' +" && echo "after_processing = 'delete' with WRITE on S3: allowed" +$CLICKHOUSE_CLIENT -q "ALTER TABLE ${db}.t MODIFY SETTING after_processing = 'keep'" +# With `ON CLUSTER` the table on another host may be an `AzureQueue`, so both grants are needed. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" +# In a `Replicated` database the initiator checks the same grants. +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE DATABASE ${db}_replicated ENGINE = Replicated('/test/05441_${db}', 's1', 'r1'); + CREATE TABLE ${db}_replicated.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_replicated'; + GRANT ALTER SETTINGS, SELECT ON ${db}_replicated.t TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}_replicated.t MODIFY SETTING after_processing = 'delete' +" && echo "after_processing = 'delete' in a Replicated database with WRITE on S3: allowed" +$CLICKHOUSE_CLIENT -q "DROP DATABASE ${db}_replicated SYNC" + # Resetting the destination disables the move, so it needs no grant for a destination. $CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" $CLICKHOUSE_CLIENT --user "${user_alter}" -q " @@ -181,6 +225,10 @@ $CLICKHOUSE_CLIENT -q " ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} -- { serverError NOT_IMPLEMENTED } " +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing = 'delete' + -- { serverError NOT_IMPLEMENTED } +" $CLICKHOUSE_CLIENT -q " ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 " && echo "settings that are not a destination through an alias: allowed" @@ -206,6 +254,15 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -q " after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' -- { serverError ACCESS_DENIED } " +# `CREATE` with `delete`, `move` or `tag` needs `WRITE` on the source too. +for action in delete move tag; do + $CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = '${action}', + after_processing_move_prefix = 'p', after_processing_tag_key = 'k', after_processing_tag_value = 'v' + -- { serverError ACCESS_DENIED } + " +done # The same CREATE without a destination, or with an empty one, needs no grant for it. $CLICKHOUSE_CLIENT --user "${user_create}" -q " @@ -321,6 +378,20 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -m -q " SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; " +# `RESTORE` is checked like `CREATE`: a queue with a different source cannot use an existing `keeper_path`. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_src (x UInt8) ENGINE = S3Queue('${dst}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_src'; + BACKUP TABLE ${db}.t_src TO ${backup_src} FORMAT Null; + DROP TABLE ${db}.t_src SYNC; + CREATE TABLE ${db}.t_src_other (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_src'; +" +$CLICKHOUSE_CLIENT -q " + RESTORE TABLE ${db}.t_src FROM ${backup_src} SETTINGS structure_only = 1 FORMAT Null + -- { serverError METADATA_MISMATCH } +" + echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" # The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. @@ -328,6 +399,10 @@ $CLICKHOUSE_CLIENT -q "GRANT WRITE ON S3 TO ${user_create}" $CLICKHOUSE_CLIENT --user "${user_create}" -q " CREATE TABLE ${db}.t_as AS ${db}.t_as_src " && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_delete (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_delete', after_processing = 'delete' +" && echo "after_processing = 'delete' with WRITE on S3: created" $CLICKHOUSE_CLIENT --user "${user_create}" -q " CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', @@ -363,6 +438,9 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_alias SYNC; DROP TABLE IF EXISTS ${db}.t SYNC; DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_delete SYNC; + DROP TABLE IF EXISTS ${db}.t_src SYNC; + DROP TABLE IF EXISTS ${db}.t_src_other SYNC; DROP TABLE IF EXISTS ${db}.t_as SYNC; DROP TABLE IF EXISTS ${db}.t_as_src SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; @@ -372,6 +450,7 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_backup SYNC; DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP DATABASE IF EXISTS ${db}_replicated SYNC; DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; DROP USER IF EXISTS ${user_alter}, ${user_create}; " From 98ce18ed6d8a68c21479aaef27ab74be88b83d84 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 23 Nov 2026 16:02:39 +0000 Subject: [PATCH 075/116] Update autogenerated version to 26.3.70.5 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index aacbec831bd3..0008486649f8 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54577) +SET(VERSION_REVISION 54578) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 70) -SET(VERSION_GITHASH 414926d4672ef6d14b9370239931cd49c3c15170) -SET(VERSION_DESCRIBE v26.3.70.1-lts) -SET(VERSION_STRING 26.3.70.1) +SET(VERSION_PATCH 71) +SET(VERSION_GITHASH bf0deed7c0db58f539d8181466ea631775dcbceb) +SET(VERSION_DESCRIBE v26.3.71.1-lts) +SET(VERSION_STRING 26.3.71.1) # end of autochange From 02c1c38c65ddc18626b67b112cbb91c83029f115 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 23 Nov 2026 21:33:33 +0000 Subject: [PATCH 076/116] Backport #133828 to 26.3: Mask the key of keyed SipHash functions in logged queries --- src/Functions/FunctionsHashingMisc.cpp | 9 ++++-- .../05871_keyed_siphash_key_masking.reference | 20 ++++++++++++ .../05871_keyed_siphash_key_masking.sql | 32 +++++++++++++++++++ 3 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference create mode 100644 tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql diff --git a/src/Functions/FunctionsHashingMisc.cpp b/src/Functions/FunctionsHashingMisc.cpp index 5f62049418a4..d1a9803a1455 100644 --- a/src/Functions/FunctionsHashingMisc.cpp +++ b/src/Functions/FunctionsHashingMisc.cpp @@ -11,6 +11,9 @@ namespace DB REGISTER_FUNCTION(Hashing) { + /// The key argument (1st arg) in "keyed" hash functions is secret. Block it from appearing in the query_log. + const SecretArgumentsSpec keyed_hash_secret_arguments{.positional_secret_slots = {0}}; + FunctionDocumentation::Description sipHash64_description = R"( Produces a 64-bit [SipHash](https://en.wikipedia.org/wiki/SipHash) hash value. @@ -72,7 +75,7 @@ Like [`sipHash64`](#sipHash64) but additionally takes an explicit key argument i FunctionDocumentation::IntroducedIn sipHash64Keyed_introduced_in = {23, 2}; FunctionDocumentation::Category sipHash64Keyed_category = FunctionDocumentation::Category::Hash; FunctionDocumentation sipHash64Keyed_documentation = {sipHash64Keyed_description, sipHash64Keyed_syntax, sipHash64Keyed_arguments, {}, sipHash64Keyed_returned_value, sipHash64Keyed_examples, sipHash64Keyed_introduced_in, sipHash64Keyed_category}; - factory.registerFunction(sipHash64Keyed_documentation); + factory.registerFunction(sipHash64Keyed_documentation, FunctionFactory::Case::Sensitive, keyed_hash_secret_arguments); FunctionDocumentation::Description sipHash128_description = R"( Like [`sipHash64`](#sipHash64) but produces a 128-bit hash value, i.e. the final xor-folding state is done up to 128 bits. @@ -133,7 +136,7 @@ New projects should probably use [`sipHash128ReferenceKeyed`](#sipHash128Referen FunctionDocumentation::IntroducedIn sipHash128Keyed_introduced_in = {23, 2}; FunctionDocumentation::Category sipHash128Keyed_category = FunctionDocumentation::Category::Hash; FunctionDocumentation sipHash128Keyed_documentation = {sipHash128Keyed_description, sipHash128Keyed_syntax, sipHash128Keyed_arguments, {}, sipHash128Keyed_returned_value, sipHash128Keyed_examples, sipHash128Keyed_introduced_in, sipHash128Keyed_category}; - factory.registerFunction(sipHash128Keyed_documentation); + factory.registerFunction(sipHash128Keyed_documentation, FunctionFactory::Case::Sensitive, keyed_hash_secret_arguments); FunctionDocumentation::Description sipHash128Ref_description = R"( Like [`sipHash128`](/sql-reference/functions/hash-functions#sipHash128) but implements the 128-bit algorithm from the original authors of SipHash. @@ -182,7 +185,7 @@ Same as [`sipHash128Reference`](#sipHash128Reference) but additionally takes an FunctionDocumentation::IntroducedIn sipHash128RefKeyed_introduced_in = {23, 2}; FunctionDocumentation::Category sipHash128RefKeyed_category = FunctionDocumentation::Category::Hash; FunctionDocumentation sipHash128RefKeyed_documentation = {sipHash128RefKeyed_description, sipHash128RefKeyed_syntax, sipHash128RefKeyed_arguments, {}, sipHash128RefKeyed_returned_value, sipHash128RefKeyed_examples, sipHash128RefKeyed_introduced_in, sipHash128RefKeyed_category}; - factory.registerFunction(sipHash128RefKeyed_documentation); + factory.registerFunction(sipHash128RefKeyed_documentation, FunctionFactory::Case::Sensitive, keyed_hash_secret_arguments); FunctionDocumentation::Description cityHash64_description = R"( Produces a 64-bit [CityHash](https://github.com/google/cityhash) hash value. diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference new file mode 100644 index 000000000000..f7167d89dfe9 --- /dev/null +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference @@ -0,0 +1,20 @@ +-- The key (the first argument) of the keyed SipHash functions must not be visible in formatted or logged queries. + +-- { echoOn } +EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash64Keyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash128Keyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +-- A key which is not a literal is hidden as well. +EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); +SELECT sipHash64Keyed(\'[HIDDEN]\', \'visible_input\')\nFROM numbers(1) +-- The functions without a key are not affected. +EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); +SELECT sipHash64(tuple(CAST(\'1311768467463790320\', \'UInt64\'), CAST(\'18364758544493064720\', \'UInt64\')), \'visible_input\')\nFROM system.one +1 +SELECT sipHash128Keyed(\'[HIDDEN]\', \'logged_input_2\') FORMAT `Null` +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', \'logged_input_3\') FORMAT `Null` +SELECT sipHash64Keyed(\'[HIDDEN]\', \'logged_input_1\') FORMAT `Null` +0 diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql new file mode 100644 index 000000000000..ae1de74058d0 --- /dev/null +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql @@ -0,0 +1,32 @@ +-- The key (the first argument) of the keyed SipHash functions must not be visible in formatted or logged queries. + +-- { echoOn } +EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); + +-- A key which is not a literal is hidden as well. +EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); + +-- The functions without a key are not affected. +EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); +-- { echoOff } + +-- Masking does not change the result. +SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input') = sipHash64Keyed((materialize(1311768467463790320::UInt64), 18364758544493064720::UInt64), 'visible_input'); + +SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_1') FORMAT Null; +SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_2') FORMAT Null; +SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_3') FORMAT Null; + +SYSTEM FLUSH LOGS query_log; + +SELECT query +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE '%logged\_input\__%' AND query NOT LIKE '%system.query_log%' +ORDER BY query; + +SELECT count() +FROM system.query_log +WHERE current_database = currentDatabase() AND query NOT LIKE '%system.query_log%' + AND (query LIKE '%1311768467463790320%' OR query LIKE '%18364758544493064720%') AND query NOT LIKE '%sipHash64(%'; From 8abb772cdbdb7a512d88b4c4a86d1a2fc3eda7f5 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 23 Nov 2026 22:39:29 +0000 Subject: [PATCH 077/116] Backport #133530 to 26.3: Fix handling of groups and named unions in CapnProto format --- src/Formats/CapnProtoSerializer.cpp | 64 +++++++++++++++---- src/Formats/FormatSchemaInfo.cpp | 9 +-- .../05843_capnproto_group_fields.reference | 44 +++++++++++++ .../05843_capnproto_group_fields.sql | 63 ++++++++++++++++++ ...4_capnproto_flattened_list_sizes.reference | 8 +++ .../05844_capnproto_flattened_list_sizes.sql | 27 ++++++++ 6 files changed, 195 insertions(+), 20 deletions(-) create mode 100644 tests/queries/0_stateless/05843_capnproto_group_fields.reference create mode 100644 tests/queries/0_stateless/05843_capnproto_group_fields.sql create mode 100644 tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference create mode 100644 tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql diff --git a/src/Formats/CapnProtoSerializer.cpp b/src/Formats/CapnProtoSerializer.cpp index 0daca1c6e51d..77e635b289ab 100644 --- a/src/Formats/CapnProtoSerializer.cpp +++ b/src/Formats/CapnProtoSerializer.cpp @@ -35,6 +35,7 @@ namespace ErrorCodes extern const int CAPN_PROTO_BAD_CAST; extern const int INCORRECT_DATA; extern const int ILLEGAL_COLUMN; + extern const int SIZES_OF_ARRAYS_DONT_MATCH; } namespace @@ -96,17 +97,38 @@ namespace std::vector> field_builders; }; + /// A group (or a named union) is stored inline in its parent struct: it has no slot and shares the parent's storage. + bool isGroup(const capnp::StructSchema & schema) + { + return schema.getProto().getStruct().getIsGroup(); + } + + UInt32 getFieldSlotOffset(const capnp::StructSchema::Field & field) + { + auto proto = field.getProto(); + return proto.isSlot() ? proto.getSlot().getOffset() : 0; + } + template std::unique_ptr initStructBuilder(ParentBuilder & parent_builder, UInt32 offset_or_index, const capnp::_::StructSize & struct_size, size_t elements, const capnp::StructSchema & schema) { capnp::DynamicStruct::Builder builder_impl; if constexpr (std::is_same_v) - builder_impl = capnp::DynamicStruct::Builder(schema, parent_builder.getBuilderImpl().getPointerField(offset_or_index).initStruct(struct_size)); + { + auto parent_impl = parent_builder.getBuilderImpl(); + builder_impl = capnp::DynamicStruct::Builder(schema, isGroup(schema) ? parent_impl : parent_impl.getPointerField(offset_or_index).initStruct(struct_size)); + } else builder_impl = capnp::DynamicStruct::Builder(schema, parent_builder.getBuilderImpl().getStructElement(offset_or_index)); return std::make_unique(std::move(builder_impl), elements); } + capnp::DynamicStruct::Reader getStructReader(const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset, const capnp::StructSchema & schema) + { + auto parent_impl = parent_struct_reader.getReaderImpl(); + return capnp::DynamicStruct::Reader(schema, isGroup(schema) ? parent_impl : parent_impl.getPointerField(slot_offset).getStruct(nullptr)); + } + class ICapnProtoSerializer { public: @@ -927,15 +949,18 @@ namespace auto first = union_fields[0]; auto second = union_fields[1]; auto nested_type = assert_cast(data_type.get())->getNestedType(); - nested_slot_offset = first.getProto().getSlot().getOffset(); /// Both fields have the same offset. + /// The offset of the value is taken from the non-`Void` member: `Void` always has offset 0, + /// while the value of a union declared inline in a struct can be in any slot of that struct. if (first.getType().isVoid()) { + nested_slot_offset = getFieldSlotOffset(second); nested_serializer = createSerializer(nested_type, column_name, second.getType(), settings); null_discriminant = 0; nested_discriminant = 1; } else if (second.getType().isVoid()) { + nested_slot_offset = getFieldSlotOffset(first); nested_serializer = createSerializer(nested_type, column_name, first.getType(), settings); null_discriminant = 1; nested_discriminant = 0; @@ -961,7 +986,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -983,9 +1008,8 @@ namespace const auto & nullable_column = assert_cast(*column); if (nullable_column.isNullAt(row_num)) { - auto struct_builder_impl = struct_builder.impl.getBuilderImpl(); - struct_builder_impl.setDataField(discriminant_offset, null_discriminant); - struct_builder_impl.setDataField(nested_slot_offset, capnp::Void()); + /// `Void` occupies no space, so only the discriminant is written. + struct_builder.impl.getBuilderImpl().setDataField(discriminant_offset, null_discriminant); } else { @@ -1078,6 +1102,14 @@ namespace field_builder = std::make_unique(capnp::DynamicList::Builder(list_schema, initListBuilder(parent_builder, offset_or_index, size)), size); auto & list_builder = assert_cast(*field_builder); + /// Several columns with flattened names (like `l.x` and `l.y`) write to the same list. + if (list_builder.nested_builders.size() != size) + throw Exception( + ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH, + "Arrays that are written to the same CapnProto list have different sizes: {} and {}", + list_builder.nested_builders.size(), + size); + for (UInt32 i = 0; i != size; ++i) nested_serializer->writeRow(nested_column, list_builder.nested_builders[i], list_builder.impl, i, offset + i); } @@ -1198,7 +1230,7 @@ namespace Names names = {"key", "value"}; auto entries_type = std::make_shared(std::make_shared(types, names)); nested_serializer = createSerializer(entries_type, column_name, field_type, settings); - entries_slot_offset = struct_schema.getFields()[0].getProto().getSlot().getOffset(); + entries_slot_offset = getFieldSlotOffset(struct_schema.getFields()[0]); } void writeRow(const ColumnPtr & column, std::unique_ptr & field_builder, capnp::DynamicStruct::Builder & parent_struct_builder, UInt32 slot_offset, size_t row_num) override @@ -1213,7 +1245,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -1273,6 +1305,7 @@ namespace data_type->getName(), getCapnProtoFullTypeName(capnp_type)); + is_tuple = true; const auto * tuple_data_type = assert_cast(data_type.get()); auto nested_types = tuple_data_type->getElements(); Names nested_names; @@ -1328,7 +1361,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -1363,7 +1396,7 @@ namespace auto capnp_type = field->getType(); fields_serializers.push_back(createSerializer(data_types[i], names[i], capnp_type, settings)); - fields_offsets.push_back(field->getProto().getSlot().getOffset()); + fields_offsets.push_back(getFieldSlotOffset(*field)); fields_indexes.push_back(field->getIndex()); } } @@ -1375,9 +1408,9 @@ namespace field_builder = initStructBuilder(parent_builder, offset_or_index, struct_size, fields_count, struct_schema); auto & struct_builder = assert_cast(*field_builder); - if (const auto * tuple_column = typeid_cast(column.get())) + if (is_tuple) { - const auto & columns = tuple_column->getColumns(); + const auto & columns = assert_cast(*column).getColumns(); for (size_t i = 0; i != columns.size(); ++i) fields_serializers[i]->writeRow(columns[i], struct_builder.field_builders[fields_indexes[i]], struct_builder.impl, fields_offsets[i], row_num); } @@ -1389,8 +1422,9 @@ namespace void readRowImpl(IColumn & column, const capnp::DynamicStruct::Reader & struct_reader) { - if (auto * tuple_column = typeid_cast(&column)) + if (is_tuple) { + auto * tuple_column = assert_cast(&column); auto read_tuple = [&]() { for (size_t i = 0; i != tuple_column->tupleSize(); ++i) @@ -1406,6 +1440,10 @@ namespace capnp::StructSchema struct_schema; capnp::_::StructSize struct_size; size_t fields_count; + /// True if the struct is mapped to a `Tuple` column, one field per tuple element. + /// Otherwise the serializer is the root one or an adapter for a flattened column name (`a.b`) + /// with a single field, which gets the whole column, even if the column itself is a `Tuple`. + bool is_tuple = false; std::vector> fields_serializers; std::vector fields_offsets; std::vector fields_indexes; diff --git a/src/Formats/FormatSchemaInfo.cpp b/src/Formats/FormatSchemaInfo.cpp index aa76491a33d7..d3e4fdc044f5 100644 --- a/src/Formats/FormatSchemaInfo.cpp +++ b/src/Formats/FormatSchemaInfo.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include namespace DB @@ -291,12 +290,8 @@ void FormatSchemaInfo::storeSchemaOnDisk(const fs::path & file_path, const Strin out.sync(); out.close(); - if (fs::exists(file_path)) - DB::renameExchange(temp_path, file_path); - else - DB::renameNoReplace(temp_path, file_path); - - fs::remove(temp_path); + /// `rename` replaces the target atomically, so a concurrent writer of the same schema cannot make it fail. + fs::rename(temp_path, file_path); } catch (...) { diff --git a/tests/queries/0_stateless/05843_capnproto_group_fields.reference b/tests/queries/0_stateless/05843_capnproto_group_fields.reference new file mode 100644 index 000000000000..920aaa9d364b --- /dev/null +++ b/tests/queries/0_stateless/05843_capnproto_group_fields.reference @@ -0,0 +1,44 @@ +two groups in a struct without pointers +6 1 2 3 +20971526 4 5 6 +117440518 7 8 9 +16045690984833335023 1229782938533634594 3689348815028241476 18446744073709551615 +the same as tuples +(6) 1 2 (3) +(20971526) 4 5 (6) +groups in a struct with pointers +a (6,'b',(7)) c +dd (20971526,'ee',(4294967295)) ff +named unions +6 1 a +\N 2 \N +20971526 3 \N +\N 4 b +groups in a nested struct and in a list +303132335758595A343536376162636438392D2D65666768 (1,(7)) [((6,'a')),((20971526,'b'))] +0600400100000000 (2,(20971526)) [] +null-first named unions after other fields +42 a 7 b +43 c \N \N +44 d 20971526 \N +45 e \N f +the same data read as plain fields +42 a 1 7 1 b +43 c 0 0 0 +44 d 1 20971526 0 +45 e 0 0 1 f +a tuple under a flattened name in a group +(6,7) 1 +(20971526,117440518) 2 +6 7 1 +20971526 117440518 2 +a tuple under a flattened name in a struct +(6,7) 1 +(20971526,117440518) 2 +6 7 1 +20971526 117440518 2 +schema inference +g Tuple(\n x UInt64) +m1 UInt64 +m2 UInt64 +h Tuple(\n y UInt64) diff --git a/tests/queries/0_stateless/05843_capnproto_group_fields.sql b/tests/queries/0_stateless/05843_capnproto_group_fields.sql new file mode 100644 index 000000000000..da33b61bbd3e --- /dev/null +++ b/tests/queries/0_stateless/05843_capnproto_group_fields.sql @@ -0,0 +1,63 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the Cap'n Proto format is not built in the Fast test build. + +-- A group (or a named union) is stored inline in its parent struct, not behind a pointer. + +SET output_format_parallel_formatting = 0; +SET input_format_parallel_parsing = 0; +-- The `file` table function is used so that both the writer and the reader use the schema below. +SET engine_file_truncate_on_insert = 1; + +SET format_schema_source = 'string'; +SET format_schema = '@0xd508eaf2a79b4a10; struct Inner { a @0 :UInt64; g :group { x @1 :UInt64; } } struct Elem { g :group { x @0 :UInt64; s @1 :Text; } } struct TwoGroups { g :group { x @0 :UInt64; } m1 @1 :UInt64; m2 @2 :UInt64; h :group { y @3 :UInt64; } } struct WithPointers { s1 @0 :Text; g :group { x @1 :UInt64; s @2 :Text; n :group { y @3 :UInt32; } } s2 @4 :Text; } struct NamedUnion { n :union { value @0 :UInt64; null @1 :Void; } m @2 :UInt64; t :union { null @3 :Void; value @4 :Text; } } struct Nested { blob @0 :Data; inner @1 :Inner; elems @2 :List(Elem); } struct NullFirst { prefix @0 :UInt64; s @1 :Text; n :union { null @2 :Void; value @3 :UInt64; } t :union { null @4 :Void; value @5 :Text; } } struct NullFirstPlain { prefix @0 :UInt64; s @1 :Text; nTag @2 :UInt16; nValue @3 :UInt64; tTag @4 :UInt16; tValue @5 :Text; } struct FlatGroups { g :group { h :group { x @0 :UInt64; y @1 :UInt64; } z @2 :UInt64; } } struct Pair { x @0 :UInt64; y @1 :UInt64; } struct Mid { h @0 :Pair; z @1 :UInt64; } struct FlatStructs { g @0 :Mid; }'; + +SELECT 'two groups in a struct without pointers'; +SET format_schema_message_name = 'TwoGroups'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_1.capnp', CapnProto, '`g.x` UInt64, m1 UInt64, m2 UInt64, `h.y` UInt64') VALUES (6, 1, 2, 3), (20971526, 4, 5, 6), (117440518, 7, 8, 9), (16045690984833335023, 1229782938533634594, 3689348815028241476, 18446744073709551615); +SELECT * FROM file(currentDatabase() || '_05843_1.capnp', CapnProto, '`g.x` UInt64, m1 UInt64, m2 UInt64, `h.y` UInt64') ORDER BY m1; + +SELECT 'the same as tuples'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_2.capnp', CapnProto, 'g Tuple(x UInt64), m1 UInt64, m2 UInt64, h Tuple(y UInt64)') VALUES ((6), 1, 2, (3)), ((20971526), 4, 5, (6)); +SELECT * FROM file(currentDatabase() || '_05843_2.capnp', CapnProto, 'g Tuple(x UInt64), m1 UInt64, m2 UInt64, h Tuple(y UInt64)') ORDER BY m1; + +SELECT 'groups in a struct with pointers'; +SET format_schema_message_name = 'WithPointers'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_3.capnp', CapnProto, 's1 String, g Tuple(x UInt64, s String, n Tuple(y UInt32)), s2 String') VALUES ('a', (6, 'b', (7)), 'c'), ('dd', (20971526, 'ee', (4294967295)), 'ff'); +SELECT * FROM file(currentDatabase() || '_05843_3.capnp', CapnProto, 's1 String, g Tuple(x UInt64, s String, n Tuple(y UInt32)), s2 String') ORDER BY s1; + +SELECT 'named unions'; +SET format_schema_message_name = 'NamedUnion'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_4.capnp', CapnProto, 'n Nullable(UInt64), m UInt64, t Nullable(String)') VALUES (6, 1, 'a'), (NULL, 2, NULL), (20971526, 3, NULL), (NULL, 4, 'b'); +SELECT * FROM file(currentDatabase() || '_05843_4.capnp', CapnProto, 'n Nullable(UInt64), m UInt64, t Nullable(String)') ORDER BY m; + +SELECT 'groups in a nested struct and in a list'; +SET format_schema_message_name = 'Nested'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_5.capnp', CapnProto, 'blob String, inner Tuple(a UInt64, g Tuple(x UInt64)), elems Array(Tuple(g Tuple(x UInt64, s String)))') VALUES ('0123WXYZ4567abcd89--efgh', (1, (7)), [((6, 'a')), ((20971526, 'b'))]), (unhex('0600400100000000'), (2, (20971526)), []); +SELECT hex(blob), inner, elems FROM file(currentDatabase() || '_05843_5.capnp', CapnProto, 'blob String, inner Tuple(a UInt64, g Tuple(x UInt64)), elems Array(Tuple(g Tuple(x UInt64, s String)))') ORDER BY inner.a; + +-- The value of a union is not in the slot 0 here, unlike its `Void` member. +SELECT 'null-first named unions after other fields'; +SET format_schema_message_name = 'NullFirst'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, n Nullable(UInt64), t Nullable(String)') VALUES (42, 'a', 7, 'b'), (43, 'c', NULL, NULL), (44, 'd', 20971526, NULL), (45, 'e', NULL, 'f'); +SELECT * FROM file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, n Nullable(UInt64), t Nullable(String)') ORDER BY prefix; + +-- `NullFirstPlain` has the same layout as `NullFirst`, with the discriminants of the unions as ordinary fields. +SELECT 'the same data read as plain fields'; +SET format_schema_message_name = 'NullFirstPlain'; +SELECT * FROM file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, nTag UInt16, nValue UInt64, tTag UInt16, tValue String') ORDER BY prefix; + +SELECT 'a tuple under a flattened name in a group'; +SET format_schema_message_name = 'FlatGroups'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') VALUES ((6, 7), 1), ((20971526, 117440518), 2); +SELECT * FROM file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') ORDER BY `g.z`; +SELECT * FROM file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h.x` UInt64, `g.h.y` UInt64, `g.z` UInt64') ORDER BY `g.z`; + +SELECT 'a tuple under a flattened name in a struct'; +SET format_schema_message_name = 'FlatStructs'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') VALUES ((6, 7), 1), ((20971526, 117440518), 2); +SELECT * FROM file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') ORDER BY `g.z`; +SELECT * FROM file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h.x` UInt64, `g.h.y` UInt64, `g.z` UInt64') ORDER BY `g.z`; + +SELECT 'schema inference'; +SET format_schema_message_name = 'TwoGroups'; +DESC format(CapnProto, ''); diff --git a/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference new file mode 100644 index 000000000000..b5535d7646e5 --- /dev/null +++ b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference @@ -0,0 +1,8 @@ +a list in a group +([],[]) +([1],[2]) +([3,4],[5,6]) +a list in a struct +([],[]) +([1],[2]) +([3,4],[5,6]) diff --git a/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql new file mode 100644 index 000000000000..36c42eb0304c --- /dev/null +++ b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql @@ -0,0 +1,27 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the Cap'n Proto format is not built in the Fast test build. + +-- Columns with flattened names (like `l.x` and `l.y`) are written to the same list, so the sizes of their arrays must match. +-- For top-level columns it is also checked on `INSERT` before the format, so the flattened names are put inside a `Tuple` +-- to reach the check in the format itself, like `SELECT ... FORMAT CapnProto` does. + +SET output_format_parallel_formatting = 0; +SET input_format_parallel_parsing = 0; +SET engine_file_truncate_on_insert = 1; + +SET format_schema_source = 'string'; +SET format_schema = '@0xeed9ecfa9f9df117; struct E { x @0 :UInt64; y @1 :UInt64; } struct T { l @0 :List(E); } struct InGroup { t :group { l @0 :List(E); } } struct InStruct { t @0 :T; }'; + +SELECT 'a list in a group'; +SET format_schema_message_name = 'InGroup'; +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([1, 2], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') VALUES (([], [])), (([1], [2])), (([3, 4], [5, 6])); +SELECT * FROM file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') ORDER BY length(t.1); + +SELECT 'a list in a struct'; +SET format_schema_message_name = 'InStruct'; +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([1, 2], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') VALUES (([], [])), (([1], [2])), (([3, 4], [5, 6])); +SELECT * FROM file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') ORDER BY length(t.1); From f5f8158b748980acd09f8ff8cc825d66dc347411 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Tue, 24 Nov 2026 15:12:04 +0000 Subject: [PATCH 078/116] Update autogenerated version to 26.3.71.3 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index 0008486649f8..c39ad8897825 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54578) +SET(VERSION_REVISION 54579) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 71) -SET(VERSION_GITHASH bf0deed7c0db58f539d8181466ea631775dcbceb) -SET(VERSION_DESCRIBE v26.3.71.1-lts) -SET(VERSION_STRING 26.3.71.1) +SET(VERSION_PATCH 72) +SET(VERSION_GITHASH 7100b1a7cf9138b947e94017164a35223581fc21) +SET(VERSION_DESCRIBE v26.3.72.1-lts) +SET(VERSION_STRING 26.3.72.1) # end of autochange From e8d6837ab67fe2a9083d8256d94712bd98a11dd8 Mon Sep 17 00:00:00 2001 From: Robert Schulze Date: Tue, 24 Nov 2026 20:03:12 +0000 Subject: [PATCH 079/116] Fix --- src/Functions/FunctionsHashingMisc.cpp | 9 +++------ src/Parsers/FunctionSecretArgumentsFinder.cpp | 7 +++++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Functions/FunctionsHashingMisc.cpp b/src/Functions/FunctionsHashingMisc.cpp index d1a9803a1455..5f62049418a4 100644 --- a/src/Functions/FunctionsHashingMisc.cpp +++ b/src/Functions/FunctionsHashingMisc.cpp @@ -11,9 +11,6 @@ namespace DB REGISTER_FUNCTION(Hashing) { - /// The key argument (1st arg) in "keyed" hash functions is secret. Block it from appearing in the query_log. - const SecretArgumentsSpec keyed_hash_secret_arguments{.positional_secret_slots = {0}}; - FunctionDocumentation::Description sipHash64_description = R"( Produces a 64-bit [SipHash](https://en.wikipedia.org/wiki/SipHash) hash value. @@ -75,7 +72,7 @@ Like [`sipHash64`](#sipHash64) but additionally takes an explicit key argument i FunctionDocumentation::IntroducedIn sipHash64Keyed_introduced_in = {23, 2}; FunctionDocumentation::Category sipHash64Keyed_category = FunctionDocumentation::Category::Hash; FunctionDocumentation sipHash64Keyed_documentation = {sipHash64Keyed_description, sipHash64Keyed_syntax, sipHash64Keyed_arguments, {}, sipHash64Keyed_returned_value, sipHash64Keyed_examples, sipHash64Keyed_introduced_in, sipHash64Keyed_category}; - factory.registerFunction(sipHash64Keyed_documentation, FunctionFactory::Case::Sensitive, keyed_hash_secret_arguments); + factory.registerFunction(sipHash64Keyed_documentation); FunctionDocumentation::Description sipHash128_description = R"( Like [`sipHash64`](#sipHash64) but produces a 128-bit hash value, i.e. the final xor-folding state is done up to 128 bits. @@ -136,7 +133,7 @@ New projects should probably use [`sipHash128ReferenceKeyed`](#sipHash128Referen FunctionDocumentation::IntroducedIn sipHash128Keyed_introduced_in = {23, 2}; FunctionDocumentation::Category sipHash128Keyed_category = FunctionDocumentation::Category::Hash; FunctionDocumentation sipHash128Keyed_documentation = {sipHash128Keyed_description, sipHash128Keyed_syntax, sipHash128Keyed_arguments, {}, sipHash128Keyed_returned_value, sipHash128Keyed_examples, sipHash128Keyed_introduced_in, sipHash128Keyed_category}; - factory.registerFunction(sipHash128Keyed_documentation, FunctionFactory::Case::Sensitive, keyed_hash_secret_arguments); + factory.registerFunction(sipHash128Keyed_documentation); FunctionDocumentation::Description sipHash128Ref_description = R"( Like [`sipHash128`](/sql-reference/functions/hash-functions#sipHash128) but implements the 128-bit algorithm from the original authors of SipHash. @@ -185,7 +182,7 @@ Same as [`sipHash128Reference`](#sipHash128Reference) but additionally takes an FunctionDocumentation::IntroducedIn sipHash128RefKeyed_introduced_in = {23, 2}; FunctionDocumentation::Category sipHash128RefKeyed_category = FunctionDocumentation::Category::Hash; FunctionDocumentation sipHash128RefKeyed_documentation = {sipHash128RefKeyed_description, sipHash128RefKeyed_syntax, sipHash128RefKeyed_arguments, {}, sipHash128RefKeyed_returned_value, sipHash128RefKeyed_examples, sipHash128RefKeyed_introduced_in, sipHash128RefKeyed_category}; - factory.registerFunction(sipHash128RefKeyed_documentation, FunctionFactory::Case::Sensitive, keyed_hash_secret_arguments); + factory.registerFunction(sipHash128RefKeyed_documentation); FunctionDocumentation::Description cityHash64_description = R"( Produces a 64-bit [CityHash](https://github.com/google/cityhash) hash value. diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index e2698652f3fc..a56d79bd68aa 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -401,6 +401,13 @@ void FunctionSecretArgumentsFinder::findOrdinaryFunctionSecretArguments() /// HMAC('mode', 'message', 'key') -> HMAC('mode', 'message', '[HIDDEN]') findHMACSecretArguments(); } + else if ((function->name() == "sipHash64Keyed") || (function->name() == "sipHash128Keyed") + || (function->name() == "sipHash128ReferenceKeyed")) + { + /// sipHash64Keyed(key, data, ...) -> sipHash64Keyed('[HIDDEN]', data, ...) + /// These functions have no named-argument grammar, so the key is always at raw index 0. + markSecretArgument(0); + } else if (function->name() == "url" || function->name() == "urlCluster") { /// url('url', ...) keeps the url at slot 0; urlCluster('cluster', 'url', ...) at slot 1. From 2c5e15773f5bbfc20278fdf445c4fc43321aae9d Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Wed, 25 Nov 2026 05:36:14 +0000 Subject: [PATCH 080/116] Backport #133506 to 26.3: Fix JSON schema inference applying the mark of a freed type to an unrelated value --- src/Formats/JSONExtractTree.cpp | 10 +-- src/Formats/SchemaInferenceUtils.cpp | 76 ++++++++++++++----- src/Formats/SchemaInferenceUtils.h | 21 +++-- ...schema_inference_freed_type_mark.reference | 10 +++ ..._json_schema_inference_freed_type_mark.sql | 15 ++++ 5 files changed, 99 insertions(+), 33 deletions(-) create mode 100644 tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference create mode 100644 tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql diff --git a/src/Formats/JSONExtractTree.cpp b/src/Formats/JSONExtractTree.cpp index 4dc4a33a4ce1..8bac3f5adf32 100644 --- a/src/Formats/JSONExtractTree.cpp +++ b/src/Formats/JSONExtractTree.cpp @@ -1748,10 +1748,9 @@ class DynamicNode : public JSONExtractTreeNode return DataTypeFactory::instance().get("Bool"); case ElementType::INT64: { - auto type = std::make_shared(); if (element.getInt64() < 0) - json_inference_info.negative_integers.insert(type.get()); - return type; + return json_inference_info.getNegativeInt64(); + return std::make_shared(); } case ElementType::UINT64: return std::make_shared(); @@ -1767,10 +1766,7 @@ class DynamicNode : public JSONExtractTreeNode if (format_settings.json.try_infer_numbers_from_strings) { if (auto type = tryInferJSONNumberFromString(data, format_settings, &json_inference_info)) - { - json_inference_info.numbers_parsed_from_json_strings.insert(type.get()); - return type; - } + return json_inference_info.getNumberParsedFromString(type); } return std::make_shared(); diff --git a/src/Formats/SchemaInferenceUtils.cpp b/src/Formats/SchemaInferenceUtils.cpp index 276af29a8e8e..4e12886389ed 100644 --- a/src/Formats/SchemaInferenceUtils.cpp +++ b/src/Formats/SchemaInferenceUtils.cpp @@ -35,6 +35,7 @@ namespace ErrorCodes extern const int NOT_IMPLEMENTED; extern const int INCORRECT_DATA; extern const int ONLY_NULLS_WHILE_READING_SCHEMA; + extern const int LOGICAL_ERROR; } namespace @@ -274,10 +275,16 @@ namespace { if (WhichDataType(type).isInt64()) { - bool is_negative = json_info && json_info->negative_integers.contains(type.get()); + bool is_negative = json_info && json_info->isNegativeInteger(*type); have_negative_integers |= is_negative; if (!is_negative) - type = std::make_shared(); + { + auto new_type = std::make_shared(); + if (json_info && json_info->isNumberParsedFromString(*type)) + type = json_info->getNumberParsedFromString(new_type); + else + type = new_type; + } } } @@ -299,9 +306,10 @@ namespace if (which.isInt64() || which.isUInt64()) { auto new_type = std::make_shared(); - if (json_info && json_info->numbers_parsed_from_json_strings.erase(type.get())) - json_info->numbers_parsed_from_json_strings.insert(new_type.get()); - type = new_type; + if (json_info && json_info->isNumberParsedFromString(*type)) + type = json_info->getNumberParsedFromString(new_type); + else + type = new_type; } } @@ -392,7 +400,7 @@ namespace { if (isNumber(type) && (settings.json.read_numbers_as_strings || !json_info - || json_info->numbers_parsed_from_json_strings.contains(type.get()))) + || json_info->isNumberParsedFromString(*type))) type = std::make_shared(); } @@ -1043,10 +1051,9 @@ namespace buf.position() = number_start; if (tryReadIntText(tmp_int, buf)) { - auto type = std::make_shared(); if (json_info && tmp_int < 0) - json_info->negative_integers.insert(type.get()); - return type; + return json_info->getNegativeInt64(); + return std::make_shared(); } /// In case of Int64 overflow we can try to infer UInt64. @@ -1071,10 +1078,9 @@ namespace Int64 tmp_int; if (tryReadIntText(tmp_int, peekable_buf)) { - auto type = std::make_shared(); if (json_info && tmp_int < 0) - json_info->negative_integers.insert(type.get()); - return type; + return json_info->getNegativeInt64(); + return std::make_shared(); } peekable_buf.rollbackToCheckpoint(/* drop= */ true); @@ -1102,10 +1108,9 @@ namespace Int64 tmp_int; if (tryReadIntText(tmp_int, buf) && buf.eof()) { - auto type = std::make_shared(); if (json_inference_info && tmp_int < 0) - json_inference_info->negative_integers.insert(type.get()); - return type; + return json_inference_info->getNegativeInt64(); + return std::make_shared(); } /// We can safely get back to the start of buffer, because we read from a string and we didn't reach eof. @@ -1158,10 +1163,7 @@ namespace if (settings.json.try_infer_numbers_from_strings) { if (auto number_type = tryInferNumberFromStringImpl(field, settings, json_info)) - { - json_info->numbers_parsed_from_json_strings.insert(number_type.get()); - return number_type; - } + return json_info->getNumberParsedFromString(number_type); } } @@ -1404,6 +1406,42 @@ namespace /// Number return tryInferNumber(buf, settings, json_info); } + + template + DataTypePtr getOrCreate(DataTypePtr & instance) + { + if (!instance) + instance = std::make_shared(); + return instance; + } +} + +DataTypePtr JSONInferenceInfo::getNegativeInt64() +{ + return getOrCreate(negative_int64); +} + +DataTypePtr JSONInferenceInfo::getNumberParsedFromString(const DataTypePtr & number_type) +{ + WhichDataType which(number_type); + if (which.isInt64()) + return getOrCreate(isNegativeInteger(*number_type) ? negative_int64_from_string : int64_from_string); + if (which.isUInt64()) + return getOrCreate(uint64_from_string); + if (which.isFloat64()) + return getOrCreate(float64_from_string); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected type {} of a number parsed from a string", number_type->getName()); +} + +bool JSONInferenceInfo::isNegativeInteger(const IDataType & type) const +{ + return &type == negative_int64.get() || &type == negative_int64_from_string.get(); +} + +bool JSONInferenceInfo::isNumberParsedFromString(const IDataType & type) const +{ + return &type == int64_from_string.get() || &type == negative_int64_from_string.get() || &type == uint64_from_string.get() + || &type == float64_from_string.get(); } bool canBeInsideNullableBySchemaSettings(const DataTypePtr & type, const FormatSettings & settings) diff --git a/src/Formats/SchemaInferenceUtils.h b/src/Formats/SchemaInferenceUtils.h index 83151305f104..2700297e5ba9 100644 --- a/src/Formats/SchemaInferenceUtils.h +++ b/src/Formats/SchemaInferenceUtils.h @@ -17,13 +17,13 @@ using NamesAndTypesLists = std::vector; /// Struct with some additional information about inferred types for JSON formats. struct JSONInferenceInfo { - /// We store numbers that were parsed from strings. - /// It's used in types transformation to change such numbers back to string if needed. - std::unordered_set numbers_parsed_from_json_strings; - /// Store integer types that were inferred from negative numbers. - /// It's used to determine common type for Int64 and UInt64 - /// TODO: check it not only in JSON formats. - std::unordered_set negative_integers; + /// Int64 inferred from a negative number and numbers parsed from JSON strings are marked by being one of + /// the instances owned below. + DataTypePtr getNegativeInt64(); + /// number_type is Int64, UInt64 or Float64. + DataTypePtr getNumberParsedFromString(const DataTypePtr & number_type); + [[nodiscard]] bool isNegativeInteger(const IDataType & type) const; + [[nodiscard]] bool isNumberParsedFromString(const IDataType & type) const; /// Indicates if currently we are inferring type for Map/Object key. bool is_object_key = false; @@ -32,6 +32,13 @@ struct JSONInferenceInfo /// because DataTypeJSONPaths was already finalized to named tuple. IN this case /// we can only merge named tuples from different files together. bool allow_merging_named_tuples = false; + +private: + DataTypePtr negative_int64; + DataTypePtr int64_from_string; + DataTypePtr negative_int64_from_string; + DataTypePtr uint64_from_string; + DataTypePtr float64_from_string; }; /// Check whether a type can be wrapped into Nullable according to schema inference settings. diff --git a/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference new file mode 100644 index 000000000000..08552bc1f284 --- /dev/null +++ b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference @@ -0,0 +1,10 @@ +x Nullable(Int64) +y Nullable(UInt64) +x Nullable(Int64) +y Nullable(UInt64) +a Array(Nullable(Float64)) +b Array(Nullable(UInt64)) +x Nullable(String) +x Nullable(String) +x Nullable(String) +Array(Nullable(Int64)) Array(Dynamic) Array(Dynamic) diff --git a/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql new file mode 100644 index 000000000000..422740e3deaa --- /dev/null +++ b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql @@ -0,0 +1,15 @@ +-- A type freed during inference must not pass its negative or parsed-from-string mark to another value. + +DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":1}\n{"y":18446744073709551615}'); +DESC format(JSONEachRow, '{"x":-1}\n{"x":-2}\n{"y":1}\n{"y":18446744073709551615}'); +DESC format(JSONEachRow, '{"a":[-1, 1.5], "b":[1, 18446744073709551615]}'); +DESC format(JSONEachRow, '{"x":"1"}\n{"x":"2"}\n{"y":1}\n{"y":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- The marks still work. +DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":-1}\n{"y":18446744073709551615}'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":["-1"]}\n{"x":["18446744073709551615"]}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":"1"}\n{"x":1.5}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +DESC format(JSONEachRow, '{"x":"-1"}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +DESC format(JSONEachRow, '{"x":1}\n{"x":1.5}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":"1"}\n{"x":"18446744073709551615"}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +SELECT dynamicType(j.a), dynamicType(j.b), dynamicType(j.c) FROM format(JSONEachRow, 'j JSON', '{"j":{"a":[-1, 1], "b":["-1", "18446744073709551615"], "c":[-1, 18446744073709551615]}}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1; From a7ab97ffcf96518e536be439eacd088b6a27f0da Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Wed, 25 Nov 2026 05:49:44 +0000 Subject: [PATCH 081/116] Fix the backported test: use an old server that sends settings in `Hello` The test `test_new_client_and_initiator_with_negative_seconds_in_old_server_profile` failed in the `26.3` branch because the client printed no warning: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=133563&sha=1bbdecdd052ce77fe88935c3d090a4109bb6fb9e&name_0=BackportPR&name_1=Integration%20tests%20%28amd_tsan%2C%202%2F6%29 https://github.com/ClickHouse/ClickHouse/pull/133563 In this branch `CLICKHOUSE_CI_MIN_TESTED_VERSION` is `23.3` (it is `25.3` in master), and such a server does not send its settings in `Hello` (`DBMS_MIN_REVISION_WITH_SERVER_SETTINGS`), so there was nothing for the client to skip. Run the test against a separate instance of version `25.3`, as in master. Co-Authored-By: Claude Fable 5.2 --- .../test_backward_compatibility/test.py | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/integration/test_backward_compatibility/test.py b/tests/integration/test_backward_compatibility/test.py index b55acd1ab7ff..60d2dd2bc7ae 100644 --- a/tests/integration/test_backward_compatibility/test.py +++ b/tests/integration/test_backward_compatibility/test.py @@ -17,6 +17,14 @@ with_zookeeper=True, use_old_analyzer=True, ) +# The oldest tested version (`CLICKHOUSE_CI_MIN_TESTED_VERSION`) in this branch does not send its settings +# in `Hello` yet, so the test of the settings received from the server needs a newer old server. +node3 = cluster.add_instance( + "node3", + image="clickhouse/clickhouse-server", + tag="25.3", + with_installed_binary=True, +) @pytest.fixture(scope="module") @@ -45,14 +53,14 @@ def test_backward_compatability1(start_cluster): def test_new_client_and_initiator_with_negative_seconds_in_old_server_profile(start_cluster): - node1.query("DROP USER IF EXISTS u_negative_seconds") - node1.query("CREATE USER u_negative_seconds IDENTIFIED WITH no_password SETTINGS max_execution_time = -1") - node1.query("GRANT SELECT ON system.one TO u_negative_seconds") + node3.query("DROP USER IF EXISTS u_negative_seconds") + node3.query("CREATE USER u_negative_seconds IDENTIFIED WITH no_password SETTINGS max_execution_time = -1") + node3.query("GRANT SELECT ON system.one TO u_negative_seconds") try: - # `node1.query*` runs the tested client against the old server; the client warns about the value it skips. - out, err = node1.query_and_get_answer_with_error("SELECT 1", user="u_negative_seconds") + # `node3.query*` runs the tested client against the old server; the client warns about the value it skips. + out, err = node3.query_and_get_answer_with_error("SELECT 1", user="u_negative_seconds") assert out == "1\n" assert "Cannot parse the value of setting `max_execution_time`, skipping it" in err - assert node2.query("SELECT count() FROM remote('node1', system.one, 'u_negative_seconds', '')") == "1\n" + assert node2.query("SELECT count() FROM remote('node3', system.one, 'u_negative_seconds', '')") == "1\n" finally: - node1.query("DROP USER IF EXISTS u_negative_seconds") + node3.query("DROP USER IF EXISTS u_negative_seconds") From 28a7a9aa72362e9172e9f9ea5e796e5a367a70e9 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Wed, 25 Nov 2026 09:58:43 +0000 Subject: [PATCH 082/116] Backport #129438 to 26.3: Keep sizes of Nested arrays when a column TTL resets a subcolumn --- src/Processors/TTL/TTLColumnAlgorithm.cpp | 30 ++++++- src/Processors/TTL/TTLColumnAlgorithm.h | 10 ++- src/Processors/Transforms/TTLTransform.cpp | 29 ++++++- src/Processors/Transforms/TTLTransform.h | 1 + ..._nested_subcolumn_keeps_siblings.reference | 8 ++ ...mn_ttl_nested_subcolumn_keeps_siblings.sql | 83 +++++++++++++++++++ 6 files changed, 154 insertions(+), 7 deletions(-) create mode 100644 tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference create mode 100644 tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql diff --git a/src/Processors/TTL/TTLColumnAlgorithm.cpp b/src/Processors/TTL/TTLColumnAlgorithm.cpp index 91cb9f5080fe..208ffb08c7a5 100644 --- a/src/Processors/TTL/TTLColumnAlgorithm.cpp +++ b/src/Processors/TTL/TTLColumnAlgorithm.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include namespace DB { @@ -12,12 +15,14 @@ TTLColumnAlgorithm::TTLColumnAlgorithm( const String & column_name_, const ExpressionActionsPtr & default_expression_, const String & default_column_name_, - bool is_compact_part_) + bool is_compact_part_, + bool shares_nested_offsets_) : ITTLAlgorithm(ttl_expressions_, description_, old_ttl_info_, current_time_, force_) , column_name(column_name_) , default_expression(default_expression_) , default_column_name(default_column_name_) , is_compact_part(is_compact_part_) + , shares_nested_offsets(shares_nested_offsets_) { if (!isMinTTLExpired()) { @@ -29,6 +34,14 @@ TTLColumnAlgorithm::TTLColumnAlgorithm( new_ttl_info.ttl_finished = true; } +ColumnPtr TTLColumnAlgorithm::createArraysOfDefaults(const IDataType & type, const IColumn & column_with_sizes) +{ + const auto & column_array = assert_cast(column_with_sizes); + const auto & nested_type = assert_cast(type).getNestedType(); + auto data = nested_type->createColumnConstWithDefaultValue(column_array.getData().size()); + return ColumnArray::create(data->convertToFullColumnIfConst(), column_array.getOffsetsPtr()); +} + void TTLColumnAlgorithm::execute(Block & block) { if (block.empty()) @@ -48,6 +61,17 @@ void TTLColumnAlgorithm::execute(Block & block) /// projections can correctly recalculate using it. if (isMaxTTLExpired() && !is_compact_part) { + /// A `Nested` subcolumn stays in the part, so it has to hold the value a read would return: + /// its `DEFAULT` expression, or arrays of defaults with the sizes shared with the other subcolumns. + if (shares_nested_offsets) + { + auto default_column = executeExpressionAndGetColumn(default_expression, block, default_column_name); + if (!default_column) + default_column = createArraysOfDefaults(*column_with_type.type, *column_with_type.column); + column_with_type.column = default_column->convertToFullColumnIfConst(); + return; + } + auto empty_column = column_with_type.column->cloneEmpty(); empty_column->insertManyDefaults(block.rows()); column_with_type.column = std::move(empty_column); @@ -55,6 +79,8 @@ void TTLColumnAlgorithm::execute(Block & block) } auto default_column = executeExpressionAndGetColumn(default_expression, block, default_column_name); + if (!default_column && shares_nested_offsets) + default_column = createArraysOfDefaults(*column_with_type.type, *column_with_type.column); if (default_column) default_column = default_column->convertToFullColumnIfConst(); @@ -89,7 +115,7 @@ void TTLColumnAlgorithm::finalize(const MutableDataPartPtr & data_part) const { data_part->ttl_infos.columns_ttl[column_name] = new_ttl_info; data_part->ttl_infos.updatePartMinMaxTTL(new_ttl_info); - if (is_fully_empty) + if (is_fully_empty && !shares_nested_offsets) data_part->expired_columns.insert(column_name); } diff --git a/src/Processors/TTL/TTLColumnAlgorithm.h b/src/Processors/TTL/TTLColumnAlgorithm.h index f34dae952d16..6ef19bb98c70 100644 --- a/src/Processors/TTL/TTLColumnAlgorithm.h +++ b/src/Processors/TTL/TTLColumnAlgorithm.h @@ -6,7 +6,8 @@ namespace DB { /// Deletes (replaces to default) values in column according to column's TTL description. -/// If all values in column are replaced with defaults, this column won't be written to part. +/// If all values in column are replaced with defaults, this column won't be written to part, +/// unless it is a `Nested` subcolumn that shares the array sizes with the other subcolumns. class TTLColumnAlgorithm final : public ITTLAlgorithm { public: @@ -19,12 +20,16 @@ class TTLColumnAlgorithm final : public ITTLAlgorithm const String & column_name_, const ExpressionActionsPtr & default_expression_, const String & default_column_name_, - bool is_compact_part_ + bool is_compact_part_, + bool shares_nested_offsets_ ); void execute(Block & block) override; void finalize(const MutableDataPartPtr & data_part) const override; + /// The default of a `Nested` subcolumn keeps the array sizes, which it shares with the other subcolumns. + static ColumnPtr createArraysOfDefaults(const IDataType & type, const IColumn & column_with_sizes); + private: const String column_name; const ExpressionActionsPtr default_expression; @@ -32,6 +37,7 @@ class TTLColumnAlgorithm final : public ITTLAlgorithm bool is_fully_empty = true; bool is_compact_part; + bool shares_nested_offsets; }; } diff --git a/src/Processors/Transforms/TTLTransform.cpp b/src/Processors/Transforms/TTLTransform.cpp index 1d1154f217ce..496b0f883e5f 100644 --- a/src/Processors/Transforms/TTLTransform.cpp +++ b/src/Processors/Transforms/TTLTransform.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -31,6 +32,17 @@ static TTLExpressions getExpressions(const TTLDescription & ttl_descr, PreparedS return {expr.expression, where_expr.expression}; } +/// Returns a stored `Nested` sibling of `name`, whose array sizes a read uses to fill `name`. +static const ColumnWithTypeAndName * findNestedSiblingWithSizes(const Block & block, const String & name, const auto & expired_columns) +{ + auto table_name = Nested::extractTableName(name); + for (const auto & column : block) + if (column.name != name && !expired_columns.contains(column.name) && isArray(column.type) + && Nested::extractTableName(column.name) == table_name) + return &column; + return nullptr; +} + SharedHeader TTLTransform::addExpiredColumnsToBlock(const SharedHeader & header, const NamesAndTypesList & expired_columns_) { if (expired_columns_.empty()) @@ -108,11 +120,18 @@ TTLTransform::TTLTransform( return Result{actions, default_ast->getColumnName()}; }; + /// An `Array` column with a dotted name is a `Nested` subcolumn: it shares the array sizes with its siblings. + auto shares_nested_offsets = [&](const NameAndTypePair & column) + { + return isArray(column.type) && Nested::extractTableName(column.name) != column.name; + }; + for (const auto & expired_column : expired_columns) { auto [default_expression, default_column_name] = build_default_expr(expired_column.name); - expired_columns_data.emplace( - expired_column.name, ExpiredColumnData{expired_column.type, std::move(default_expression), std::move(default_column_name)}); + ExpiredColumnData data{ + expired_column.type, std::move(default_expression), std::move(default_column_name), shares_nested_offsets(expired_column)}; + expired_columns_data.emplace(expired_column.name, std::move(data)); } if (metadata_snapshot_->hasAnyColumnTTL()) @@ -132,7 +151,8 @@ TTLTransform::TTLTransform( name, default_expression, default_column_name, - isCompactPart(data_part))); + isCompactPart(data_part), + shares_nested_offsets(storage_columns.getPhysical(name)))); } } } @@ -173,6 +193,9 @@ void TTLTransform::consume(Chunk chunk) { auto default_column = ITTLAlgorithm::executeExpressionAndGetColumn(data.default_expression, block, data.default_column_name); + if (!default_column && data.shares_nested_offsets) + if (const auto * sibling = findNestedSiblingWithSizes(block, column, expired_columns_data)) + default_column = TTLColumnAlgorithm::createArraysOfDefaults(*data.type, *sibling->column); if (default_column) default_column = default_column->convertToFullColumnIfConst(); else diff --git a/src/Processors/Transforms/TTLTransform.h b/src/Processors/Transforms/TTLTransform.h index 0fed59119a86..6df494b06482 100644 --- a/src/Processors/Transforms/TTLTransform.h +++ b/src/Processors/Transforms/TTLTransform.h @@ -57,6 +57,7 @@ class TTLTransform : public IAccumulatingTransform DataTypePtr type; ExpressionActionsPtr default_expression; String default_column_name; + bool shares_nested_offsets; }; std::unordered_map expired_columns_data; LoggerPtr log; diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference new file mode 100644 index 000000000000..d573890cb58f --- /dev/null +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference @@ -0,0 +1,8 @@ +wide 1 [NULL,NULL] ['x','y'] +rows 1 ['',''] ['x','y'] +rows 2 ['c'] ['z'] +compact 1 ['',''] ['x','y'] +enum 1 ['ok','ok'] ['x','y'] +enum 2 ['other'] ['z'] +single ['',''] ['',''] 2 2 +added ['a','b'] ['x','y'] ['',''] ['e','e'] diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql new file mode 100644 index 000000000000..80bf9de58148 --- /dev/null +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql @@ -0,0 +1,83 @@ +-- A column TTL on one `Nested` subcolumn resets it to arrays of defaults of the same size, +-- because its array sizes are shared with the other subcolumns, which keep their values. + +DROP TABLE IF EXISTS t_nested_ttl_wide; +DROP TABLE IF EXISTS t_nested_ttl_rows; +DROP TABLE IF EXISTS t_nested_ttl_compact; +DROP TABLE IF EXISTS t_nested_ttl_enum; +DROP TABLE IF EXISTS t_nested_ttl_single; +DROP TABLE IF EXISTS t_nested_ttl_added; + +-- A Wide part with every row expired, the type change also rewrites the subcolumn. +CREATE TABLE t_nested_ttl_wide (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_wide VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_wide MODIFY COLUMN `n.a` Array(Nullable(String)) TTL ts + INTERVAL 1 DAY; +ALTER TABLE t_nested_ttl_wide MATERIALIZE TTL SETTINGS mutations_sync = 2; +SELECT 'wide', id, `n.a`, `n.b` FROM t_nested_ttl_wide; + +-- Only some rows of the part are expired. +CREATE TABLE t_nested_ttl_rows (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_rows VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']), (2, '2100-01-01 00:00:00', ['c'], ['z']); +ALTER TABLE t_nested_ttl_rows MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_rows FINAL; +SELECT 'rows', id, `n.a`, `n.b` FROM t_nested_ttl_rows ORDER BY id; + +-- A Compact part stores the sizes of each subcolumn separately, but it gets the same default. +CREATE TABLE t_nested_ttl_compact (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000; + +INSERT INTO t_nested_ttl_compact VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_compact MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY; +ALTER TABLE t_nested_ttl_compact MATERIALIZE TTL SETTINGS mutations_sync = 2; +SELECT 'compact', id, `n.a`, `n.b` FROM t_nested_ttl_compact; + +-- The default of an `Enum` element is its first value, not zero. +CREATE TABLE t_nested_ttl_enum (id UInt64, ts DateTime, n Nested(a Enum8('ok' = 1, 'other' = 2), b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_enum VALUES (1, '2020-01-01 00:00:00', ['other', 'other'], ['x', 'y']), (2, '2100-01-01 00:00:00', ['other'], ['z']); +ALTER TABLE t_nested_ttl_enum MODIFY COLUMN `n.a` Array(Enum8('ok' = 1, 'other' = 2)) TTL ts + INTERVAL 1 DAY SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_enum FINAL; +SELECT 'enum', id, `n.a`, `n.b` FROM t_nested_ttl_enum ORDER BY id; + +-- The sizes are kept when every subcolumn expires. +CREATE TABLE t_nested_ttl_single (id UInt64, ts DateTime, n Nested(a String, b String), m UInt64 MATERIALIZED length(`n.a`)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_single VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_single + MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY, + MODIFY COLUMN `n.b` Array(String) TTL ts + INTERVAL 1 DAY +SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_single FINAL; +SELECT 'single', `n.a`, `n.b`, m, length(`n.a`) FROM t_nested_ttl_single; + +-- A subcolumn that no part stores gets the sizes of the other subcolumns, as in a read. +-- A vertical merge does not use the TTL transform for these columns, so it is disabled here. +CREATE TABLE t_nested_ttl_added (id UInt64, n Nested(a String, c String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, enable_vertical_merge_algorithm = 0; + +INSERT INTO t_nested_ttl_added VALUES (1, ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_added ADD COLUMN `n.d` Array(String); +ALTER TABLE t_nested_ttl_added ADD COLUMN `n.e` Array(String) MATERIALIZED arrayMap(x -> concat('e', x), `n.d`); +ALTER TABLE t_nested_ttl_added ADD COLUMN ts DateTime DEFAULT '2020-01-01 00:00:00'; +ALTER TABLE t_nested_ttl_added MODIFY TTL ts + INTERVAL 1 DAY WHERE id = 100 SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_added FINAL; +SELECT 'added', `n.a`, `n.c`, `n.d`, `n.e` FROM t_nested_ttl_added; + +DROP TABLE t_nested_ttl_wide; +DROP TABLE t_nested_ttl_rows; +DROP TABLE t_nested_ttl_compact; +DROP TABLE t_nested_ttl_enum; +DROP TABLE t_nested_ttl_single; +DROP TABLE t_nested_ttl_added; From 69d19a60bbc2cbe099dd76c2abf5e93e370852c2 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Wed, 25 Nov 2026 11:37:35 +0000 Subject: [PATCH 083/116] Backport #134192 to 26.3: Do Not Remove Root Folder in Case of `table_disk` --- ...ataStorageFromPlainRewritableObjectStorageOperations.cpp | 5 +---- src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp | 6 ------ src/Storages/MergeTree/MergeTreeData.cpp | 6 ++++++ 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp index 7bc2a3e32b66..b67c2af415a9 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp @@ -677,11 +677,8 @@ MetadataStorageFromPlainObjectStorageRemoveRecursiveOperation::MetadataStorageFr void MetadataStorageFromPlainObjectStorageRemoveRecursiveOperation::execute() { - /// Unfortunately we are able to create merge tree unlinked from database directory. - /// In this case during the dropAllData method removeRecursive can be called pointing to the root folder. - /// I don't know what to do in this case, so right now it is a no-op. if (normalizePath(path).empty()) - return; + throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't remove root folder"); if (fs_tree->existsDirectory(path).first) { diff --git a/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp b/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp index b83b39f722a1..3289064e8871 100644 --- a/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp +++ b/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp @@ -837,12 +837,6 @@ TEST_F(MetadataPlainRewritableDiskTest, RemoveRoot) EXPECT_ANY_THROW(tx->commit(DB::NoCommitOptions{})); } - { - auto tx = metadata->createTransaction(); - tx->removeRecursive("/", /*should_remove_blob=*/nullptr); - tx->commit(DB::NoCommitOptions{}); - } - EXPECT_EQ(listAllBlobs("RemoveRecursiveRoot"), std::vector({ "./RemoveRecursiveRoot/__root/A", "./RemoveRecursiveRoot/__root/B" diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index 9f791f73def6..a73264c06dd3 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -4110,6 +4110,12 @@ void MergeTreeData::dropAllData() if (disk->existsDirectory(fs::path(relative_data_path) / MOVING_DIR_NAME)) disk->removeRecursive(fs::path(relative_data_path) / MOVING_DIR_NAME); + if ((*settings_ptr)[MergeTreeSetting::table_disk]) + { + LOG_INFO(log, "dropAllData: the table directory is the root of disk {}, it is kept", disk->getName()); + continue; + } + try { if (!isSharedStorage() && !disk->isDirectoryEmpty(relative_data_path) From 6b3a53c80d2732c18847ca6a602ffc18f0e5a831 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Wed, 25 Nov 2026 16:07:48 +0000 Subject: [PATCH 084/116] Backport #133025 to 26.3: Validate full-definition `ATTACH MATERIALIZED VIEW` like `CREATE` --- src/Interpreters/InterpreterCreateQuery.cpp | 10 +++-- .../test_replicated_database/test.py | 29 ++++++++++++ ..._view_full_definition_validation.reference | 4 ++ ...ialized_view_full_definition_validation.sh | 44 +++++++++++++++++++ 4 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference create mode 100755 tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index b94ee3563d48..94b71dc55918 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -1743,11 +1743,15 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) if (need_add_to_database) database = DatabaseCatalog::instance().tryGetDatabase(database_name); - /// Check type compatible for materialized dest table and select columns - if (create.select && create.is_materialized_view && mode <= LoadingStrictnessLevel::CREATE) + /// Check type compatible for materialized dest table and select columns. + /// A full-definition `ATTACH` by a user is validated like `CREATE`, unlike a replayed one: a follower replica + /// gets `ATTACH` (not `SECONDARY_CREATE`), and the initiator has already validated it before enqueueing. + const bool is_user_full_attach = !internal && mode == LoadingStrictnessLevel::ATTACH && !create.attach_short_syntax + && !is_secondary_query && !is_restore_from_backup && !getContext()->isRecoveryFromStoredMetadata(); + if (create.select && create.is_materialized_view && (mode <= LoadingStrictnessLevel::CREATE || is_user_full_attach)) { // An MV with a flattened nested column in an inner table can never be filled - if (create.is_materialized_view_with_inner_table()) + if (mode <= LoadingStrictnessLevel::CREATE && create.is_materialized_view_with_inner_table()) getContext()->setSetting("flatten_nested", false); validateMaterializedViewColumnsAndEngine(create, properties, database); } diff --git a/tests/integration/test_replicated_database/test.py b/tests/integration/test_replicated_database/test.py index 783121399dc0..e94a85137f17 100644 --- a/tests/integration/test_replicated_database/test.py +++ b/tests/integration/test_replicated_database/test.py @@ -2044,3 +2044,32 @@ def test_alias_with_dropped_target(started_cluster): # Cleanup for node in [main_node, dummy_node]: node.query(f"DROP DATABASE IF EXISTS {db_name} SYNC") + + +def test_attach_mv_replays_on_replica_without_source(started_cluster): + # The initiator validates a full-definition ATTACH MATERIALIZED VIEW, a follower replays it as is. + main_node.query("CREATE DATABASE attach_mv_src") + main_node.query("CREATE TABLE attach_mv_src.src (n Int32) ENGINE = MergeTree ORDER BY n") + for i, node in enumerate([main_node, dummy_node]): + node.query( + f"CREATE DATABASE attach_mv_db ENGINE = Replicated('/test/attach_mv_db', 'shard1', 'replica{i + 1}')" + ) + main_node.query( + "CREATE TABLE attach_mv_db.dst (n Int32) ENGINE = ReplicatedMergeTree ORDER BY n" + ) + main_node.query( + "ATTACH MATERIALIZED VIEW attach_mv_db.mv UUID '5a2b6c61-7e43-4d6f-9b4b-1ad7b9b33d71' " + "TO attach_mv_db.dst (n Int32) AS SELECT n FROM attach_mv_src.src", + settings={"database_replicated_allow_explicit_uuid": 1}, + ) + dummy_node.query("SYSTEM SYNC DATABASE REPLICA attach_mv_db", timeout=60) + assert ( + dummy_node.query( + "SELECT count() FROM system.tables WHERE database = 'attach_mv_db' AND name = 'mv'" + ) + == "1\n" + ) + + for node in [main_node, dummy_node]: + node.query("DROP DATABASE attach_mv_db SYNC") + main_node.query("DROP DATABASE attach_mv_src SYNC") diff --git a/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference new file mode 100644 index 000000000000..996d06fdddaf --- /dev/null +++ b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.reference @@ -0,0 +1,4 @@ +THERE_IS_NO_COLUMN +ACCESS_DENIED +ACCESS_DENIED +x y diff --git a/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh new file mode 100755 index 000000000000..a9f02762ca78 --- /dev/null +++ b/tests/queries/0_stateless/05836_attach_materialized_view_full_definition_validation.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A full-definition ATTACH MATERIALIZED VIEW validates the SELECT query like CREATE does. + +user="user05836_${CLICKHOUSE_DATABASE}_$RANDOM" +db=${CLICKHOUSE_DATABASE} + +${CLICKHOUSE_CLIENT} <&1 | grep -o -m1 -E "ACCESS_DENIED|THERE_IS_NO_COLUMN" +} + +# The SELECT outputs a column which is not in the target table. +${CLICKHOUSE_CLIENT} --send_logs_level=none --query " + ATTACH MATERIALIZED VIEW $db.mv UUID '$(${CLICKHOUSE_CLIENT} -q "SELECT generateUUIDv4()")' TO $db.dst (a String, b String) + AS SELECT a, b AS c FROM $db.src" 2>&1 | grep -o -m1 "THERE_IS_NO_COLUMN" + +# Privileges on the tables in the SELECT are required, the same as for CREATE. +${CLICKHOUSE_CLIENT} --user "$user" --query " + CREATE MATERIALIZED VIEW $db.mv TO $db.dst (a String, b String) AS SELECT a, b FROM $db.src" 2>&1 | grep -o -m1 "ACCESS_DENIED" +attach_mv --user "$user" + +${CLICKHOUSE_CLIENT} --query "GRANT SELECT ON $db.src TO $user" +attach_mv --user "$user" +${CLICKHOUSE_CLIENT} --query "INSERT INTO $db.src VALUES ('x', 'y')" +${CLICKHOUSE_CLIENT} --user "$user" --query "SELECT * FROM $db.dst" + +${CLICKHOUSE_CLIENT} --query "DROP TABLE $db.mv" +${CLICKHOUSE_CLIENT} --query "DROP USER $user" From 70b9d371fe0ce3c6ad62acfbfd66660908624eb0 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Wed, 25 Nov 2026 18:51:36 +0000 Subject: [PATCH 085/116] Backport #132488 to 26.3: Reject server file paths in `Kafka` named collections created with SQL --- .../table-engines/integrations/kafka.md | 2 + src/Storages/Kafka/KafkaConfigLoader.cpp | 272 +++++++++++++++--- src/Storages/Kafka/KafkaConfigLoader.h | 6 + src/Storages/Kafka/StorageKafkaUtils.cpp | 11 +- tests/config/config.d/named_collection.xml | 12 + .../configs/named_collections.xml | 25 ++ .../test_storage_kerberized_kafka/test.py | 26 +- ...fka_server_local_file_properties.reference | 55 ++++ ...5816_kafka_server_local_file_properties.sh | 145 ++++++++++ 9 files changed, 484 insertions(+), 70 deletions(-) create mode 100644 tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml create mode 100644 tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference create mode 100755 tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh diff --git a/docs/en/engines/table-engines/integrations/kafka.md b/docs/en/engines/table-engines/integrations/kafka.md index e06880eccfed..32b8a446a040 100644 --- a/docs/en/engines/table-engines/integrations/kafka.md +++ b/docs/en/engines/table-engines/integrations/kafka.md @@ -233,6 +233,8 @@ Similar to GraphiteMergeTree, the Kafka engine supports extended configuration u For a list of possible configuration options, see the [librdkafka configuration reference](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md). Use the underscore (`_`) instead of a dot in the ClickHouse configuration. For example, `check.crcs=true` will be `true`. +A named collection created with `CREATE NAMED COLLECTION` accepts only the `librdkafka` properties on the [allowlist](https://github.com/ClickHouse/ClickHouse/blob/26.3/src/Storages/Kafka/KafkaConfigLoader.cpp), such as `security.protocol`, `sasl.username`, and `fetch.min.bytes`. If a table uses a collection with an unlisted property, such as `ssl.ca.location` or `sasl.kerberos.keytab`, ClickHouse returns `BAD_ARGUMENTS`. To use these properties, define the collection in the server configuration file. This restriction also applies to properties added with `ALTER NAMED COLLECTION` after the table was created. Instead of the path of a TLS file, a named collection created with SQL can contain the contents of the file: `ssl.key.pem`, `ssl.certificate.pem`, and `ssl.ca.pem`. + ### Kerberos support {#kafka-kerberos-support} To deal with Kerberos-aware Kafka, add `security_protocol` child element with `sasl_plaintext` value. It is enough if Kerberos ticket-granting ticket is obtained and cached by OS facilities. diff --git a/src/Storages/Kafka/KafkaConfigLoader.cpp b/src/Storages/Kafka/KafkaConfigLoader.cpp index 5825b9ad0b97..d8c6be6434f6 100644 --- a/src/Storages/Kafka/KafkaConfigLoader.cpp +++ b/src/Storages/Kafka/KafkaConfigLoader.cpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include namespace CurrentMetrics { @@ -40,6 +42,7 @@ namespace KafkaSetting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; } @@ -160,12 +163,157 @@ template struct KafkaInterceptors; namespace { -void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & key, const String & value) +/// librdkafka reads the name as a C string, so it must not contain a null character. +void checkKafkaPropertyName(const String & key) { + if (key.contains('\0')) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Kafka property name {} contains a null character", backQuote(key)); +} + +String toKafkaPropertyName(const String & key) +{ + checkKafkaPropertyName(key); /// "log_level" has valid underscore, the remaining librdkafka setting use dot.separated.format which isn't acceptable for XML. /// See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md - const String setting_name_in_kafka_config = (key == "log_level") ? key : boost::replace_all_copy(key, "_", "."); - kafka_config.set(setting_name_in_kafka_config, value); + return (key == "log_level") ? key : boost::replace_all_copy(key, "_", "."); +} + +/// Only properties reviewed for use without access to server-local resources may be set from SQL. +/// Match the exact name passed to librdkafka, including any `topic.` prefix. +void checkSQLKafkaProperty(const String & name, const String & value) +{ + static constexpr std::string_view allowed_properties[] = { + "acks", + "allow.auto.create.topics", + "api.version.request", + "auto.commit.interval.ms", + "auto.offset.reset", + "batch.num.messages", + "batch.size", + "bootstrap.servers", + "broker.address.family", + "broker.address.ttl", + "check.crcs", + "client.id", + "client.rack", + "compression.codec", + "compression.level", + "compression.type", + "connections.max.idle.ms", + "coordinator.query.interval.ms", + "debug", + "delivery.timeout.ms", + "enable.auto.commit", + "enable.auto.offset.store", + "enable.idempotence", + "enable.partition.eof", + "fetch.error.backoff.ms", + "fetch.max.bytes", + "fetch.message.max.bytes", + "fetch.min.bytes", + "fetch.queue.backoff.ms", + "fetch.wait.max.ms", + "group.id", + "group.instance.id", + "group.protocol", + "group.remote.assignor", + "heartbeat.interval.ms", + "https.ca.pem", + "isolation.level", + "linger.ms", + "log.connection.close", + "log_level", + "max.in.flight", + "max.in.flight.requests.per.connection", + "max.partition.fetch.bytes", + "max.poll.interval.ms", + "message.max.bytes", + "message.send.max.retries", + "message.timeout.ms", + "metadata.broker.list", + "metadata.max.age.ms", + "partition.assignment.strategy", + "partitioner", + "queue.buffering.backpressure.threshold", + "queue.buffering.max.kbytes", + "queue.buffering.max.messages", + "queue.buffering.max.ms", + "queued.max.messages.kbytes", + "queued.min.messages", + "receive.message.max.bytes", + "reconnect.backoff.max.ms", + "reconnect.backoff.ms", + "request.required.acks", + "request.timeout.ms", + "retries", + "retry.backoff.max.ms", + "retry.backoff.ms", + "sasl.mechanism", + "sasl.mechanisms", + "sasl.oauthbearer.assertion.private.key.pem", + "sasl.password", + "sasl.username", + "security.protocol", + "session.timeout.ms", + "socket.connection.setup.timeout.ms", + "socket.keepalive.enable", + "socket.receive.buffer.bytes", + "socket.send.buffer.bytes", + "socket.timeout.ms", + "ssl.ca.pem", + "ssl.certificate.pem", + "ssl.key.password", + "ssl.key.pem", + "statistics.interval.ms", + "topic.acks", + "topic.auto.offset.reset", + "topic.compression.codec", + "topic.compression.level", + "topic.compression.type", + "topic.delivery.timeout.ms", + "topic.message.timeout.ms", + "topic.metadata.refresh.interval.ms", + "topic.partitioner", + "topic.request.required.acks", + "topic.request.timeout.ms", + }; + static_assert(std::ranges::is_sorted(allowed_properties)); + if (std::ranges::binary_search(allowed_properties, std::string_view(name))) + return; + + /// `probe` is not a path: librdkafka searches a fixed list of the standard locations of CA certificates. + if (value == "probe" && (name == "ssl.ca.location" || name == "https.ca.location")) + return; + + static constexpr std::pair pem_alternatives[] = { + {"ssl.key.location", "ssl.key.pem"}, + {"ssl.certificate.location", "ssl.certificate.pem"}, + {"ssl.ca.location", "ssl.ca.pem"}, + {"https.ca.location", "https.ca.pem"}, + {"sasl.oauthbearer.assertion.private.key.file", "sasl.oauthbearer.assertion.private.key.pem"}, + }; + for (const auto & [path_property, pem_property] : pem_alternatives) + if (name == path_property) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Kafka property `{}` can only be specified in a named collection defined in the server configuration file. " + "Pass the contents of the file in the property `{}` instead", + name, + pem_property); + + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Kafka property `{}` can only be specified in a named collection defined in the server configuration file", + name); +} + +void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & key, const String & value, bool from_sql_collection) +{ + const String name = toKafkaPropertyName(key); + if (from_sql_collection) + checkSQLKafkaProperty(name, value); + + kafka_config.set(name, value); } void loadConfigProperty( @@ -177,17 +325,47 @@ void loadConfigProperty( const String property_path = config_prefix + "." + tag; const String property_value = config.getString(property_path); - setKafkaConfigValue(kafka_config, tag, property_value); + setKafkaConfigValue(kafka_config, tag, property_value, /*from_sql_collection=*/false); +} + +bool isNamedTopicSection(std::string_view tag) +{ + return tag == KafkaConfigLoader::CONFIG_KAFKA_TOPIC_TAG || tag.starts_with("kafka_topic["); +} + +/// Return the key within its configuration section. Dots in the property itself are significant. +std::string_view namedCollectionPropertyKey(std::string_view key) +{ + static constexpr std::string_view prefix = "kafka."; + if (!key.starts_with(prefix)) + return {}; /// The collection has no properties below `kafka`. + key.remove_prefix(prefix.size()); + if (key.starts_with("consumer.") || key.starts_with("producer.")) + key.remove_prefix(key.find('.') + 1); + + /// Both `kafka_` and `kafka_topic` (possibly indexed) are topic sections. + if (const auto dot = key.find('.'); dot != std::string_view::npos && key.starts_with("kafka_")) + { + const auto section = key.substr(0, dot); + key.remove_prefix(dot + 1); + if (isNamedTopicSection(section) && key == KafkaConfigLoader::CONFIG_NAME_TAG) + return {}; /// Topic selector, not a librdkafka property. + } + return key; } -void loadNamedCollectionConfig(cppkafka::Configuration & kafka_config, const String & collection_name, const String & config_prefix) +void loadNamedCollectionConfig(cppkafka::Configuration & kafka_config, const NamedCollection & collection, const String & config_prefix) { - const auto & collection = NamedCollectionFactory::instance().get(collection_name); - for (const auto & key : collection->getKeys(-1, config_prefix)) + for (const auto & key : collection.getKeys(-1, config_prefix)) { - // Cut prefix with '.' before actual config tag. - const auto param_name = key.substr(config_prefix.size() + 1); - setKafkaConfigValue(kafka_config, param_name, collection->get(key)); + const auto property_key = namedCollectionPropertyKey(key); + if (property_key.empty() || key.size() != config_prefix.size() + 1 + property_key.size()) + continue; /// Subsections are loaded separately. + const String param_name(property_key); + const auto value = collection.get(key); + /// The check when the table is created or loaded is not sufficient: the collection is read again here, + /// and `ALTER NAMED COLLECTION` can add a property while the table exists. + setKafkaConfigValue(kafka_config, param_name, value, collection.getSourceId() != NamedCollection::SourceId::CONFIG); } } @@ -199,7 +377,12 @@ void loadLegacyTopicConfig( { if (!collection_name.empty()) { - loadNamedCollectionConfig(kafka_config, collection_name, config_prefix); + const auto collection = NamedCollectionFactory::instance().get(collection_name); + /// For a topic called `topic`, the legacy section is also called `kafka_topic`. + /// If it has a `name`, the topic selector must be matched by `loadFromConfig`. + if (config_prefix == "kafka.kafka_topic" && collection->has(config_prefix + ".name")) + return; + loadNamedCollectionConfig(kafka_config, *collection, config_prefix); return; } @@ -212,43 +395,15 @@ void loadLegacyTopicConfig( } } -/// Read server configuration into cppkafa configuration, used by new per-topic configuration -void loadTopicConfig( - cppkafka::Configuration & kafka_config, - const Poco::Util::AbstractConfiguration & config, - const String & collection_name, - const String & config_prefix, - const String & topic) +/// Read a matching per-topic section of the server configuration. +void loadTopicConfig(cppkafka::Configuration & kafka_config, const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { - if (!collection_name.empty()) - { - const auto topic_prefix = fmt::format("{}.{}", config_prefix, KafkaConfigLoader::CONFIG_KAFKA_TOPIC_TAG); - const auto & collection = NamedCollectionFactory::instance().get(collection_name); - for (const auto & key : collection->getKeys(1, config_prefix)) - { - /// Only consider key . Multiple occurrences given as "kafka_topic", "kafka_topic[1]", etc. - if (!key.starts_with(topic_prefix)) - continue; - - const String kafka_topic_path = config_prefix + "." + key; - const String kafka_topic_name_path = kafka_topic_path + "." + KafkaConfigLoader::CONFIG_NAME_TAG; - if (topic == collection->get(kafka_topic_name_path)) - /// Found it! Now read the per-topic configuration into cppkafka. - loadNamedCollectionConfig(kafka_config, collection_name, kafka_topic_path); - } - } - else + Poco::Util::AbstractConfiguration::Keys tags; + config.keys(config_prefix, tags); + for (const auto & tag : tags) { - /// Read all tags one level below - Poco::Util::AbstractConfiguration::Keys tags; - config.keys(config_prefix, tags); - - for (const auto & tag : tags) - { - if (tag == KafkaConfigLoader::CONFIG_NAME_TAG) - continue; // ignore , it is used to match topic configurations + if (tag != KafkaConfigLoader::CONFIG_NAME_TAG) loadConfigProperty(kafka_config, config, config_prefix, tag); - } } } @@ -258,7 +413,16 @@ void loadFromConfig( { if (!params.collection_name.empty()) { - loadNamedCollectionConfig(kafka_config, params.collection_name, config_prefix); + const auto collection = NamedCollectionFactory::instance().get(params.collection_name); + loadNamedCollectionConfig(kafka_config, *collection, config_prefix); + for (const auto & key : collection->getKeys(0, config_prefix)) + { + if (key.size() <= config_prefix.size() || !isNamedTopicSection(std::string_view(key).substr(config_prefix.size() + 1))) + continue; + const String name_key = key + "." + KafkaConfigLoader::CONFIG_NAME_TAG; + if (collection->has(name_key) && std::ranges::contains(params.topics, collection->get(name_key))) + loadNamedCollectionConfig(kafka_config, *collection, key); + } return; } @@ -299,7 +463,7 @@ void loadFromConfig( if (topic_name != topic) continue; - loadTopicConfig(kafka_config, params.config, params.collection_name, kafka_topic_path, topic); + loadTopicConfig(kafka_config, params.config, kafka_topic_path); } continue; } @@ -568,4 +732,18 @@ KafkaConfigLoader::getProducerConfiguration(StorageKafka & storage template cppkafka::Configuration KafkaConfigLoader::getProducerConfiguration(StorageKafka2 & storage, const ProducerConfigParams & params); +void KafkaConfigLoader::checkNamedCollection(const NamedCollection & collection) +{ + if (collection.getSourceId() == NamedCollection::SourceId::CONFIG) + return; + + for (const auto & key : collection.getKeys(-1, CONFIG_KAFKA_TAG)) + { + checkKafkaPropertyName(key); + const auto property_key = namedCollectionPropertyKey(key); + if (!property_key.empty()) + checkSQLKafkaProperty(toKafkaPropertyName(String(property_key)), collection.get(key)); + } +} + } diff --git a/src/Storages/Kafka/KafkaConfigLoader.h b/src/Storages/Kafka/KafkaConfigLoader.h index 9fd04c3750e9..52c332e7483c 100644 --- a/src/Storages/Kafka/KafkaConfigLoader.h +++ b/src/Storages/Kafka/KafkaConfigLoader.h @@ -11,6 +11,7 @@ namespace DB { struct KafkaSettings; +class NamedCollection; class VirtualColumnsDescription; struct KafkaConfigLoader @@ -53,5 +54,10 @@ struct KafkaConfigLoader template static cppkafka::Configuration getProducerConfiguration(TKafkaStorage & storage, const ProducerConfigParams & params); + + /// Throws if a named collection created with SQL sets a librdkafka property that is not explicitly allowed. + /// The same check is done when the configuration of a consumer or a producer is loaded, because the named + /// collection can change while the table exists. + static void checkNamedCollection(const NamedCollection & collection); }; } diff --git a/src/Storages/Kafka/StorageKafkaUtils.cpp b/src/Storages/Kafka/StorageKafkaUtils.cpp index af22807a2eaa..c20430d822d5 100644 --- a/src/Storages/Kafka/StorageKafkaUtils.cpp +++ b/src/Storages/Kafka/StorageKafkaUtils.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -116,8 +117,16 @@ void registerStorageKafka(StorageFactory & factory) &args.table_id, args.storage_def->settings)) { - kafka_settings->loadFromNamedCollection(named_collection); collection_name = assert_cast(args.engine_args[0].get())->name(); + + /// The named collection is checked every time, also when the definition is read back from metadata + /// (server startup, short `ATTACH`): the collection can change after the table is created. + /// `named_collection` is a copy, and a copy does not keep the source of the collection + /// (see `NamedCollection::duplicate`). Thus the collection of the factory is checked: + /// the configuration of the consumers and of the producers is loaded from it. + KafkaConfigLoader::checkNamedCollection(*NamedCollectionFactory::instance().get(collection_name)); + + kafka_settings->loadFromNamedCollection(named_collection); } if (has_settings) diff --git a/tests/config/config.d/named_collection.xml b/tests/config/config.d/named_collection.xml index 555c3b7f65ba..60341fc98ed2 100644 --- a/tests/config/config.d/named_collection.xml +++ b/tests/config/config.d/named_collection.xml @@ -49,5 +49,17 @@ http://127.0.0.1:8123?query=select+1 RawBLOB + + + 127.0.0.1:1 + topic + group + JSONEachRow + + /etc/clickhouse-server/server.crt + + diff --git a/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml b/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml new file mode 100644 index 000000000000..7f6c26058269 --- /dev/null +++ b/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml @@ -0,0 +1,25 @@ + + + + + kerberized_kafka1:19092 + kafka_json_as_string_named_collection + 1 + kafka_json_as_string_named_collection + JSONAsString + 1000 + + SASL_PLAINTEXT + GSSAPI + kafka + /tmp/keytab/clickhouse.keytab + anotherkafkauser/instance@TEST.CLICKHOUSE.TECH + security + false + + + + diff --git a/tests/integration/test_storage_kerberized_kafka/test.py b/tests/integration/test_storage_kerberized_kafka/test.py index 0fb5f39dbdaf..702909aafdb8 100644 --- a/tests/integration/test_storage_kerberized_kafka/test.py +++ b/tests/integration/test_storage_kerberized_kafka/test.py @@ -26,7 +26,7 @@ cluster = ClickHouseCluster(__file__) instance = cluster.add_instance( "instance", - main_configs=["configs/kafka.xml"], + main_configs=["configs/kafka.xml", "configs/named_collections.xml"], user_configs=["configs/users.xml"], with_kerberized_kafka=True, clickhouse_path_dir="clickhouse_path", @@ -246,7 +246,9 @@ def test_kafka_json_as_string_no_kdc(kafka_cluster): assert instance.contains_in_log("KerberosInit failure:") -def test_kafka_config_from_sql_named_collection(kafka_cluster): +def test_kafka_config_from_named_collection(kafka_cluster): + # The named collection `kafka_config` is in `configs/named_collections.xml`: a named collection created with SQL + # cannot set `kafka.sasl_kerberos_keytab`, because it is a path on the server. kafka_produce( kafka_cluster, "kafka_json_as_string_named_collection", @@ -258,26 +260,6 @@ def test_kafka_config_from_sql_named_collection(kafka_cluster): ], ) - instance.query( - """ - DROP NAMED COLLECTION IF EXISTS kafka_config; - CREATE NAMED COLLECTION kafka_config AS - kafka.security_protocol = 'SASL_PLAINTEXT', - kafka.sasl_mechanism = 'GSSAPI', - kafka.sasl_kerberos_service_name = 'kafka', - kafka.sasl_kerberos_keytab = '/tmp/keytab/clickhouse.keytab', - kafka.sasl_kerberos_principal = 'anotherkafkauser/instance@TEST.CLICKHOUSE.TECH', - kafka.debug = 'security', - kafka.api_version_request = 'false', - - kafka_broker_list = 'kerberized_kafka1:19092', - kafka_topic_list = 'kafka_json_as_string_named_collection', - kafka_commit_on_select = 1, - kafka_group_name = 'kafka_json_as_string_named_collection', - kafka_format = 'JSONAsString', - kafka_flush_interval_ms=1000; - """ - ) instance.query( """ CREATE TABLE test.kafka (field String) diff --git a/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference new file mode 100644 index 000000000000..af49df254bf0 --- /dev/null +++ b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference @@ -0,0 +1,55 @@ +--- File properties are rejected in a collection created by SQL +kafka.ssl_key_location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_certificate_location: Kafka property `ssl.certificate.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.certificate.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_crl_location: Kafka property `ssl.crl.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_keystore_location: Kafka property `ssl.keystore.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_engine_location: Kafka property `ssl.engine.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_engine_id: Kafka property `ssl.engine.id` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_providers: Kafka property `ssl.providers` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.https_ca_location: Kafka property `https.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `https.ca.pem` instead. (BAD_ARGUMENTS) +kafka.sasl_kerberos_keytab: Kafka property `sasl.kerberos.keytab` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_kerberos_kinit_cmd: Kafka property `sasl.kerberos.kinit.cmd` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_file: Kafka property `sasl.oauthbearer.assertion.file` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_private_key_file: Kafka property `sasl.oauthbearer.assertion.private.key.file` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `sasl.oauthbearer.assertion.private.key.pem` instead. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_jwt_template_file: Kafka property `sasl.oauthbearer.assertion.jwt.template.file` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.plugin_library_paths: Kafka property `plugin.library.paths` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.offset_store_path: Kafka property `offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +--- Unlisted properties are server-local by default +kafka.future_option: Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.consumer.future.fetch_min_bytes: Kafka property `future.fetch.min.bytes` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +--- Other spellings and sections +kafka.ssl.key.location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.topic.offset.store.path: Kafka property `topic.offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.consumer.ssl_key_location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.producer.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +kafka.kafka_topic.offset_store_path: Kafka property `offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.kafka_topic.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +--- A null character in the name of a property +kafka.ssl_key_location\0suffix: Kafka property name `kafka.ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +kafka.consumer.ssl_key_location\0: Kafka property name `kafka.consumer.ssl_key_location\0` contains a null character. (BAD_ARGUMENTS) +kafka.client_rack\0suffix: Kafka property name `kafka.client_rack\0suffix` contains a null character. (BAD_ARGUMENTS) +--- The contents of the file are accepted, and also the value that is not a path +kafka.ssl_ca_location: OK +kafka.ssl_key_pem: OK +kafka.consumer.fetch.min.bytes: OK +--- A collection from the server configuration file is accepted +OK +--- Consumers are created for the accepted properties +Consumer set property fetch.min.bytes:456 +kafka_config_table: OK 0 +kafka_pem_table: OK 0 +kafka_probe_table: OK 0 +--- A property that is added after the table is created +kafka.ssl_key_pem: OK +kafka.future_option: +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +OK +kafka.ssl_key_pem: OK +kafka.ssl_key_location\0suffix: +Kafka property name `ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +Kafka property name `ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +Kafka property name `kafka.ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +OK diff --git a/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh new file mode 100755 index 000000000000..b1adaaa9e2d6 --- /dev/null +++ b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-replicated-database +# no-fasttest: the Kafka engine is not built in fasttest +# no-replicated-database: named collections created by SQL are not replicated + +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=fatal + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The `kafka.*` keys of a named collection are forwarded to librdkafka. Some librdkafka properties refer to +# the filesystem of the server: librdkafka reads, creates, loads or runs the file with the privileges of the server. +# `CREATE NAMED COLLECTION` does not require the privileges to access the files of the server, thus these +# properties are accepted only from a named collection that is defined in the server configuration file. +# No broker is needed: `CREATE TABLE` does not connect, and the configuration of a consumer or a producer +# is checked before the connection. + +collection="${CLICKHOUSE_TEST_UNIQUE_NAME}" +required_keys="kafka_broker_list = '127.0.0.1:1', kafka_topic_list = 'topic', kafka_group_name = 'group', kafka_format = 'JSONEachRow'" +table_settings="SETTINGS kafka_poll_timeout_ms = 100, kafka_flush_interval_ms = 100" +all_collections=() +all_tables=(kafka_table kafka_probe_table kafka_pem_table kafka_config_table kafka_scoped_table kafka_altered_table kafka_altered_null_table) + +function cleanup() +{ + local queries="" + for name in "${all_tables[@]}" + do + queries+=" DROP TABLE IF EXISTS ${name};" + done + for name in "${all_collections[@]}" + do + queries+=" DROP NAMED COLLECTION IF EXISTS ${name};" + done + $CLICKHOUSE_CLIENT -q "$queries" +} +trap cleanup EXIT + +# Prints `OK` and the result of the queries, or the message of the error about the Kafka property. +function run() +{ + local output + local message + if output=$($CLICKHOUSE_CLIENT -q "$1" 2>&1) + then + echo "OK${output:+ $output}" + else + message=$(grep -o 'Kafka property .*(BAD_ARGUMENTS)' <<< "$output" | sed 's/: While executing [A-Za-z]*\././' | head -1) + echo "${message:-$output}" + fi +} + +# Creates a named collection with one extended property and then a table that uses it. +function create_table() +{ + local key="$1" + local value="$2" + local table="${3:-kafka_table}" + local name="${collection}_${#all_collections[@]}" + all_collections+=("$name") + + echo "${key}: $(run " + CREATE NAMED COLLECTION ${name} AS ${required_keys}, \`${key}\` = '${value}'; + CREATE TABLE ${table} (x UInt64) ENGINE = Kafka(${name}) ${table_settings};")" +} + +# Creates a table with an accepted named collection, and then adds a property to the collection. +function alter_collection_of_existing_table() +{ + local key="$1" + local table="$2" + + create_table 'kafka.ssl_key_pem' 'contents of the file' "$table" + $CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${all_collections[-1]} SET \`${key}\` = '/etc/passwd'" + echo "${key}:" + run "SELECT count() FROM ${table} SETTINGS stream_like_engine_allow_direct_select = 1" + run "INSERT INTO ${table} VALUES (1)" + # A table that is read back from its metadata is checked in the same way as a new table. + $CLICKHOUSE_CLIENT -q "DETACH TABLE ${table}" + run "ATTACH TABLE ${table}" + # The table is attached again when the collection does not have the property. + # `ALTER NAMED COLLECTION ... DELETE` is not used: the formatted query cannot be parsed back if the key has a dot. + # The collection is created again instead: the detached table does not prevent `DROP NAMED COLLECTION`. + $CLICKHOUSE_CLIENT -q " + DROP NAMED COLLECTION ${all_collections[-1]}; + CREATE NAMED COLLECTION ${all_collections[-1]} AS ${required_keys};" + run "ATTACH TABLE ${table}" +} + +echo '--- File properties are rejected in a collection created by SQL' +for key in \ + ssl_key_location ssl_certificate_location ssl_ca_location ssl_crl_location ssl_keystore_location \ + ssl_engine_location ssl_engine_id ssl_providers https_ca_location \ + sasl_kerberos_keytab sasl_kerberos_kinit_cmd \ + sasl_oauthbearer_assertion_file sasl_oauthbearer_assertion_private_key_file sasl_oauthbearer_assertion_jwt_template_file \ + plugin_library_paths offset_store_path +do + create_table "kafka.${key}" '/etc/passwd' +done + +echo '--- Unlisted properties are server-local by default' +create_table 'kafka.future_option' '1' +create_table 'kafka.consumer.future.fetch_min_bytes' '1' + +echo '--- Other spellings and sections' +create_table 'kafka.ssl.key.location' '/etc/passwd' +create_table 'kafka.topic.offset.store.path' '/etc/passwd' +create_table 'kafka.consumer.ssl_key_location' '/etc/passwd' +create_table 'kafka.producer.ssl_ca_location' '/etc/passwd' +create_table 'kafka.kafka_topic.offset_store_path' '/etc/passwd' +create_table 'kafka.kafka_topic.ssl_ca_location' '' + +echo '--- A null character in the name of a property' +# librdkafka gets the name as a C string, thus it uses only the part before the null character: +# without the check, the first key sets `ssl.key.location`. +create_table 'kafka.ssl_key_location\0suffix' '/etc/passwd' +create_table 'kafka.consumer.ssl_key_location\0' '/etc/passwd' +create_table 'kafka.client_rack\0suffix' 'rack' + +echo '--- The contents of the file are accepted, and also the value that is not a path' +create_table 'kafka.ssl_ca_location' 'probe' kafka_probe_table +create_table 'kafka.ssl_key_pem' 'contents of the file' kafka_pem_table +create_table 'kafka.consumer.fetch.min.bytes' '123' kafka_scoped_table +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${all_collections[-1]} SET + \`kafka.consumer.kafka_topic.name\` = 'topic', \`kafka.consumer.kafka_topic.fetch_min_bytes\` = '456'" + +echo '--- A collection from the server configuration file is accepted' +run "CREATE TABLE kafka_config_table (x UInt64) ENGINE = Kafka(kafka_config_file_paths) ${table_settings}" + +echo '--- Consumers are created for the accepted properties' +# Each consumer waits for the assignment of partitions for 15 seconds, thus the tables are read at the same time. +{ + for table in kafka_probe_table kafka_pem_table kafka_config_table + do + echo "${table}: $(run "SELECT count() FROM ${table} SETTINGS stream_like_engine_allow_direct_select = 1")" & + done + $CLICKHOUSE_CLIENT --send_logs_level=trace -q 'SELECT count() FROM kafka_scoped_table SETTINGS stream_like_engine_allow_direct_select = 1' 2>&1 \ + | grep -o 'Consumer set property fetch.min.bytes:456' | sort -u & + wait +} | sort + +echo '--- A property that is added after the table is created' +alter_collection_of_existing_table 'kafka.future_option' kafka_altered_table +alter_collection_of_existing_table 'kafka.ssl_key_location\0suffix' kafka_altered_null_table From 3bde43330badcb8137ec3a32183a8272baa842fc Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Wed, 25 Nov 2026 19:52:01 +0000 Subject: [PATCH 086/116] Do not test a `MATERIALIZED` `Nested` subcolumn in the 26.3 backport The test `05508_column_ttl_nested_subcolumn_keeps_siblings` failed in the backport: the `n.e` column of `t_nested_ttl_added`, which is `MATERIALIZED` from the missing subcolumn `n.d`, was read back as garbage, followed by `Unknown packet 0 from server`. That column is not what this change fixes. A merge computes `n.e` in the reader from `n.d` filled with empty arrays, and writes it next to the array sizes shared with `n.a` and `n.c`, so its data streams are empty while the sizes say two elements. This happens in 26.3 without this backport and without any TTL (a plain `OPTIMIZE ... FINAL` is enough). In master the TTL merge passes only because `TTLTransform` recomputes the `MATERIALIZED` columns that depend on a reset column, and that change is not in 26.3. Keep the rest of the case: the added subcolumn `n.d` still gets the sizes of the other subcolumns. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=134392&sha=28a7a9aa72362e9172e9f9ea5e796e5a367a70e9&name_0=BackportPR&name_1=Stateless%20tests%20%28amd_asan%2C%20distributed%20plan%2C%20parallel%2C%201%2F2%29 https://github.com/ClickHouse/ClickHouse/pull/134392 Co-Authored-By: Claude Fable 5.2 --- .../05508_column_ttl_nested_subcolumn_keeps_siblings.reference | 2 +- .../05508_column_ttl_nested_subcolumn_keeps_siblings.sql | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference index d573890cb58f..32cc47d3073e 100644 --- a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference @@ -5,4 +5,4 @@ compact 1 ['',''] ['x','y'] enum 1 ['ok','ok'] ['x','y'] enum 2 ['other'] ['z'] single ['',''] ['',''] 2 2 -added ['a','b'] ['x','y'] ['',''] ['e','e'] +added ['a','b'] ['x','y'] ['',''] diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql index 80bf9de58148..990fb36db1db 100644 --- a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql @@ -69,11 +69,10 @@ SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, enable_vertica INSERT INTO t_nested_ttl_added VALUES (1, ['a', 'b'], ['x', 'y']); ALTER TABLE t_nested_ttl_added ADD COLUMN `n.d` Array(String); -ALTER TABLE t_nested_ttl_added ADD COLUMN `n.e` Array(String) MATERIALIZED arrayMap(x -> concat('e', x), `n.d`); ALTER TABLE t_nested_ttl_added ADD COLUMN ts DateTime DEFAULT '2020-01-01 00:00:00'; ALTER TABLE t_nested_ttl_added MODIFY TTL ts + INTERVAL 1 DAY WHERE id = 100 SETTINGS materialize_ttl_after_modify = 0; OPTIMIZE TABLE t_nested_ttl_added FINAL; -SELECT 'added', `n.a`, `n.c`, `n.d`, `n.e` FROM t_nested_ttl_added; +SELECT 'added', `n.a`, `n.c`, `n.d` FROM t_nested_ttl_added; DROP TABLE t_nested_ttl_wide; DROP TABLE t_nested_ttl_rows; From 52651f4e691b076f0b854fe82da3876bd0f83ea4 Mon Sep 17 00:00:00 2001 From: Robert Schulze Date: Wed, 25 Nov 2026 21:40:15 +0000 Subject: [PATCH 087/116] fix, maybe probably --- .../05871_keyed_siphash_key_masking.reference | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference index f7167d89dfe9..c7fe4b160b3b 100644 --- a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference @@ -2,17 +2,22 @@ -- { echoOn } EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); -SELECT sipHash64Keyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +SELECT sipHash64Keyed(\'[HIDDEN]\', number, \'visible_input\') +FROM numbers(1) EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); -SELECT sipHash128Keyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +SELECT sipHash128Keyed(\'[HIDDEN]\', number, \'visible_input\') +FROM numbers(1) EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); -SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', number, \'visible_input\') +FROM numbers(1) -- A key which is not a literal is hidden as well. EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); -SELECT sipHash64Keyed(\'[HIDDEN]\', \'visible_input\')\nFROM numbers(1) +SELECT sipHash64Keyed(\'[HIDDEN]\', \'visible_input\') +FROM numbers(1) -- The functions without a key are not affected. EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); -SELECT sipHash64(tuple(CAST(\'1311768467463790320\', \'UInt64\'), CAST(\'18364758544493064720\', \'UInt64\')), \'visible_input\')\nFROM system.one +SELECT sipHash64((CAST(\'1311768467463790320\', \'UInt64\'), CAST(\'18364758544493064720\', \'UInt64\')), \'visible_input\') +FROM system.one 1 SELECT sipHash128Keyed(\'[HIDDEN]\', \'logged_input_2\') FORMAT `Null` SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', \'logged_input_3\') FORMAT `Null` From 80bfd58300aa5be18d297b90379784bfb1fd6109 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1nos=20Benjamin=20Antal?= Date: Wed, 25 Nov 2026 22:29:49 +0000 Subject: [PATCH 088/116] Preserve the source when copying a named collection --- src/Common/NamedCollections/NamedCollections.cpp | 11 +++++++---- src/Common/NamedCollections/NamedCollections.h | 14 +++++--------- src/Storages/Kafka/StorageKafkaUtils.cpp | 8 ++------ 3 files changed, 14 insertions(+), 19 deletions(-) diff --git a/src/Common/NamedCollections/NamedCollections.cpp b/src/Common/NamedCollections/NamedCollections.cpp index 90e4b5aaa141..6b524d379a71 100644 --- a/src/Common/NamedCollections/NamedCollections.cpp +++ b/src/Common/NamedCollections/NamedCollections.cpp @@ -178,10 +178,12 @@ class NamedCollection::Impl NamedCollection::NamedCollection( ImplPtr pimpl_, const std::string & collection_name_, - const bool is_mutable_) + const bool is_mutable_, + const SourceId source_id_) : pimpl(std::move(pimpl_)) , collection_name(collection_name_) , is_mutable(is_mutable_) + , source_id(source_id_) { } @@ -286,7 +288,7 @@ MutableNamedCollectionPtr NamedCollection::duplicate() const std::lock_guard lock(mutex); auto impl = pimpl->createCopy(collection_name); return std::unique_ptr( - new NamedCollection(std::move(impl), collection_name, true)); + new NamedCollection(std::move(impl), collection_name, true, source_id)); } NamedCollection::Keys NamedCollection::getKeys(ssize_t depth, const std::string & prefix) const @@ -335,7 +337,8 @@ NamedCollectionFromConfig::NamedCollectionFromConfig( const std::string & collection_name_, const std::string & collection_path_, const Keys & keys_) - : NamedCollection(Impl::create(config_, collection_name_, collection_path_, keys_), collection_name_, /* is_mutable */ false) + : NamedCollection( + Impl::create(config_, collection_name_, collection_path_, keys_), collection_name_, /* is_mutable */ false, SourceId::CONFIG) { } @@ -356,7 +359,7 @@ MutableNamedCollectionPtr NamedCollectionFromSQL::create(const ASTCreateNamedCol } NamedCollectionFromSQL::NamedCollectionFromSQL(const ASTCreateNamedCollectionQuery & query_) - : NamedCollection(nullptr, query_.collection_name, true) + : NamedCollection(nullptr, query_.collection_name, true, SourceId::SQL) , create_query_ptr(query_.clone()->as()) { const auto config = NamedCollectionConfiguration::createConfiguration(collection_name, create_query_ptr.changes, create_query_ptr.overridability); diff --git a/src/Common/NamedCollections/NamedCollections.h b/src/Common/NamedCollections/NamedCollections.h index 673476271387..bc0693724b8c 100644 --- a/src/Common/NamedCollections/NamedCollections.h +++ b/src/Common/NamedCollections/NamedCollections.h @@ -29,8 +29,6 @@ class NamedCollection using Keys = std::set>; enum class SourceId : uint8_t { - /// None source_id is possible only if the object is a - /// duplicate of some named collection. See `duplicate` method. NONE = 0, CONFIG = 1, SQL = 2, @@ -65,7 +63,7 @@ class NamedCollection template void remove(const Key & key); - /// Creates mutable, with NONE source id full copy. + /// Creates a mutable full copy, keeping the source of the original. MutableNamedCollectionPtr duplicate() const; Keys getKeys(ssize_t depth = -1, const std::string & prefix = "") const; @@ -81,7 +79,7 @@ class NamedCollection bool isMutable() const { return is_mutable; } - virtual SourceId getSourceId() const { return SourceId::NONE; } + SourceId getSourceId() const { return source_id; } virtual String getCreateStatement(bool /*show_secrects*/) { return {}; } @@ -95,7 +93,8 @@ class NamedCollection NamedCollection( ImplPtr pimpl_, const std::string & collection_name, - bool is_mutable_ + bool is_mutable_, + SourceId source_id_ ); void assertMutable() const; @@ -104,6 +103,7 @@ class NamedCollection ImplPtr pimpl; const std::string collection_name; const bool is_mutable; + const SourceId source_id; mutable std::mutex mutex; }; @@ -116,8 +116,6 @@ class NamedCollectionFromSQL final : public NamedCollection void update(const ASTAlterNamedCollectionQuery & query) override; - NamedCollection::SourceId getSourceId() const override { return SourceId::SQL; } - private: explicit NamedCollectionFromSQL(const ASTCreateNamedCollectionQuery & query_); @@ -138,8 +136,6 @@ class NamedCollectionFromConfig final : public NamedCollection void update(const ASTAlterNamedCollectionQuery & /*query*/) override { NamedCollection::assertMutable(); } - NamedCollection::SourceId getSourceId() const override { return SourceId::CONFIG; } - private: NamedCollectionFromConfig( diff --git a/src/Storages/Kafka/StorageKafkaUtils.cpp b/src/Storages/Kafka/StorageKafkaUtils.cpp index c20430d822d5..44e594f00c95 100644 --- a/src/Storages/Kafka/StorageKafkaUtils.cpp +++ b/src/Storages/Kafka/StorageKafkaUtils.cpp @@ -117,16 +117,12 @@ void registerStorageKafka(StorageFactory & factory) &args.table_id, args.storage_def->settings)) { - collection_name = assert_cast(args.engine_args[0].get())->name(); - /// The named collection is checked every time, also when the definition is read back from metadata /// (server startup, short `ATTACH`): the collection can change after the table is created. - /// `named_collection` is a copy, and a copy does not keep the source of the collection - /// (see `NamedCollection::duplicate`). Thus the collection of the factory is checked: - /// the configuration of the consumers and of the producers is loaded from it. - KafkaConfigLoader::checkNamedCollection(*NamedCollectionFactory::instance().get(collection_name)); + KafkaConfigLoader::checkNamedCollection(*named_collection); kafka_settings->loadFromNamedCollection(named_collection); + collection_name = assert_cast(args.engine_args[0].get())->name(); } if (has_settings) From 215c4d2e707a4f913f1ea74e38434317b041f58f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1nos=20Benjamin=20Antal?= Date: Tue, 19 May 2026 07:26:15 +0000 Subject: [PATCH 089/116] Do not reuse macro expansion info for consecutive calls (cherry picked from commit dde44b6b52439da85158b2b158df09f8db1c72a1) --- src/Storages/ObjectStorageQueue/registerQueueStorage.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 5408a63d273b..6dccd0d714a8 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -119,8 +119,13 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) if (!allow_uuid_macro) info.table_id.uuid = UUIDHelpers::Nil; - /// Make sure that {uuid} macro is allowed, if present. - args.getContext()->getMacros()->expand(path, info); + { + /// Some fields (e.g.: level) in MacroExpansionInfo are modified during macro expansion. + /// Let's make a copy, so the next call won't interfere with this one. + auto info_copy = info; + /// Make sure that {uuid} macro is allowed, if present. + args.getContext()->getMacros()->expand(path, info); + } /// Actually expand all the macros except {uuid} macro. info.expand_special_macros_only = true; From bc12da5e0536d44a0aad1539d3096db22a3153e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1nos=20Benjamin=20Antal?= Date: Tue, 19 May 2026 12:04:30 +0000 Subject: [PATCH 090/116] Use the copied MacroExpansionInfo (cherry picked from commit a73d58f40ac7bb7696799741761cb7dcbaad2d29) --- src/Storages/ObjectStorageQueue/registerQueueStorage.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 6dccd0d714a8..e6deb4bb7e7c 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -124,7 +124,7 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) /// Let's make a copy, so the next call won't interfere with this one. auto info_copy = info; /// Make sure that {uuid} macro is allowed, if present. - args.getContext()->getMacros()->expand(path, info); + args.getContext()->getMacros()->expand(path, info_copy); } /// Actually expand all the macros except {uuid} macro. From 5f6c21900d7115a6790d668b2569de0c66b25d3f Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Thu, 26 Nov 2026 13:45:25 +0000 Subject: [PATCH 091/116] Backport #133845 to 26.3: Bump `krb5` from 1.22.2 to 1.22.3 --- contrib/krb5 | 2 +- contrib/krb5-cmake/autoconf_darwin.h | 4 ++-- contrib/krb5-cmake/autoconf_linux.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/contrib/krb5 b/contrib/krb5 index 857c2d1edd7a..17f660ca561d 160000 --- a/contrib/krb5 +++ b/contrib/krb5 @@ -1 +1 @@ -Subproject commit 857c2d1edd7a4218b84594768587aa53fd63da9e +Subproject commit 17f660ca561db6716125041396ce2cdd8ebd594a diff --git a/contrib/krb5-cmake/autoconf_darwin.h b/contrib/krb5-cmake/autoconf_darwin.h index 64c28f90b41b..7c7ee22fa1ff 100644 --- a/contrib/krb5-cmake/autoconf_darwin.h +++ b/contrib/krb5-cmake/autoconf_darwin.h @@ -635,7 +635,7 @@ #define PACKAGE_NAME "Kerberos 5" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Kerberos 5 1.22.1" +#define PACKAGE_STRING "Kerberos 5 1.22.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "krb5" @@ -644,7 +644,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.22.1" +#define PACKAGE_VERSION "1.22.3" /* Define if setjmp indicates POSIX interface */ #define POSIX_SETJMP 1 diff --git a/contrib/krb5-cmake/autoconf_linux.h b/contrib/krb5-cmake/autoconf_linux.h index ec8e867eec38..efa76cd145fc 100644 --- a/contrib/krb5-cmake/autoconf_linux.h +++ b/contrib/krb5-cmake/autoconf_linux.h @@ -637,7 +637,7 @@ #define PACKAGE_NAME "Kerberos 5" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Kerberos 5 1.22.1" +#define PACKAGE_STRING "Kerberos 5 1.22.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "krb5" @@ -646,7 +646,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.22.1" +#define PACKAGE_VERSION "1.22.3" /* Define if setjmp indicates POSIX interface */ /* #undef POSIX_SETJMP */ From 583b8ce4953a3da589c7969dd14b6b9b74968266 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Thu, 26 Nov 2026 16:09:40 +0000 Subject: [PATCH 092/116] Update autogenerated version to 26.3.72.6 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index c39ad8897825..63b28418a544 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54579) +SET(VERSION_REVISION 54580) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 72) -SET(VERSION_GITHASH 7100b1a7cf9138b947e94017164a35223581fc21) -SET(VERSION_DESCRIBE v26.3.72.1-lts) -SET(VERSION_STRING 26.3.72.1) +SET(VERSION_PATCH 73) +SET(VERSION_GITHASH a587d4a24dd81de9a0793ec1567d9f95dff33e12) +SET(VERSION_DESCRIBE v26.3.73.1-lts) +SET(VERSION_STRING 26.3.73.1) # end of autochange From fe9c5eedae05dbdbdffed7954d97bc2e2a318295 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Thu, 26 Nov 2026 16:21:29 +0000 Subject: [PATCH 093/116] Backport #134248 to 26.3: Bump `zstd` from v1.4.7-3098-g8388bfae to v1.6.0-11-g16631708 --- contrib/zstd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/zstd b/contrib/zstd index 437081852c39..1663170820f4 160000 --- a/contrib/zstd +++ b/contrib/zstd @@ -1 +1 @@ -Subproject commit 437081852c396eeb61edb7d47044d8cad911885e +Subproject commit 1663170820f4825123ddfc4976223ad2c78b21cc From 84224cdb01b904e5d6e37dc9d18c98d58008efad Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Thu, 26 Nov 2026 16:47:00 +0000 Subject: [PATCH 094/116] Backport #133762 to 26.3: Refuse `SET DEFAULT ROLE` in readonly mode when `SET ROLE` is refused --- .../_server_settings_outside_source.md | 2 +- programs/server/config.xml | 2 +- .../Access/InterpreterSetRoleQuery.cpp | 34 ++++++++++---- .../test_readonly_restricts_set_role/test.py | 46 +++++++++++++++++++ 4 files changed, 74 insertions(+), 10 deletions(-) diff --git a/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md b/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md index 29a47ac82112..2f7ef5e437df 100644 --- a/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md +++ b/docs/en/operations/server-configuration-parameters/_server_settings_outside_source.md @@ -1837,7 +1837,7 @@ Settings for optional improvements in the access control system. | Setting | Description | Default | |-------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| | `on_cluster_queries_require_cluster_grant` | Sets whether `ON CLUSTER` queries require the `CLUSTER` grant. | `true` | -| `readonly_restricts_set_role` | Sets whether the `SET ROLE` statement is refused when the session or the query is readonly. When `false`, `readonly` does not restrict `SET ROLE`. The `role` HTTP query parameter is not affected. | `false` | +| `readonly_restricts_set_role` | Sets whether the `SET ROLE` and `SET DEFAULT ROLE` statements are refused when the session or the query is readonly. When `false`, `readonly` does not restrict `SET ROLE`, nor `SET DEFAULT ROLE ... TO CURRENT_USER`. The `role` HTTP query parameter is not affected. | `false` | | `role_cache_expiration_time_seconds` | Sets the number of seconds since last access, that a role is stored in the Role Cache. | `600` | | `select_from_information_schema_requires_grant` | Sets whether `SELECT * FROM information_schema.
` requires any grants and can be executed by any user. If set to true, then this query requires `GRANT SELECT ON information_schema.
`, just as for ordinary tables. | `true` | | `select_from_system_db_requires_grant` | Sets whether `SELECT * FROM system.
` requires any grants and can be executed by any user. If set to true then this query requires `GRANT SELECT ON system.
` just as for non-system tables. Exceptions: a few system tables (`tables`, `columns`, `databases`, and some constant tables like `one`, `contributors`) are still accessible for everyone; and if there is a `SHOW` privilege (e.g. `SHOW USERS`) granted then the corresponding system table (i.e. `system.users`) will be accessible. | `true` | diff --git a/programs/server/config.xml b/programs/server/config.xml index 1ebf35710243..7236111373ea 100644 --- a/programs/server/config.xml +++ b/programs/server/config.xml @@ -870,7 +870,7 @@ however you can change this behaviour by setting this to true --> false - false diff --git a/src/Interpreters/Access/InterpreterSetRoleQuery.cpp b/src/Interpreters/Access/InterpreterSetRoleQuery.cpp index e175282ff202..252ca3e991e9 100644 --- a/src/Interpreters/Access/InterpreterSetRoleQuery.cpp +++ b/src/Interpreters/Access/InterpreterSetRoleQuery.cpp @@ -23,6 +23,26 @@ namespace ErrorCodes } +namespace +{ + +/// `readonly` is read from the query context: a client `--readonly 1` raises it there only, while a +/// mid-session `SET readonly = 1` also reaches it because a query context inherits session settings. +void throwIfReadonlyRestrictsSetRole(const ContextPtr & context, std::string_view statement) +{ + if (context->getAccessControl().doesReadonlyRestrictSetRole() && context->getSettingsRef()[Setting::readonly]) + { + throw Exception( + ErrorCodes::READONLY, + "Cannot execute {} in readonly mode. " + "This restriction is enabled by access_control_improvements.readonly_restricts_set_role", + statement); + } +} + +} + + BlockIO InterpreterSetRoleQuery::execute() { const auto & query = query_ptr->as(); @@ -38,14 +58,7 @@ void InterpreterSetRoleQuery::setRole(const ASTSetRoleQuery & query) { auto session_context = getContext()->getSessionContext(); - /// `readonly` is read from the query context: a client `--readonly 1` raises it there only, while a - /// mid-session `SET readonly = 1` also reaches it because a query context inherits session settings. - if (getContext()->getAccessControl().doesReadonlyRestrictSetRole() - && getContext()->getSettingsRef()[Setting::readonly]) - throw Exception( - ErrorCodes::READONLY, - "Cannot execute SET ROLE in readonly mode. " - "This restriction is enabled by access_control_improvements.readonly_restricts_set_role"); + throwIfReadonlyRestrictsSetRole(getContext(), "SET ROLE"); if (query.kind == ASTSetRoleQuery::Kind::SET_ROLE_DEFAULT) session_context->setCurrentRolesDefault(); @@ -56,6 +69,11 @@ void InterpreterSetRoleQuery::setRole(const ASTSetRoleQuery & query) void InterpreterSetRoleQuery::setDefaultRole(const ASTSetRoleQuery & query) { + /// The default roles are what the next session of the user starts with, so changing them is a way around the + /// restriction of `SET ROLE` if it is not restricted as well. The access check below does not catch it for the + /// user's own default roles: `TO CURRENT_USER` requires no grant, so `readonly` has nothing to deny there. + throwIfReadonlyRestrictsSetRole(getContext(), "SET DEFAULT ROLE"); + getContext()->checkAccess(query.to_users->collectRequiredGrants(AccessType::ALTER_USER)); auto & access_control = getContext()->getAccessControl(); diff --git a/tests/integration/test_readonly_restricts_set_role/test.py b/tests/integration/test_readonly_restricts_set_role/test.py index c36af86fa720..a640267ad01f 100644 --- a/tests/integration/test_readonly_restricts_set_role/test.py +++ b/tests/integration/test_readonly_restricts_set_role/test.py @@ -25,6 +25,11 @@ def started_cluster(): "CREATE USER probe IDENTIFIED WITH plaintext_password BY 'x';" "GRANT ro_role, other_role TO probe;" "ALTER USER probe DEFAULT ROLE ro_role;" + # A separate user for `SET DEFAULT ROLE`, so that the cases changing its default roles + # do not affect the ones above, which expect `probe` to start with `ro_role`. + "CREATE USER default_role_probe IDENTIFIED WITH plaintext_password BY 'x';" + "GRANT ro_role, other_role TO default_role_probe;" + "ALTER USER default_role_probe DEFAULT ROLE ro_role;" ) yield cluster @@ -114,3 +119,44 @@ def post(sql, **extra): answer, error = post("SELECT currentRoles()") assert error is None assert answer.strip() == "['ro_role']" + + +def default_roles(node): + return node.query( + "SELECT default_roles_list FROM system.users WHERE name = 'default_role_probe'" + ).strip() + + +@pytest.mark.parametrize( + "readonly, statement", + [ + # `TO CURRENT_USER` requires no grant, so it is not refused by the access check. + (1, "SET DEFAULT ROLE other_role TO CURRENT_USER"), + (1, "SET DEFAULT ROLE ALL TO CURRENT_USER"), + (1, "SET DEFAULT ROLE ALL EXCEPT ro_role TO CURRENT_USER"), + (1, "SET DEFAULT ROLE NONE TO CURRENT_USER"), + (2, "SET DEFAULT ROLE other_role TO CURRENT_USER"), + ], +) +def test_set_default_role_refused_when_enabled(readonly, statement): + _, error = node_on.query_and_get_answer_with_error( + statement, user="default_role_probe", password="x", settings={"readonly": readonly} + ) + assert "READONLY" in error + assert default_roles(node_on) == "['ro_role']" + # The next session starts with the same role. + answer = node_on.query( + "SELECT currentRoles()", user="default_role_probe", password="x" + ) + assert answer.strip() == "['ro_role']" + + +def test_set_default_role_allowed_at_default_settings(): + _, error = node_off.query_and_get_answer_with_error( + "SET DEFAULT ROLE other_role TO CURRENT_USER", + user="default_role_probe", + password="x", + settings={"readonly": 1}, + ) + assert error == "" + assert default_roles(node_off) == "['other_role']" From 5bef7c36a8b769fa99f0d727ca34c4351d565d0e Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Fri, 27 Nov 2026 14:08:44 +0000 Subject: [PATCH 095/116] Backport #132506 to 26.3: Update mongo-c-driver to reject malformed cursor batches --- contrib/mongo-c-driver | 2 +- .../malformed_cursor_batch_server.py | 151 ++++++++++++++++++ .../test_table_function_mongodb/test.py | 65 +++++++- 3 files changed, 216 insertions(+), 2 deletions(-) create mode 100644 tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py diff --git a/contrib/mongo-c-driver b/contrib/mongo-c-driver index 58b4e1f39c6f..69c77fcb894e 160000 --- a/contrib/mongo-c-driver +++ b/contrib/mongo-c-driver @@ -1 +1 @@ -Subproject commit 58b4e1f39c6f8bcf4da4204deb84f9b3527388d4 +Subproject commit 69c77fcb894eeadd4cc2059d4c65e8968db1462c diff --git a/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py b/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py new file mode 100644 index 000000000000..8642b61ce073 --- /dev/null +++ b/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 + +""" +A fake MongoDB server that answers `find` and `getMore` with hand-encoded cursor replies. + +The collection name of the `find` command selects the reply, see `SCENARIOS`. +The cursor ID of the `getMore` command selects the next batch. + +The server listens on a free port that the kernel selects, and writes the port number to the port file. + +Usage: malformed_cursor_batch_server.py +""" + +import os +import socketserver +import struct +import sys + + +# Encode BSON directly so the server can send malformed embedded documents. +def document(*elements): + body = b"".join(elements) + return struct.pack(" (first batch, cursor ID, next batch). +# A nonzero cursor ID keeps the cursor open. Each open cursor has a different ID. +# If the next batch is `None`, the server does not expect `getMore`. +SCENARIOS = { + "valid": ([VALID, VALID], 0, None), + "empty": ([], 0, None), + # Neither a short length nor a missing NUL terminator must abort the process. + "short": ([SHORT], 0, None), + "nonnul": ([NONNUL], 0, None), + # A bad document after a valid one, while the cursor is still open. + "after_valid": ([VALID, SHORT], 1, None), + # A bad document in a `getMore` reply. + "next_batch": ([VALID], 2, [NONNUL]), +} +NEXT_BATCHES = { + cursor_id: (collection, next_batch) + for collection, (_, cursor_id, next_batch) in SCENARIOS.items() + if cursor_id != 0 +} + + +def cursor_reply(collection, documents, batch, cursor_id): + return document( + element( + 0x03, + "cursor", + document( + element(0x12, "id", struct.pack(" /var/log/clickhouse-server/malformed_cursor_batch_server.log 2>&1", + ], + detach=True, + ) + # The server binds to port 0 in the container of `node`, and writes the port to the port file when it listens. + port = wait_condition( + lambda: node.exec_in_container( + ["bash", "-c", f"cat {port_file} 2>/dev/null"], nothrow=True + ).strip(), + lambda reply: reply.isdigit(), + max_attempts=40, + delay=0.5, + ) + return f"127.0.0.1:{port}" + + +def test_malformed_cursor_batch(started_cluster, malformed_cursor_batch_server): + # A MongoDB server that returned a malformed document in a cursor batch used to abort the ClickHouse server + # (`BSON_ASSERT` in `_mongoc_cursor_response_read` of the C driver). Now the query fails with an exception. + # The fake MongoDB server answers `find` and `getMore` with hand-encoded replies. + # The collection name selects the reply. + node = started_cluster.instances["node"] + + def select(collection): + return ( + f"SELECT * FROM mongodb('{malformed_cursor_batch_server}', 'db', '{collection}', '', '', 'v String', " + "'serverSelectionTimeoutMS=30000&socketTimeoutMS=30000')" + ) + + # The fake server is good enough for the driver when all documents are valid. + assert node.query(select("valid")) == "hello\nhello\n" + assert node.query(select("empty")) == "" + + for collection in [ + # Neither a short length nor a missing NUL terminator must abort the process. + "short", + "nonnul", + # Reject a bad document after reading a valid one, even when the cursor is still open. + "after_valid", + # The same validation must apply to a `getMore` reply. + "next_batch", + ]: + error = node.query_and_get_error(select(collection)) + assert "Invalid BSON document in cursor reply." in error, (collection, error) + assert node.query("SELECT 1") == "1\n", collection From 57815f89b29da192dd4fb6bb672e07af86e9b6ee Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Fri, 27 Nov 2026 15:35:58 +0000 Subject: [PATCH 096/116] Update autogenerated version to 26.3.73.9 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index 63b28418a544..cf2e1afb217b 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54580) +SET(VERSION_REVISION 54581) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 73) -SET(VERSION_GITHASH a587d4a24dd81de9a0793ec1567d9f95dff33e12) -SET(VERSION_DESCRIBE v26.3.73.1-lts) -SET(VERSION_STRING 26.3.73.1) +SET(VERSION_PATCH 74) +SET(VERSION_GITHASH f78b33d463261f7accb099733697dac2a1c66835) +SET(VERSION_DESCRIBE v26.3.74.1-lts) +SET(VERSION_STRING 26.3.74.1) # end of autochange From 295ae3cd2fcc529420a0f8884711f8eb33b09557 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Fri, 27 Nov 2026 16:31:52 +0000 Subject: [PATCH 097/116] Backport #124094 to 26.3: Run apk upgrade in alpine Docker images so base packages get security fixes --- docker/keeper/Dockerfile | 4 ++++ docker/server/Dockerfile.alpine | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/docker/keeper/Dockerfile b/docker/keeper/Dockerfile index 70b045cdc1ae..e2ea0519ef56 100644 --- a/docker/keeper/Dockerfile +++ b/docker/keeper/Dockerfile @@ -54,6 +54,9 @@ RUN addgroup -S -g "${DEFAULT_GID}" clickhouse && \ adduser -S -h "/var/lib/clickhouse" -s /bin/bash -G clickhouse -g "ClickHouse keeper" -u "${DEFAULT_UID}" clickhouse ARG TARGETARCH +# `apk upgrade` runs before `apk add` because `apk add` never bumps packages already in +# the base image, so without it the image keeps whatever (possibly vulnerable) packages +# the `alpine` snapshot had at build time. RUN arch=${TARGETARCH:-amd64} \ && cd /tmp && rm -f /tmp/*tgz && rm -f /tmp/*tgz.sha512 |: \ && if [ -n "${DIRECT_DOWNLOAD_URLS}" ]; then \ @@ -79,6 +82,7 @@ RUN arch=${TARGETARCH:-amd64} \ ; done \ && rm /tmp/*.tgz /install -r \ && chmod +x /entrypoint.sh \ + && apk upgrade --no-cache \ && apk add --no-cache su-exec bash tzdata \ && cp /usr/share/zoneinfo/UTC /etc/localtime \ && echo "UTC" > /etc/timezone diff --git a/docker/server/Dockerfile.alpine b/docker/server/Dockerfile.alpine index 4f4aab188b33..afbefe51f998 100644 --- a/docker/server/Dockerfile.alpine +++ b/docker/server/Dockerfile.alpine @@ -50,6 +50,9 @@ ARG DEFAULT_GID="101" RUN addgroup -S -g "${DEFAULT_GID}" clickhouse && \ adduser -S -h "/var/lib/clickhouse" -s /bin/bash -G clickhouse -g "ClickHouse server" -u "${DEFAULT_UID}" clickhouse +# `apk upgrade` runs before `apk add` because `apk add` never bumps packages already in +# the base image, so without it the image keeps whatever (possibly vulnerable) packages +# the `alpine` snapshot had at build time. RUN arch=${TARGETARCH:-amd64} \ && cd /tmp \ && if [ -n "${DIRECT_DOWNLOAD_URLS}" ]; then \ @@ -74,6 +77,7 @@ RUN arch=${TARGETARCH:-amd64} \ ; done \ && rm /tmp/*.tgz /install -r \ && chmod +x /entrypoint.sh \ + && apk upgrade --no-cache \ && apk add --no-cache bash tzdata \ && cp /usr/share/zoneinfo/UTC /etc/localtime \ && echo "UTC" > /etc/timezone From 05b3846a600308c3ab1bdd47f4da0b00fa1a28c1 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Fri, 27 Nov 2026 19:16:27 +0000 Subject: [PATCH 098/116] Backport #134753 to 26.3: Fix dictionaries with a remote ClickHouse source over `Distributed` with a cluster secret --- src/Interpreters/Session.cpp | 6 ++++- .../test.py | 19 ++++++++------ ...rce_over_distributed_with_secret.reference | 1 + ...te_source_over_distributed_with_secret.sql | 25 +++++++++++++++++++ 4 files changed, 42 insertions(+), 9 deletions(-) create mode 100644 tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference create mode 100644 tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql diff --git a/src/Interpreters/Session.cpp b/src/Interpreters/Session.cpp index c145b3091a05..4ead0a20dbb2 100644 --- a/src/Interpreters/Session.cpp +++ b/src/Interpreters/Session.cpp @@ -706,7 +706,11 @@ ContextMutablePtr Session::makeQueryContextImpl(const ClientInfo * client_info_t if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::NO_QUERY) query_context->setQueryKind(ClientInfo::QueryKind::INITIAL_QUERY); - if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::INITIAL_QUERY) + if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::INITIAL_QUERY || + /// Some places can send SECONDARY_QUERY with initial_user empty (e.g. dictionaries), and this is OK, + /// it should not block subsequent queries over TCP_INTERSERVER in this session + /// (Connection::sendQuery() forbids forwarding if initial_user != current_user) + (query_context->getClientInfo().initial_user.empty() && !query_context->getClientInfo().current_user.empty())) { query_context->setInitialUserName(query_context->getClientInfo().current_user); query_context->setInitialAddress(*query_context->getClientInfo().current_address); diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/test.py b/tests/integration/test_interserver_marker_requires_cluster_secret/test.py index dca0c1eb639a..e19b9a9be2a0 100644 --- a/tests/integration/test_interserver_marker_requires_cluster_secret/test.py +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/test.py @@ -138,10 +138,10 @@ def send_forged_secondary_query(user, password, query, forged_initial_user): def test_forged_secondary_query_cannot_impersonate_on_secret_cluster(started_cluster): - """A user forges a SECONDARY_QUERY and reads a Distributed table over a secret cluster. The fix - refuses to forward a client-chosen initial_user, so the attacker never gets the admin-only data -- - neither by impersonating 'admin' nor by sending an empty initial_user (which the shard would - otherwise authenticate as no user, i.e. with full access).""" + """A user forges a SECONDARY_QUERY and reads a Distributed table over a secret cluster. The attacker + never gets the admin-only data: a query impersonating 'admin' is not forwarded, and an empty + initial_user means the authenticated user (the shard would otherwise authenticate it as no user, + i.e. with full access).""" try: # A table only `admin` may read, exposed through a Distributed table over the secret cluster. node.query( @@ -158,8 +158,12 @@ def test_forged_secondary_query_cannot_impersonate_on_secret_cluster(started_clu node.query("CREATE USER attacker IDENTIFIED WITH no_password HOST ANY") node.query("GRANT SELECT ON default.secret_dist TO attacker") - # The forged initial_user is rejected whether it impersonates 'admin' or is empty. - for forged_initial_user in [b"admin", b""]: + for forged_initial_user, expected_error in [ + # Another user's name is refused at the interserver-secret boundary. + (b"admin", b"Refusing to forward a query over the cluster secret"), + # An empty name means the authenticated user, which has no access on the shard. + (b"", b"attacker: Not enough privileges"), + ]: response = send_forged_secondary_query( user=b"attacker", password=b"", @@ -169,8 +173,7 @@ def test_forged_secondary_query_cannot_impersonate_on_secret_cluster(started_clu # The attacker must not obtain the admin-only data. assert b"TOP_SECRET_ADMIN_ONLY" not in response - # The query is rejected at the interserver-secret boundary, not silently downgraded. - assert b"Refusing to forward a query over the cluster secret" in response + assert expected_error in response finally: node.query("DROP TABLE IF EXISTS default.secret_dist SYNC") node.query("DROP TABLE IF EXISTS default.secret_data SYNC") diff --git a/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference new file mode 100644 index 000000000000..78981922613b --- /dev/null +++ b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference @@ -0,0 +1 @@ +a diff --git a/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql new file mode 100644 index 000000000000..7546f3b71464 --- /dev/null +++ b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql @@ -0,0 +1,25 @@ +-- Tags: no-fasttest +-- no-fasttest: the cluster secret requires SSL + +-- A remote (non-local) ClickHouse dictionary source sends its query without `initial_user`, +-- and the remote server has to forward it over a cluster with a secret. + +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dist; +DROP TABLE IF EXISTS data; + +CREATE TABLE data (key UInt64, value String) ENGINE = MergeTree ORDER BY key; +INSERT INTO data VALUES (1, 'a'); +CREATE TABLE dist AS data ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), data); + +CREATE DICTIONARY dict (key UInt64, value String) +PRIMARY KEY key +SOURCE(CLICKHOUSE(HOST '127.0.0.2' PORT tcpPort() DB currentDatabase() TABLE 'dist')) +LAYOUT(HASHED()) +LIFETIME(0); + +SELECT dictGet('dict', 'value', 1::UInt64); + +DROP DICTIONARY dict; +DROP TABLE dist; +DROP TABLE data; From 8ca07490b78b78ad61647f367d6be78a17513f77 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Fri, 27 Nov 2026 19:59:16 +0000 Subject: [PATCH 099/116] Backport #134279 to 26.3: Fix TTL merges of tables with a column TTL on an `ALIAS` or `EPHEMERAL` column --- src/Processors/Transforms/TTLTransform.cpp | 3 ++- ...4_column_ttl_on_alias_column_merge.reference | 3 +++ .../05874_column_ttl_on_alias_column_merge.sql | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference create mode 100644 tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql diff --git a/src/Processors/Transforms/TTLTransform.cpp b/src/Processors/Transforms/TTLTransform.cpp index 496b0f883e5f..e84465cbb661 100644 --- a/src/Processors/Transforms/TTLTransform.cpp +++ b/src/Processors/Transforms/TTLTransform.cpp @@ -142,6 +142,7 @@ TTLTransform::TTLTransform( if (!expired_columns_map.contains(name)) { auto [default_expression, default_column_name] = build_default_expr(name); + auto physical_column = storage_columns.tryGetPhysical(name); algorithms.emplace_back(std::make_unique( getExpressions(description, subqueries_for_sets, context), description, @@ -152,7 +153,7 @@ TTLTransform::TTLTransform( default_expression, default_column_name, isCompactPart(data_part), - shares_nested_offsets(storage_columns.getPhysical(name)))); + physical_column && shares_nested_offsets(*physical_column))); } } } diff --git a/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference new file mode 100644 index 000000000000..616bb8316151 --- /dev/null +++ b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference @@ -0,0 +1,3 @@ +1 [1,2,3] [1,2,3] +2 [4] [4] +1 5 diff --git a/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql new file mode 100644 index 000000000000..ee1916b245ab --- /dev/null +++ b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql @@ -0,0 +1,17 @@ +-- A column TTL on a column that is not stored (ALIAS, EPHEMERAL) must not break TTL merges. + +DROP TABLE IF EXISTS t_alias_ttl; +CREATE TABLE t_alias_ttl (id UInt64, dt Date, arr Array(UInt64), al Array(UInt64) ALIAS arr TTL dt + INTERVAL 1 MONTH) +ENGINE = MergeTree ORDER BY id; +INSERT INTO t_alias_ttl VALUES (1, '2000-01-01', [1, 2, 3]), (2, '2100-01-01', [4]); +OPTIMIZE TABLE t_alias_ttl FINAL; +SELECT id, arr, al FROM t_alias_ttl ORDER BY id; +DROP TABLE t_alias_ttl; + +DROP TABLE IF EXISTS t_ephemeral_ttl; +CREATE TABLE t_ephemeral_ttl (id UInt64, dt Date, e UInt64 EPHEMERAL 0 TTL dt + INTERVAL 1 MONTH, v UInt64 DEFAULT e) +ENGINE = MergeTree ORDER BY id; +INSERT INTO t_ephemeral_ttl (id, dt, e) VALUES (1, '2000-01-01', 5); +OPTIMIZE TABLE t_ephemeral_ttl FINAL; +SELECT id, v FROM t_ephemeral_ttl; +DROP TABLE t_ephemeral_ttl; From 6781b1aa361c618d59a245ac1c07d987e55b9599 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sat, 28 Nov 2026 00:31:20 +0000 Subject: [PATCH 100/116] Backport #122078 to 26.3: Fix `REVOKE GRANT OPTION` disappearing from `SHOW GRANTS` when another revoked name shares a prefix --- src/Access/AccessRights.cpp | 35 +++++++------ src/Access/tests/gtest_access_rights_ops.cpp | 49 +++++++++++++++++++ ...evoke_grant_option_shared_prefix.reference | 20 ++++++++ ...05255_revoke_grant_option_shared_prefix.sh | 41 ++++++++++++++++ 4 files changed, 127 insertions(+), 18 deletions(-) create mode 100644 tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference create mode 100755 tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh diff --git a/src/Access/AccessRights.cpp b/src/Access/AccessRights.cpp index 16e8518686e0..113937fce741 100644 --- a/src/Access/AccessRights.cpp +++ b/src/Access/AccessRights.cpp @@ -974,7 +974,9 @@ struct AccessRights::Node auto grants = flags - parent_fl - grants_go; /// Inserts into result only meaningful nodes (e.g. wildcards or leafs). - if (target_node && (target_node->isLeaf() || target_node->wildcard_grant)) + const bool node_meaningful = node && (node->isLeaf() || node->wildcard_grant); + const bool node_go_meaningful = node_go && (node_go->isLeaf() || node_go->wildcard_grant); + if (node_meaningful || node_go_meaningful) { boost::container::small_vector new_full_name = full_name; @@ -990,19 +992,27 @@ struct AccessRights::Node } } - if (node && revokes) + if (node_meaningful && revokes) res.push_back(ProtoElement{revokes, new_full_name, false, true, node->wildcard_grant}); - if (node_go && revokes_go) + if (node_go_meaningful && revokes_go) res.push_back(ProtoElement{revokes_go, new_full_name, true, true, node_go->wildcard_grant}); - if (node && grants) + if (node_meaningful && grants) res.push_back(ProtoElement{grants, new_full_name, false, false, node->wildcard_grant}); - if (node_go && grants_go) + if (node_go_meaningful && grants_go) res.push_back(ProtoElement{grants_go, new_full_name, true, false, node_go->wildcard_grant}); } + /// The two tries compress child names independently: a child of one can be a strict name + /// prefix of a child of the other, and only exactly-named pairs can be walked together. + if (node && node_go && node_go->children) + { + for (auto & child_go : *node_go->children) + node->getLeaf(child_go.node_name, child_go.level, !child_go.isLeaf()); + } + if (node && node->children) { for (auto & child : *node->children) @@ -1022,19 +1032,8 @@ struct AccessRights::Node { for (auto & child : *node_go->children) { - if (node && node->children) - { - auto starts_with = [&child](const Node & n) - { - if (child.isLeaf()) - return n.isLeaf(); - - return !n.isLeaf() && child.node_name[0] == n.node_name[0]; - }; - - if (auto it = std::find_if(node->children->begin(), node->children->end(), starts_with); it != node->children->end()) - continue; /// already processed - } + if (node && node->tryGetChildNode(child.node_name)) + continue; /// already processed String new_path = path; new_path.append(child.node_name); diff --git a/src/Access/tests/gtest_access_rights_ops.cpp b/src/Access/tests/gtest_access_rights_ops.cpp index 7e6f3362a902..4909f9797a15 100644 --- a/src/Access/tests/gtest_access_rights_ops.cpp +++ b/src/Access/tests/gtest_access_rights_ops.cpp @@ -598,6 +598,55 @@ TEST(AccessRights, ParialRevokeWithGrantOption) ASSERT_TRUE(root.isGranted(AccessType::SELECT, "default", "zoo")); } +TEST(AccessRights, PartialRevokeGrantOptionWithSharedPrefix) +{ + /// Each arm pairs a grant-option-only revoke whose name shares a prefix with a plain revoke + /// (the shape that used to be dropped) with a control name that shares nothing. + + /// Database level. + AccessRights root; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "db1"); + root.revokeGrantOption(AccessType::SELECT, "db2"); + root.revokeGrantOption(AccessType::SELECT, "zdb2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON db1.*, " + "REVOKE GRANT OPTION SELECT ON db2.*, REVOKE GRANT OPTION SELECT ON zdb2.*"); + + /// Database level, grant-option name is a strict prefix of the plain one. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "dbx"); + root.revokeGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db.*, " + "REVOKE SELECT ON dbx.*"); + + /// Table level. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "d", "t1"); + root.revokeGrantOption(AccessType::SELECT, "d", "t2"); + root.revokeGrantOption(AccessType::SELECT, "d", "zt2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON d.t1, " + "REVOKE GRANT OPTION SELECT ON d.t2, REVOKE GRANT OPTION SELECT ON d.zt2"); + + /// Column level. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "d", "t", "c1"); + root.revokeGrantOption(AccessType::SELECT, "d", "t", "c2"); + root.revokeGrantOption(AccessType::SELECT, "d", "t", "zc2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT(c1) ON d.t, " + "REVOKE GRANT OPTION SELECT(c2, zc2) ON d.t"); + + /// Wildcard grant-option revoke whose name is a strict prefix of the plain one. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "dbx1"); + root.revokeWildcardGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db*.*, " + "REVOKE SELECT ON dbx1.*"); +} + TEST(AccessRights, WildcardGrantEdgeCases) { AccessRights root; diff --git a/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference new file mode 100644 index 000000000000..290dcff21a62 --- /dev/null +++ b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference @@ -0,0 +1,20 @@ +--- SHOW GRANTS +GRANT SELECT ON *.* TO grantor WITH GRANT OPTION +REVOKE SELECT ON d.t1 FROM grantor +REVOKE GRANT OPTION FOR SELECT ON d.t2 FROM grantor +REVOKE GRANT OPTION FOR SELECT ON d.zt2 FROM grantor +REVOKE SELECT ON db1.* FROM grantor +REVOKE GRANT OPTION FOR SELECT ON db2.* FROM grantor +REVOKE GRANT OPTION FOR SELECT ON zdb2.* FROM grantor +--- system.grants +d t1 SELECT 0 1 +d t2 SELECT 1 1 +d zt2 SELECT 1 1 +db1 \N SELECT 0 1 +db2 \N SELECT 1 1 +zdb2 \N SELECT 1 1 +\N \N SELECT 1 0 +--- the grant option cannot be passed on for a database whose grant option was revoked +GRANT SELECT ON db2.* TO victim1 +--- positive control: a database that was never revoked is still passed on with grant option +GRANT SELECT ON db3.* TO victim2 WITH GRANT OPTION diff --git a/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh new file mode 100755 index 000000000000..b6bd0e6c58d6 --- /dev/null +++ b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tests that "REVOKE GRANT OPTION FOR" is listed by SHOW GRANTS and by system.grants, and that the +# user can no longer pass the grant option on, also when another revoked database or table name +# shares a prefix with it. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +grantor="user05255_1_${CLICKHOUSE_DATABASE}_$RANDOM" +victim1="user05255_2_${CLICKHOUSE_DATABASE}_$RANDOM" +victim2="user05255_3_${CLICKHOUSE_DATABASE}_$RANDOM" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS $grantor, $victim1, $victim2" +${CLICKHOUSE_CLIENT} --query "CREATE USER $grantor, $victim1, $victim2" + +${CLICKHOUSE_CLIENT} --query "GRANT SELECT ON *.* TO $grantor WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "REVOKE SELECT ON db1.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON db2.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON zdb2.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE SELECT ON d.t1 FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON d.t2 FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON d.zt2 FROM $grantor" + +echo "--- SHOW GRANTS" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $grantor" | sed "s/$grantor/grantor/g" + +echo "--- system.grants" +${CLICKHOUSE_CLIENT} --query " + SELECT database, table, access_type, grant_option, is_partial_revoke + FROM system.grants WHERE user_name = '$grantor' ORDER BY database, table, access_type" + +echo "--- the grant option cannot be passed on for a database whose grant option was revoked" +${CLICKHOUSE_CLIENT} --user "$grantor" --query "GRANT CURRENT GRANTS(SELECT ON db2.*) TO $victim1 WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $victim1" | sed "s/$victim1/victim1/g" + +echo "--- positive control: a database that was never revoked is still passed on with grant option" +${CLICKHOUSE_CLIENT} --user "$grantor" --query "GRANT CURRENT GRANTS(SELECT ON db3.*) TO $victim2 WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $victim2" | sed "s/$victim2/victim2/g" + +${CLICKHOUSE_CLIENT} --query "DROP USER $grantor, $victim1, $victim2" From b6f63da235226b4d22a86282c60a0848d1468584 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sat, 28 Nov 2026 11:35:11 +0000 Subject: [PATCH 101/116] Backport #130673 to 26.3: Apply `ROW POLICY ... ON CLUSTER` with a bare table name to the current database --- .../InterpreterCreateRowPolicyQuery.cpp | 6 ++- .../InterpreterDropAccessEntityQuery.cpp | 5 +- .../InterpreterMoveAccessEntityQuery.cpp | 5 +- ...licy_on_cluster_current_database.reference | 6 +++ ..._row_policy_on_cluster_current_database.sh | 48 +++++++++++++++++++ 5 files changed, 64 insertions(+), 6 deletions(-) create mode 100644 tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference create mode 100755 tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh diff --git a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp index 51442059b01f..2bcf7b8fb975 100644 --- a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp @@ -57,9 +57,13 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() auto & query = updated_query_ptr->as(); auto required_access = getRequiredAccess(); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) { query.replaceCurrentUserTag(getContext()->getUserName()); + required_access.replaceEmptyDatabase(getContext()->getCurrentDatabase()); DDLQueryOnClusterParams params; params.access_to_check = std::move(required_access); return executeDDLQueryOnCluster(updated_query_ptr, getContext(), params); @@ -69,8 +73,6 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(required_access); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - std::optional roles_from_query; if (query.roles) roles_from_query = RolesOrUsersSet{*query.roles, access_control, getContext()->getUserID()}; diff --git a/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp b/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp index 9763dedcef49..27d2746c9c67 100644 --- a/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp +++ b/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp @@ -28,11 +28,12 @@ BlockIO InterpreterDropAccessEntityQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(getRequiredAccess()); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) return executeDDLQueryOnCluster(updated_query_ptr, getContext()); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - auto do_drop = [&](const Strings & names, const String & storage_name) { IAccessStorage * storage = &access_control; diff --git a/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp b/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp index dffa03b2eee8..951a4efe6b3e 100644 --- a/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp +++ b/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp @@ -23,11 +23,12 @@ BlockIO InterpreterMoveAccessEntityQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(getRequiredAccess()); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) return executeDDLQueryOnCluster(query_ptr, getContext()); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - std::vector ids; if (query.type == AccessEntityType::ROW_POLICY) ids = access_control.getIDs(query.type, query.row_policy_names->toStrings()); diff --git a/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference new file mode 100644 index 000000000000..d7624b276d3a --- /dev/null +++ b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference @@ -0,0 +1,6 @@ +1 t_05620 x = 1 local_directory +1 t_05620 x = 2 local_directory +1 t_05620 x = 2 memory +1 t_05620 x = 3 local_directory +denied +denied diff --git a/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh new file mode 100755 index 000000000000..4ed4ded7baf2 --- /dev/null +++ b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# Tag no-replicated-database: its replicated access storage replaces the local_directory and memory storages + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="u_05620_${CLICKHOUSE_DATABASE}" +user2="u2_05620_${CLICKHOUSE_DATABASE}" +policy="p_05620_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_05620 (x Int32) ENGINE = MergeTree ORDER BY x" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user}, ${user2} IDENTIFIED WITH no_password" +${CLICKHOUSE_CLIENT} --query "GRANT CLUSTER ON *.* TO ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY ON ${CLICKHOUSE_DATABASE}.* TO ${user}" + +# A bare table name refers to the current database, as it does without ON CLUSTER. +on_cluster() { ${CLICKHOUSE_CLIENT} --user "${user}" --distributed_ddl_output_mode none --query "$1"; } +show() { ${CLICKHOUSE_CLIENT} --query "SELECT database = currentDatabase(), table, select_filter, storage FROM system.row_policies WHERE short_name = '${policy}'"; } + +on_cluster "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost IN local_directory USING x = 1 TO ALL" +show +on_cluster "ALTER ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost USING x = 2" +show +on_cluster "MOVE ROW POLICY ${policy} ON t_05620 TO memory ON CLUSTER test_shard_localhost" +show +on_cluster "DROP ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost" +show + +# On a cluster with , the privileges are also checked on the current database. +on_cluster "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_cluster_two_shards_different_databases USING x = 3 TO ALL" +show +on_cluster "DROP ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost" +show + +# The privileges are checked before the query is queued: on the current database, and globally for ON *. +denied() +{ + if ${CLICKHOUSE_CLIENT} --user "$1" --query "$2" 2>&1 | grep -qF "necessary to have the grant $3"; then echo denied; else echo "not denied"; fi +} +denied "${user2}" "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_cluster_two_shards_different_databases USING 1 TO ALL" "CREATE ROW POLICY ON ${CLICKHOUSE_DATABASE}.t_05620" +denied "${user}" "CREATE ROW POLICY ${policy} ON * ON CLUSTER test_shard_localhost USING 1 TO ALL" "CREATE ROW POLICY ON *.*" +show + +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_05620" From d3bb5038e8f8fb78de53521733cbf2813dc44159 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sat, 28 Nov 2026 15:16:31 +0000 Subject: [PATCH 102/116] Update autogenerated version to 26.3.74.3 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index cf2e1afb217b..f1dea9e1825f 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54581) +SET(VERSION_REVISION 54582) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 74) -SET(VERSION_GITHASH f78b33d463261f7accb099733697dac2a1c66835) -SET(VERSION_DESCRIBE v26.3.74.1-lts) -SET(VERSION_STRING 26.3.74.1) +SET(VERSION_PATCH 75) +SET(VERSION_GITHASH 0bb99a1b527c9c8dd1edf5b5487f2db2e1a98f96) +SET(VERSION_DESCRIBE v26.3.75.1-lts) +SET(VERSION_STRING 26.3.75.1) # end of autochange From 7d00f327c81fb3a248313be926ac24a771faaa7e Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sat, 28 Nov 2026 23:10:18 +0000 Subject: [PATCH 103/116] Backport #134815 to 26.3: Fix a crash when the `_headers` virtual column of `url` is requested before another virtual column --- src/Storages/StorageURL.cpp | 31 ++++++------ src/Storages/VirtualColumnUtils.cpp | 6 +++ src/Storages/VirtualColumnUtils.h | 3 ++ ...url_headers_virtual_column_order.reference | 18 +++++++ ...05878_url_headers_virtual_column_order.sql | 50 +++++++++++++++++++ 5 files changed, 91 insertions(+), 17 deletions(-) create mode 100644 tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference create mode 100644 tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql diff --git a/src/Storages/StorageURL.cpp b/src/Storages/StorageURL.cpp index a51f1edd4557..ee242fee1f44 100644 --- a/src/Storages/StorageURL.cpp +++ b/src/Storages/StorageURL.cpp @@ -343,7 +343,7 @@ StorageURLSource::StorageURLSource( , columns_description(info.columns_description) , requested_columns(info.requested_columns) , need_headers_virtual_column(info.requested_virtual_columns.contains("_headers")) - , requested_virtual_columns(info.requested_virtual_columns.eraseNames({"_headers"})) + , requested_virtual_columns(info.requested_virtual_columns) , block_for_format(info.format_header) , uri_iterator(uri_iterator_) , format(format_) @@ -393,7 +393,9 @@ StorageURLSource::StorageURLSource( QueryPipelineBuilder builder; std::optional num_rows_from_cache = std::nullopt; - if (need_only_count && getContext()->getSettingsRef()[Setting::use_cache_for_count_from_files]) + /// The number of rows from the cache is returned without a request for the data, while the `_headers` + /// virtual column is the headers of the response to that request. Do the request when `_headers` is requested. + if (need_only_count && !need_headers_virtual_column && getContext()->getSettingsRef()[Setting::use_cache_for_count_from_files]) num_rows_from_cache = tryGetNumRowsFromCache(curr_uri.toString(), last_mod_time); if (num_rows_from_cache) @@ -491,30 +493,25 @@ Chunk StorageURLSource::generate() path); } + chassert(dynamic_cast(read_buf.get())); + if (need_headers_virtual_column && !http_response_headers_initialized) + { + http_response_headers = dynamic_cast(read_buf.get())->getResponseHeaders(); + http_response_headers_initialized = true; + } + + /// `_headers` is added along with the other virtual columns, in the order they are requested in, + /// which is the order of the columns in the header of the source. VirtualColumnUtils::addRequestedFileLikeStorageVirtualsToChunk( chunk, requested_virtual_columns, { .path = curr_uri.getPath(), .size = current_file_size, + .http_response_headers = need_headers_virtual_column ? &http_response_headers : nullptr, }, getContext()); - chassert(dynamic_cast(read_buf.get())); - if (need_headers_virtual_column) - { - if (!http_response_headers_initialized) - { - http_response_headers = dynamic_cast(read_buf.get())->getResponseHeaders(); - http_response_headers_initialized = true; - } - - auto type = std::make_shared( - std::make_shared(std::make_shared()), - std::make_shared(std::make_shared())); - - chunk.addColumn(type->createColumnConst(chunk.getNumRows(), http_response_headers)->convertToFullColumnIfConst()); - } return chunk; } diff --git a/src/Storages/VirtualColumnUtils.cpp b/src/Storages/VirtualColumnUtils.cpp index c07e2e4b712b..c2ecd03f6e90 100644 --- a/src/Storages/VirtualColumnUtils.cpp +++ b/src/Storages/VirtualColumnUtils.cpp @@ -469,6 +469,12 @@ void addRequestedFileLikeStorageVirtualsToChunk( /// Row numbers not known, _row_number = NULL. chunk.addColumn(virtual_column.type->createColumnConstWithDefaultValue(chunk.getNumRows())->convertToFullColumnIfConst()); } + else if (virtual_column.name == "_headers" && virtual_values.http_response_headers) + { + /// Added here, in its place among the requested virtual columns, and not by the caller after the other ones: + /// the columns of the chunk must go in the order of the header of the source, which is the requested order. + chunk.addColumn(virtual_column.type->createColumnConst(chunk.getNumRows(), *virtual_values.http_response_headers)->convertToFullColumnIfConst()); + } else if (auto it = hive_map.find(virtual_column.getNameInStorage()); it != hive_map.end()) { chunk.addColumn( diff --git a/src/Storages/VirtualColumnUtils.h b/src/Storages/VirtualColumnUtils.h index 631ab9250d26..eb8956bca967 100644 --- a/src/Storages/VirtualColumnUtils.h +++ b/src/Storages/VirtualColumnUtils.h @@ -11,6 +11,7 @@ namespace DB { +struct Map; class Block; class Chunk; class NamesAndTypesList; @@ -140,6 +141,8 @@ struct VirtualsForFileLikeStorage const String * etag { nullptr }; const std::map * tags { nullptr }; std::optional data_lake_snapshot_version { std::nullopt }; + /// The HTTP response headers of the read: the value of the `_headers` virtual column of the storages which read over HTTP. + const Map * http_response_headers { nullptr }; }; void addRequestedFileLikeStorageVirtualsToChunk( diff --git a/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference new file mode 100644 index 000000000000..2f72dd2c0684 --- /dev/null +++ b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference @@ -0,0 +1,18 @@ +-- _headers before another virtual column +hello / 1 +-- _headers between other virtual columns +/ hello 1 +-- _headers after the other virtual columns +/ hello 1 +-- _headers in SELECT, another virtual column in WHERE +hello 1 +-- the query of the AST fuzzer, with the condition negated to get a row +1 1 +-- _headers before all the other virtual columns +hello 1 1 / 1 +-- the number of rows is in the cache +1 +-- only virtual columns, _headers before another virtual column +hello / +-- only virtual columns, _headers after another virtual column +/ hello diff --git a/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql new file mode 100644 index 000000000000..2b656def13df --- /dev/null +++ b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql @@ -0,0 +1,50 @@ +-- The `url` table function added the `_headers` virtual column to its chunks after all the other +-- virtual columns, while the header of the source lists the virtual columns in the order they are +-- requested in. With `_headers` requested before another virtual column, the query read one column +-- in place of the other: an exception about the type of a column at best, a server crash otherwise. + +-- The HTTP interface adds the header of the `http_response_headers` setting, `{'X-Test':'hello'}`, to its response. + +SELECT '-- _headers before another virtual column'; +SELECT _headers['X-Test'], _path, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers between other virtual columns'; +SELECT _path, _headers['X-Test'], _file, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers after the other virtual columns'; +SELECT _path, _file, _headers['X-Test'], s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers in SELECT, another virtual column in WHERE'; +SELECT _headers['X-Test'], s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String') +WHERE _path = '/'; + +SELECT '-- the query of the AST fuzzer, with the condition negated to get a row'; +SELECT empty(_headers['X-Long']), s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String') +WHERE NOT isNotDistinctFrom(_size, true); + +-- The HTTP interface does not tell the size and the modification time of its response. +SELECT '-- _headers before all the other virtual columns'; +SELECT _headers['X-Test'], _size IS NULL OR _size > 0, _time IS NULL OR _time > '2000-01-01 00:00:00', _path, _file, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +-- A read of only virtual columns takes the number of rows from the cache without a request for the +-- data, and `_headers` was empty then, while it is the headers of the response to that request. +-- The cache is used for a URL without the `Last-Modified` header only with the setting below. +SET schema_inference_cache_require_modification_time_for_url = 0; + +SELECT '-- the number of rows is in the cache'; +SELECT count() +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers before another virtual column'; +SELECT _headers['X-Test'], _path +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers after another virtual column'; +SELECT _path, _headers['X-Test'] +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); From 5828472495717060c39f4df17a765c5db97da5f6 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sun, 29 Nov 2026 00:17:17 +0000 Subject: [PATCH 104/116] Backport #131728 to 26.3: Forbid users with the same name in different user directories --- src/Access/LDAPAccessStorage.cpp | 9 +- src/Access/MultipleAccessStorage.cpp | 95 ++++++++++- .../Access/InterpreterCreateQuotaQuery.cpp | 6 +- .../Access/InterpreterCreateRoleQuery.cpp | 6 +- .../InterpreterCreateRowPolicyQuery.cpp | 6 +- .../InterpreterCreateSettingsProfileQuery.cpp | 6 +- .../Access/InterpreterCreateUserQuery.cpp | 6 +- .../configs/http_handler_with_user.xml | 16 ++ .../configs/memory_user_directory.xml | 7 + .../test_ldap_external_user_directory/test.py | 159 +++++++++++++++++- ..._same_name_user_in_other_storage.reference | 13 ++ .../05770_same_name_user_in_other_storage.sh | 38 +++++ ...uota_row_policy_in_other_storage.reference | 10 ++ ..._name_quota_row_policy_in_other_storage.sh | 35 ++++ 14 files changed, 390 insertions(+), 22 deletions(-) create mode 100644 tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml create mode 100644 tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml create mode 100644 tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference create mode 100755 tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh create mode 100644 tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference create mode 100755 tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh diff --git a/src/Access/LDAPAccessStorage.cpp b/src/Access/LDAPAccessStorage.cpp index 939b99396c30..e0f18010b2e4 100644 --- a/src/Access/LDAPAccessStorage.cpp +++ b/src/Access/LDAPAccessStorage.cpp @@ -400,37 +400,36 @@ String LDAPAccessStorage::getStorageParamsJSON() const } +/// The read-only methods below don't lock `mutex`: `memory_storage` is synchronized by itself, +/// and `mutex` is held by `authenticateImpl` during the network communication with the LDAP server. +/// Waiting for it here would make lookups (e.g. the check for a name collision in `MultipleAccessStorage`) +/// wait for unrelated LDAP authentications. std::optional LDAPAccessStorage::findImpl(AccessEntityType type, const String & name) const { - std::lock_guard lock(mutex); return memory_storage.find(type, name); } std::vector LDAPAccessStorage::findAllImpl(AccessEntityType type) const { - std::lock_guard lock(mutex); return memory_storage.findAll(type); } bool LDAPAccessStorage::exists(const UUID & id) const { - std::lock_guard lock(mutex); return memory_storage.exists(id); } AccessEntityPtr LDAPAccessStorage::readImpl(const UUID & id, bool throw_if_not_exists) const { - std::lock_guard lock(mutex); return memory_storage.read(id, throw_if_not_exists); } std::optional> LDAPAccessStorage::readNameWithTypeImpl(const UUID & id, bool throw_if_not_exists) const { - std::lock_guard lock(mutex); return memory_storage.readNameWithType(id, throw_if_not_exists); } diff --git a/src/Access/MultipleAccessStorage.cpp b/src/Access/MultipleAccessStorage.cpp index c7247900b1c2..40158681c287 100644 --- a/src/Access/MultipleAccessStorage.cpp +++ b/src/Access/MultipleAccessStorage.cpp @@ -17,6 +17,7 @@ namespace ErrorCodes extern const int ACCESS_ENTITY_ALREADY_EXISTS; extern const int ACCESS_STORAGE_FOR_INSERTION_NOT_FOUND; extern const int ACCESS_ENTITY_NOT_FOUND; + extern const int AUTHENTICATION_FAILED; } using Storage = IAccessStorage; @@ -256,6 +257,24 @@ void MultipleAccessStorage::moveAccessEntities(const std::vector & ids, co auto destination_storage = getStorageByName(destination_storage_name); auto to_move = source_storage->read(ids); + + /// The same name must not refer to entities in different storages, so a move is refused if any storage + /// other than the source one already holds the name (e.g. a user of the config with the same name). + /// This is checked before anything is removed from the source storage. + auto storages = getStoragesInternal(); + for (const auto & entity : to_move) + { + for (const auto & other_storage : *storages) + { + if (other_storage == source_storage) + continue; + if (other_storage->find(entity->getType(), entity->getName())) + throw Exception(ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS, "{}: cannot move to {} because {} already exists in {}", + entity->formatTypeWithName(), backQuote(destination_storage_name), entity->formatTypeWithName(), + backQuote(other_storage->getStorageName())); + } + } + bool need_rollback = false; try @@ -397,6 +416,22 @@ bool MultipleAccessStorage::insertImpl(const UUID & id, const AccessEntityPtr & getStorageName()); } + /// The same name must not refer to entities in different storages. + /// A replacement replaces only an entity of the destination storage, so it is refused too if another storage holds the name. + for (const auto & other_storage : *storages) + { + if (other_storage == storage_for_insertion) + continue; + if (auto existing_id = other_storage->find(entity->getType(), entity->getName())) + { + if (conflicting_id) + *conflicting_id = *existing_id; + if (throw_if_exists || replace_if_exists) + throwNameCollisionCannotInsert(entity->getType(), entity->getName(), other_storage->getStorageName()); + return false; + } + } + if (storage_for_insertion->insert(id, entity, replace_if_exists, throw_if_exists, conflicting_id)) { std::lock_guard lock{mutex}; @@ -431,9 +466,10 @@ bool MultipleAccessStorage::updateImpl(const UUID & id, const UpdateFunc & updat return false; } - /// If the updating involves renaming check that the renamed entity will be accessible by name. + /// If the updating involves renaming check that the new name is not used in another storage: + /// the same name must not refer to entities in different storages. auto storages = getStoragesInternal(); - if ((storages->size() > 1) && (storages->front() != storage_for_updating)) + if (storages->size() > 1) { if (auto old_entity = storage_for_updating->tryRead(id)) { @@ -443,7 +479,7 @@ bool MultipleAccessStorage::updateImpl(const UUID & id, const UpdateFunc & updat for (const auto & storage : *storages) { if (storage == storage_for_updating) - break; + continue; if (storage->find(new_entity->getType(), new_entity->getName())) { throw Exception(ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS, "{}: cannot rename to {} because {} already exists in {}", @@ -466,15 +502,62 @@ MultipleAccessStorage::authenticateImpl(const Credentials & credentials, const P bool allow_no_password, bool allow_plaintext_password) const { auto storages = getStoragesInternal(); - for (size_t i = 0; i != storages->size(); ++i) + + /// Users from different user directories are distinct entities, but some code identifies users by name, + /// so the same name must not refer to more than one user. + auto throw_name_collision = [&](const String & user_name, const StoragePtr & storage, const StoragePtr & other_storage) -> void + { + throw Exception(ErrorCodes::AUTHENTICATION_FAILED, + "User {} exists in {}, but a user with the same name also exists in {}", + backQuote(user_name), storage->getStorageName(), other_storage->getStorageName()); + }; + + /// If a user with this name already exists, only its storage may authenticate it. Otherwise an external directory + /// (e.g. LDAP) could introduce a second user with the same name on login, in particular with `AlwaysAllowCredentials`, + /// which LDAP accepts without contacting the LDAP server. + /// + /// The same name with the same ID in several storages is one identity, not a collision: external directories + /// which derive both the name and the ID of a user from the verified identity (e.g. several token-based directories, + /// one per signing key or identity provider) each keep their own copy of the same user, and any of them may authenticate it. + std::vector existing_user_storages; + if (storages->size() > 1 && credentials.isReady()) + { + std::optional existing_user_id; + for (const auto & storage : *storages) + { + auto user_id = storage->find(AccessEntityType::USER, credentials.getUserName()); + if (!user_id) + continue; + if (existing_user_id && *existing_user_id != *user_id) + throw_name_collision(credentials.getUserName(), existing_user_storages.front(), storage); + existing_user_id = user_id; + existing_user_storages.push_back(storage); + } + } + + /// The storages which may authenticate these credentials. + std::vector candidate_storages = existing_user_storages.empty() ? *storages : existing_user_storages; + + for (size_t i = 0; i != candidate_storages.size(); ++i) { - const auto & storage = (*storages)[i]; - bool is_last_storage = (i == storages->size() - 1); + const auto & storage = candidate_storages[i]; + bool is_last_storage = (i == candidate_storages.size() - 1); auto auth_result = storage->authenticate(credentials, address, external_authenticators, client_info, (throw_if_user_not_exists && is_last_storage), allow_no_password, allow_plaintext_password); if (auth_result) { + /// Check again: a user with the same name could have appeared in another storage concurrently, + /// or the storage could have just introduced the user. + for (const auto & other_storage : *storages) + { + if (other_storage == storage) + continue; + auto other_user_id = other_storage->find(AccessEntityType::USER, auth_result->user_name); + if (other_user_id && *other_user_id != auth_result->user_id) + throw_name_collision(auth_result->user_name, storage, other_storage); + } + std::lock_guard lock{mutex}; ids_cache.set(auth_result->user_id, storage); return auth_result; diff --git a/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp b/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp index cec66bc8ce5d..4df18ccb520c 100644 --- a/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp @@ -129,10 +129,12 @@ BlockIO InterpreterCreateQuotaQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp b/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp index 7c0262df363f..ea1d81e02154 100644 --- a/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp @@ -96,10 +96,12 @@ BlockIO InterpreterCreateRoleQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp index 2bcf7b8fb975..633d3eb0d38a 100644 --- a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp @@ -98,10 +98,12 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() if (query.if_exists) { auto ids = storage->find(names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(names), update_func); + access_control.update(storage->getIDs(names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp b/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp index 61a6f66a3113..73f9b173a426 100644 --- a/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp @@ -107,10 +107,12 @@ BlockIO InterpreterCreateSettingsProfileQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateUserQuery.cpp b/src/Interpreters/Access/InterpreterCreateUserQuery.cpp index 82184d0cf54c..043d488f5a8e 100644 --- a/src/Interpreters/Access/InterpreterCreateUserQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateUserQuery.cpp @@ -303,10 +303,12 @@ BlockIO InterpreterCreateUserQuery::execute() if (query.if_exists) { auto ids = storage->find(names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(names), update_func); + access_control.update(storage->getIDs(names), update_func); } else { diff --git a/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml b/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml new file mode 100644 index 000000000000..f2632aa4fb13 --- /dev/null +++ b/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml @@ -0,0 +1,16 @@ + + + + + /handler_with_user + GET,POST + + predefined_query_handler + SELECT currentUser() + http_handler_user + + + + + diff --git a/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml b/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml new file mode 100644 index 000000000000..23888f3dcef6 --- /dev/null +++ b/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/tests/integration/test_ldap_external_user_directory/test.py b/tests/integration/test_ldap_external_user_directory/test.py index 9ffdaf00f25b..9f153e673c10 100644 --- a/tests/integration/test_ldap_external_user_directory/test.py +++ b/tests/integration/test_ldap_external_user_directory/test.py @@ -1,4 +1,5 @@ import logging +import uuid import pytest @@ -12,7 +13,12 @@ instance1 = cluster.add_instance( "instance1", - main_configs=["configs/ldap_with_role_mapping.xml", "configs/remote_servers.xml"], + main_configs=[ + "configs/ldap_with_role_mapping.xml", + "configs/memory_user_directory.xml", + "configs/http_handler_with_user.xml", + "configs/remote_servers.xml", + ], user_configs=["configs/users.xml"], macros={"shard": 1, "replica": "instance1"}, stay_alive=True, @@ -229,3 +235,154 @@ def test_remote_query_user_does_not_exist_locally(ldap_cluster): instance2.query("DROP USER IF EXISTS non_local", user="common_user", password="qwerty") instance2.query("DROP TABLE IF EXISTS test_table SYNC", user="common_user", password="qwerty") + + +def add_ldap_user(ldap_cluster, user_cn, password): + code, (stdout, stderr) = ldap_cluster.ldap_container.exec_run( + [ + "sh", + "-c", + """echo "dn: cn={user_cn},ou=users,dc=example,dc=org +objectClass: inetOrgPerson +cn: {user_cn} +sn: {user_cn} +userPassword: {password}" | \ +ldapadd -H ldap://{host}:{port} -D "{admin_bind_dn}" -x -w {admin_password} + """.format( + host=ldap_cluster.ldap_host, + port=ldap_cluster.ldap_port, + admin_bind_dn=LDAP_ADMIN_BIND_DN, + admin_password=LDAP_ADMIN_PASSWORD, + user_cn=user_cn, + password=password, + ), + ], + demux=True, + ) + logging.debug( + f"test_ldap_external_user_directory code:{code} stdout:{stdout}, stderr:{stderr}" + ) + assert code == 0 + + +def delete_ldap_user(ldap_cluster, user_cn): + code, (stdout, stderr) = ldap_cluster.ldap_container.exec_run( + [ + "sh", + "-c", + """ldapdelete 'cn={user_cn},ou=users,dc=example,dc=org' \ +-H ldap://{host}:{port} -D "{admin_bind_dn}" -x -w {admin_password} + """.format( + host=ldap_cluster.ldap_host, + port=ldap_cluster.ldap_port, + admin_bind_dn=LDAP_ADMIN_BIND_DN, + admin_password=LDAP_ADMIN_PASSWORD, + user_cn=user_cn, + ), + ], + demux=True, + ) + logging.debug( + f"test_ldap_external_user_directory code:{code} stdout:{stdout}, stderr:{stderr}" + ) + assert code == 0 + + +def user_storages(name): + return instance1.query( + f"SELECT storage FROM system.users WHERE name = '{name}' ORDER BY storage", + user="common_user", + password="qwerty", + ).split() + + +def test_same_name_user_in_other_directory(ldap_cluster): + """ + A user authenticated by LDAP must not share its name with a user from another user directory. + The `memory` directory follows the LDAP one, so a login by LDAP credentials would reach LDAP first + if the user were not looked up in all directories before. + """ + # A unique name, so that the LDAP user is not yet known to the server even if the test is retried. + name = f"same_name_{uuid.uuid4().hex[:8]}" + add_ldap_user(ldap_cluster, name, "ldap_password") + + try: + instance1.query( + f"CREATE USER {name} IDENTIFIED WITH plaintext_password BY 'local_password' IN memory", + user="common_user", + password="qwerty", + ) + + # The LDAP user is not known yet, so there is no conflict. + assert instance1.query( + "SELECT currentUser()", user=name, password="local_password" + ) == TSV([[name]]) + assert user_storages(name) == ["memory"] + + # The LDAP directory would recognize the user, but the name is already used in the `memory` directory, + # so only that directory authenticates the user, and LDAP does not introduce a second user with this name. + assert f"{name}: Authentication failed" in instance1.query_and_get_error( + "SELECT currentUser()", user=name, password="ldap_password" + ) + assert user_storages(name) == ["memory"] + + # The local user can still log in. + assert instance1.query( + "SELECT currentUser()", user=name, password="local_password" + ) == TSV([[name]]) + + instance1.query( + f"DROP USER {name} FROM memory", + user="common_user", + password="qwerty", + ) + + # Now the LDAP user can log in. + assert instance1.query( + "SELECT currentUser()", user=name, password="ldap_password" + ) == TSV([[name]]) + assert user_storages(name) == ["ldap"] + + # A new user with the same name cannot be created in another directory, whether it is specified or not. + for query in [ + f"CREATE USER {name}", + f"CREATE USER {name} IN memory", + f"CREATE USER OR REPLACE {name} IN memory", + ]: + assert "ACCESS_ENTITY_ALREADY_EXISTS" in instance1.query_and_get_error( + query, user="common_user", password="qwerty" + ) + finally: + for storage in ["memory", "local_directory"]: + instance1.query( + f"DROP USER IF EXISTS {name} FROM {storage}", + user="common_user", + password="qwerty", + ) + delete_ldap_user(ldap_cluster, name) + + +def test_same_name_user_in_other_directory_always_allow_credentials(ldap_cluster): + """ + An HTTP handler with a configured user authenticates it with `AlwaysAllowCredentials`, which the LDAP directory + accepts without contacting the LDAP server. If the user exists in another directory, LDAP must not introduce + a second user with the same name. + """ + name = "http_handler_user" + try: + instance1.query( + f"CREATE USER {name} IN memory", + user="common_user", + password="qwerty", + ) + for _ in range(2): + response = instance1.http_request("handler_with_user") + assert response.status_code == 200, response.text + assert response.text.strip() == name + assert user_storages(name) == ["memory"] + finally: + instance1.query( + f"DROP USER IF EXISTS {name} FROM memory", + user="common_user", + password="qwerty", + ) diff --git a/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference new file mode 100644 index 000000000000..6f1822583bd6 --- /dev/null +++ b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference @@ -0,0 +1,13 @@ +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +memory +1 +1 +ACCESS_ENTITY_ALREADY_EXISTS +0 local_directory +1 memory +1 +1 +0 diff --git a/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh new file mode 100755 index 000000000000..c2526dc6f58e --- /dev/null +++ b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# no-replicated-database: that configuration replaces the user directories, so there is no `memory` storage. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A user name must not be used in more than one user directory. +# `memory` is the last user directory, so `CREATE USER` without `IN` would pick an earlier one. + +user="user_05770_${CLICKHOUSE_DATABASE}" +source_user="user_05770_source_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}, ${source_user}" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'p1' IN memory" + +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user} IN local_directory" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER IF NOT EXISTS ${user}" + +# A replacement is refused if another directory holds the name, but allowed within the same directory. +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2'" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2' IN local_directory" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT storage FROM system.users WHERE name = '${user}'" +${CLICKHOUSE_CLIENT} --user "${user}" --password p1 --query "SELECT currentUser() = '${user}'" +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2' IN memory" +${CLICKHOUSE_CLIENT} --user "${user}" --password p2 --query "SELECT currentUser() = '${user}'" + +# A rename to a name held by another directory is refused, and both users remain usable. +${CLICKHOUSE_CLIENT} --query "CREATE USER ${source_user} IDENTIFIED WITH plaintext_password BY 'p3' IN local_directory" +${CLICKHOUSE_CLIENT} --query "ALTER USER ${source_user} RENAME TO ${user}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT name = '${user}', storage FROM system.users WHERE name IN ('${user}', '${source_user}') ORDER BY storage" +${CLICKHOUSE_CLIENT} --user "${user}" --password p2 --query "SELECT currentUser() = '${user}'" +${CLICKHOUSE_CLIENT} --user "${source_user}" --password p3 --query "SELECT currentUser() = '${source_user}'" + +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}, ${source_user}" +${CLICKHOUSE_CLIENT} --query "SELECT count() FROM system.users WHERE name IN ('${user}', '${source_user}')" diff --git a/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference new file mode 100644 index 000000000000..d669fdca1cc6 --- /dev/null +++ b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference @@ -0,0 +1,10 @@ +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +0 local_directory +1 memory +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +policy_05813_source local_directory +policy_05813_target memory +policy_05813_renamed local_directory +policy_05813_target memory diff --git a/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh new file mode 100755 index 000000000000..08195f41a32c --- /dev/null +++ b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# no-replicated-database: that configuration replaces the user directories, so there is no `memory` storage. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A rename of a quota or a row policy with `IN` must not take a name used in another user directory. + +source_quota="quota_05813_source_${CLICKHOUSE_DATABASE}" +target_quota="quota_05813_target_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP QUOTA IF EXISTS ${source_quota}, ${target_quota}" +${CLICKHOUSE_CLIENT} --query "CREATE QUOTA ${source_quota} IN local_directory" +${CLICKHOUSE_CLIENT} --query "CREATE QUOTA ${target_quota} IN memory" +${CLICKHOUSE_CLIENT} --query "ALTER QUOTA ${source_quota} IN local_directory RENAME TO ${target_quota}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "ALTER QUOTA IF EXISTS ${source_quota} IN local_directory RENAME TO ${target_quota}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT name = '${target_quota}', storage FROM system.quotas WHERE name IN ('${source_quota}', '${target_quota}') ORDER BY storage" +${CLICKHOUSE_CLIENT} --query "DROP QUOTA ${source_quota}, ${target_quota}" + +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_05813 (x UInt8) ENGINE = Memory" +${CLICKHOUSE_CLIENT} --query "DROP ROW POLICY IF EXISTS policy_05813_source, policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813" +${CLICKHOUSE_CLIENT} --query "CREATE ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory" +${CLICKHOUSE_CLIENT} --query "CREATE ROW POLICY policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813 IN memory" +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_target" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY IF EXISTS policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_target" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT short_name, storage FROM system.row_policies WHERE database = '${CLICKHOUSE_DATABASE}' AND table = 't_05813' ORDER BY storage" + +# A rename within the requested directory to a free name still works. +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_renamed" +${CLICKHOUSE_CLIENT} --query "SELECT short_name, storage FROM system.row_policies WHERE database = '${CLICKHOUSE_DATABASE}' AND table = 't_05813' ORDER BY storage" + +${CLICKHOUSE_CLIENT} --query "DROP ROW POLICY policy_05813_renamed, policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813" +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_05813" From 92d48b9855bb1777677e9c5efb1656b91335db4c Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Sun, 29 Nov 2026 14:54:41 +0000 Subject: [PATCH 105/116] Update autogenerated version to 26.3.75.5 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index f1dea9e1825f..6dca5e2ae5ef 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54582) +SET(VERSION_REVISION 54583) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 75) -SET(VERSION_GITHASH 0bb99a1b527c9c8dd1edf5b5487f2db2e1a98f96) -SET(VERSION_DESCRIBE v26.3.75.1-lts) -SET(VERSION_STRING 26.3.75.1) +SET(VERSION_PATCH 76) +SET(VERSION_GITHASH bcdf086361ce604a2ad4c5db8c4abf7385ae548e) +SET(VERSION_DESCRIBE v26.3.76.1-lts) +SET(VERSION_STRING 26.3.76.1) # end of autochange From 8b62bb365b5f2ee78ba26a366fe95814a9c7a4ac Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 30 Nov 2026 14:47:38 +0000 Subject: [PATCH 106/116] Backport #134818 to 26.3: Confine `Filesystem` database tables to the database directory --- src/Databases/DatabaseFilesystem.cpp | 31 +++++++++++++++ ...system_confined_to_its_directory.reference | 13 +++++++ ...se_filesystem_confined_to_its_directory.sh | 39 +++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.reference create mode 100755 tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.sh diff --git a/src/Databases/DatabaseFilesystem.cpp b/src/Databases/DatabaseFilesystem.cpp index 6e5e3010d685..34826778564b 100644 --- a/src/Databases/DatabaseFilesystem.cpp +++ b/src/Databases/DatabaseFilesystem.cpp @@ -18,6 +18,8 @@ #include #include #include +#include +#include #include #include @@ -43,6 +45,31 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + +/// Whether `table_path`, already normalized, stays inside `directory`. The `file` table function +/// expands `{a,b}` groups before it walks the filesystem and does not normalize the result, so an +/// alternative carrying a `..` is refused instead of being resolved against a possible symlink. +bool isInsideDirectory(const String & table_path, const String & directory) +{ + if (!containsGlobs(table_path)) + return fileOrSymlinkPathStartsWith(table_path, directory); + + for (const auto & expanded_path : expandSelectionGlob(table_path)) + { + for (const auto & component : fs::path(expanded_path)) + if (component == "..") + return false; + + if (!fileOrSymlinkPathStartsWith(expanded_path, directory)) + return false; + } + return true; +} + +} + DatabaseFilesystem::DatabaseFilesystem( const String & name_, const String & path_, ContextPtr context_, bool is_internal_metadata_replay) : IDatabase(name_), WithContext(context_->getGlobalContext()), path(path_), log(getLogger("DatabaseFileSystem(" + name_ + ")")) @@ -105,6 +132,10 @@ bool DatabaseFilesystem::checkTableFilePath(const std::string & table_path, Cont throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File is not inside {}", user_files_path); } + /// A table of this database is a file under its own directory, not anywhere in `user_files`. + if (check_path && !isInsideDirectory(table_path, path)) + throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File is not inside the database directory {}", path); + if (!containsGlobs(table_path)) { /// Check if the corresponding file exists. diff --git a/tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.reference b/tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.reference new file mode 100644 index 000000000000..956c59ae757c --- /dev/null +++ b/tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.reference @@ -0,0 +1,13 @@ +-- inside +inner +inner +inner +1 +-- outside +PATH_ACCESS_DENIED +PATH_ACCESS_DENIED +PATH_ACCESS_DENIED +PATH_ACCESS_DENIED +PATH_ACCESS_DENIED +PATH_ACCESS_DENIED +PATH_ACCESS_DENIED diff --git a/tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.sh b/tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.sh new file mode 100755 index 000000000000..2330eb62fea3 --- /dev/null +++ b/tests/queries/0_stateless/05878_database_filesystem_confined_to_its_directory.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A table of a `Filesystem` database must be a file under the directory of the database, +# not anywhere in `user_files`. + +base="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}" +mkdir -p "$base/db/sub" "$base/other" +echo 'inner' > "$base/db/inner.csv" +echo 'secret' > "$base/other/secret.csv" + +fs_db="${CLICKHOUSE_DATABASE}_fs" +${CLICKHOUSE_CLIENT} -q "CREATE DATABASE $fs_db ENGINE = Filesystem('$base/db')" + +function query() +{ + ${CLICKHOUSE_CLIENT} -q "$1" 2>&1 | grep -o -m1 -e 'PATH_ACCESS_DENIED' -e '^[a-z01]*$' +} + +echo "-- inside" +query "SELECT * FROM $fs_db.\`inner.csv\`" +query "SELECT * FROM $fs_db.\`sub/../inner.csv\`" +query "SELECT * FROM $fs_db.\`{inner,missing}.csv\`" +query "EXISTS TABLE $fs_db.\`inner.csv\`" + +echo "-- outside" +query "SELECT * FROM $fs_db.\`../other/secret.csv\`" +query "SELECT * FROM $fs_db.\`$base/other/secret.csv\`" +query "SELECT * FROM $fs_db.\`../other/*.csv\`" +query "SELECT * FROM $fs_db.\`{..,sub}/other/secret.csv\`" +query "SELECT * FROM $fs_db.\`{../other/secret,inner}.csv\`" +query "EXISTS TABLE $fs_db.\`../other/secret.csv\`" +query "EXISTS TABLE $fs_db.\`../other/missing.csv\`" + +${CLICKHOUSE_CLIENT} -q "DROP DATABASE $fs_db" +rm -rf "$base" From b8dd76a915719d4a6853804253506c473c7366ba Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 30 Nov 2026 15:40:24 +0000 Subject: [PATCH 107/116] Update autogenerated version to 26.3.76.2 and contributors --- cmake/autogenerated_versions.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index 6dca5e2ae5ef..61e273de9675 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,11 +2,11 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54583) +SET(VERSION_REVISION 54584) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -SET(VERSION_PATCH 76) -SET(VERSION_GITHASH bcdf086361ce604a2ad4c5db8c4abf7385ae548e) -SET(VERSION_DESCRIBE v26.3.76.1-lts) -SET(VERSION_STRING 26.3.76.1) +SET(VERSION_PATCH 77) +SET(VERSION_GITHASH 510026b533dac3dda78e8c67076b01ff496b0c72) +SET(VERSION_DESCRIBE v26.3.77.1-lts) +SET(VERSION_STRING 26.3.77.1) # end of autochange From 6e09a757a89e8e2aa298b9138aeb0d442c051686 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 30 Nov 2026 16:23:08 +0000 Subject: [PATCH 108/116] Backport #130576 to 26.3: Mask the connection string in ODBC/JDBC bridge request URLs --- src/Common/maskURIPassword.h | 10 ++-- ...17_xdbc_connection_string_masked.reference | 3 ++ .../05617_xdbc_connection_string_masked.sh | 54 +++++++++++++++++++ 3 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference create mode 100755 tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index a4f762ec2d57..a16f7263c508 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -71,10 +71,11 @@ inline bool maskURIPassword(std::string * uri) } /** Mask the values of the query parameters that carry credentials in a presigned URL, so that - * `...?X-Amz-Signature=abc&foo=1` becomes `...?X-Amz-Signature=[HIDDEN]&foo=1`. Every occurrence - * is masked. Returns whether anything was masked. + * `...?X-Amz-Signature=abc&foo=1` becomes `...?X-Amz-Signature=[HIDDEN]&foo=1`, and of the + * `connection_string` parameter of an ODBC/JDBC bridge request. Every occurrence is masked. + * Returns whether anything was masked. * - * Mirrors the regular expression + * Apart from `connection_string`, mirrors the regular expression * `([?&](?:AWSAccessKeyId|Signature|Expires|GoogleAccessId|X-Amz-[A-Za-z0-9\-]*|X-Goog-[A-Za-z0-9\-]*)=)[^&#]*` * that `FunctionSecretArgumentsFinder` applies to a presigned URL, and the parameter set mirrors * `BackupInfo::removeCredentialsFromS3URL`. Matching is case-sensitive, as in the expression. @@ -86,6 +87,9 @@ inline bool maskPresignedURLParameters(std::string & url) auto is_secret_parameter = [](std::string_view name) { + if (name == "connection_string") + return true; + for (auto exact : exact_names) if (name == exact) return true; diff --git a/tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference new file mode 100644 index 000000000000..bc8f970e4471 --- /dev/null +++ b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference @@ -0,0 +1,3 @@ +odbc_table_function: OK masked +query_log: OK masked +odbc_engine_insert: OK masked diff --git a/tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh new file mode 100755 index 000000000000..23ccef17ba5b --- /dev/null +++ b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Tags: no-asan, no-msan, no-fasttest, no-cpu-aarch64 +# Tag no-msan: can't pass because odbc libraries are not instrumented +# Tag no-cpu-aarch64: clickhouse-odbc is not setup for arm + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A bridge request carries the ODBC connection string in the `connection_string` parameter of its URI. +# Wherever that URI is shown, the value must be shown as [HIDDEN], as it is in the query text. + +SECRET="xdbcpw${CLICKHOUSE_TEST_UNIQUE_NAME}" +SHAPE="connection_string=[HIDDEN]" + +# Reads text from stdin: the secret must be absent and the masked parameter present, so a text that never +# carried the URI fails instead of passing. +assert_shape() { + local label="$1" secret="$2" shape="$3" text + text=$(cat) + if echo "$text" | grep -qF "$secret"; then + echo "$label: FAIL cleartext" + elif echo "$text" | grep -qF "$shape"; then + echo "$label: OK masked" + else + echo "$label: FAIL uri absent" + fi +} + +# The bridge is started on first use. +for _ in $(seq 1 10); do + ${CLICKHOUSE_CLIENT} --query "SELECT * FROM odbc('DSN=no_such_dsn', 'db', 't')" 2>&1 | grep -qF 'Received error from remote server' && break + sleep 0.1 +done + +# The bridge cannot connect to the DSN and answers with an error, which quotes the request URI. Grep that +# line: the client also echoes the submitted query, which legitimately contains what the user typed. +${CLICKHOUSE_CLIENT} --query_id "${CLICKHOUSE_TEST_UNIQUE_NAME}_tf" --query "SELECT * FROM odbc('DSN=no_such_dsn;PWD=${SECRET}', 'db', 't')" 2>&1 \ + | grep -F 'Received error from remote server' | assert_shape "odbc_table_function" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" +${CLICKHOUSE_CLIENT} --query " + SELECT exception + FROM system.query_log + WHERE event_date >= yesterday() + AND current_database = currentDatabase() + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_tf' + AND type != 'QueryStart'" | assert_shape "query_log" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_odbc (a Int32) ENGINE = ODBC('DSN=no_such_dsn;PWD=${SECRET}', 'db', 't')" +${CLICKHOUSE_CLIENT} --query "INSERT INTO t_odbc VALUES (1)" 2>&1 \ + | grep -F 'Received error from remote server' | assert_shape "odbc_engine_insert" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_odbc" From c59242033f832cda2e36809977be9899386c9c25 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 30 Nov 2026 16:31:58 +0000 Subject: [PATCH 109/116] Backport #134994 to 26.3: Fix a client bypassing the grant check of forwarded roles with a forged `TCP_INTERSERVER` interface --- src/Server/TCPHandler.cpp | 4 ++++ ...877_forged_interserver_interface.reference | 2 ++ .../05877_forged_interserver_interface.sh | 23 +++++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 tests/queries/0_stateless/05877_forged_interserver_interface.reference create mode 100755 tests/queries/0_stateless/05877_forged_interserver_interface.sh diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index ecfb00acd1db..aee3989bac6d 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2389,6 +2389,10 @@ void TCPHandler::processQuery(std::shared_ptr & state) throw exception; /// NOLINT #endif } + /// `TCP_INTERSERVER` passed with `ClientInfo` in a `Query` packet is not trusted: + /// only a connection that uses the cluster secret is interserver. + else if (client_info.interface == ClientInfo::Interface::TCP_INTERSERVER) + client_info.interface = ClientInfo::Interface::TCP; state->query_context = session->makeQueryContext(client_info); diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.reference b/tests/queries/0_stateless/05877_forged_interserver_interface.reference new file mode 100644 index 000000000000..7a5939195a45 --- /dev/null +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.reference @@ -0,0 +1,2 @@ +forged interface: query accepted +TCP diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.sh b/tests/queries/0_stateless/05877_forged_interserver_interface.sh new file mode 100755 index 000000000000..824717dc22bb --- /dev/null +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +python3 - < Date: Mon, 30 Nov 2026 18:56:26 +0100 Subject: [PATCH 110/116] Fix `05877_forged_interserver_interface` in the backport The test uses the helper `05061_query_log_interface_enum_unknown.python` from #118136, which is not in this branch, add it. And `system.query_log.interface` is `UInt8` here, not `Enum8`. Co-Authored-By: Claude Fable 5.2 --- ...61_query_log_interface_enum_unknown.python | 275 ++++++++++++++++++ ...877_forged_interserver_interface.reference | 2 +- 2 files changed, 276 insertions(+), 1 deletion(-) create mode 100644 tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python diff --git a/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python b/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python new file mode 100644 index 000000000000..db56872e4742 --- /dev/null +++ b/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# `ClientInfo::read` stores the reported `interface` and `http_method` bytes without checking that +# they name an enumerator, so `system.query_log` and `system.processes` must be able to render any +# byte a client sends. This script speaks the raw native protocol to report values outside both +# enums. +# +# The queries are sent as `SECONDARY_QUERY`. That is the query kind whose reported interface is +# allowed to differ from the receiving session's: a query forwarded to a shard carries the +# initiator's interface, so an HTTP initiator forwarding over a native TCP connection reports +# `HTTP` on a TCP session, and `validateClientInfo` exempts it. An `INITIAL_QUERY` reporting +# anything but the session's own interface is refused with `CLIENT_INFO_DOES_NOT_MATCH` wherever +# `validate_tcp_client_information` is on, which includes the stateless-test server. +# +# The revision is pinned to 54484, the newest one whose `ClientInfo` layout is fully written below +# (`client_agent` is added at 54485), so the set of exchanged fields is fixed and does not drift. + +import os +import socket +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") +CLIENT_NAME = "interface enum poc" + +REVISION = 54484 + +INTERFACE_TCP = 1 +INTERFACE_HTTP = 2 +# Each `*_LOW` byte is the smallest value its own enum does not name, so a projection keyed on a +# threshold instead of on membership either passes it through, and rendering then throws, or has +# already remapped a named value that `03258_refreshable_mv_misc` and `04306_create_handler_http` +# pin. 200 narrows to -56, keeping the negative `Int8` class armed. Adding an enumerator to either +# enum moves that field's `*_LOW` byte: it is the next value that enum would allocate. +INTERFACE_UNMAPPED_LOW = 12 +HTTP_METHOD_UNMAPPED_LOW = 7 +UNMAPPED_HIGH_BIT = 200 + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") if isinstance(s, str) else s + writeVarUInt(len(b), ba) + ba.extend(b) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt(s, size=1): + res = readStrict(s, size) + val = 0 + for i in range(len(res)): + val += res[i] << (i * 8) + return val + + +def readVarUInt(s): + x = 0 + for i in range(9): + byte = readStrict(s)[0] + x |= (byte & 0x7F) << (7 * i) + if not byte & 0x80: + return x + return x + + +def readStringBinary(s): + size = readVarUInt(s) + return readStrict(s, size).decode("utf-8") + + +def sendHello(s): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeStringBinary(CLICKHOUSE_DATABASE, ba) + writeStringBinary("default", ba) # user + writeStringBinary("", ba) # password + s.sendall(ba) + + +def receiveHello(s): + assert readVarUInt(s) == 0 # Hello + readStringBinary(s) # server name + readVarUInt(s) # major + readVarUInt(s) # minor + readVarUInt(s) # revision + readVarUInt(s) # parallel replicas protocol version (>= 54471) + readStringBinary(s) # timezone (>= 54058) + readStringBinary(s) # display name (>= 54372) + readVarUInt(s) # version patch (>= 54401) + readStringBinary(s) # proto_send chunked (>= 54470) + readStringBinary(s) # proto_recv chunked (>= 54470) + for _ in range(readVarUInt(s)): # password complexity rules (>= 54461) + readStringBinary(s) + readStringBinary(s) + readStrict(s, 8) # nonce, UInt64 (>= 54462) + while True: # server settings in STRINGS_WITH_FLAGS format (>= 54474) + if readStringBinary(s) == "": + break + readVarUInt(s) # flags + readStringBinary(s) # value + readVarUInt(s) # query plan serialization version (>= 54477) + readVarUInt(s) # cluster function protocol version (>= 54479) + + +def sendAddendum(s): + ba = bytearray() + writeStringBinary("", ba) # quota key (>= 54458) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # parallel replicas protocol version (>= 54471) + s.sendall(ba) + + +def serializeClientInfo(ba, query_id, interface, http_method): + ba.append(2) # SECONDARY_QUERY + writeStringBinary("default", ba) # initial_user + writeStringBinary(query_id, ba) # initial_query_id + writeStringBinary("127.0.0.1:9000", ba) # initial_address + ba.extend([0] * 8) # initial_query_start_time_microseconds (>= 54449) + ba.append(interface) + if interface == INTERFACE_TCP: + writeStringBinary("os_user", ba) + writeStringBinary("client_hostname", ba) + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # client major + writeVarUInt(9, ba) # client minor + writeVarUInt(REVISION, ba) # client tcp protocol version + elif interface == INTERFACE_HTTP: + ba.append(http_method) + writeStringBinary(CLIENT_NAME, ba) # http_user_agent + writeStringBinary("", ba) # forwarded_for (>= 54443) + writeStringBinary("", ba) # http_referer (>= 54447) + writeStringBinary("", ba) # quota key (>= 54060) + writeVarUInt(0, ba) # distributed_depth (>= 54448) + if interface == INTERFACE_TCP: + writeVarUInt(1, ba) # client version patch (>= 54401) + ba.append(0) # opentelemetry: no trace id (>= 54442) + writeVarUInt(0, ba) # parallel replicas: collaborate_with_initiator (>= 54453) + writeVarUInt(0, ba) # parallel replicas: obsolete count + writeVarUInt(0, ba) # parallel replicas: number_of_current_replica + writeVarUInt(0, ba) # script query number (>= 54475) + writeVarUInt(0, ba) # script line number (>= 54475) + ba.append(0) # jwt: none (>= 54476) + + +def sendQuery(s, query, interface, http_method, query_id, settings): + ba = bytearray() + writeVarUInt(1, ba) # Query + writeStringBinary(query_id, ba) + serializeClientInfo(ba, query_id, interface, http_method) + for key, value in settings.items(): + writeStringBinary(key, ba) + writeVarUInt(1, ba) # is_important + writeStringBinary(str(value), ba) + writeStringBinary("", ba) # end of per-query settings + writeStringBinary("", ba) # interserver externally granted roles (>= 54472) + writeStringBinary("", ba) # interserver secret (>= 54441) + writeVarUInt(2, ba) # stage = Complete + ba.append(0) # no compression + writeStringBinary(query, ba) + writeStringBinary("", ba) # query parameters terminator (>= 54459) + s.sendall(ba) + + +def sendEmptyBlock(s): + ba = bytearray() + writeVarUInt(2, ba) # Data + writeStringBinary("", ba) + writeVarUInt(1, ba) # block info field 1 + ba.append(0) # is_overflows = false + writeVarUInt(2, ba) # block info field 2 + ba.extend((-1).to_bytes(4, "little", signed=True)) # bucket_num = -1 + writeVarUInt(0, ba) # end of block info + writeVarUInt(0, ba) # columns + writeVarUInt(0, ba) # rows + s.sendall(ba) + + +def expectQueryAccepted(s): + # Any first packet other than an `Exception` proves the server accepted the reported client info: + # a `SELECT` answers with its result header once the query has started, and a completed + # `INSERT ... SELECT` run with `interactive_delay = 0` answers only after its commit. The rest of + # the stream is not read. + packet_type = readVarUInt(s) + if packet_type == 2: # Exception + readUInt(s, 4) # code + readStringBinary(s) # name + raise RuntimeError("Unexpected exception: {}".format(readStringBinary(s))) + + +def runQuery(label, query, interface, http_method, query_id=None, settings=None): + query_id = query_id or uuid.uuid4().hex + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(30) + s.connect((CLICKHOUSE_HOST, CLICKHOUSE_PORT)) + sendHello(s) + receiveHello(s) + sendAddendum(s) + sendQuery(s, query, interface, http_method, query_id, settings or {}) + sendEmptyBlock(s) + expectQueryAccepted(s) + print("{}: query accepted".format(label)) + + +def observeSelfInProcesses(label, interface, http_method): + # `system.processes` is filled from the live process list, so a running query sees its own row + # and can persist what the server renders for it. That is the only way to assert on + # `system.processes`: it holds nothing once the query has ended. + query_id = uuid.uuid4().hex + # With `interactive_delay = 0` the server runs a completed pipeline without a periodic progress + # callback, so the first packet it sends is the one after the INSERT has committed. A client that + # disconnects while such a pipeline is still running has its query cancelled, losing the row. + runQuery( + label, + "INSERT INTO processes_snapshot " + "SELECT toString(interface), toString(http_method) " + "FROM system.processes WHERE query_id = '{}'".format(query_id), + interface, + http_method, + query_id, + settings={"interactive_delay": 0}, + ) + + +def main(): + runQuery( + "reported interface out of domain", + "SELECT 1 SETTINGS log_comment = 'interface_enum_unknown'", + INTERFACE_UNMAPPED_LOW, + 0, + ) + runQuery( + "reported http_method out of domain", + "SELECT 2 SETTINGS log_comment = 'http_method_enum_unknown'", + INTERFACE_HTTP, + UNMAPPED_HIGH_BIT, + ) + # Two queries, because one cannot report an out-of-domain value for both columns at once: + # `http_method` is only read off the wire when the reported interface is `HTTP`. + # The `system.processes` probes carry the other byte of each pair, so both projections are + # reported both classes across their two call sites. + observeSelfInProcesses("processes: reported interface out of domain", UNMAPPED_HIGH_BIT, 0) + observeSelfInProcesses( + "processes: reported http_method out of domain", INTERFACE_HTTP, HTTP_METHOD_UNMAPPED_LOW + ) + + +if __name__ == "__main__": + main() diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.reference b/tests/queries/0_stateless/05877_forged_interserver_interface.reference index 7a5939195a45..3e43aed0dcab 100644 --- a/tests/queries/0_stateless/05877_forged_interserver_interface.reference +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.reference @@ -1,2 +1,2 @@ forged interface: query accepted -TCP +1 From b396b46e84472dc6b5dce61ea155ec62329c4ad1 Mon Sep 17 00:00:00 2001 From: robot-clickhouse Date: Mon, 30 Nov 2026 19:09:27 +0000 Subject: [PATCH 111/116] Backport #135200 to 26.3: Fix the order of a wildcard revoke and a grant on the same name in `SHOW GRANTS` --- src/Access/AccessRights.cpp | 4 ++ src/Access/tests/gtest_access_rights_ops.cpp | 49 +++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/Access/AccessRights.cpp b/src/Access/AccessRights.cpp index 113937fce741..2cb66e10b800 100644 --- a/src/Access/AccessRights.cpp +++ b/src/Access/AccessRights.cpp @@ -38,6 +38,10 @@ namespace if (left.full_name.size() != right.full_name.size()) return left.full_name.size() < right.full_name.size(); + /// Wildcards before exact names: `db*` covers `db`, so its element must be applied first. + if (left.wildcard != right.wildcard) + return left.wildcard; + /// Grants before partial revokes. if (left.is_partial_revoke != right.is_partial_revoke) return right.is_partial_revoke; /// if left is grant, right is partial revoke, we assume left < right diff --git a/src/Access/tests/gtest_access_rights_ops.cpp b/src/Access/tests/gtest_access_rights_ops.cpp index 4909f9797a15..25a0b13b2108 100644 --- a/src/Access/tests/gtest_access_rights_ops.cpp +++ b/src/Access/tests/gtest_access_rights_ops.cpp @@ -96,13 +96,13 @@ TEST(AccessRights, GrantWildcard) root.grantWildcard(AccessType::INSERT, "default", "t"); ASSERT_EQ(root.isGranted(AccessType::SELECT, "default", "t"), true); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "t"), true); - ASSERT_EQ(root.toString(), "GRANT SELECT ON default.t, GRANT INSERT ON default.t*"); + ASSERT_EQ(root.toString(), "GRANT INSERT ON default.t*, GRANT SELECT ON default.t"); root.revoke(AccessType::INSERT, "default", "t"); ASSERT_EQ(root.isGranted(AccessType::SELECT, "default", "t"), true); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "t"), false); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "test"), true); - ASSERT_EQ(root.toString(), "GRANT SELECT ON default.t, GRANT INSERT ON default.t*, REVOKE INSERT ON default.t"); + ASSERT_EQ(root.toString(), "GRANT INSERT ON default.t*, GRANT SELECT ON default.t, REVOKE INSERT ON default.t"); root = {}; root.grant(AccessType::SELECT, "default", "t"); @@ -235,6 +235,51 @@ TEST(AccessRights, GrantWildcard) ASSERT_EQ(root.toString(), "GRANT SELECT ON db*.* WITH GRANT OPTION, GRANT INSERT ON db.`table`"); } +TEST(AccessRights, WildcardBeforeExactNameInElements) +{ + /// The elements are applied in the order of `getElements`, so `REVOKE ... ON dbx*.*` must precede `GRANT ... ON dbx.*`. + AccessRights root; + root.grantWildcard(AccessType::SELECT, "db"); + root.revokeWildcard(AccessType::SELECT, "dbx"); + root.grant(AccessType::SELECT, "dbx"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON db*.*, REVOKE SELECT ON dbx*.*, GRANT SELECT ON dbx.*"); + AccessRights restored{root.getElements()}; + ASSERT_TRUE(restored.isGranted(AccessType::SELECT, "dbx")); + ASSERT_FALSE(restored.isGranted(AccessType::SELECT, "dbx1")); + ASSERT_EQ(restored, root); + + root = {}; + root.grant(AccessType::SELECT, "db"); + root.revokeWildcard(AccessType::SELECT, "db", "t"); + root.grant(AccessType::SELECT, "db", "t"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON db.*, REVOKE SELECT ON db.t*, GRANT SELECT ON db.t"); + restored = AccessRights{root.getElements()}; + ASSERT_TRUE(restored.isGranted(AccessType::SELECT, "db", "t")); + ASSERT_FALSE(restored.isGranted(AccessType::SELECT, "db", "t1")); + ASSERT_EQ(restored, root); + + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revokeWildcardGrantOption(AccessType::SELECT, "db"); + root.grantWithGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), + "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db*.*, GRANT SELECT ON db.* WITH GRANT OPTION"); + restored = AccessRights{root.getElements()}; + ASSERT_TRUE(restored.hasGrantOption(AccessType::SELECT, "db")); + ASSERT_FALSE(restored.hasGrantOption(AccessType::SELECT, "db1")); + ASSERT_EQ(restored, root); + + /// The same after a union, like the rights of two roles. + AccessRights lhs; + AccessRights rhs; + lhs.grant(AccessType::SELECT); + lhs.revokeWildcard(AccessType::SELECT, "db"); + rhs.grant(AccessType::SELECT, "db"); + lhs.makeUnion(rhs); + ASSERT_EQ(lhs.toString(), "GRANT SELECT ON *.*, REVOKE SELECT ON db*.*, GRANT SELECT ON db.*"); + ASSERT_TRUE(AccessRights{lhs.getElements()}.isGranted(AccessType::SELECT, "db")); +} + TEST(AccessRights, Union) { AccessRights lhs; From 267e37bfccd4094aca2428a7c71193ee7acc419c Mon Sep 17 00:00:00 2001 From: blau-ai <302218339+blau-ai@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:01:59 +0000 Subject: [PATCH 112/116] Resolve conflicts in merge of v26.3.77.6-lts Took upstream's version bump and PPA removal, and kept Altinity's clang-tools install and Altinity version suffix. --- ci/docker/binary-builder/Dockerfile | 7 ------- cmake/autogenerated_versions.txt | 11 ++--------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/ci/docker/binary-builder/Dockerfile b/ci/docker/binary-builder/Dockerfile index 62214531bc06..402674446465 100644 --- a/ci/docker/binary-builder/Dockerfile +++ b/ci/docker/binary-builder/Dockerfile @@ -19,16 +19,9 @@ COPY --from=altinityinfra/cctools:c0aae9395f33405b6e2b \ /etc/ssl/ RUN apt-get update \ -<<<<<<< HEAD - && apt-get install software-properties-common --yes --no-install-recommends --verbose-versions - -RUN add-apt-repository ppa:ubuntu-toolchain-r/test --yes \ - && apt-get update \ && apt-get remove --yes clang-tools-${LLVM_VERSION} || true \ && apt-get install --yes \ clang-tools-${LLVM_VERSION} \ -======= ->>>>>>> v26.3.77.6-lts && apt-get install --yes \ binutils-dev \ build-essential \ diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index f7abfbf9c4bd..bd9470b11cb1 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -5,17 +5,10 @@ SET(VERSION_REVISION 54584) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 3) -<<<<<<< HEAD -SET(VERSION_PATCH 64) -SET(VERSION_GITHASH f4eb235f16580439cd374038ecd8c013a0011cd9) -SET(VERSION_DESCRIBE v26.3.64.10001.altinitytest) -SET(VERSION_STRING 26.3.64.10001.altinitytest) -======= SET(VERSION_PATCH 77) SET(VERSION_GITHASH 510026b533dac3dda78e8c67076b01ff496b0c72) -SET(VERSION_DESCRIBE v26.3.77.1-lts) -SET(VERSION_STRING 26.3.77.1) ->>>>>>> v26.3.77.6-lts +SET(VERSION_DESCRIBE v26.3.77.10001.altinitytest) +SET(VERSION_STRING 26.3.77.10001.altinitytest) # end of autochange SET(VERSION_TWEAK 10001) From bae109123ccf0efcbf0dc9a9354f674294ef6807 Mon Sep 17 00:00:00 2001 From: blau-ai Date: Thu, 3 Dec 2026 15:05:38 +0000 Subject: [PATCH 113/116] Mark 05802_parquet_plain_string_fully_filtered_pages as no-fasttest --- .../05802_parquet_plain_string_fully_filtered_pages.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/queries/0_stateless/05802_parquet_plain_string_fully_filtered_pages.sh b/tests/queries/0_stateless/05802_parquet_plain_string_fully_filtered_pages.sh index 792424fb1335..008089dc27be 100755 --- a/tests/queries/0_stateless/05802_parquet_plain_string_fully_filtered_pages.sh +++ b/tests/queries/0_stateless/05802_parquet_plain_string_fully_filtered_pages.sh @@ -1,4 +1,6 @@ #!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: Parquet format is not built in Fast test # `PREWHERE` over a Parquet file with many small pages, where some pages lie entirely inside runs of # filtered-out rows. Such pages are passed to the page decoders with an all-zero filter, and the decoders From a168a0686bbe9cf6f188f79fdeca6c366f3cda18 Mon Sep 17 00:00:00 2001 From: Konstantin Bogdanov Date: Wed, 25 Mar 2026 15:46:21 +0100 Subject: [PATCH 114/116] Fix recorded prql test result due to `prqlc` update (cherry picked from commit 1941bea97a526403fcec39f1daf62a420729bccf) --- src/Parsers/tests/gtest_Parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Parsers/tests/gtest_Parser.cpp b/src/Parsers/tests/gtest_Parser.cpp index 429e65d8d125..daf71a85d715 100644 --- a/src/Parsers/tests/gtest_Parser.cpp +++ b/src/Parsers/tests/gtest_Parser.cpp @@ -371,6 +371,6 @@ INSTANTIATE_TEST_SUITE_P( }, { "from matches\nfilter start_date > @2023-05-30 # Some comment here\nderive {\n some_derived_value_1 = a + (b ?? 0), # And there\n some_derived_value_2 = c + some_derived_value\n}\nfilter some_derived_value_2 > 0\ngroup {country, city} (\n aggregate {\n average some_derived_value_2,\n aggr = max some_derived_value_2\n }\n)\nderive place = f\"{city} in {country}\"\nderive country_code = s\"LEFT(country, 2)\"\nsort {aggr, -country}\ntake 1..20", - "WITH\n table_1 AS\n (\n SELECT\n country,\n city,\n c + some_derived_value AS _expr_1\n FROM matches\n WHERE start_date > toDate('2023-05-30')\n ),\n table_0 AS\n (\n SELECT\n country,\n city,\n AVG(_expr_1) AS _expr_0,\n MAX(_expr_1) AS aggr\n FROM table_1\n WHERE _expr_1 > 0\n GROUP BY\n country,\n city\n )\nSELECT\n country,\n city,\n _expr_0,\n aggr,\n CONCAT(city, ' in ', country) AS place,\n LEFT(country, 2) AS country_code\nFROM table_0\nORDER BY\n aggr ASC,\n country DESC\nLIMIT 20", + "WITH table_0 AS\n (\n SELECT\n country,\n city,\n AVG(c + some_derived_value) AS _expr_0,\n MAX(c + some_derived_value) AS aggr\n FROM matches\n WHERE (start_date > toDate('2023-05-30')) AND ((c + some_derived_value) > 0)\n GROUP BY\n country,\n city\n )\nSELECT\n country,\n city,\n _expr_0,\n aggr,\n CONCAT(city, ' in ', country) AS place,\n LEFT(country, 2) AS country_code\nFROM table_0\nORDER BY\n aggr ASC,\n country DESC\nLIMIT 20", }, }))); From 5cd409ba5a89bd5b337aad41dd058c67bf213dcf Mon Sep 17 00:00:00 2001 From: blau-ai Date: Fri, 4 Dec 2026 18:37:41 +0000 Subject: [PATCH 115/116] Drop local ppc64le libunwind VSX patch, now included in contrib/llvm-project The bumped contrib/llvm-project (85d6c707358) already contains the extra xxswapd in PPC64_STVS (upstream ClickHouse#129808), so applying the patch fails at CMake configure time. Match upstream contrib/libunwind-cmake. --- contrib/libunwind-cmake/CMakeLists.txt | 26 ------------------- .../ppc64le-vsx-register-save.patch | 10 ------- 2 files changed, 36 deletions(-) delete mode 100644 contrib/libunwind-cmake/ppc64le-vsx-register-save.patch diff --git a/contrib/libunwind-cmake/CMakeLists.txt b/contrib/libunwind-cmake/CMakeLists.txt index 1f10c2881ab0..c37c485f0f0b 100644 --- a/contrib/libunwind-cmake/CMakeLists.txt +++ b/contrib/libunwind-cmake/CMakeLists.txt @@ -17,32 +17,6 @@ set(LIBUNWIND_ASM_SOURCES "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersRestore.S" "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S") -# stxvd2x stores VSX doublewords swapped on ppc64le. The first xxswapd fixes the -# saved image and leaves the live register swapped; the patch swaps it back. -if(ARCH_PPC64LE) - find_program(LIBUNWIND_PATCH_EXECUTABLE patch REQUIRED) - set(LIBUNWIND_REGISTERS_SAVE_ASM "${CMAKE_CURRENT_BINARY_DIR}/UnwindRegistersSave.S") - set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS - "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S" - "${CMAKE_CURRENT_SOURCE_DIR}/ppc64le-vsx-register-save.patch") - execute_process( - COMMAND "${LIBUNWIND_PATCH_EXECUTABLE}" -o "${LIBUNWIND_REGISTERS_SAVE_ASM}" - "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S" - "${CMAKE_CURRENT_SOURCE_DIR}/ppc64le-vsx-register-save.patch" - RESULT_VARIABLE LIBUNWIND_PATCH_RESULT - OUTPUT_VARIABLE LIBUNWIND_PATCH_OUTPUT - ERROR_VARIABLE LIBUNWIND_PATCH_ERROR - ) - if(NOT LIBUNWIND_PATCH_RESULT EQUAL 0) - message(FATAL_ERROR "Failed to apply ppc64le-vsx-register-save.patch\n${LIBUNWIND_PATCH_OUTPUT}\n${LIBUNWIND_PATCH_ERROR}") - endif() - list(REMOVE_ITEM LIBUNWIND_ASM_SOURCES "${LIBUNWIND_SOURCE_DIR}/src/UnwindRegistersSave.S") - list(APPEND LIBUNWIND_ASM_SOURCES "${LIBUNWIND_REGISTERS_SAVE_ASM}") - # "assembly.h" is included from the directory of the .S file. - set_source_files_properties("${LIBUNWIND_REGISTERS_SAVE_ASM}" PROPERTIES - COMPILE_FLAGS "-I${LIBUNWIND_SOURCE_DIR}/src") -endif() - enable_language(ASM) set(LIBUNWIND_SOURCES diff --git a/contrib/libunwind-cmake/ppc64le-vsx-register-save.patch b/contrib/libunwind-cmake/ppc64le-vsx-register-save.patch deleted file mode 100644 index 79eed78d63ab..000000000000 --- a/contrib/libunwind-cmake/ppc64le-vsx-register-save.patch +++ /dev/null @@ -1,10 +0,0 @@ ---- a/UnwindRegistersSave.S -+++ b/UnwindRegistersSave.S -@@ -427,6 +427,7 @@ - #define PPC64_STVS(n) \ - xxswapd n, n ;\ - stxvd2x n, 0, 4 ;\ -+ xxswapd n, n ;\ - addi 4, 4, 16 - #else - #define PPC64_STVS(n) \ From b59041fc86efe12a22d37bf79caadac27b085287 Mon Sep 17 00:00:00 2001 From: blau-ai Date: Sat, 5 Dec 2026 17:33:47 +0000 Subject: [PATCH 116/116] Check the in-tree libunwind source in the ppc64le patch check The local libunwind patch was dropped because contrib/llvm-project now contains the VSX register save fix, so contrib/libunwind-cmake/UnwindRegistersSave.S is no longer generated. Read contrib/llvm-project/libunwind/src/UnwindRegistersSave.S instead and require it as the build input. Signed-off-by: blau-ai --- ci/jobs/build_clickhouse.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/ci/jobs/build_clickhouse.py b/ci/jobs/build_clickhouse.py index 0fee05526581..4a08b132858f 100644 --- a/ci/jobs/build_clickhouse.py +++ b/ci/jobs/build_clickhouse.py @@ -89,14 +89,17 @@ def run_shell(name, command, **kwargs): def check_ppc64le_patches(build_root): - asm_path = os.path.join(build_root, "contrib/libunwind-cmake/UnwindRegistersSave.S") + # The ppc64le VSX register save fix is part of contrib/llvm-project itself now, + # so the unpatched libunwind source must contain it and must be the build input. + libunwind_asm = "contrib/llvm-project/libunwind/src/UnwindRegistersSave.S" + asm_path = os.path.join(current_directory, libunwind_asm) ninja_path = os.path.join(build_root, "build.ninja") try: with open(asm_path, encoding="utf-8") as asm_file: asm = asm_file.read() except OSError as error: - print(f"Could not read patched libunwind source {asm_path}: {error}") + print(f"Could not read libunwind source {asm_path}: {error}") return False restored = ( @@ -105,12 +108,11 @@ def check_ppc64le_patches(build_root): " xxswapd n, n ;\\" ) if restored not in asm: - print(f"ppc64le libunwind patch was not applied to {asm_path}") + print(f"ppc64le libunwind VSX register save fix is missing in {asm_path}") return False # CMAKE_CXX_FLAGS in CMakeCache.txt stays empty. The real flags are on the ninja FLAGS lines. frame_flag = "-Wframe-larger-than=131072" - patched_asm = "contrib/libunwind-cmake/UnwindRegistersSave.S" found_frame = False found_asm = False found_altivec = False @@ -118,11 +120,11 @@ def check_ppc64le_patches(build_root): try: with open(ninja_path, encoding="utf-8", errors="replace") as ninja: for line in ninja: - if "FLAGS" not in line and patched_asm not in line: + if "FLAGS" not in line and libunwind_asm not in line: continue if not found_frame and frame_flag in line: found_frame = True - if not found_asm and patched_asm in line: + if not found_asm and libunwind_asm in line: found_asm = True if "FLAGS" in line: if "-maltivec" in line and ( @@ -144,7 +146,7 @@ def check_ppc64le_patches(build_root): print(f"{frame_flag} is not in {ninja_path}") return False if not found_asm: - print(f"{patched_asm} is not a build input in {ninja_path}") + print(f"{libunwind_asm} is not a build input in {ninja_path}") return False print("ppc64le patches are present") return True